fix(editor): Task 3 round 1, literal journey, pin, limits, notice

This commit is contained in:
bchanot committed 2026-11-13 20:38:04 +01:00
1 parent 8b42816270
commit 3bb3603115
9 files changed
+295 -97

No files matched your search

@@ -14,6 +14,7 @@ import {
place, place,
referenceDialog, referenceDialog,
referenceSettled, referenceSettled,
revealFinding,
seedDraft, seedDraft,
showCitations, showCitations,
standardShape, standardShape,
@@ -33,6 +34,8 @@ const chip = (page: Page) =>
libraryRoot(page).getByTestId('editor-references-filter') libraryRoot(page).getByTestId('editor-references-filter')
const headers = (page: Page) => const headers = (page: Page) =>
libraryRoot(page).locator('button[aria-controls][id$="-header"]') libraryRoot(page).locator('button[aria-controls][id$="-header"]')
const sheetHeaders = (page: Page) =>
panel(page).locator('button[aria-controls][id$="-header"]')
const undo = (page: Page) => historyButton(page, dict, 'undo') const undo = (page: Page) => historyButton(page, dict, 'undo')
const dialogs = (page: Page) => page.locator('dialog[open]') const dialogs = (page: Page) => page.locator('dialog[open]')
@@ -107,6 +110,46 @@ test.describe('the owner journey through the history', () => {
await dropLateReplays(context) await dropLateReplays(context)
}) })
test("the owner's eight steps, nothing in between: Back returns to finding A with its sheet open", async ({
page,
}) => {
test.setTimeout(240_000)
await open(page)
// 1. the Constats tab; 2. finding A opens.
await openTab(page, dict, 'findings')
await (await revealFinding(page, 'Constat A')).click()
await expect(findingDialog(page)).toBeVisible()
await entryHolds(page, 'view.finding !== null')
// 3. « 2 références »; 4. the sheet opens and lists the two references.
const trigger = page.locator('[data-citations-trigger]:visible')
await expect(trigger).toContainText('2 références')
await trigger.click()
await expect(place(page, 'citations')).toBeVisible()
await expect(sheetHeaders(page)).toHaveCount(2)
await entryHolds(page, 'view.finding && view.finding.citations')
// 5. « Tout afficher dans l'onglet Références »; 6. the tab filtered on A's two references.
await panel(page)
.getByRole('button', { name: dict['editor.references.panel_show_all'] })
.click()
await expectNoDialog(page)
await entryHolds(
page,
"view.tab === 'references' && !!view.referenceFilter",
)
await expect(chip(page)).toContainText('Constat A')
await expect(headers(page)).toHaveCount(2)
await expect(
libraryRoot(page).getByText('2 références', { exact: true }),
).toBeVisible()
// 7. browser Back; 8. finding A with its sheet on top, as left.
await page.goBack()
await expect(dialogs(page)).toHaveCount(2)
await expect(findingDialog(page)).toBeVisible()
await expect(findingDialog(page)).toContainText('Constat A')
expect(await sheetOnTop(page)).toBe(true)
await expect(sheetHeaders(page)).toHaveCount(2)
})
test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({ test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({
page, page,
}, info) => { }, info) => {
@@ -8,8 +8,8 @@ export type DiscardTarget = 'form' | 'dialog'
/** /**
* The layer's guard (the finding dialog's, or the reference dialog's) while a form holds * The layer's guard (the finding dialog's, or the reference dialog's) while a form holds
* changes (R2F-3, R2F-5): a user close that reaches the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les * changes (R2F-3, R2F-5): a user close that reaches the layer (✕, Escape, scrim, Back)
* modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and * is refused and the form asks « Abandonner les modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and
* says the draft was dropped (BDR-115); a form with nothing typed says nothing. * says the draft was dropped (BDR-115); a form with nothing typed says nothing.
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too. * `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
*/ */
@@ -89,6 +89,15 @@ const positionOf = (all: readonly Reference[], key: ElementKey) =>
type Show = (key: ElementKey) => 'found' | 'none' type Show = (key: ElementKey) => 'found' | 'none'
/** Whether the finding filter or the search hides `reference` from the list. */
function hiddenBy(lib: ReferenceLibraryState, reference: Reference) {
const cited = lib.finding && citedIds(lib.finding)
return {
filtered: !!cited && !cited.includes(reference.id),
matches: referenceMatches(reference, lib.shown.view.query),
}
}
/** /**
* Shows a reference's tile: opened, the search cleared (only it, P3) and the finding * Shows a reference's tile: opened, the search cleared (only it, P3) and the finding
* filter removed when they hide it, its button focused after the commit that shows it * filter removed when they hide it, its button focused after the commit that shows it
@@ -102,14 +111,13 @@ function useShowReference(
return (key) => { return (key) => {
const at = positionOf(lib.all, key) const at = positionOf(lib.all, key)
if (at < 0) return 'none' if (at < 0) return 'none'
const reference = lib.all[at]
lib.tiles.reveal(lib.keys[at]) lib.tiles.reveal(lib.keys[at])
const cited = lib.finding && citedIds(lib.finding) const hidden = hiddenBy(lib, lib.all[at])
const filtered = !!cited && !cited.includes(reference.id) if (hidden.matches && !hidden.filtered) {
const matches = referenceMatches(reference, lib.shown.view.query) return focusRowLater(key) ? 'found' : 'none'
if (matches && !filtered) return focusRowLater(key) ? 'found' : 'none' }
if (filtered) layer.clearFilter() if (hidden.filtered) layer.clearFilter()
if (!matches) lib.shown.update({ query: '' }) if (!hidden.matches) lib.shown.update({ query: '' })
later(key) later(key)
return 'found' return 'found'
} }
@@ -122,14 +130,21 @@ function useReferenceFocus(focus: FocusRequest | undefined, show: Show) {
) )
} }
/** The notice of a reference just added: shown until « Afficher », or until it is gone. */ /**
* The notice of a reference just added: shown until « Afficher », until it is gone, or
* until the user leaves the References tab (it would be stale on their return).
*/
function useAddedNotice( function useAddedNotice(
all: readonly Reference[], all: readonly Reference[],
added: ReferenceLayer['added'], added: ReferenceLayer['added'],
show: Show, show: Show,
) { ) {
const [dismissed, setDismissed] = useState(0) const [dismissed, setDismissed] = useState(0)
const visible = usePlaceVisible()
const reference = added && all.find((r) => r.id === added.id) const reference = added && all.find((r) => r.id === added.id)
if (added && !visible && dismissed !== added.serial) {
setDismissed(added.serial)
}
if (!added || !reference || added.serial === dismissed) return null if (!added || !reference || added.serial === dismissed) return null
return { return {
citation: reference.citation, citation: reference.citation,
@@ -5,16 +5,21 @@ import type { CiterItem } from '@/editor/references/citations'
import { import {
isSheetView, isSheetView,
shownPositions, shownPositions,
type Pin,
type ReferenceView, type ReferenceView,
} from '@/editor/references/view' } from '@/editor/references/view'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
const INITIAL: ReferenceView = { query: '', sort: 'sheet' } const INITIAL: ReferenceView = { query: '', sort: 'sheet' }
/** The tile kept in the shown set, by key, and the index it is shown at (P23). */ /**
* The tile kept in the shown set, by key, and the index it is shown at (P23); it is valid
* for the `view` it was pinned under only, so any search or sort change ends it.
*/
interface Pinned { interface Pinned {
key: string key: string
index: number index: number
view: ReferenceView
} }
/** The bibliography the view reads: references, one tile key per position, citers. */ /** The bibliography the view reads: references, one tile key per position, citers. */
@@ -24,6 +29,73 @@ interface Shown {
citers: ReadonlyMap<string, readonly CiterItem[]> citers: ReadonlyMap<string, readonly CiterItem[]>
} }
/** The search and the sort; the search is emptied once per `resetSignal` bump. */
function useViewState(resetSignal: number) {
const [state, setState] = useState({ view: INITIAL, seen: resetSignal })
if (state.seen !== resetSignal) {
setState({ view: { ...state.view, query: '' }, seen: resetSignal })
}
const update = (patch: Partial<ReferenceView>) =>
setState((now) => ({ ...now, view: { ...now.view, ...patch } }))
return [state.view, update] as const
}
/** The positions to show for a pin (or none): the filter, the search, the sort, the pin. */
function useOrder(
shown: Shown,
view: ReferenceView,
cited: ReadonlySet<string> | null,
) {
const locale = useLocaleStore((state) => state.locale)
const context = {
locale,
citedCount: (id: string) => shown.citers.get(id)?.length ?? 0,
}
return (pin: Pin | null) =>
shownPositions(shown.all, view, context, pin, cited)
}
/**
* The pin of the tile the dialog edits. Only a shown tile is pinned (a reference just
* created is not part of the list), never under a filter (R2F-6: a tile outside it never
* shows, and a pin of the filtered session must not outlive it).
*/
function usePin(
keys: readonly string[],
editingKey: string | null,
view: ReferenceView,
order: (pin: Pin | null) => number[],
filtered: boolean,
) {
const [pinned, setPinned] = useState<Pinned | null>(null)
const edited = editingKey === null ? -1 : keys.indexOf(editingKey)
const plain = order(null)
const current = pinned?.view === view && pinned.key === editingKey
if (filtered && pinned !== null) setPinned(null)
else if (!filtered && plain.includes(edited) && !current) {
setPinned({ key: editingKey as string, index: plain.indexOf(edited), view })
}
const at = pinned === null ? -1 : keys.indexOf(pinned.key)
const live = !filtered && pinned?.view === view && at >= 0
return live && !isSheetView(view)
? { position: at, index: Math.max(0, pinned?.index ?? 0) }
: null
}
/** How many references match (the filter, then the search), and how many the filter holds. */
function countsOf(
all: readonly Reference[],
query: string,
cited: ReadonlySet<string> | null,
) {
const inFilter = (r: Reference) => cited === null || cited.has(r.id)
// The count is the matches: a pinned tile the search misses is shown, not counted.
const matchCount = all.filter(
(r) => inFilter(r) && referenceMatches(r, query),
).length
return { matchCount, total: all.filter(inFilter).length }
}
/** /**
* The search, the sort and the resulting tile order of the Références tab. All three are * The search, the sort and the resulting tile order of the Références tab. All three are
* display state: nothing here reaches the document (BDR-114), and the search is a personal * display state: nothing here reaches the document (BDR-114), and the search is a personal
@@ -34,53 +106,23 @@ interface Shown {
* The tile the dialog edits (`editingKey`) is pinned at the index it was shown at, whatever * The tile the dialog edits (`editingKey`) is pinned at the index it was shown at, whatever
* the search or the sort, and stays pinned after the dialog closes until the next search * the search or the sort, and stays pinned after the dialog closes until the next search
* or sort change, so the tile the user just edited never vanishes under their focus (P23, * or sort change, so the tile the user just edited never vanishes under their focus (P23,
* I1). With a filter nothing is pinned: a tile outside it never shows. * I1). With a filter nothing is pinned.
*/ */
export function useReferenceView( export function useReferenceView(
{ all, keys, citers }: Shown, shown: Shown,
editingKey: string | null, editingKey: string | null,
resetSignal: number, resetSignal: number,
cited: ReadonlySet<string> | null, cited: ReadonlySet<string> | null,
) { ) {
const locale = useLocaleStore((state) => state.locale) const [view, update] = useViewState(resetSignal)
const [view, setView] = useState(INITIAL) const order = useOrder(shown, view, cited)
const [seen, setSeen] = useState(resetSignal) const filtered = cited !== null
const [pinned, setPinned] = useState<Pinned | null>(null) const pin = usePin(shown.keys, editingKey, view, order, filtered)
if (seen !== resetSignal) {
setSeen(resetSignal)
setView({ ...view, query: '' })
setPinned(null)
}
const context = {
locale,
citedCount: (id: string) => citers.get(id)?.length ?? 0,
}
const plain = shownPositions(all, view, context, null, cited)
const editedAt = editingKey === null ? -1 : keys.indexOf(editingKey)
// Only a tile that is shown is pinned: a reference just created is not part of the list.
if (plain.includes(editedAt) && pinned?.key !== editingKey) {
setPinned({ key: editingKey as string, index: plain.indexOf(editedAt) })
}
const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
const pin =
pinned !== null && pinAt >= 0 && !isSheetView(view, cited !== null)
? { position: pinAt, index: Math.max(0, pinned.index) }
: null
const positions = shownPositions(all, view, context, pin, cited)
const inFilter = (r: Reference) => cited === null || cited.has(r.id)
// The count is the matches: a pinned tile the search misses is shown, not counted.
const matchCount = all.filter(
(r) => inFilter(r) && referenceMatches(r, view.query),
).length
return { return {
view, view,
positions, update,
matchCount, positions: order(pin),
total: all.filter(inFilter).length, filtered,
filtered: cited !== null, ...countsOf(shown.all, view.query, cited),
update: (patch: Partial<ReferenceView>) => {
setPinned(null)
setView((current) => ({ ...current, ...patch }))
},
} }
} }
@@ -74,37 +74,50 @@ interface BodyProps {
props: Props props: Props
} }
/** The notice, the empty and no-result lines, the hint and the tiles. */ /** The notice, the empty and no-result lines and the reorder hint. */
function LibraryBody({ lib, act, props }: BodyProps) { function LibraryNotices(body: BodyProps) {
const t = useT() const t = useT()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null) const { shown } = body.lib
const { all, shown } = lib const reorderable =
const sheetView = isSheetView(shown.view, shown.filtered) !body.props.readOnly && !isSheetView(shown.view, shown.filtered)
return ( return (
<> <>
{act.notice && ( {body.act.notice && (
<AddedNotice citation={act.notice.citation} onShow={act.notice.show} /> <AddedNotice
citation={body.act.notice.citation}
onShow={body.act.notice.show}
/>
)} )}
{all.length === 0 && <EmptyLine />} {body.lib.all.length === 0 && <EmptyLine />}
{all.length > 0 && shown.positions.length === 0 && ( {body.lib.all.length > 0 && shown.positions.length === 0 && (
<NoResult query={shown.view.query} onClear={act.clearSearch} /> <NoResult query={shown.view.query} onClear={body.act.clearSearch} />
)} )}
{!props.readOnly && !sheetView && shown.positions.length > 0 && ( {reorderable && shown.positions.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.reorder_hint')} {t('editor.references.reorder_hint')}
</p> </p>
)} )}
</>
)
}
/** The tiles and the delete dialog they open. */
function LibraryTiles(body: BodyProps) {
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const { lib } = body
return (
<>
<ReferenceTiles <ReferenceTiles
positions={shown.positions} positions={lib.shown.positions}
all={all} all={lib.all}
keys={lib.keys} keys={lib.keys}
citers={lib.citers} citers={lib.citers}
tiles={lib.tiles} tiles={lib.tiles}
query={shown.view.query} query={lib.shown.view.query}
readOnly={props.readOnly} readOnly={body.props.readOnly}
movable={sheetView} movable={isSheetView(lib.shown.view, lib.shown.filtered)}
navigate={props.navigate} navigate={body.props.navigate}
onEdit={act.edit} onEdit={body.act.edit}
onDelete={(reference) => onDelete={(reference) =>
setDeleting({ setDeleting({
key: { kind: 'reference', id: reference.id }, key: { kind: 'reference', id: reference.id },
@@ -128,23 +141,27 @@ function Library(props: Props) {
const searchRef = useRef<HTMLInputElement>(null) const searchRef = useRef<HTMLInputElement>(null)
const act = useReferenceActions(lib, props.focus, props.layer, searchRef) const act = useReferenceActions(lib, props.focus, props.layer, searchRef)
const chip = useFilterChip(lib, props.layer) const chip = useFilterChip(lib, props.layer)
const { shown } = lib
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<ReferenceToolbar <ReferenceToolbar
query={shown.view.query} query={lib.shown.view.query}
onQuery={(query) => shown.update({ query })} onQuery={(query) => lib.shown.update({ query })}
onClear={act.clearSearch} onClear={act.clearSearch}
searchRef={searchRef} searchRef={searchRef}
sort={shown.view.sort} sort={lib.shown.view.sort}
onSort={(sort) => shown.update({ sort })} onSort={(sort) => lib.shown.update({ sort })}
shown={shown.matchCount} shown={lib.shown.matchCount}
total={shown.total} total={lib.shown.total}
canAdd={!props.readOnly} canAdd={!props.readOnly}
onAdd={act.startAdd} onAdd={act.startAdd}
filter={chip} filter={chip}
/> />
{lib.loaded && <LibraryBody lib={lib} act={act} props={props} />} {lib.loaded && (
<>
<LibraryNotices lib={lib} act={act} props={props} />
<LibraryTiles lib={lib} act={act} props={props} />
</>
)}
</div> </div>
) )
} }
+1 -7
View File
@@ -20,11 +20,6 @@ export interface ModalDialogProps {
* move that closed it. * move that closed it.
*/ */
returnFocus?: (() => HTMLElement | null) | null returnFocus?: (() => HTMLElement | null) | null
/**
* Escape typed where this answers true is swallowed: no close request. For a part that
* still edits inline (the citations sheet's tiles) and keeps Escape for the field.
*/
ignoreEscape?: (target: EventTarget) => boolean
/** /**
* A view layer of the editor (R2F-1): its state is in the browser history, so a Back * A view layer of the editor (R2F-1): its state is in the browser history, so a Back
* may close it. Any other modal open refuses a Back. * may close it. Any other modal open refuses a Back.
@@ -105,7 +100,6 @@ function restoreFocus(
export default function ModalDialog({ export default function ModalDialog({
onClose, onClose,
returnFocus, returnFocus,
ignoreEscape,
layer, layer,
labelledBy, labelledBy,
label, label,
@@ -161,7 +155,7 @@ export default function ModalDialog({
event.preventDefault() event.preventDefault()
event.stopPropagation() event.stopPropagation()
// A held key repeats: only the first press asks. // A held key repeats: only the first press asks.
if (event.repeat || ignoreEscape?.(event.target)) return if (event.repeat) return
onClose() onClose()
} }
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => { const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
+12 -11
View File
@@ -57,7 +57,8 @@ function useOpening({ dispatch, mark }: LayerContext, held: RefObject<Opener>) {
} }
/** The moves that take it away: a user close, and the replace that is no Back step. */ /** The moves that take it away: a user close, and the replace that is no Back step. */
function useClosing({ dispatch, announce, guards, mark }: LayerContext) { function useClosing(ctx: LayerContext) {
const { dispatch, announce, guards, mark } = ctx
const close = useCallback( const close = useCallback(
(forced = false) => { (forced = false) => {
if (!guards.ask('reference', forced).allowed) return false if (!guards.ask('reference', forced).allowed) return false
@@ -82,17 +83,19 @@ function useClosing({ dispatch, announce, guards, mark }: LayerContext) {
} }
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */ /** A creation that succeeded: its entry becomes the reference's own, then it closes. */
function useCreated( function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
{ dispatch, mark }: LayerContext, const { dispatch, mark } = ctx
replace: ReferenceMoves['replace'],
) {
const [added, setAdded] = useState<AddedReference | null>(null) const [added, setAdded] = useState<AddedReference | null>(null)
const created = useCallback( const created = useCallback(
(id: string) => { (id: string) => {
replace(id) replace(id)
setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 })) setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
// After the commit that wrote the replace: the entry is the reference's own before // Precondition: the caller is a discrete event (the form's submit). React then
// the close goes back over it, so a Forward never reopens a creation. // renders the replace and runs the history effect before this microtask, so the
// entry is the reference's own before the close goes back over it and a Forward
// never reopens a creation. Called from anywhere else, the replace and the close
// would merge into one view change (a Back, and the entry keeps its creation).
// The microtask also keeps `mark()` from overwriting the replace hint early.
queueMicrotask(() => { queueMicrotask(() => {
mark() mark()
dispatch({ type: 'close_reference' }) dispatch({ type: 'close_reference' })
@@ -104,10 +107,8 @@ function useCreated(
} }
/** The filter's two moves: remove it by replace, return to the finding it names. */ /** The filter's two moves: remove it by replace, return to the finding it names. */
function useFilter( function useFilter(ctx: LayerContext, trace: MoveTrace) {
{ dispatch, announce, mark }: LayerContext, const { dispatch, announce, mark } = ctx
trace: MoveTrace,
) {
const clearFilter = useCallback( const clearFilter = useCallback(
(text?: string) => { (text?: string) => {
if (text) announce(text) if (text) announce(text)
@@ -9,7 +9,7 @@ import {
within, within,
} from '@testing-library/react' } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import type { ReferenceType } from '@faunosteo/core-wasm/types' import type { ElementKey, ReferenceType } from '@faunosteo/core-wasm/types'
import { targetOfKey } from '@/editor/navigation' import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures' import { edit, insert } from '../helpers/editorFixtures'
@@ -20,6 +20,8 @@ import {
store, store,
} from '../helpers/editorHarness' } from '../helpers/editorHarness'
import ReferencesHost from '../helpers/referencesHost' import ReferencesHost from '../helpers/referencesHost'
import { PlaceVisibleContext } from '@/lib/placeVisibility'
import type { EditorNavigation } from '@/editor/useEditorNavigation'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({ vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -411,6 +413,90 @@ describe('the tile outside the search (C3)', () => {
}) })
}) })
describe('no pin while a finding filter is set (R2F-6)', () => {
const category: ElementKey = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a'],
}
let nav: EditorNavigation
const hosted = async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
render(<ReferencesHost onNav={(n) => (nav = n)} />)
return user
}
it('the tile edited under a filter leaves no pin once the filter is removed', async () => {
const user = await hosted()
await user.selectOptions(sortBox(), 'citation')
act(() => nav.showAllReferences(category))
expect(order()).toEqual(['r5', 'r2', 'r1'])
await startEdit(user, 'r2')
await cancelDialog(user)
act(() => nav.references.clearFilter())
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
})
it('a pin from before the filter does not come back after it', async () => {
const user = await hosted()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r1')
await cancelDialog(user)
act(() => nav.showAllReferences(category))
act(() => nav.references.clearFilter())
await user.selectOptions(sortBox(), 'citation')
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
})
it('a tile edited out of the search is not kept under a filter', async () => {
const user = await hosted()
act(() => nav.showAllReferences(category))
await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
await startEdit(user, 'r5')
await saveCitation(user, 'Autre titre')
expect(order()).toEqual([])
})
})
describe('the added-reference notice', () => {
it('goes when the user leaves the References tab', async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
let nav!: EditorNavigation
const { rerender } = render(
<PlaceVisibleContext value>
<ReferencesHost onNav={(n) => (nav = n)} />
</PlaceVisibleContext>,
)
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
const dialog = screen.getByRole('dialog', { name: 'Nouvelle référence' })
await user.selectOptions(within(dialog).getByLabelText('Type'), 'book')
await user.type(within(dialog).getByLabelText('Citation'), 'Nouvelle')
await user.click(
within(dialog).getByRole('button', { name: 'Ajouter la référence' }),
)
await waitFor(() =>
expect(screen.getByText('Référence ajoutée : Nouvelle')).toBeVisible(),
)
rerender(
<PlaceVisibleContext value={false}>
<ReferencesHost onNav={(n) => (nav = n)} />
</PlaceVisibleContext>,
)
rerender(
<PlaceVisibleContext value>
<ReferencesHost onNav={(n) => (nav = n)} />
</PlaceVisibleContext>,
)
expect(screen.queryByText(/Référence ajoutée/)).toBeNull()
expect(nav).toBeDefined()
})
})
describe('after a dialog closes, the view is unchanged (R2F-5)', () => { describe('after a dialog closes, the view is unchanged (R2F-5)', () => {
it('keeps scroll position inputs: search, sort, open tiles', async () => { it('keeps scroll position inputs: search, sort, open tiles', async () => {
const { user } = await mount() const { user } = await mount()
+1 -1
View File
@@ -304,7 +304,7 @@ concrete constraint.
| `lib/{dates,id}.ts` | `nowIso`, `todayIso`, `formatDate` (screen), `generateId` | Web APIs | clock and ids injected into the core; screen dates stay `Intl` | no | | | | **C** | n/a | | `lib/{dates,id}.ts` | `nowIso`, `todayIso`, `formatDate` (screen), `generateId` | Web APIs | clock and ids injected into the core; screen dates stay `Intl` | no | | | | **C** | n/a |
| `apps/app/src/editor/references/{filter,citations,panel}.ts` | Références tab and citations panel: search match on citation, DOI and URL (`folded`); who cites each reference (`citersOf`); the citations and the path of one finding | TS over the validated document | portable (pure functions), but display lists over the document the core already validated; the one rule nearby, which finding depends on a reference, stays the core's `sheet.dependents` | no | none; read in `useMemo` on the parsed document | none | existing unit suites (`editor-references-view`, `editor-citations`) | **C**: display-only search and listing over validated data, no business rule, no mutation; owner decision BDR-114 (A) 2026-11-12 | n/a | | `apps/app/src/editor/references/{filter,citations,panel}.ts` | Références tab and citations panel: search match on citation, DOI and URL (`folded`); who cites each reference (`citersOf`); the citations and the path of one finding | TS over the validated document | portable (pure functions), but display lists over the document the core already validated; the one rule nearby, which finding depends on a reference, stays the core's `sheet.dependents` | no | none; read in `useMemo` on the parsed document | none | existing unit suites (`editor-references-view`, `editor-citations`) | **C**: display-only search and listing over validated data, no business rule, no mutation; owner decision BDR-114 (A) 2026-11-12 | n/a |
| `apps/app/src/editor/references/{sort,view,referenceTypes}.ts` | the four display orders of the Références tab (sheet, citation A to Z, count, type), the shown set after the finding filter, the search and the sort (R2F-6: the ids a finding cites narrow the list; no pin under a filter) | TS, `Intl.Collator` of the current language | the collation needs the browser's ICU data (a Rust equivalent would ship its own); a pure function of positions that never writes the document, the stored order or the history | no | none | none | `editor-reference-sort.test.ts` (stable, equal keys keep the stored order, inputs untouched), view suites | **C**: display-only ordering, no business rule, no mutation; BDR-114 (A) | n/a | | `apps/app/src/editor/references/{sort,view,referenceTypes}.ts` | the four display orders of the Références tab (sheet, citation A to Z, count, type), the shown set after the finding filter, the search and the sort (R2F-6: the ids a finding cites narrow the list; no pin under a filter) | TS, `Intl.Collator` of the current language | the collation needs the browser's ICU data (a Rust equivalent would ship its own); a pure function of positions that never writes the document, the stored order or the history | no | none | none | `editor-reference-sort.test.ts` (stable, equal keys keep the stored order, inputs untouched), view suites | **C**: display-only ordering, no business rule, no mutation; BDR-114 (A) | n/a |
| `apps/app/src/editor/references/safeLink.ts` | `http` and `https` link target for a URL, `https://doi.org/` target for a well-formed DOI | TS (`URL`) | portable; it builds a display link, it validates no stored field (the core's reference rules stay authoritative) | no | none | none | `editor-safe-link.test.ts` | **C**: display-only link building over validated data; BDR-114 (A) | n/a | | `apps/app/src/editor/references/safeLink.ts` | `http` and `https` link target for a URL, `https://doi.org/` target for a well-formed DOI | TS (`URL`) | portable; it builds a display link, and its `http`/`https` test also backs the reference dialog's precheck of the stored URL field (UI form validation: the same refusal the core makes, shown on the field; the core's reference rules stay authoritative and refuse anything else) | no | none | none | `editor-safe-link.test.ts` | **C**: display-only link building over validated data; BDR-114 (A) | n/a |
| `apps/app/src/components/editor/references/useReferenceView.ts` | search text and sort choice (React state), the finding filter read from the history view (navigation, not typed text), tile order handed to the tab | React hook | holds view state only and calls the pure functions above; it reaches no wasm call and no document write | no | none | none | `editor-references-view.test.tsx` | **C**: React state of a display view; BDR-114 (A) | n/a | | `apps/app/src/components/editor/references/useReferenceView.ts` | search text and sort choice (React state), the finding filter read from the history view (navigation, not typed text), tile order handed to the tab | React hook | holds view state only and calls the pure functions above; it reaches no wasm call and no document write | no | none | none | `editor-references-view.test.tsx` | **C**: React state of a display view; BDR-114 (A) | n/a |
| `i18n/*` (281 keys ×2, `useT`, `pickLocaleLabel`) | UI strings | TS | UI data and hook; the engine's 25 archived labels move with the engine | no | | | parity test | **C** | n/a | | `i18n/*` (281 keys ×2, `useT`, `pickLocaleLabel`) | UI strings | TS | UI data and hook; the engine's 25 archived labels move with the engine | no | | | parity test | **C** | n/a |
| `config/env.ts`, `lib/supabase.ts`, providers, guards, routes, components, styles | runtime config, React | TS | glue | no | | | | **C** | n/a | | `config/env.ts`, `lib/supabase.ts`, providers, guards, routes, components, styles | runtime config, React | TS | glue | no | | | | **C** | n/a |