feat(editor): contextual citations panel of a finding (board 25)

The panel opens only from a finding's « {n} références » trigger: 34 rem
at most, never wider than the room, a scrim, slide in 180 ms and out
140 ms (motion/react; none under reduced motion, callbacks still fire).
It lists the finding's references as tiles with « Modifier », « Retirer
de ce constat » (one « Défaire » restores it and the review status) and
« Aller à »; dangling ids read « Référence introuvable »; zero left
reads « Ce constat ne cite plus aucune référence. ». « Tout afficher
dans l'onglet Références » resets search and sort, keeps open tiles and
edits. Every close (✕, Escape outside fields, scrim, tab, « Aller à »,
« Tout afficher », element gone) records one pending move applied
after the exit, page inert until then; focus back to the trigger, else
the active tab button. A refused draft cancels a user close; a forced
close drops it and announces « Saisie non appliquée : {field} ». Places
keeps a permanent dvh min-height; the panel fits the visible viewport
at every scroll position, document size unchanged.

Gates: typecheck, lint, test:run (app 1488), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (admin and editor-equine excluded):
117 passed / 107 skipped / 0 failed, rerun after the fix rounds: 118
passed / 108 skipped / 0 failed; layout spec 13 passed after round 2;
full-row guard: no pre-existing row changed in any table. Known limit:
landscape 667 x 375 at scroll 0 leaves ~13 px of panel (the trigger is
below the fold there).

## R-24 (removed or rewritten assertions)

| file | old | new |
|---|---|---|
| editor-references-panel.test.tsx (whole file) | R2.1 interim-panel tests, synchronous closes | rewritten: 39 tests (opening, motion, close matrix in both modes, exit, Retirer, P22'', library + history) |
| same, opening | heading `Références` focused right after the click | heading `Références citées` focused after the enter (`waitFor`), `aria-expanded` only after click |
| same | chip `references-filter-chip` « Citées par « Node A » (2) » | REMOVED (REVUE: path line + count line « 2 références citées par ce constat ») |
| same | `listitem` cards « Citée 2 fois » | tiles (`ul > li`) with the same counts, in the finding's order |
| same | field id `#panel-reference-0-ref-a-citation` present at once | tile opened + « Modifier » first (tiles since R2.2) |
| same | « Tout afficher (3) », sync | « Tout afficher dans l'onglet Références », after exit, heading focus asserted |
| same | Escape / ✕ / scrim / tab / vanish: sync null panel | all `await closed()` + `document.activeElement` checks, `describe.each` normal / reduced motion |
| same | « makes the tab panels inert while open, header usable » | split: inert page + inert panel until the exit ends then lifted; « Défaire / Refaire usable »; the `Enregistrer` enabled check dropped (covered by the focus-moved-off test) |
| same | Ctrl+Z test on an always-open field | open tile + Modifier first |
| same | read-only: no Supprimer, no textbox | open tile: no Modifier, no Retirer, no textbox |
| same | P6 under « Plus »: sync | in the close matrix, awaited |
| editor-escape.test.tsx (2 tests) | `expect(citations()).toBeNull()` right after Escape | `await waitFor(...)`; trigger `aria-expanded` false after exit |
| editor-keep-alive.test.tsx | « Escape in a citations panel field commits the text before the panel closes » | REPLACED by « Escape in a field of a panel tile neither closes nor commits » (A5, P27) |
| same | scrim click closes the panel after committing, sync, id on a closed tile | tile opened in edit first, close awaited, commit asserted before the exit |
| editor-focus-request.test.tsx | `ReferenceLibrary` with `resetSignal`; `ownedBy(ref,'citations')` undefined | `ReferencesTab` (+ `reloadSheet`); the `'citations'` assertion removed with the type |
| editor-references-tab / -view.test.tsx | `ReferenceLibrary`, `resetSignal` | `ReferencesTab`, `libraryReset` (+ `reloadSheet`) |
| e2e support `openCitations` | waited for the panel visible | also waits for the heading focus (slide over) |

New unit coverage: editor-citations-exit.test.tsx (hook, fake timers), editor-findings (aria-expanded per finding),
`useDecisionsOpen` gate, panel file (Retirer + status + one undo, P20 chain, zero state, dangling id, P4 reset, P6 after undo,
P22'' four paths, reduced motion, inert/exit, second close, tab replace, focus-moved-off).

## i18n (FR / EN)

Added: `editor.references.panel_title` Références citées / Cited references; `panel_count_one|other` « {count} référence citée par
ce constat » / « {count} références citées par ce constat » and « {count} reference cited by this finding » / « … references … »;
`panel_show_all` Tout afficher dans l'onglet Références / Show all in the References tab; `panel_empty` Ce constat ne cite plus
aucune référence. / This finding no longer cites any reference.; `remove_citation` Retirer de ce constat / Remove from this finding;
`this_finding` ce constat / this finding; `missing` Référence introuvable / Reference not found; `draft_dropped`
Saisie non appliquée : {field} / Entry not applied: {field}.
Changed: none. Removed: `editor.references.cited_by` (« Citées par « {name} » ({count}) » / « Cited by « {name} » ({count}) »),
`editor.references.show_all` (« Tout afficher ({count}) » / « Show all ({count}) »). R10 grep over src, tests and e2e including
editor-equine: no reader left. `editor-equine` has no panel reference: « updated, not run » (nothing to update). The three
provisional FR labels are exactly as listed in the brief; `…` = the refused field's label.
This commit is contained in:
bchanot committed 2026-11-12 22:27:32 +01:00
1 parent 3baac4dbb5
commit 8db6f4287f
38 files changed
+2524 -705

No files matched your search

+491
View File
@@ -0,0 +1,491 @@
import { fr } from '@/i18n/fr'
import type { Locator, Page, TestInfo } from '@playwright/test'
import {
expect,
expectAccessible,
expectNoHorizontalOverflow,
test,
} from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
closeCitations,
editorActor,
libraryRoot,
openCitations,
openEditor,
openTab,
place,
saveDraft,
seedDraft,
serverDocument,
standardShape,
} from '../support/editor'
// V1-2.6 R2.4: the contextual citations panel of one finding (board 25): its contents,
// « Retirer de ce constat » and « Défaire », « Tout afficher », every close path with the
// focus checked after the exit (motion and reduced motion), Escape in a tile field, the
// inert page during the exit sampled in the page, axe open (edit, read-only at 375 px).
// The spec seeds its own sheet and never touches another.
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
/** « Constat A » cites twelve references: its panel list outgrows the screen. */
function longShape(document: Record<string, unknown>) {
shape(document)
const refs = Array.from({ length: 12 }, (_, index) => ({
id: `ref-${index}`,
type: 'book',
citation: `Ouvrage numéro ${index + 1}`,
url: null,
doi: null,
}))
document.references = refs
const zone = (document.finding_zones as { categories: unknown[] }[])[0]
const family = zone.categories[0] as {
reference_ids: string[]
children: { reference_ids: string[] }[]
}
family.reference_ids = []
family.children[0].reference_ids = refs.map((ref) => ref.id)
}
/** « Constat A » cites A, B and C; the family cites B; D is cited by nobody. */
function shape(document: Record<string, unknown>) {
standardShape(document)
const reference = (id: string, citation: string, type = 'book') => ({
id,
type,
citation,
url: null,
doi: null,
})
document.references = [
reference('ref-a', 'Référence A'),
reference('ref-b', 'Source B', 'web'),
reference('ref-c', 'Source C', 'journal'),
reference('ref-d', 'Source libre', 'manual'),
]
const zone = (document.finding_zones as { categories: unknown[] }[])[0]
const family = zone.categories[0] as {
reference_ids: string[]
children: { reference_ids: string[] }[]
}
family.reference_ids = ['ref-b']
family.children[0].reference_ids = ['ref-a', 'ref-b', 'ref-c']
}
async function open(page: Page, seedShape = shape) {
const actor = await editorActor('fr')
const seed = await seedDraft(actor, { shape: seedShape })
await openEditor(page, dict, actor, seed.sheetId)
return { actor, seed }
}
const panel = (page: Page) => page.getByTestId('editor-citations-panel')
const heads = (page: Page) =>
panel(page).locator('button[aria-controls][id$="-header"]')
const trigger = (page: Page) => page.locator('[data-citations-trigger]:visible')
const link = (page: Page) =>
panel(page).getByRole('button', {
name: dict['editor.references.panel_show_all'],
})
const undo = (page: Page) => page.getByRole('button', { name: /Défaire/ })
const retire = (tile: Locator) =>
tile.getByRole('button', { name: dict['editor.references.remove_citation'] })
type Node = { reference_ids: string[]; review_status: string }
const nodeOf = (document: Record<string, unknown>) =>
(
document.finding_zones as {
categories: { children: Node[] }[]
}[]
)[0].categories[0].children[0]
test.describe('citations panel, editing', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(
isPhone(info),
'editing needs >= 1 024 px; the read-only twin at 375 px is below',
) // floor-guard: allow C16 editing needs >= 1024 px; read-only twin in this file
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('opens filtered on its finding, « Retirer » and one « Défaire », saved status', async ({
page,
requests,
}) => {
test.setTimeout(150_000)
const { actor, seed } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await openCitations(page, dict, 'Constat A')
await expect(trigger(page)).toHaveAttribute('aria-expanded', 'true')
await expect(panel(page).getByRole('heading')).toHaveText(
dict['editor.references.panel_title'],
)
await expect(panel(page)).toContainText(
'Zone A › Dysfonction A › Constat A',
)
await expect(panel(page)).toContainText(
dict['editor.references.panel_count_other'].replace('{count}', '3'),
)
await expect(heads(page)).toHaveCount(3)
await expect(panel(page).getByText('Source libre')).toHaveCount(0)
await expect(panel(page).getByRole('searchbox')).toHaveCount(0)
await expectAccessible(page, 'the citations panel, closed tiles')
await heads(page).nth(1).click()
const tile = heads(page).nth(1).locator('xpath=ancestor::li[1]')
await expect(
tile.getByText(dict['editor.references.this_finding'], { exact: true }),
).toBeVisible()
await expect(retire(tile)).toBeVisible()
for (const name of [
dict['editor.action.delete'],
dict['editor.action.move_up'],
]) {
await expect(panel(page).getByRole('button', { name })).toHaveCount(0)
}
await expectAccessible(page, 'the citations panel, an open tile')
// « Retirer » then one « Défaire » restores the citation and the status together.
await retire(tile).click()
await expect(heads(page)).toHaveCount(2)
// The next tile (« Source C », now second) takes the focus (P20).
await expect(heads(page).nth(1)).toBeFocused()
await expect(heads(page).nth(1)).toContainText('Source C')
await undo(page).click()
await expect(heads(page)).toHaveCount(3)
// The tile that came back is closed (its open state went with it): open it again.
await heads(page).nth(1).click()
await retire(tile).click()
await expect(heads(page)).toHaveCount(2)
await saveDraft(page, dict, seed.revision + 1)
const saved = await serverDocument<Record<string, unknown>>(seed.draftId)
expect(nodeOf(saved).reference_ids).toEqual(['ref-a', 'ref-c'])
expect(nodeOf(saved).review_status).toBe('to_confirm')
expect((saved.references as unknown[]).length).toBe(4)
})
test('a long list scrolls inside the panel: the last tile is reachable from scroll 0, the page never moves', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page, longShape)
await openCitations(page, dict, 'Constat A')
await expect(heads(page)).toHaveCount(12)
expect(await page.evaluate(() => window.scrollY)).toBe(0)
const list = panel(page).locator('div.overflow-y-auto')
await list.evaluate((node) => {
node.scrollTop = node.scrollHeight
})
const last = heads(page).last()
await expect(last).toBeInViewport({ ratio: 1 })
const view = await page.evaluate(() => window.innerHeight)
const box = await last.boundingBox()
expect(box!.y + box!.height).toBeLessThanOrEqual(view + 1)
expect(await page.evaluate(() => window.scrollY)).toBe(0)
await last.click()
await expect(last).toHaveAttribute('aria-expanded', 'true')
})
test('the last citations gone: the panel stays with its line, then closes on the tab', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
for (const remaining of [2, 1, 0]) {
await heads(page).first().click()
await retire(heads(page).first().locator('xpath=ancestor::li[1]')).click()
await expect(heads(page)).toHaveCount(remaining)
}
await expect(
panel(page).getByText(dict['editor.references.panel_empty']),
).toBeVisible()
await expect(link(page)).toBeVisible()
await expect(page.locator('#editor-citations-title')).toBeFocused()
await page.keyboard.press('Escape')
await expect(panel(page)).toHaveCount(0)
// The trigger went with the last citation: the active tab takes the focus (P6).
await expect(
page.getByRole('tab', { name: dict['editor.tab.findings'] }),
).toBeFocused()
})
test('« Tout afficher » closes it, resets search and sort, keeps open tiles, focuses the tab heading', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openTab(page, dict, 'references')
const root = libraryRoot(page)
await root.getByRole('searchbox').fill('Source')
await root
.getByLabel(dict['editor.references.sort_by'])
.selectOption('citation')
await root.getByRole('button', { name: /Source B/ }).click()
await openCitations(page, dict, 'Constat A')
await link(page).click()
await expect(panel(page)).toHaveCount(0)
await expect(page.locator('#editor-references-title')).toBeFocused()
await expect(root.getByRole('searchbox')).toHaveValue('')
await expect(
root.getByLabel(dict['editor.references.sort_by']),
).toHaveValue('sheet')
await expect(
root.getByRole('button', { name: /Source B/ }),
).toHaveAttribute('aria-expanded', 'true')
await expect(
root.locator('button[aria-controls][id$="-header"]'),
).toHaveCount(4)
})
test('Escape in a field of a tile neither closes the panel nor commits; ✕ then commits', async ({
page,
}) => {
test.setTimeout(150_000)
const { seed } = await open(page)
await openCitations(page, dict, 'Constat A')
await heads(page).first().click()
await panel(page)
.getByRole('button', { name: dict['editor.references.edit'] })
.click()
const field = panel(page).getByLabel(dict['editor.reference.citation'])
await field.fill('Référence A, révisée')
await field.press('Escape')
await expect(panel(page)).toBeVisible()
await expect(field).toHaveValue('Référence A, révisée')
await expect(undo(page)).toBeDisabled()
// A user close applies a valid draft first (P22''), then the panel exits.
await panel(page)
.getByRole('button', { name: dict['editor.references.close'] })
.click()
await expect(panel(page)).toHaveCount(0)
await saveDraft(page, dict, seed.revision + 1)
const saved = await serverDocument<{ references: { citation: string }[] }>(
seed.draftId,
)
expect(saved.references[0].citation).toBe('Référence A, révisée')
})
test('a refused draft cancels the close: panel open, field focused, message shown', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
await heads(page).first().click()
await panel(page)
.getByRole('button', { name: dict['editor.references.edit'] })
.click()
const field = panel(page).getByLabel(dict['editor.reference.citation'])
await field.fill('')
await page
.getByRole('tab', {
name: new RegExp(`^${dict['editor.tab.verification']}`),
})
.click()
await expect(panel(page)).toBeVisible()
await expect(field).toBeFocused()
await expect(panel(page).getByRole('alert')).toBeVisible()
await expect(page.getByRole('tab', { selected: true })).toHaveText(
new RegExp(`^${dict['editor.tab.findings']}`),
)
})
test('the page and the panel are inert through the exit (sampled in the page)', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
await page.evaluate(() => {
const samples: { panel: boolean; page: boolean; inert: boolean }[] = []
Object.assign(window, { samples })
const tick = () => {
const layer = document.querySelector('[data-place="citations"]')
const body = document.querySelector('[data-place="findings"]')
samples.push({
panel: layer !== null,
page: body?.closest('[inert]') !== null,
inert: layer?.hasAttribute('inert') ?? false,
})
if (layer !== null) requestAnimationFrame(tick)
}
tick()
})
await panel(page)
.getByRole('button', { name: dict['editor.references.close'] })
.click()
await expect(panel(page)).toHaveCount(0)
const samples = await page.evaluate(
() =>
(
window as unknown as {
samples: { panel: boolean; page: boolean; inert: boolean }[]
}
).samples,
)
const leaving = samples.filter((sample) => sample.panel && sample.inert)
expect(leaving.length).toBeGreaterThan(0)
expect(leaving.every((sample) => sample.page)).toBe(true)
await expect(page.locator('[data-place="findings"]')).toBeVisible()
expect(
await page
.locator('[data-place="findings"]')
.evaluate((body) => body.closest('[inert]') === null),
).toBe(true)
})
})
/** Every way out of the panel, the focus read from the document after the exit. */
for (const reduced of [false, true]) {
test.describe(`citations panel closes, ${reduced ? 'reduced motion' : 'motion'}`, () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context, page }, info) => {
test.skip(isPhone(info), 'the paths are walked on desktop') // floor-guard: allow C16 editing needs >= 1 024 px
await routeToSandbox(context)
await page.emulateMedia({
reducedMotion: reduced ? 'reduce' : 'no-preference',
})
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('✕, Escape and the scrim give the focus back to the trigger', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
await closeCitations(page, dict)
await expect(trigger(page)).toBeFocused()
await expect(trigger(page)).toHaveAttribute('aria-expanded', 'false')
await trigger(page).click()
await expect(page.locator('#editor-citations-title')).toBeFocused()
await page.keyboard.press('Escape')
await expect(panel(page)).toHaveCount(0)
await expect(trigger(page)).toBeFocused()
await trigger(page).click()
await expect(page.locator('#editor-citations-title')).toBeFocused()
await page
.getByTestId('references-scrim')
.click({ position: { x: 12, y: 40 } })
await expect(panel(page)).toHaveCount(0)
await expect(trigger(page)).toBeFocused()
})
test('« Tout afficher », « Aller à » and a tab choice land where the pending move says', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
await link(page).click()
await expect(panel(page)).toHaveCount(0)
await expect(page.locator('#editor-references-title')).toBeFocused()
await openCitations(page, dict, 'Constat A')
await heads(page).nth(1).click()
await panel(page)
.getByRole('button', { name: dict['editor.references.go_to'] })
.first()
.click()
await expect(panel(page)).toHaveCount(0)
await expect(
page.getByRole('treeitem', { name: /Dysfonction A/ }),
).toBeFocused()
await openCitations(page, dict, 'Constat A')
const verification = page.getByRole('tab', {
name: new RegExp(`^${dict['editor.tab.verification']}`),
})
await verification.click()
await expect(panel(page)).toHaveCount(0)
await expect(verification).toBeFocused()
})
test('the panel slides only when motion is allowed', async ({ page }) => {
test.setTimeout(150_000)
await open(page)
await page.getByRole('tab', { name: dict['editor.tab.findings'] }).click()
await page
.getByRole('treeitem', { expanded: false })
.first()
.press('ArrowRight')
await page.getByRole('treeitem', { name: 'Constat A' }).click()
await page.evaluate(() => {
const seen: string[] = []
Object.assign(window, { seen })
new MutationObserver(() => {
const layer = document.querySelector('[data-place="citations"]')
const slider = layer?.firstElementChild as HTMLElement | null
if (slider) seen.push(slider.style.transform)
}).observe(document.body, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['style'],
})
})
await trigger(page).click()
await expect(page.locator('#editor-citations-title')).toBeFocused()
const seen = await page.evaluate(
() => (window as unknown as { seen: string[] }).seen,
)
const slid = seen.some((value) => /translateX\((?!0)[1-9]/.test(value))
expect(slid).toBe(!reduced)
})
})
}
test.describe('citations panel, read-only at 375 px', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(!isPhone(info), 'the read-only twin runs at 375 px only')
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('full width through « Plus » then Constats, no edit control, axe open @phone', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
// Full width: the whole content area (the page's side gutters stay).
const layer = page.locator('[data-place="citations"]')
const box = await layer.boundingBox()
const area = await layer.locator('xpath=..').boundingBox()
expect(box?.width ?? 0).toBeLessThanOrEqual(375)
expect(Math.abs((box?.width ?? 0) - (area?.width ?? 0))).toBeLessThan(1)
await expect(heads(page)).toHaveCount(3)
await expectNoHorizontalOverflow(page, 'the panel at 375 px')
await heads(page).first().click()
for (const name of [
dict['editor.references.edit'],
dict['editor.references.remove_citation'],
]) {
await expect(panel(page).getByRole('button', { name })).toHaveCount(0)
}
await expect(panel(page).getByRole('textbox')).toHaveCount(0)
const close = await panel(page)
.getByRole('button', { name: dict['editor.references.close'] })
.boundingBox()
expect(close?.width ?? 0).toBeGreaterThanOrEqual(44)
expect(close?.height ?? 0).toBeGreaterThanOrEqual(44)
await expectAccessible(page, 'the citations panel, read-only at 375 px')
await closeCitations(page, dict)
await expect(trigger(page)).toBeFocused()
await expect(place(page, 'findings')).toBeVisible()
})
})
+175 -8
View File
@@ -52,6 +52,100 @@ async function open(page: Page) {
return { ...seed, actor }
}
/** Selects a finding in the tree of Constats (expanding down to it), the panel closed. */
async function selectFinding(page: Page, name: string) {
await openTab(page, dict, 'findings')
const item = page.getByRole('treeitem', { name })
for (let depth = 0; depth < 4 && (await item.count()) === 0; depth++) {
const closed = page.getByRole('treeitem', { expanded: false }).first()
await closed.focus()
await closed.press('ArrowRight')
}
await item.click()
}
/**
* Samples the document's size on every frame until stopped (the click that opens or
* closes the panel is inside the window): the distinct sizes seen come back.
*/
async function watchDocumentSize(page: Page) {
await page.evaluate(() => {
const seen = new Set<string>()
const state = { live: true }
const tick = () => {
const root = document.documentElement
seen.add(`${root.scrollWidth}x${root.scrollHeight}`)
if (state.live) requestAnimationFrame(tick)
}
Object.assign(window, { sizes: seen, sampling: state })
tick()
})
return () =>
page.evaluate(() => {
const w = window as unknown as {
sizes: Set<string>
sampling: { live: boolean }
}
w.sampling.live = false
return [...w.sizes]
})
}
const REM = 16
/** The panel's own padding (`p-4` top and bottom): its box cannot be shorter than this. */
const PANEL_PADDING_PX = 32
/**
* The panel is at most 34 rem and no wider than the viewport, and at scroll 0, halfway and
* at the end of the page its bottom is the nearer of the viewport's bottom and its
* container's bottom (its visible height is kept right on scroll).
*/
async function expectPanelWithin(
page: Page,
viewportWidth: number,
cramped = false,
) {
const layer = page.locator('[data-place="citations"]')
const box = await layer.boundingBox()
expect(box!.width).toBeLessThanOrEqual(34 * REM + 0.5)
expect(box!.width).toBeLessThanOrEqual(viewportWidth)
for (const at of [0, 0.5, 1]) {
await page.evaluate((share) => {
const root = document.documentElement
window.scrollTo(0, (root.scrollHeight - window.innerHeight) * share)
}, at)
await page.evaluate(
() => new Promise((done) => requestAnimationFrame(() => done(null))),
)
const edges = await page.evaluate(() => {
const container = document.querySelector('[data-place="citations"]')!
const panel = document.querySelector('#editor-citations-panel')!
const outer = container.getBoundingClientRect()
const inner = panel.getBoundingClientRect()
const viewport = window.visualViewport?.height ?? window.innerHeight
return {
panelBottom: inner.bottom,
expected: Math.min(viewport, outer.bottom),
panelTop: inner.top,
}
})
if (edges.expected - edges.panelTop < PANEL_PADDING_PX) {
// Only the landscape phone at scroll 0 may leave less room than the padding.
expect(
cramped && at === 0,
`panel room below its padding at scroll share ${at}`,
).toBe(true)
continue
}
expect(
Math.abs(edges.panelBottom - edges.expected),
`panel bottom at scroll share ${at}`,
).toBeLessThanOrEqual(1)
expect(edges.panelBottom).toBeGreaterThan(edges.panelTop)
}
await page.evaluate(() => window.scrollTo(0, 0))
}
async function settle(page: Page) {
await page.evaluate(
() =>
@@ -92,6 +186,28 @@ test.describe('editor shell layout (H)', () => {
}
})
test('the open panel is at most 34 rem and the viewport wide, and the document never changes size, before, during and after', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
for (const width of WIDTHS) {
await page.setViewportSize({ width, height: 800 })
await selectFinding(page, 'Constat A')
const stop = await watchDocumentSize(page)
await page.locator('[data-citations-trigger]:visible').click()
await expect(page.locator('#editor-citations-title')).toBeFocused()
await expectPanelWithin(page, width)
await expectNoHorizontalOverflow(page, `the open panel at ${width} px`)
await closeCitations(page, dict)
const sizes = await stop()
expect(
sizes,
`document size at ${width} px, before/during/after`,
).toHaveLength(1)
}
})
test('read-only at 320, 375 and 768 px: the five tabs fit and pass axe', async ({
page,
requests,
@@ -273,14 +389,7 @@ test.describe('editor shell keyboard order (H)', () => {
type: 'keyboard-order',
description: order.join(' > '),
})
expect(order).toEqual([
'tab',
'undo',
'redo',
'tools',
'canvas',
'side',
])
expect(order).toEqual(['tab', 'undo', 'redo', 'tools', 'canvas', 'side'])
})
test('with the panel open: tab list, Défaire, Refaire, the panel, then the page content', async ({
@@ -305,3 +414,61 @@ test.describe('editor shell keyboard order (H)', () => {
expect(after.at(-1)).toBe('side')
})
})
test.describe('citations panel at 375 px, read-only (O4-2)', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(!isPhone(info), 'the phone sizes are set by the test itself')
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('full width, never wider than the screen, bottom on the viewport bottom through a height change and a rotation, the drawing box unchanged @phone', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openTab(page, dict, 'annotations')
const drawingBox = () => place(page, 'annotations.drawing').boundingBox()
await expect(place(page, 'annotations.drawing')).toBeVisible()
const drawing = await drawingBox()
await selectFinding(page, 'Constat A')
await page.locator('[data-citations-trigger]:visible').click()
await expect(page.locator('#editor-citations-title')).toBeFocused()
for (const size of [
{ width: 375, height: 667 },
{ width: 375, height: 560 },
{ width: 667, height: 375 },
]) {
await page.setViewportSize(size)
await page.evaluate(
() => new Promise((done) => requestAnimationFrame(() => done(null))),
)
await expectPanelWithin(page, size.width, size.width === 667)
await expectNoHorizontalOverflow(
page,
`the panel at ${size.width} x ${size.height}`,
)
}
await page.setViewportSize({ width: 375, height: 667 })
await closeCitations(page, dict)
await openTab(page, dict, 'annotations')
await expect(place(page, 'annotations.drawing')).toBeVisible()
expect(await drawingBox()).toEqual(drawing)
})
test('the document size does not change while the panel opens and closes @phone', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await selectFinding(page, 'Constat A')
const stop = await watchDocumentSize(page)
await page.locator('[data-citations-trigger]:visible').click()
await expect(page.locator('#editor-citations-title')).toBeFocused()
await closeCitations(page, dict)
expect(await stop()).toHaveLength(1)
})
})
+8 -2
View File
@@ -407,7 +407,10 @@ export async function openTab(page: Page, dict: Dict, tab: string) {
})
if ((await more.getAttribute('aria-expanded')) !== 'true')
await more.click()
await page.locator('#editor-tabs-more').getByRole('button', { name }).click()
await page
.locator('#editor-tabs-more')
.getByRole('button', { name })
.click()
} else {
await page.getByRole('tab', { name }).click()
}
@@ -416,7 +419,8 @@ export async function openTab(page: Page, dict: Dict, tab: string) {
/**
* Opens the citations panel of the finding named `element`: the Constats tab, the tree
* expanded down to it, the element selected, its « n références » trigger pressed.
* expanded down to it, the element selected, its « n références » trigger pressed, the
* slide over (the heading holds the focus).
*/
export async function openCitations(page: Page, dict: Dict, element: string) {
await openTab(page, dict, 'findings')
@@ -429,6 +433,8 @@ export async function openCitations(page: Page, dict: Dict, element: string) {
await item.click()
await page.locator('[data-citations-trigger]:visible').click()
await expect(place(page, 'citations')).toBeVisible()
// The slide is over when the panel's heading takes the focus (P9).
await expect(page.locator('#editor-citations-title')).toBeFocused()
}
/** Closes the citations panel with its ✕ button. */
@@ -1,8 +1,14 @@
import { useEffect, useRef, type ReactNode } from 'react'
import { AnimatePresence } from 'motion/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
import Notice from '@/components/ui/Notice'
import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext'
import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest'
import {
AnnounceContext,
FocusConsumedContext,
isTextField,
} from '@/editor/focusRequest'
import { saveFailureMessage } from '@/editor/messages'
import type { EditorMode } from '@/editor/mode'
import { useEditorStore } from '@/editor/state/editorStore'
@@ -18,10 +24,9 @@ import CopyIssueNotice from './CopyIssueNotice'
import DraftHeader from './DraftHeader'
import EditorTabBody from './EditorTabBody'
import EditorTabs from './EditorTabs'
import KeptPlace from './KeptPlace'
import ModeNotice from './ModeNotice'
import RecoveryNotice from './RecoveryNotice'
import ReferencesPanel from './references/ReferencesPanel'
import CitationsLayer from './references/CitationsLayer'
interface Props {
sheet: OfficialSheetAdmin
@@ -51,16 +56,16 @@ function SaveFailureNotice() {
/** What dialogs and edit-only parts below need of the editor's state. */
function EditingState({
readOnly,
referencesOpen,
citationsOf,
children,
}: {
readOnly: boolean
referencesOpen: boolean
citationsOf: ElementKey | null
children: ReactNode
}) {
return (
<ReadOnlyContext value={readOnly}>
<ReferencesOpenContext value={referencesOpen}>
<ReferencesOpenContext value={citationsOf}>
{children}
</ReferencesOpenContext>
</ReadOnlyContext>
@@ -76,35 +81,29 @@ interface PlacesProps {
/**
* Under the tab row: the tab panels and the citations panel of a finding beside them. The
* container starts after the tab row, so the panel and its scrim never cover the header or
* the tabs; while the panel is open the tab panels are inert (the scrim sits over them).
* the tabs; from the opening to the end of the exit the tab panels are inert. Its minimum
* height is permanent (never toggled): the panel and the scrim reach the bottom of the
* window and the document never changes size when the panel opens or closes (P16').
*/
function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
const { state } = nav
const open = state.citationsOf !== null
return (
<div className={`relative ${open ? 'min-h-[calc(100dvh-3.5rem)]' : ''}`}>
{state.citationsOf && (
<KeptPlace
name="citations"
visible
className="absolute bottom-0 right-0 top-0 z-20 w-[min(27rem,100%)]"
>
<ReferencesPanel
<div className="relative min-h-[calc(100dvh-3.5rem)]">
<AnimatePresence onExitComplete={nav.exitComplete}>
{state.citationsOf && !nav.exiting && (
<CitationsLayer
key="citations"
readOnly={readOnly}
citedBy={state.citationsOf}
onClose={nav.closeCitations}
onGone={nav.dropCitations}
onShowAll={nav.showAllReferences}
navigate={nav.navigate}
registerCanLeave={nav.registerCanLeave}
/>
</KeptPlace>
)}
{open && (
<div
aria-hidden="true"
data-testid="references-scrim"
onClick={nav.closeCitations}
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
/>
)}
)}
</AnimatePresence>
<div inert={open}>
<EditorTabBody
tab={state.tab}
@@ -163,13 +162,14 @@ export default function EditorWorkspace(props: Props) {
const open = nav.state.citationsOf !== null
useBodyEscape(open, nav.closeCitations)
return (
<EditingState readOnly={readOnly} referencesOpen={open}>
<EditingState readOnly={readOnly} citationsOf={nav.state.citationsOf}>
<div
className="space-y-4"
data-editor-workspace
onKeyDown={(event) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.nativeEvent.isComposing || !open) return
if (isTextField(event.target)) return
event.preventDefault()
nav.closeCitations()
}}
@@ -7,6 +7,7 @@ import Icon from '@/components/ui/Icon'
import { ReferencesOpenContext } from '@/editor/editingContext'
import {
patchElement,
sameKey,
type FindingItem,
type FindingPatch,
} from '@/editor/findings/tree'
@@ -139,7 +140,8 @@ function Citations({
const t = useT()
const plural = usePlural()
const doc = useSheetDocument()
const panelOpen = useContext(ReferencesOpenContext)
const citationsOf = useContext(ReferencesOpenContext)
const panelOpen = citationsOf !== null && sameKey(citationsOf, item.key)
const references = doc?.references ?? []
const citation = (id: string) =>
references.find((r) => r.id === id)?.citation ?? id
@@ -0,0 +1,122 @@
import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'
import { motion, useIsPresent, useReducedMotion } from 'motion/react'
import { PANEL_ENTER_S, PANEL_EXIT_S } from '@/editor/useCitationsExit'
import KeptPlace from '../KeptPlace'
import CitationsPanel from './CitationsPanel'
type Props = Parameters<typeof CitationsPanel>[0]
/** The top bar (`h-14`): the panel sticks right under it. */
const TOP_BAR_REM = 3.5
/**
* The panel's visible height: from its top (under the top bar once the page has scrolled)
* to the nearer of the container's bottom and the viewport's bottom. Kept right on scroll,
* resize and visual-viewport changes (mobile URL bar, keyboard); only the panel's own
* height is written, so the document never changes size.
*/
function useFitToViewport(panel: RefObject<HTMLElement | null>) {
useLayoutEffect(() => {
const element = panel.current
const container = element?.parentElement
if (!element || !container) return
const bar =
TOP_BAR_REM *
parseFloat(getComputedStyle(document.documentElement).fontSize)
const fit = () => {
const box = container.getBoundingClientRect()
const viewport = window.visualViewport?.height ?? window.innerHeight
const visible = Math.min(box.bottom, viewport) - Math.max(box.top, bar)
element.style.height = `${Math.max(visible, 0)}px`
}
fit()
const watched: EventTarget[] = [window]
if (window.visualViewport) watched.push(window.visualViewport)
for (const target of watched) {
target.addEventListener('scroll', fit, { passive: true })
target.addEventListener('resize', fit)
}
const observer =
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(fit)
// Content above the container reflowing moves its top without resizing it.
observer?.observe(container)
observer?.observe(document.documentElement)
return () => {
for (const target of watched) {
target.removeEventListener('scroll', fit)
target.removeEventListener('resize', fit)
}
observer?.disconnect()
}
}, [panel])
}
/**
* The citations panel and its scrim over the places (board 25). The panel slides in from
* the right (translateX only), the scrim fades on the same timings; under reduced motion
* both change at once, the callbacks still fire (P29). While it exits, the panel is inert
* (the page behind stays inert until the workspace lifts it, P9).
*
* Geometry (P16, P16'): the wrapper fills the Places container, clips the slide on the x
* axis only (`clip`, never `hidden`) and is 34 rem at most; the panel inside sticks under
* the top bar, is exactly as tall as what is visible (`useFitToViewport`) and scrolls its
* own list, so the page's size never changes.
*/
export default function CitationsLayer(props: Props) {
const reduced = useReducedMotion()
const present = useIsPresent()
const layer = useRef<HTMLDivElement>(null)
const focused = useRef(false)
useFitToViewport(layer)
// A reopen during a slow exit reuses this instance: it focuses its heading again.
useEffect(() => {
if (!present) focused.current = false
}, [present])
const slide = { x: reduced ? 0 : '100%' }
const enter = {
duration: reduced ? 0 : PANEL_ENTER_S,
ease: 'easeOut',
} as const
const leave = {
duration: reduced ? 0 : PANEL_EXIT_S,
ease: 'easeIn',
} as const
// The heading takes the focus once the panel is in place (P9, P29).
const entered = () => {
if (!present || focused.current) return
focused.current = true
layer.current
?.querySelector<HTMLElement>('[data-place-heading]')
?.focus({ preventScroll: true })
}
return (
<>
<motion.div
aria-hidden="true"
data-testid="references-scrim"
onClick={props.onClose}
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: enter }}
exit={{ opacity: 0, transition: leave }}
/>
<KeptPlace
name="citations"
visible
inert={!present}
className="absolute inset-y-0 right-0 z-20 w-[min(34rem,100%)] overflow-x-clip"
>
<motion.div
ref={layer}
className="sticky top-14"
initial={slide}
animate={{ x: 0, transition: enter }}
exit={{ ...slide, transition: leave }}
onAnimationComplete={entered}
>
<CitationsPanel {...props} />
</motion.div>
</KeptPlace>
</>
)
}
@@ -0,0 +1,248 @@
import type { KeyboardEvent, RefObject } from 'react'
import type { LocalizedText, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { isTextField } from '@/editor/focusRequest'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import { usePlural } from '@/editor/plural'
import type { CitationEntry } from '@/editor/references/panel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import ReferenceTile from './ReferenceTile'
import { useCitationsPanel, type PanelHooks } from './useCitationsPanel'
interface Props extends PanelHooks {
/** ✕, Escape and the scrim: a close the tile in edit may refuse. */
onClose: () => void
/** « Tout afficher dans l'onglet Références ». */
onShowAll: () => void
/** « Aller à » a citing finding or family: closes the panel, then moves. */
navigate: (target: EditorTarget) => void
}
const RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
interface HeaderProps {
onClose: () => void
headingRef: RefObject<HTMLHeadingElement | null>
}
function PanelHeader({ onClose, headingRef }: HeaderProps) {
const t = useT()
return (
<div className="flex items-center justify-between gap-2">
<h2
ref={headingRef}
id="editor-citations-title"
tabIndex={-1}
data-place-heading
className="flex items-center gap-2 font-serif text-xl outline-none"
>
<Icon name="book" size={20} />
{t('editor.references.panel_title')}
</h2>
<button
type="button"
aria-label={t('editor.references.close')}
onClick={onClose}
className={`inline-flex h-11 w-11 items-center justify-center rounded-md ${RING}`}
>
<Icon name="close" size={18} />
</button>
</div>
)
}
/** « Zone › Famille › **Constat** »: where the finding sits, the finding itself in bold. */
function FindingPath({ path }: { path: readonly LocalizedText[] }) {
const locale = useLocaleStore((s) => s.locale)
const names = path.map((name) => name[locale])
const own = names.pop()
return (
<p className="text-sm">
<span className="text-[var(--color-ink-muted)]">
{names.map((name) => `${name} › `).join('')}
</span>
<b className="font-semibold">{own}</b>
</p>
)
}
function ShowAllLink({ onShowAll }: { onShowAll: () => void }) {
const t = useT()
return (
<button
type="button"
onClick={onShowAll}
className={`inline-flex min-h-11 items-center gap-1 text-sm text-[var(--color-accent-strong)] underline ${RING}`}
>
{t('editor.references.panel_show_all')}
<Icon name="chevron-right" size={14} />
</button>
)
}
/** « {n} références citées par ce constat » and the way to the whole library. */
function Summary({
count,
onShowAll,
}: {
count: number
onShowAll: () => void
}) {
const plural = usePlural()
return (
<div className="flex flex-wrap items-center justify-between gap-x-3">
<p className="text-sm text-[var(--color-ink-muted)]">
{count > 0 && plural('editor.references.panel_count', count)}
</p>
<ShowAllLink onShowAll={onShowAll} />
</div>
)
}
/** A cited id the sheet no longer holds (P30): named, and removable like any citation. */
function MissingRow({
entry,
readOnly,
onRemove,
}: {
entry: CitationEntry
readOnly: boolean
onRemove: () => void
}) {
const t = useT()
const missing = t('editor.references.missing')
return (
<li className="flex items-center gap-2 rounded-lg border border-[var(--color-border)] p-3 text-sm">
<span className="min-w-0 flex-1">
{missing}
<span className="ml-2 text-[var(--color-ink-muted)]">{entry.id}</span>
</span>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
aria-label={`${t('editor.action.remove')} ${missing} ${entry.id}`}
onClick={onRemove}
>
{t('editor.action.remove')}
</ActionButton>
</li>
)
}
type Panel = ReturnType<typeof useCitationsPanel>
/** One cited reference as a tile (« Modifier », « Retirer de ce constat »). */
function EntryTile({
entry,
reference,
panel,
props,
}: {
entry: CitationEntry
reference: Reference
panel: Panel
props: Props
}) {
const { tiles, keys, citers, entries, remove } = panel
const { readOnly, citedBy, navigate } = props
const key = keys[entry.index]
return (
<ReferenceTile
host="panel"
panel={{ current: citedBy, onRemove: () => remove(entry.index) }}
reference={reference}
position={entry.index}
count={entries.length}
citers={citers.get(reference.id) ?? []}
open={tiles.openKeys.has(key)}
editing={!readOnly && tiles.editingKey === key}
readOnly={readOnly}
movable={false}
on={{
toggle: () => tiles.toggle(key),
edit: () => void tiles.startEdit(key),
done: tiles.finish,
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
}}
/>
)
}
/** The cited references as tiles, the dangling ids as rows. */
function Entries({ panel, props }: { panel: Panel; props: Props }) {
return (
<ul ref={panel.list} className="space-y-3">
{panel.entries.map((entry) =>
entry.reference ? (
<EntryTile
key={panel.keys[entry.index]}
entry={entry}
reference={entry.reference}
panel={panel}
props={props}
/>
) : (
<MissingRow
key={`${entry.index}-${entry.id}`}
entry={entry}
readOnly={props.readOnly}
onRemove={() => panel.remove(entry.index)}
/>
),
)}
</ul>
)
}
/** Escape closes the panel, unless a field of it is being typed in (A5, P27). */
function closeOnEscape(onClose: () => void) {
return (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.nativeEvent.isComposing || isTextField(event.target)) return
event.stopPropagation()
onClose()
}
}
/**
* The citations of one finding (board 25): the references it cites as tiles, « Tout
* afficher » for the whole library. No search, add, delete or order (P7). Not a dialog:
* the workspace makes the page behind it inert. Opens from a finding's trigger only.
*/
export default function CitationsPanel(props: Props) {
const { onClose, onShowAll } = props
const t = useT()
const panel = useCitationsPanel(props)
const count = panel.entries.length
return (
<section
id="editor-citations-panel"
data-testid="editor-citations-panel"
aria-labelledby="editor-citations-title"
onKeyDown={closeOnEscape(onClose)}
className="flex h-full flex-col gap-3 border-l border-[var(--color-border)] bg-[var(--color-surface)] p-4 shadow-xl"
>
<PanelHeader onClose={onClose} headingRef={panel.heading} />
<FindingPath path={panel.path} />
<Summary count={count} onShowAll={onShowAll} />
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto pr-2">
{count === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.panel_empty')}
</p>
)}
{panel.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{panel.error}
</p>
)}
<Entries panel={panel} props={props} />
</div>
</section>
)
}
@@ -1,5 +1,6 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { CiterItem } from '@/editor/references/citations'
import { sameKey } from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -7,9 +8,12 @@ import { useLocaleStore } from '@/state/localeStore'
/** « Citée {n} fois, par : » and who cites, each with « Aller à »; the empty line when none. */
export default function CitersList({
citers,
current,
onGoTo,
}: {
citers: readonly CiterItem[]
/** The finding the citations panel belongs to: its row carries « ce constat ». */
current?: ElementKey
onGoTo: (key: ElementKey) => void
}) {
const t = useT()
@@ -36,6 +40,11 @@ export default function CitersList({
{' › '}
</span>
{citer.name[locale]}
{current && sameKey(citer.key, current) && (
<span className="ml-1 rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 text-xs">
{t('editor.references.this_finding')}
</span>
)}
{citer.isFamily && (
<span className="ml-1 rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 text-xs">
{t('editor.references.family')}
@@ -1,92 +0,0 @@
import { useRef, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly'
import type { FocusRequest } from '@/editor/focusRequest'
import type { EditorTarget } from '@/editor/navigation'
import { isSheetView } from '@/editor/references/view'
import { useT } from '@/i18n/useT'
import NewReferenceTile from './NewReferenceTile'
import NoResult from './NoResult'
import { EmptyLine } from './ReferenceList'
import ReferenceTiles from './ReferenceTiles'
import ReferenceToolbar from './ReferenceToolbar'
import { useReferenceActions, useReferenceLibrary } from './useReferenceLibrary'
interface Props {
readOnly: boolean
/** « Aller à » a citing finding or family. */
navigate: (target: EditorTarget) => void
focus?: FocusRequest
/** Bumped by « Tout afficher »: the search and the sort are reset once per bump. */
resetSignal?: number
}
/**
* The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
* reference, the draft tile and the delete dialog. Lives in the Références tab (ids
* prefixed `tab-`).
*/
export default function ReferenceLibrary(props: Props) {
const { readOnly, navigate, focus, resetSignal = 0 } = props
const t = useT()
const lib = useReferenceLibrary(readOnly, resetSignal)
const searchRef = useRef<HTMLInputElement>(null)
const act = useReferenceActions(lib, focus, searchRef)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const { all, shown } = lib
const sheetView = isSheetView(shown.view)
return (
<div className="space-y-3">
<ReferenceToolbar
query={shown.view.query}
onQuery={(query) => shown.update({ query })}
onClear={act.clearSearch}
searchRef={searchRef}
sort={shown.view.sort}
onSort={(sort) => shown.update({ sort })}
shown={shown.matchCount}
total={all.length}
canAdd={!readOnly}
onAdd={act.startAdd}
/>
{lib.loaded && (
<>
{all.length === 0 && <EmptyLine />}
{all.length > 0 && shown.matchCount === 0 && (
<NoResult query={shown.view.query} onClear={act.clearSearch} />
)}
{!readOnly && !sheetView && shown.positions.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.reorder_hint')}
</p>
)}
<ReferenceTiles
positions={shown.positions}
all={all}
keys={lib.keys}
citers={lib.citers}
tiles={lib.tiles}
readOnly={readOnly}
movable={sheetView}
navigate={navigate}
onEdit={act.edit}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
<EditOnly readOnly={readOnly}>
{act.draft !== null && (
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
)}
</EditOnly>
</>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</div>
)
}
@@ -1,46 +0,0 @@
import type { Reference } from '@faunosteo/core-wasm/types'
import type { CiterItem } from '@/editor/references/citations'
import { useT } from '@/i18n/useT'
import ReferenceRow from './ReferenceRow'
import type { ReferenceHost } from './referenceTypes'
interface ListProps {
host: ReferenceHost
shown: readonly Reference[]
all: readonly Reference[]
citers: ReadonlyMap<string, readonly CiterItem[]>
readOnly: boolean
onDelete: (reference: Reference) => void
}
/** The panel's cards of `shown`, each knowing its place in the whole bibliography `all`. */
export function ReferenceList({ shown, all, citers, ...rest }: ListProps) {
return (
<ul className="space-y-3">
{shown.map((reference) => {
const index = all.indexOf(reference)
return (
<ReferenceRow
key={`${index}-${reference.id}`}
host={rest.host}
reference={reference}
index={index}
cited={citers.get(reference.id)?.length ?? 0}
readOnly={rest.readOnly}
onDelete={() => rest.onDelete(reference)}
/>
)
})}
</ul>
)
}
/** The empty line: the sheet has no reference at all. */
export function EmptyLine() {
const t = useT()
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.reference.empty')}
</p>
)
}
@@ -1,107 +0,0 @@
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { usePlural } from '@/editor/plural'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES, type ReferenceHost } from './referenceTypes'
const CARD = 'space-y-3 rounded-lg border border-[var(--color-border)] p-3'
/** One reference as the citations panel shows it (interim until R2.4): fields commit one by one. */
export default function ReferenceRow({
host,
reference,
index,
cited,
readOnly,
onDelete,
}: {
/** The place showing the row: its field ids carry it, both can be mounted at once. */
host: ReferenceHost
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
index: number
/** How many findings cite it. */
cited: number
readOnly: boolean
onDelete: () => void
}) {
const plural = usePlural()
const t = useT()
const edit = useEditCommand()
const key = { kind: 'reference', id: reference.id } as const
const send = (field: string, patch: Partial<Reference>) =>
edit.run(field, {
op: 'update',
key,
element: { kind: 'reference', value: { ...reference, ...patch } },
})
const options = REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
}))
const prefix = `${host}-reference-${index}-${reference.id}`
return (
<li {...focusAttrs(key)} className={`${CARD} ${FOCUS_CLASS}`}>
<p className="text-right text-sm text-[var(--color-ink-muted)]">
{cited === 0
? t('editor.references.uncited')
: plural('editor.references.cited', cited)}
</p>
<div className="grid gap-3">
<SelectField
id={`${prefix}-type`}
label={t('editor.reference.type')}
value={reference.type}
options={options}
onCommit={(type) => send('type', { type: type as ReferenceType })}
readOnly={readOnly}
error={edit.fieldError('type')}
/>
<TextField
id={`${prefix}-citation`}
label={t('editor.reference.citation')}
value={reference.citation}
onCommit={(value) =>
isBlank(value)
? edit.reject('citation', 'editor.field.required')
: send('citation', { citation: value })
}
readOnly={readOnly}
multiline
error={edit.fieldError('citation')}
/>
<TextField
id={`${prefix}-url`}
label={t('editor.reference.url')}
value={reference.url ?? ''}
onCommit={(value) => send('url', { url: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('url')}
/>
<TextField
id={`${prefix}-doi`}
label={t('editor.reference.doi')}
value={reference.doi ?? ''}
onCommit={(value) => send('doi', { doi: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('doi')}
/>
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
</li>
)
}
@@ -17,14 +17,24 @@ export interface TileHandlers {
edit: () => void
/** Leaves the edit view; false (the view stays) when a field refuses. */
done: () => boolean
remove: () => void
move: (position: number) => void
/** « Supprimer »: the Références tab only. */
remove?: () => void
/** « Monter » / « Descendre »: the Références tab only. */
move?: (position: number) => void
goTo: (key: ElementKey) => void
registerLeave: (guard: LeaveGuard | null) => void
}
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
export interface PanelTile {
current: ElementKey
onRemove: () => void
}
export interface TileProps {
host: ReferenceHost
/** Set for the citations panel: « ce constat » marks, « Retirer de ce constat ». */
panel?: PanelTile
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
position: number
@@ -45,6 +55,12 @@ export const tileBase = (
reference: Reference,
) => `${host}-reference-${position}-${reference.id}`
/** The meta column (type, count) from 640 px: the panel gives it a fixed 132 px. */
const META_COLUMN = {
tab: 'sm:grid-cols-[1.25rem_1fr_auto]',
panel: 'sm:grid-cols-[1.25rem_1fr_8.25rem]',
} as const
const BUTTON_RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
@@ -72,7 +88,7 @@ function TileHeader({
aria-expanded={open || editing}
aria-controls={`${base}-body`}
onClick={props.on.toggle}
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left sm:grid-cols-[1.25rem_1fr_auto] ${BUTTON_RING}`}
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left ${META_COLUMN[props.host]} ${BUTTON_RING}`}
>
<Icon
name={open || editing ? 'chevron-down' : 'chevron-right'}
@@ -99,11 +115,43 @@ function TileHeader({
)
}
/** The panel's actions (P7): « Modifier » and « Retirer de ce constat », nothing else. */
function PanelActions({
props,
panel,
}: {
props: TileProps
panel: PanelTile
}) {
const t = useT()
return (
<div className="flex flex-wrap items-center gap-2">
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={props.on.edit}
>
{t('editor.references.edit')}
</ActionButton>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={panel.onRemove}
>
{t('editor.references.remove_citation')}
</ActionButton>
</div>
)
}
/** « Modifier », « Supprimer » (uncited only, else the hint), « Monter » / « Descendre ». */
function TileActions({ props }: { props: TileProps }) {
const t = useT()
const { position, count, citers, readOnly, movable, on } = props
if (readOnly) return null
if (props.panel) return <PanelActions props={props} panel={props.panel} />
return (
<>
<div className="flex flex-wrap items-center gap-2">
@@ -115,7 +163,7 @@ function TileActions({ props }: { props: TileProps }) {
>
{t('editor.references.edit')}
</ActionButton>
{citers.length === 0 && (
{citers.length === 0 && on.remove && (
<ActionButton
readOnly={false}
variant="ghost"
@@ -126,14 +174,14 @@ function TileActions({ props }: { props: TileProps }) {
{t('editor.action.delete')}
</ActionButton>
)}
{movable && (
{movable && on.move && (
<>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={position === 0}
onClick={() => on.move(position - 1)}
onClick={() => on.move?.(position - 1)}
>
{t('editor.action.move_up')}
</ActionButton>
@@ -142,7 +190,7 @@ function TileActions({ props }: { props: TileProps }) {
variant="secondary"
size="sm"
disabled={position >= count - 1}
onClick={() => on.move(position + 1)}
onClick={() => on.move?.(position + 1)}
>
{t('editor.action.move_down')}
</ActionButton>
@@ -188,7 +236,11 @@ export default function ReferenceTile(props: TileProps) {
) : (
<ReferenceFacts reference={reference} />
)}
<CitersList citers={props.citers} onGoTo={on.goTo} />
<CitersList
citers={props.citers}
current={props.panel?.current}
onGoTo={on.goTo}
/>
{editing ? (
<ActionButton
readOnly={false}
@@ -1,154 +0,0 @@
import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import Icon from '@/components/ui/Icon'
import { citersOf } from '@/editor/references/citations'
import {
citedIds,
citingFinding,
visibleReferences,
} from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { ReferenceList } from './ReferenceList'
interface Props {
readOnly: boolean
/** The finding whose citations the panel lists. */
citedBy: ElementKey
/** ✕, Escape, and the finding vanishing (deleted, or an undo removed it). */
onClose: () => void
/** « Tout afficher »: closes the panel and opens the Références tab. */
onShowAll: () => void
}
function PanelHeader({ onClose }: { onClose: () => void }) {
const t = useT()
return (
<div className="flex items-center justify-between gap-2">
<h2
id="editor-citations-title"
tabIndex={-1}
data-place-heading
className="flex items-center gap-2 outline-none font-serif text-xl"
>
<Icon name="book" size={20} />
{t('editor.place.references')}
</h2>
<button
type="button"
aria-label={t('editor.references.close')}
onClick={onClose}
className="inline-flex min-h-11 min-w-11 items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name="close" size={18} />
</button>
</div>
)
}
/** « Citées par « nom » (n) » and « Tout afficher (N) ». */
function FilterChip({
name,
cited,
total,
onShowAll,
}: {
name: string
cited: number
total: number
onShowAll: () => void
}) {
const t = useT()
const text = t('editor.references.cited_by')
.replace('{name}', name)
.replace('{count}', String(cited))
return (
<div className="flex flex-wrap items-center gap-2">
<span
data-testid="references-filter-chip"
className="rounded-full border border-[var(--color-accent)] bg-[var(--color-surface-strong)] px-3 py-1 text-sm"
>
{text}
</span>
<button
type="button"
onClick={onShowAll}
className="min-h-11 text-sm underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
{t('editor.references.show_all').replace('{count}', String(total))}
</button>
</div>
)
}
/** The finding read from the current document; `gone` once the document lacks it. */
function useCitingFinding(citedBy: ElementKey, onGone: () => void) {
const doc = useSheetDocument()
const finding = useMemo(
() => (doc ? citingFinding(doc, citedBy) : null),
[doc, citedBy],
)
const gone = doc !== null && finding === null
useEffect(() => {
if (gone) onGone()
}, [gone, onGone])
return { doc, finding }
}
/**
* The citations of one finding: the references it cites, each with how often it is cited.
* Not a dialog: the workspace makes the page behind it inert. Opened only from a finding's
* trigger; the whole library lives in the Références tab.
*/
export default function ReferencesPanel(props: Props) {
const { readOnly, citedBy, onClose, onShowAll } = props
const locale = useLocaleStore((s) => s.locale)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const { doc, finding } = useCitingFinding(citedBy, onClose)
const all = doc?.references ?? []
const cited = finding ? citedIds(finding) : []
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
event.stopPropagation()
onClose()
}
return (
<section
id="editor-citations-panel"
data-testid="editor-citations-panel"
aria-labelledby="editor-citations-title"
onKeyDown={onKeyDown}
className="sticky top-14 h-[calc(100dvh-3.5rem)] space-y-3 overflow-y-auto border-l border-[var(--color-border)] bg-[var(--color-surface)] p-4 shadow-xl"
>
<PanelHeader onClose={onClose} />
{finding && (
<FilterChip
name={finding.name[locale]}
cited={cited.length}
total={all.length}
onShowAll={onShowAll}
/>
)}
{doc && (
<ReferenceList
host="panel"
shown={visibleReferences(all, cited, '')}
all={all}
citers={citersOf(doc)}
readOnly={readOnly}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
)
}
@@ -1,4 +1,4 @@
export { REFERENCE_TYPES } from '@/editor/references/referenceTypes'
/** Where reference cards are shown: the Références tab or a finding's citations panel. */
/** Where reference tiles are shown: the Références tab or a finding's citations panel. */
export type ReferenceHost = 'tab' | 'panel'
@@ -0,0 +1,140 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { citersOf } from '@/editor/references/citations'
import { citedIds, citingFinding } from '@/editor/references/filter'
import { citationEntries, findingPath } from '@/editor/references/panel'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { CanLeave } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
readOnly: boolean
citedBy: ElementKey
/** The finding vanished: a close nobody can refuse. */
onGone: () => void
registerCanLeave: (guard: CanLeave | null) => void
}
/** The finding read from the current document; null once the document lacks it. */
function useCitedFinding(citedBy: ElementKey) {
const doc = useSheetDocument()
const item = useMemo(
() => (doc ? citingFinding(doc, citedBy) : null),
[doc, citedBy],
)
return { doc, item }
}
/**
* The panel closes once its finding is gone: a forced close. It runs after the leave
* check registered itself (effects of one component run in order), so a tile in edit is
* still asked. A read-only flip does not close it: the panel stays, as the crossing
* specs expect, and its tiles stop being editable.
*/
function useCloseWhenGone(gone: boolean, onGone: () => void) {
useEffect(() => {
if (gone) onGone()
}, [gone, onGone])
}
/** P22'': a user close asks the tile in edit first; a forced one drops a refused draft. */
function useLeaveCheck(
tiles: ReturnType<typeof useTileState>,
register: PanelHooks['registerCanLeave'],
) {
const t = useT()
useEffect(() => {
register((forced) => {
const refused = tiles.leave()
if (refused === null) return { allowed: true }
if (!forced) return { allowed: false }
const field = t(`editor.reference.${refused}`)
const note = t('editor.references.draft_dropped').replace(
'{field}',
field,
)
return { allowed: true, note }
})
return () => register(null)
})
}
/** After a removal the focus goes to the next row's button, else the previous, else the heading. */
function useFocusAfterRemoval(count: number) {
const list = useRef<HTMLUListElement>(null)
const heading = useRef<HTMLHeadingElement>(null)
const [removed, setRemoved] = useState<{ at: number; before: number } | null>(
null,
)
useEffect(() => {
if (removed === null || count >= removed.before) return
setRemoved(null)
const rows = [...(list.current?.children ?? [])]
const row = rows[removed.at] ?? rows[removed.at - 1]
const target = row?.querySelector('button') ?? heading.current
target?.focus()
}, [removed, count])
return { list, heading, afterRemoval: setRemoved }
}
/**
* What the panel shows of the finding: its cited ids and its path. Once the finding is
* gone (the panel is leaving) the last known answer stays, so the panel does not empty
* while it slides out and a tile in edit can still be asked to apply its draft.
*/
function useShownFinding(
doc: ReturnType<typeof useSheetDocument>,
item: FindingItem | null,
citedBy: ElementKey,
) {
const found = useMemo(
() =>
doc && item
? { ids: citedIds(item), path: findingPath(doc, citedBy) }
: null,
[doc, item, citedBy],
)
const [last, setLast] = useState(found)
if (found !== null && found !== last) setLast(found)
return found ?? last ?? { ids: [], path: [] }
}
/** What the citations panel reads and does: the cited entries, tiles, « Retirer ». */
export function useCitationsPanel(hooks: PanelHooks) {
const { doc, item } = useCitedFinding(hooks.citedBy)
const edit = useEditCommand()
const { ids, path } = useShownFinding(doc, item, hooks.citedBy)
const entries = citationEntries(doc?.references ?? [], ids)
const keys = tileKeys(entries)
const tiles = useTileState(doc ? keys : null)
const focus = useFocusAfterRemoval(ids.length)
useLeaveCheck(tiles, hooks.registerCanLeave)
useCloseWhenGone(doc !== null && item === null, hooks.onGone)
// « Retirer de ce constat » is the detail's « Retirer »: the same update of the finding's
// reference_ids, so the core marks the finding « À confirmer » (P15) and one « Défaire »
// restores the citation and the status together. The reference itself stays in the sheet.
const remove = (at: number) => {
if (!item || !tiles.finish()) return
const rest = ids.filter((_, index) => index !== at)
const element = patchElement(item, { reference_ids: rest })
const command = { op: 'update', key: item.key, element } as const
if (edit.run('references', command)) {
focus.afterRemoval({ at, before: ids.length })
}
}
return {
doc,
entries,
tiles,
keys,
citers: doc ? citersOf(doc) : new Map<string, never[]>(),
path,
error: edit.fieldError('references'),
remove,
list: focus.list,
heading: focus.heading,
}
}
@@ -8,8 +8,11 @@ export const FIELDS = ['citation', 'doi', 'url'] as const
export type Field = (typeof FIELDS)[number]
type Drafts = Record<Field, string>
/** What the guard calls on a leave: true when every pending field was applied. */
export type LeaveGuard = () => boolean
/**
* What the guard calls on a leave: null when every pending field was applied, else the
* field that refused (its draft stays, the field is focused).
*/
export type LeaveGuard = () => Field | null
const committedOf = (reference: Reference): Drafts => ({
citation: reference.citation,
@@ -79,11 +82,11 @@ export function useReferenceEdit(
const next = apply(current, field)
if (!next) {
document.getElementById(`${base}-${field}`)?.focus()
return false
return field
}
current = next
}
return true
return null
}
useEffect(() => {
registerLeave(leave)
@@ -1,12 +1,11 @@
import { useRef, useState } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import type { LeaveGuard } from './useReferenceEdit'
import type { LeaveGuard, Field } from './useReferenceEdit'
/**
* One key per tile: the id and its occurrence among equal ids, so a duplicated id stays
* two distinct tiles (P31) and a tile keeps its state when ↑ / ↓ changes its position.
*/
export function tileKeys(all: readonly Reference[]): string[] {
export function tileKeys(all: readonly { id: string }[]): string[] {
const seen = new Map<string, number>()
return all.map((reference) => {
const occurrence = seen.get(reference.id) ?? 0
@@ -33,10 +32,11 @@ export function useTileState(keys: readonly string[] | null) {
if (editingKey !== null && !live.has(editingKey)) setEditingKey(null)
}
const guard = useRef<LeaveGuard | null>(null)
const leave = () => guard.current?.() ?? true
/** Applies the tile in edit; the field that refused, null when nothing is left to apply. */
const leave = (): Field | null => guard.current?.() ?? null
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
const finish = () => {
if (!leave()) return false
if (leave() !== null) return false
setEditingKey(null)
return true
}
@@ -49,7 +49,8 @@ export function useTileState(keys: readonly string[] | null) {
})
}
const startEdit = (key: string) => {
if (editingKey !== null && editingKey !== key && !leave()) return false
if (editingKey !== null && editingKey !== key && leave() !== null)
return false
setEditingKey(key)
open(key)
return true
@@ -60,6 +61,7 @@ export function useTileState(keys: readonly string[] | null) {
toggle,
startEdit,
finish,
leave,
reveal: open,
registerLeave: (next: LeaveGuard | null) => {
guard.current = next
@@ -1,13 +1,107 @@
import ReferenceLibrary from '@/components/editor/references/ReferenceLibrary'
import { useRef, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly'
import NewReferenceTile from '@/components/editor/references/NewReferenceTile'
import NoResult from '@/components/editor/references/NoResult'
import ReferenceTiles from '@/components/editor/references/ReferenceTiles'
import ReferenceToolbar from '@/components/editor/references/ReferenceToolbar'
import {
useReferenceActions,
useReferenceLibrary,
} from '@/components/editor/references/useReferenceLibrary'
import { isSheetView } from '@/editor/references/view'
import type { EditorPlaceProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** The empty line: the sheet has no reference at all. */
function EmptyLine() {
const t = useT()
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.reference.empty')}
</p>
)
}
type Props = Pick<EditorPlaceProps, 'readOnly' | 'navigate' | 'focus'> & {
resetSignal: number
}
/**
* The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
* reference, the draft tile and the delete dialog. Ids carry the `tab-` prefix. The
* citations panel shares only the tile (R2.4).
*/
function Library({ readOnly, navigate, focus, resetSignal }: Props) {
const t = useT()
const lib = useReferenceLibrary(readOnly, resetSignal)
const searchRef = useRef<HTMLInputElement>(null)
const act = useReferenceActions(lib, focus, searchRef)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const { all, shown } = lib
const sheetView = isSheetView(shown.view)
return (
<div className="space-y-3">
<ReferenceToolbar
query={shown.view.query}
onQuery={(query) => shown.update({ query })}
onClear={act.clearSearch}
searchRef={searchRef}
sort={shown.view.sort}
onSort={(sort) => shown.update({ sort })}
shown={shown.matchCount}
total={all.length}
canAdd={!readOnly}
onAdd={act.startAdd}
/>
{lib.loaded && (
<>
{all.length === 0 && <EmptyLine />}
{all.length > 0 && shown.matchCount === 0 && (
<NoResult query={shown.view.query} onClear={act.clearSearch} />
)}
{!readOnly && !sheetView && shown.positions.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.reorder_hint')}
</p>
)}
<ReferenceTiles
positions={shown.positions}
all={all}
keys={lib.keys}
citers={lib.citers}
tiles={lib.tiles}
readOnly={readOnly}
movable={sheetView}
navigate={navigate}
onEdit={act.edit}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
<EditOnly readOnly={readOnly}>
{act.draft !== null && (
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
)}
</EditOnly>
</>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</div>
)
}
/** The fifth tab: the sheet's reference library under its own heading. */
export default function ReferencesTab({
readOnly,
navigate,
focus,
libraryReset,
libraryReset = 0,
}: EditorPlaceProps) {
const t = useT()
return (
@@ -24,7 +118,7 @@ export default function ReferencesTab({
>
{t('editor.tab.references')}
</h2>
<ReferenceLibrary
<Library
readOnly={readOnly}
navigate={navigate}
focus={focus}
+2 -2
View File
@@ -102,8 +102,8 @@ export function useSelectionEscape(
) {
const asideRef = useRef<HTMLElement>(null)
const deselect = useDeselect(id, clear)
const referencesOpen = useContext(ReferencesOpenContext)
useEscapeDeselect(active && !referencesOpen, (event) =>
const citationsOf = useContext(ReferencesOpenContext)
useEscapeDeselect(active && citationsOf === null, (event) =>
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
)
return { asideRef, byDrawing: deselect.byDrawing }
+9 -4
View File
@@ -1,11 +1,16 @@
import { createContext, useContext, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { usePlaceVisible } from '@/lib/placeVisibility'
/** The editor cannot be edited now (route rule: mode, recovery, store not in step). */
export const ReadOnlyContext = createContext(false)
/** The citations panel is open: a place beside it is not where a modal may open. */
export const ReferencesOpenContext = createContext(false)
/**
* The finding whose citations panel is open, null when none. Set from the opening to the
* end of the exit animation: a place beside the panel is not where a modal may open, and
* only that finding's trigger reads « expanded ».
*/
export const ReferencesOpenContext = createContext<ElementKey | null>(null)
export function useEditorReadOnly(): boolean {
return useContext(ReadOnlyContext)
@@ -18,9 +23,9 @@ export function useEditorReadOnly(): boolean {
*/
export function useDecisionsOpen(): boolean {
const readOnly = useContext(ReadOnlyContext)
const referencesOpen = useContext(ReferencesOpenContext)
const citationsOf = useContext(ReferencesOpenContext)
const visible = usePlaceVisible()
return !readOnly && visible && !referencesOpen
return !readOnly && visible && citationsOf === null
}
/**
+1 -1
View File
@@ -262,6 +262,6 @@ export function itemForKey(
return { item, ancestors }
}
function sameKey(a: ElementKey, b: ElementKey): boolean {
export function sameKey(a: ElementKey, b: ElementKey): boolean {
return JSON.stringify(a) === JSON.stringify(b)
}
+2 -8
View File
@@ -15,14 +15,8 @@ export type { FocusRequest }
*/
export type FocusOutcome = 'found' | 'kept' | 'none'
/**
* The `data-place` name of a place. `citations` (the panel) is no navigation target: it
* is a name only for its heading and its focus scope.
*/
export type PlaceName =
| EditorTabId
| `annotations.${AnnotationSection}`
| 'citations'
/** The `data-place` name of a place a request can name (the citations panel is none). */
export type PlaceName = EditorTabId | `annotations.${AnnotationSection}`
export function placeOf(target: EditorTarget): PlaceName {
if (target.tab !== 'annotations') return target.tab
-13
View File
@@ -32,16 +32,3 @@ export function referenceMatches(reference: Reference, query: string): boolean {
(field) => folded(field).includes(term),
)
}
/** The references to list: those the finding cites (when filtered) that match the query. */
export function visibleReferences(
references: readonly Reference[],
cited: readonly string[] | null,
query: string,
): Reference[] {
return references.filter(
(reference) =>
(cited === null || cited.includes(reference.id)) &&
referenceMatches(reference, query),
)
}
+45
View File
@@ -0,0 +1,45 @@
import type {
AnatomicalSheetDocument,
ElementKey,
LocalizedText,
Reference,
} from '@faunosteo/core-wasm/types'
import { buildItems, itemForKey } from '@/editor/findings/tree'
/**
* One citation of the finding, in the order it lists them. A reference the sheet no
* longer holds is kept as a row of its own (`reference` null), so the count, the list and
* the trigger all describe the same ids (P30). `index` tells two entries of one id apart.
*/
export interface CitationEntry {
id: string
index: number
reference: Reference | null
}
export function citationEntries(
references: readonly Reference[],
ids: readonly string[],
): CitationEntry[] {
return ids.map((id, index) => ({
id,
index,
reference: references.find((candidate) => candidate.id === id) ?? null,
}))
}
/** The zone and the families above a finding, then the finding itself, outermost first. */
export function findingPath(
doc: AnatomicalSheetDocument,
key: ElementKey,
): LocalizedText[] {
const items = buildItems(doc)
const found = itemForKey(items, key)
if (!found) return []
const names = found.ancestors.map(
(id) => items.find((item) => item.id === id)?.name,
)
return [...names.reverse(), found.item.name].filter(
(name): name is LocalizedText => name !== undefined,
)
}
+61
View File
@@ -0,0 +1,61 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { NavigationAction } from './navigation'
/** Panel motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
export const PANEL_ENTER_S = 0.18
export const PANEL_EXIT_S = 0.14
/** The exit plus a margin: past it, a callback that never came is applied by the timer. */
const FALLBACK_MS = PANEL_EXIT_S * 1000 + 100
export type PendingKind =
| 'go_to'
| 'citations_closed'
| 'show_all'
| 'tab_selected'
/** The one move a close records: applied when the exit is over (P9). */
export interface PendingClose {
action: NavigationAction
kind: PendingKind
text: string
/** Said before `text`: a draft dropped by a forced close. It survives a replacement. */
note?: string
}
/**
* The close of the citations panel as a two-step move (P9, P28): `record` starts the exit
* (the page stays inert, the panel is inert too); `complete` runs once, from the panel's
* `onExitComplete` or from a one-shot timer when that never fires, and hands the pending
* move to `apply`. A second close is a no-op; a tab choice replaces the pending move.
*/
export function useCitationsExit(apply: (move: PendingClose) => void) {
const [exiting, setExiting] = useState(false)
const pending = useRef<PendingClose | null>(null)
const timer = useRef<number | undefined>(undefined)
const complete = useCallback(() => {
const move = pending.current
if (move === null) return
pending.current = null
window.clearTimeout(timer.current)
setExiting(false)
apply(move)
}, [apply])
const record = useCallback(
(move: PendingClose) => {
if (pending.current !== null) {
if (move.kind !== 'tab_selected') return
const note = pending.current.note ?? move.note
pending.current = note ? { ...move, note } : move
return
}
pending.current = move
setExiting(true)
timer.current = window.setTimeout(complete, FALLBACK_MS)
},
[complete],
)
const busy = useCallback(() => pending.current !== null, [])
useEffect(() => () => window.clearTimeout(timer.current), [])
return { exiting, record, complete, busy }
}
+163 -44
View File
@@ -27,21 +27,34 @@ import {
type NavigationState,
} from './navigation'
import { MORE_BUTTON_ID, tabDomId, type EditorTabId } from './tabs'
import {
useCitationsExit,
type PendingClose,
type PendingKind,
} from './useCitationsExit'
type MoveKind =
| 'go_to'
| 'section'
| 'back'
| 'citations'
| 'citations_closed'
| 'show_all'
| 'tab_selected'
type MoveKind = PendingKind | 'section' | 'back'
/** A programmatic move: a new object per move, so the effect after it runs once. */
/**
* A programmatic move: a new object per move, so the effect after it runs once.
* `afterExit`: it is the pending move of a closed panel, so a focus the user already
* placed elsewhere during the exit is left alone (P28).
*/
interface Move {
kind: MoveKind
afterExit?: boolean
}
/**
* The panel's answer before a close (P22''): `allowed` false cancels a user close. A forced
* close always goes ahead; `note` (a draft dropped) is said with the close.
*/
export interface LeaveAnswer {
allowed: boolean
note?: string
}
export type CanLeave = (forced: boolean) => LeaveAnswer
type Opener = HTMLElement | null | undefined
export interface EditorNavigation {
@@ -54,10 +67,18 @@ export interface EditorNavigation {
backToDrawing: () => void
/** Opens the citations panel of a finding node; any other key is ignored. */
openCitations: (citedBy: ElementKey, opener?: Opener) => void
/** Every close (✕, Escape, scrim, element gone): the focus goes to P6's fallbacks. */
/** A user close (✕, Escape, scrim): the panel exits, then the focus goes to P6's fallbacks. */
closeCitations: () => void
/** The finding vanished: the same close, never refused (a refused draft is dropped, said aloud). */
dropCitations: () => void
/** « Tout afficher dans l'onglet Références »: panel closed, tab shown, library reset. */
showAllReferences: () => void
/** The panel is playing its exit: the state still holds it, the page stays inert. */
exiting: boolean
/** The panel's `onExitComplete`: applies the pending move. */
exitComplete: () => void
/** The panel hands its `canLeave` over while it is mounted (P22''). */
registerCanLeave: (guard: CanLeave | null) => void
consumed: (serial: number, outcome: FocusOutcome) => void
announce: (text: string) => void
}
@@ -113,10 +134,21 @@ interface Openers {
type Go = (action: NavigationAction, kind: MoveKind, text: string) => void
/** The one way to move: commit the typed text, announce, dispatch, record the move. */
/**
* The one way to move: commit the typed text, announce, dispatch, record the move.
* `finish` is the same without the commit, for the move a closed panel recorded.
*/
function useGo(dispatch: Dispatch<NavigationAction>) {
const { live, announce } = useLiveRegion()
const [move, setMove] = useState<Move | null>(null)
const finish = useCallback(
(move: PendingClose) => {
announce(move.note ? `${move.note}. ${move.text}` : move.text)
dispatch(move.action)
setMove({ kind: move.kind, afterExit: true })
},
[announce, dispatch],
)
const go: Go = useCallback(
(action, kind, text) => {
commitFocusedField()
@@ -126,7 +158,7 @@ function useGo(dispatch: Dispatch<NavigationAction>) {
},
[announce, dispatch],
)
return { move, go, live, announce }
return { move, go, finish, live, announce }
}
/** Tab and section moves: « Aller à », a section entry, « Retour au dessin ». */
@@ -154,33 +186,92 @@ function useSectionMoves(go: Go, openers: Openers) {
return { navigate, openSection, backToDrawing }
}
/** The citations panel moves: open from a finding, close, « Tout afficher ». */
function useCitationsMoves(go: Go, openers: Openers) {
/** What the panel's moves need of the hook: its state, the exit and the leave check. */
interface PanelContext {
open: boolean
go: Go
openers: Openers
dispatch: Dispatch<NavigationAction>
announce: (text: string) => void
exit: ReturnType<typeof useCitationsExit>
canLeave: RefObject<CanLeave | null>
}
/**
* Records a close of the panel. A user close asks the panel first (P22''): a refused
* draft cancels it. While an exit is playing, a close is a no-op (a tab choice replaces
* the pending move) and asks nothing: the draft was settled by the first close.
*/
function useRequestClose(ctx: PanelContext) {
const { open, exit, canLeave } = ctx
const { busy, record } = exit
return useCallback(
(move: PendingClose, forced: boolean) => {
if (!open) return
if (busy()) return record(move)
commitFocusedField()
const { allowed, note } = canLeave.current?.(forced) ?? { allowed: true }
if (!allowed) return
record(note ? { ...move, note } : move)
},
[open, busy, record, canLeave],
)
}
/** Opens the panel of a finding node: no move is recorded, the panel focuses itself. */
function useOpenCitations(ctx: PanelContext) {
const t = useT()
const openCitations = useCallback(
const { openers, dispatch, announce } = ctx
return useCallback(
(citedBy: ElementKey, opener?: Opener) => {
if (!isFindingNode(citedBy)) return
commitFocusedField()
openers.citations.current = opener ?? null
openers.citedBy.current = citedBy
const action = { type: 'open_citations', citedBy } as const
go(action, 'citations', t('editor.place.references'))
announce(t('editor.place.references'))
dispatch({ type: 'open_citations', citedBy })
},
[go, openers, t],
[openers, dispatch, announce, t],
)
const closeCitations = useCallback(() => {
const text = t('editor.live.references_closed')
go({ type: 'close_citations' }, 'citations_closed', text)
}, [go, t])
const showAllReferences = useCallback(
() =>
go(
{ type: 'show_all_references' },
'show_all',
t('editor.tab.references'),
),
[go, t],
}
/** The closes of the panel: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
function useCloseMoves(ctx: PanelContext) {
const t = useT()
const moveText = useMoveText()
const { open, go } = ctx
const request = useRequestClose(ctx)
const closing = useCallback(
(forced: boolean) => {
const text = t('editor.live.references_closed')
request(
{ action: { type: 'close_citations' }, kind: 'citations_closed', text },
forced,
)
},
[request, t],
)
return { openCitations, closeCitations, showAllReferences }
// With no panel open there is nothing to exit: the tab shows at once.
const showAllReferences = useCallback(() => {
const action = { type: 'show_all_references' } as const
const text = t('editor.tab.references')
if (!open) return go(action, 'show_all', text)
request({ action, kind: 'show_all', text }, false)
}, [open, go, request, t])
const navigate = useCallback(
(target: EditorTarget) => {
const action = { type: 'go_to', target } as const
request({ action, kind: 'go_to', text: moveText(target) }, false)
},
[request, moveText],
)
return {
closeCitations: useCallback(() => closing(false), [closing]),
dropCitations: useCallback(() => closing(true), [closing]),
showAllReferences,
navigate,
request,
}
}
/** « Retour au dessin »: the entry that opened the section, else the canvas box. */
@@ -212,9 +303,18 @@ function focusAfterClose(openers: Openers) {
if (!focusHeld(triggerOf(openers))) focusActiveTab()
}
/** Nothing the user chose holds the focus: `body`, or what the closing panel still has. */
function focusIsFree(): boolean {
const active = document.activeElement
return (
active === null ||
active === document.body ||
active.closest('[data-place="citations"]') !== null
)
}
/** Where the focus lands after a programmatic move; never `body`. */
function landingOf(move: Move, state: NavigationState): HTMLElement | null {
if (move.kind === 'citations') return headingOf('citations')
if (move.kind === 'show_all') {
return headingOf('references') ?? tabButton(state.tab)
}
@@ -238,10 +338,6 @@ function useMoveFocus(
useEffect(() => {
if (!move || handled.current === move) return
handled.current = move
if (move.kind === 'citations_closed') {
focusAfterClose(openers)
return
}
const serial = state.focus?.serial
if (move.kind === 'go_to' && serial !== undefined) {
const outcome = outcomes.current.get(serial)
@@ -249,7 +345,9 @@ function useMoveFocus(
if (outcome === 'found' || outcome === 'kept') return
dispatch({ type: 'focus_consumed', serial })
}
if (move.kind === 'back') backTarget(openers.section.current)?.focus()
if (move.afterExit && !focusIsFree()) return
if (move.kind === 'citations_closed') focusAfterClose(openers)
else if (move.kind === 'back') backTarget(openers.section.current)?.focus()
else landingOf(move, state)?.focus()
}, [move, state, outcomes, dispatch, openers])
}
@@ -269,7 +367,7 @@ function useReceipts(dispatch: Dispatch<NavigationAction>) {
/** A tab choice; with the citations panel open it closes and the new tab takes the focus. */
function useTabSelect(
go: Go,
request: ReturnType<typeof useCloseMoves>['request'],
dispatch: Dispatch<NavigationAction>,
open: boolean,
) {
@@ -277,11 +375,14 @@ function useTabSelect(
return useCallback(
(tab: EditorTabId) => {
const action = { type: 'select_tab', tab } as const
if (open) return go(action, 'tab_selected', t(`editor.tab.${tab}`))
if (open) {
const text = t(`editor.tab.${tab}`)
return request({ action, kind: 'tab_selected', text }, false)
}
commitFocusedField()
dispatch(action)
},
[go, dispatch, open, t],
[request, dispatch, open, t],
)
}
@@ -292,21 +393,39 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation {
initialTab,
initialNavigation,
)
const { move, go, live, announce } = useGo(dispatch)
const { move, go, finish, live, announce } = useGo(dispatch)
const openers = useRef<Openers>({
citations: { current: null },
citedBy: { current: null },
section: { current: null },
}).current
const canLeave = useRef<CanLeave | null>(null)
const exit = useCitationsExit(finish)
const registerCanLeave = useCallback((guard: CanLeave | null) => {
canLeave.current = guard
}, [])
const open = state.citationsOf !== null
const receipts = useReceipts(dispatch)
useMoveFocus(move, state, receipts.outcomes, dispatch, openers)
const sections = useSectionMoves(go, openers)
const ctx = { open, go, openers, dispatch, announce, exit, canLeave }
const openCitations = useOpenCitations(ctx)
const panel = useCloseMoves(ctx)
return {
state,
live,
announce,
consumed: receipts.consumed,
selectTab: useTabSelect(go, dispatch, state.citationsOf !== null),
...useSectionMoves(go, openers),
...useCitationsMoves(go, openers),
selectTab: useTabSelect(panel.request, dispatch, open),
openSection: sections.openSection,
backToDrawing: sections.backToDrawing,
navigate: open ? panel.navigate : sections.navigate,
openCitations,
closeCitations: panel.closeCitations,
dropCitations: panel.dropCitations,
showAllReferences: panel.showAllReferences,
exiting: exit.exiting,
exitComplete: exit.complete,
registerCanLeave,
}
}
+9 -2
View File
@@ -1230,8 +1230,15 @@ export const en: Dict = {
'editor.annotations.deselected': 'No annotation selected.',
'editor.references.close': 'Close the references',
'editor.references.search': 'Search a reference',
'editor.references.cited_by': 'Cited by « {name} » ({count})',
'editor.references.show_all': 'Show all ({count})',
'editor.references.panel_title': 'Cited references',
'editor.references.panel_count_one': '{count} reference cited by this finding',
'editor.references.panel_count_other': '{count} references cited by this finding',
'editor.references.panel_show_all': 'Show all in the References tab',
'editor.references.panel_empty': 'This finding no longer cites any reference.',
'editor.references.remove_citation': 'Remove from this finding',
'editor.references.this_finding': 'this finding',
'editor.references.missing': 'Reference not found',
'editor.references.draft_dropped': 'Entry not applied: {field}',
'editor.references.cited_one': 'Cited {count} time',
'editor.references.cited_other': 'Cited {count} times',
'editor.references.uncited': 'Not cited',
+9 -2
View File
@@ -1261,8 +1261,15 @@ export const fr: Dict = {
'editor.annotations.deselected': 'Aucune annotation sélectionnée.',
'editor.references.close': 'Fermer les références',
'editor.references.search': 'Rechercher une référence',
'editor.references.cited_by': 'Citées par « {name} » ({count})',
'editor.references.show_all': 'Tout afficher ({count})',
'editor.references.panel_title': 'Références citées',
'editor.references.panel_count_one': '{count} référence citée par ce constat',
'editor.references.panel_count_other': '{count} références citées par ce constat',
'editor.references.panel_show_all': 'Tout afficher dans l\'onglet Références',
'editor.references.panel_empty': 'Ce constat ne cite plus aucune référence.',
'editor.references.remove_citation': 'Retirer de ce constat',
'editor.references.this_finding': 'ce constat',
'editor.references.missing': 'Référence introuvable',
'editor.references.draft_dropped': 'Saisie non appliquée : {field}',
'editor.references.cited_one': 'Citée {count} fois',
'editor.references.cited_other': 'Citée {count} fois',
'editor.references.uncited': 'Non citée',
+27
View File
@@ -0,0 +1,27 @@
import { vi } from 'vitest'
const preference = { reduced: false, listeners: new Set<() => void>() }
/**
* `prefers-reduced-motion` under the test's control. motion reads the query once per
* module and keeps the listener, so the stub is installed at import and answers the
* current value; a switch notifies the listener and applies to the next mount.
*/
vi.stubGlobal('matchMedia', (query: string) => ({
get matches() {
return query.includes('prefers-reduced-motion') && preference.reduced
},
media: query,
onchange: null,
addListener: (listener: () => void) => preference.listeners.add(listener),
removeListener: (listener: () => void) =>
preference.listeners.delete(listener),
addEventListener: () => undefined,
removeEventListener: () => undefined,
dispatchEvent: () => false,
}))
export function setReducedMotion(reduced: boolean): void {
preference.reduced = reduced
preference.listeners.forEach((listener) => listener())
}
@@ -0,0 +1,124 @@
/** R2.4: the exit coordinator of the citations panel (P9, P28) and the gates it feeds. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
renderHook,
render,
screen,
} from '@testing-library/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
ReadOnlyContext,
ReferencesOpenContext,
useDecisionsOpen,
} from '@/editor/editingContext'
import {
PANEL_EXIT_S,
useCitationsExit,
type PendingClose,
} from '@/editor/useCitationsExit'
beforeEach(() => vi.useFakeTimers())
afterEach(() => {
cleanup()
vi.useRealTimers()
})
const move = (kind: PendingClose['kind']): PendingClose => ({
action: { type: 'close_citations' },
kind,
text: kind,
})
describe('useCitationsExit', () => {
it('applies the pending move once, from the callback', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('citations_closed')))
expect(result.current.exiting).toBe(true)
act(() => result.current.complete())
act(() => result.current.complete())
expect(apply).toHaveBeenCalledTimes(1)
expect(apply).toHaveBeenCalledWith(move('citations_closed'))
expect(result.current.exiting).toBe(false)
})
it('applies it from the one-shot timer when the callback never fires', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('show_all')))
act(() => void vi.advanceTimersByTime(PANEL_EXIT_S * 1000 + 99))
expect(apply).not.toHaveBeenCalled()
act(() => void vi.advanceTimersByTime(2))
expect(apply).toHaveBeenCalledTimes(1)
act(() => result.current.complete())
act(() => void vi.advanceTimersByTime(1000))
expect(apply).toHaveBeenCalledTimes(1)
})
it('a callback that comes first cancels the timer', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('go_to')))
act(() => result.current.complete())
act(() => void vi.advanceTimersByTime(1000))
expect(apply).toHaveBeenCalledTimes(1)
})
it('a second close is a no-op, a tab choice replaces the move', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('citations_closed')))
act(() => result.current.record(move('show_all')))
expect(result.current.busy()).toBe(true)
act(() => result.current.record(move('tab_selected')))
act(() => result.current.complete())
expect(apply).toHaveBeenCalledWith(move('tab_selected'))
})
it('a tab choice keeps the note of a forced close it replaces', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
const note = 'Saisie non appliquée : Citation'
act(() => result.current.record({ ...move('citations_closed'), note }))
act(() => result.current.record(move('tab_selected')))
act(() => result.current.complete())
expect(apply).toHaveBeenCalledWith({ ...move('tab_selected'), note })
})
it('a timer left running does not fire after the editor is left', () => {
const apply = vi.fn()
const { result, unmount } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('citations_closed')))
unmount()
act(() => void vi.advanceTimersByTime(1000))
expect(apply).not.toHaveBeenCalled()
})
})
describe('useDecisionsOpen while the citations panel is open', () => {
const key: ElementKey = { kind: 'finding', zone_id: 'z', path: ['c', 'n'] }
const Probe = () => <p>{useDecisionsOpen() ? 'open' : 'held'}</p>
const within = (readOnly: boolean, citationsOf: ElementKey | null) =>
render(
<ReadOnlyContext value={readOnly}>
<ReferencesOpenContext value={citationsOf}>
<Probe />
</ReferencesOpenContext>
</ReadOnlyContext>,
)
it('holds every decision dialog back, panel open or still leaving (no modal in an inert page)', () => {
within(false, key)
expect(screen.getByText('held')).toBeInTheDocument()
})
it('lets them open once the panel is gone, and never while read-only', () => {
within(false, null)
expect(screen.getByText('open')).toBeInTheDocument()
cleanup()
within(true, null)
expect(screen.getByText('held')).toBeInTheDocument()
})
})
@@ -0,0 +1,53 @@
/** R2.4 fix: the layer's heading focus survives a reopen during a slow exit; it fits the viewport. */
import type { ComponentProps } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import { AnimatePresence } from 'motion/react'
import CitationsLayer from '@/components/editor/references/CitationsLayer'
import '../helpers/motion'
vi.mock('@/components/editor/references/CitationsPanel', () => ({
default: () => (
<h2 tabIndex={-1} data-place-heading>
Panel
</h2>
),
}))
afterEach(cleanup)
const props: ComponentProps<typeof CitationsLayer> = {
readOnly: false,
citedBy: { kind: 'finding', zone_id: 'z', path: ['c', 'n'] },
onClose: () => undefined,
onGone: () => undefined,
onShowAll: () => undefined,
navigate: () => undefined,
registerCanLeave: () => undefined,
}
const harness = (show: boolean) => (
<AnimatePresence>
{show && <CitationsLayer key="citations" {...props} />}
</AnimatePresence>
)
const heading = () => screen.getByRole('heading', { name: 'Panel' })
describe('CitationsLayer', () => {
it('focuses its heading again when reopened with the same key during the exit', async () => {
const view = render(harness(true))
await waitFor(() => expect(document.activeElement).toBe(heading()))
;(document.activeElement as HTMLElement).blur()
view.rerender(harness(false))
view.rerender(harness(true))
await waitFor(() => expect(document.activeElement).toBe(heading()))
})
it('writes a pixel height on the panel, never on the page', async () => {
render(harness(true))
const panel = heading().closest('[data-place="citations"]')!
.firstElementChild as HTMLElement
expect(panel.style.height).toMatch(/^\d+(\.\d+)?px$/)
expect(document.documentElement.style.height).toBe('')
})
})
+2 -2
View File
@@ -284,7 +284,7 @@ describe('Escape with the focus on the page', () => {
const trigger = screen.getByRole('button', { name: '1 référence' })
expect(trigger).toHaveAttribute('aria-expanded', 'true')
escape(document.body)
expect(citations()).toBeNull()
await waitFor(() => expect(citations()).toBeNull())
expect(trigger).toHaveAttribute('aria-expanded', 'false')
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(panel()).toBeDefined()
@@ -322,7 +322,7 @@ describe('Escape and the other layers', () => {
await select(user)
await openCitations(user)
escape(screen.getByRole('tab', { name: 'Constats' }))
expect(citations()).toBeNull()
await waitFor(() => expect(citations()).toBeNull())
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(panel()).toBeDefined()
})
@@ -4,12 +4,14 @@ import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
ElementKey,
FindingNode,
} from '@faunosteo/core-wasm/types'
import FindingCreateForm from '@/components/editor/findings/FindingCreateForm'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree'
import { initialNavigation, navigationReducer } from '@/editor/navigation'
import { ReferencesOpenContext } from '@/editor/editingContext'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
@@ -600,6 +602,41 @@ describe('Constats tab', () => {
expect(all.filter((item) => item.kind === 'node')).toHaveLength(2)
})
it('the trigger reads « expanded » only for the finding the panel shows', async () => {
let text = insert(treeText(), {
kind: 'reference',
value: { id: 'ref-a', type: 'book', citation: 'A', url: null, doi: null },
})
const nodes = buildItems(JSON.parse(text)).filter((i) => i.kind === 'node')
for (const item of nodes) {
text = edit(text, {
op: 'update',
key: item.key,
element: {
...item.element,
value: { ...item.element.value, reference_ids: ['ref-a'] },
} as never,
})
}
await openReady({ text })
const user = userEvent.setup()
const shows = (citationsOf: ElementKey | null) => (
<ReferencesOpenContext value={citationsOf}>
<FindingsTab {...props} openCitations={vi.fn()} />
</ReferencesOpenContext>
)
const { rerender } = render(shows(nodes[1].key))
await user.click(items()[1])
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
const trigger = () => screen.getByRole('button', { name: /^1 référence$/ })
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
rerender(shows(nodes[0].key))
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
rerender(shows(null))
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('a category has no vet flag; read-only hides the editing actions', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
@@ -17,7 +17,7 @@ import FindingsTab from '@/components/editor/tabs/FindingsTab'
import RegionsSection from '@/components/editor/annotations/sections/RegionsSection'
import EditorTabBody from '@/components/editor/EditorTabBody'
import EditorTabs from '@/components/editor/EditorTabs'
import ReferenceLibrary from '@/components/editor/references/ReferenceLibrary'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import {
FocusConsumedContext,
@@ -162,7 +162,7 @@ describe('focus requests', () => {
})
await openReady({ text })
render(
<ReferenceLibrary
<ReferencesTab
{...base}
focus={request({ kind: 'reference', id: 'ref-a' })}
/>,
@@ -195,9 +195,9 @@ describe('focus requests', () => {
})
await openReady({ text })
const focus = request({ kind: 'reference', id: 'ref-a' })
const view = render(<ReferenceLibrary {...base} focus={focus} />)
const view = render(<ReferencesTab {...base} focus={focus} />)
;(document.activeElement as HTMLElement).blur()
view.rerender(<ReferenceLibrary {...base} focus={focus} />)
view.rerender(<ReferencesTab {...base} focus={focus} />)
expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull()
})
@@ -222,7 +222,6 @@ describe('ownedBy', () => {
expect(ownedBy(view, 'general')).toBeUndefined()
const ref = request({ kind: 'reference', id: 'ref-a' })
expect(ownedBy(ref, 'references')).toBe(ref)
expect(ownedBy(ref, 'citations')).toBeUndefined()
expect(ownedBy(ref, 'findings')).toBeUndefined()
expect(ownedBy(undefined, 'general')).toBeUndefined()
})
@@ -412,7 +411,7 @@ function Harness() {
switch
</button>
{shown === 'references' ? (
<ReferenceLibrary {...base} focus={focus} />
<ReferencesTab {...base} focus={focus} />
) : (
<RegionsSection {...base} focus={focus} />
)}
+26 -20
View File
@@ -350,36 +350,42 @@ describe('a field still focused while a place is left', () => {
expect(store.getState().documentText).toBe(before)
})
it('Escape in a citations panel field commits the text before the panel closes', async () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
/** The panel's first tile opened in edit, its citation field typed in (not blurred). */
async function typeInPanelTile(user: Awaited<ReturnType<typeof mount>>) {
await openCitations(user)
const field = inPlace('citations').getByLabelText('Citation', {
const panel = inPlace('citations')
await user.click(panel.getByRole('button', { name: /Doe/ }))
await user.click(panel.getByRole('button', { name: 'Modifier' }))
const field = panel.getByLabelText('Citation', {
selector: '#panel-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2021' } })
return field
}
const savedCitation = () =>
(JSON.parse(store.getState().documentText) as AnatomicalSheetDocument)
.references[0].citation
it('Escape in a field of a panel tile neither closes the panel nor commits the text (A5)', async () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
const before = store.getState().documentText
await typeInPanelTile(user)
await user.keyboard('{Escape}')
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
const doc: AnatomicalSheetDocument = JSON.parse(
store.getState().documentText,
)
expect(doc.references[0].citation).toBe('Doe 2021')
expect(store.getState().unsaved).toBe(true)
expect(screen.getByTestId('editor-citations-panel')).toBeInTheDocument()
expect(store.getState().documentText).toBe(before)
})
it('the scrim (no focus move) closes the panel after committing', async () => {
it('the scrim (no focus move) commits the typed text, then closes the panel after its exit', async () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
await openCitations(user)
const field = inPlace('citations').getByLabelText('Citation', {
selector: '#panel-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2022' } })
await typeInPanelTile(user)
fireEvent.click(screen.getByTestId('references-scrim'))
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(
JSON.parse(store.getState().documentText).references[0].citation,
).toBe('Doe 2022')
expect(savedCitation()).toBe('Doe 2021')
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
expect(store.getState().unsaved).toBe(true)
})
})
@@ -1,6 +1,13 @@
/** R2.1: the citations panel of one finding (opened from its trigger only), non-modal layout. */
/** R2.4: the citations panel of one finding (board 25): contents, « Retirer », motion, closes, focus. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, screen, within } from '@testing-library/react'
import {
act,
cleanup,
fireEvent,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
@@ -12,6 +19,7 @@ import {
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import { setReducedMotion } from '../helpers/motion'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -28,6 +36,7 @@ afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
setReducedMotion(false)
})
const name = (n: string) => ({ fr: n, en: n })
@@ -70,8 +79,8 @@ function sheetText(): string {
})
}
/** The sheet plus one finding node under Cat A, citing ref-a and ref-c. */
function nodeText(): string {
/** The sheet plus one finding node under Cat A (default: citing ref-a and ref-c). */
function nodeText(ids = ['ref-a', 'ref-c']): string {
return edit(sheetText(), {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
@@ -81,7 +90,7 @@ function nodeText(): string {
id: 'fnode-a',
name: name('Node A'),
description: {},
reference_ids: ['ref-a', 'ref-c'],
reference_ids: ids,
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
@@ -93,15 +102,28 @@ function nodeText(): string {
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const panel = () => screen.getByTestId('editor-citations-panel')
const cards = () => within(panel()).getAllByRole('listitem')
const trigger = () =>
const hasPanel = () => screen.queryByTestId('editor-citations-panel') !== null
const layer = () => panel().closest('[data-place="citations"]')!
const tiles = () => [...panel().querySelectorAll('ul > li')]
const trigger = (name = '2 références') =>
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name: '2 références' },
{ name },
)
const heading = () =>
within(panel()).getByRole('heading', { name: 'Références citées' })
const doc = () => JSON.parse(store.getState().documentText)
const nodeA = () =>
doc().finding_zones[0].categories[0].children[0] as {
reference_ids: string[]
review_status: string
}
const closed = () => waitFor(() => expect(hasPanel()).toBe(false))
const focusIs = (element: () => Element) =>
waitFor(() => expect(document.activeElement).toBe(element()))
async function mount(width = 1280) {
serverHas(nodeText(), 3)
async function mount(width = 1280, text = nodeText()) {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft({ width })
await ready()
@@ -120,27 +142,37 @@ async function select(user: User, label: RegExp) {
await user.click(screen.getByRole('treeitem', { name: label }))
}
const openFromFinding = async (user: User) => {
/** The panel of Node A, open and in place: its heading holds the focus. */
async function openFromFinding(user: User, name = '2 références') {
await select(user, /Node A/)
await user.click(trigger())
await user.click(trigger(name))
await focusIs(heading)
}
describe('citations panel opening', () => {
it('has no header button, only a finding opens it on its heading', async () => {
const link = () =>
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
})
const closeButton = () =>
within(panel()).getByRole('button', { name: 'Fermer les références' })
describe('opening', () => {
it('has no header button; only a finding opens it, its heading takes the focus after the slide', async () => {
const user = await mount()
expect(screen.queryByRole('button', { name: 'Références' })).toBeNull()
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(hasPanel()).toBe(false)
await select(user, /Node A/)
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
expect(trigger()).toHaveAttribute('aria-controls', 'editor-citations-panel')
await user.click(trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).toBe(
within(panel()).getByRole('heading', { name: 'Références' }),
)
expect(document.activeElement).not.toBe(heading())
await focusIs(heading)
expect(panel()).toHaveAttribute('aria-labelledby', 'editor-citations-title')
})
it('a family keeps its inline list and has no trigger', async () => {
it('a family keeps its inline list: no trigger, no panel', async () => {
const user = await mount()
await select(user, /Cat A/)
const detail = screen.getByRole('tabpanel', { name: 'Constats' })
@@ -150,58 +182,189 @@ describe('citations panel opening', () => {
expect(
within(detail).getAllByRole('button', { name: /^Retirer / }),
).toHaveLength(2)
expect(hasPanel()).toBe(false)
})
it('lists only the references of the finding, each with its count', async () => {
it('shows the path, the count, and only the references of the finding as tiles', async () => {
const user = await mount()
await openFromFinding(user)
const chip = within(panel()).getByTestId('references-filter-chip')
expect(chip).toHaveTextContent('Citées par « Node A » (2)')
expect(cards()).toHaveLength(2)
expect(cards()[0].textContent).toContain('Citée 2 fois')
expect(cards()[1].textContent).toContain('Citée 1 fois')
expect(panel()).toHaveTextContent('Zone A › Cat A › Node A')
expect(panel()).toHaveTextContent('2 références citées par ce constat')
expect(tiles()).toHaveLength(2)
expect(tiles()[0].textContent).toContain('Barone')
expect(tiles()[0].textContent).toContain('Citée 2 fois')
expect(tiles()[1].textContent).toContain('Code rural')
expect(tiles()[1].textContent).toContain('Citée 1 fois')
expect(panel()).not.toHaveTextContent('Denoix')
})
it('has no search, no add form and no order buttons', async () => {
it('an open tile marks the current finding and offers Modifier and « Retirer de ce constat »', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
const tile = tiles()[0] as HTMLElement
expect(within(tile).getByText('ce constat')).toBeInTheDocument()
expect(
within(tile).getAllByRole('button', { name: 'Aller à' }),
).toHaveLength(2)
expect(within(tile).getByRole('button', { name: 'Modifier' })).toBeVisible()
expect(
within(tile).getByRole('button', { name: 'Retirer de ce constat' }),
).toBeVisible()
for (const absent of ['Supprimer', 'Monter', 'Descendre']) {
expect(within(panel()).queryByRole('button', { name: absent })).toBeNull()
}
})
it('has no search, no add control; field ids carry the panel prefix', async () => {
const user = await mount()
await openFromFinding(user)
expect(within(panel()).queryByRole('searchbox')).toBeNull()
expect(
within(panel()).queryByRole('button', { name: 'Ajouter la référence' }),
within(panel()).queryByRole('button', { name: /Ajouter/ }),
).toBeNull()
expect(
within(panel()).queryByRole('button', { name: 'Descendre' }),
).toBeNull()
})
it('field ids carry the panel prefix', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
expect(
panel().querySelector('#panel-reference-0-ref-a-citation'),
).not.toBeNull()
expect(document.querySelector('[id^="tab-reference-"]')).toBeNull()
})
it('« Tout afficher » closes the panel and shows the tab on its heading', async () => {
it('ids stay unique with the Références tab mounted and the panel open (P14)', async () => {
const user = await mount()
await user.click(screen.getByRole('tab', { name: 'Références' }))
await user.click(screen.getByRole('button', { name: /^Barone/ }))
await user.click(screen.getByRole('button', { name: 'Modifier' }))
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
const ids = [...document.querySelectorAll('[id]')].map((e) => e.id)
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([])
expect(ids).toContain('tab-reference-0-ref-a-citation')
expect(ids).toContain('panel-reference-0-ref-a-citation')
})
it('read-only: the tiles show, no Modifier, no Retirer, no field', async () => {
const user = await mount(800)
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
expect(
within(panel()).queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(
within(panel()).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
expect(within(panel()).queryByRole('textbox')).toBeNull()
})
})
describe('motion', () => {
const slid = () => (layer().firstElementChild as HTMLElement).style.transform
it('slides in from the right and fades the scrim, the page behind inert', async () => {
const user = await mount()
await select(user, /Node A/)
await user.click(trigger())
expect(slid()).toMatch(/translateX\(/)
expect(screen.getByTestId('references-scrim')).toBeInTheDocument()
expect(panel().closest('header')).toBeNull()
await focusIs(heading)
expect(slid()).not.toMatch(/translateX\([1-9]/)
})
it('reduced motion: no slide, the same lifecycle', async () => {
setReducedMotion(true)
const user = await mount()
await select(user, /Node A/)
await user.click(trigger())
expect(slid()).not.toMatch(/translateX\(/)
await focusIs(heading)
await user.click(closeButton())
await closed()
await focusIs(() => trigger())
})
})
const MODES = [
['motion', false],
['reduced motion', true],
] as const
describe.each(MODES)('closing, %s', (_label, reduced) => {
beforeEach(() => setReducedMotion(reduced))
it('✕, Escape and the scrim each close it after the exit: the trigger holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(heading)
await user.keyboard('{Escape}')
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(heading)
fireEvent.click(screen.getByTestId('references-scrim'))
await closed()
await focusIs(() => trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('Escape with nothing focused closes it too', async () => {
const user = await mount()
await openFromFinding(user)
;(document.activeElement as HTMLElement).blur()
await user.keyboard('{Escape}')
await closed()
await focusIs(() => trigger())
})
it('« Tout afficher » closes it, shows the tab, the heading holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(
within(panel()).getByRole('button', { name: 'Tout afficher (3)' }),
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
await closed()
expect(screen.getByRole('tab', { name: 'Références' })).toHaveAttribute(
'aria-selected',
'true',
)
const tabPanel = screen.getByRole('tabpanel', { name: 'Références' })
expect(document.activeElement).toBe(
await focusIs(() =>
within(tabPanel).getByRole('heading', { name: 'Références' }),
)
expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(3)
})
it('undo removing the cited finding closes the panel, the tab takes the focus', async () => {
it('selecting a tab closes it, the new tab button holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
await focusIs(() => screen.getByRole('tab', { name: 'Vérification' }))
})
it('« Aller à » a citer from a panel tile closes it and lands on that finding', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
const go = within(panel()).getAllByRole('button', { name: 'Aller à' })
await user.click(go[0])
await closed()
await focusIs(() => screen.getByRole('treeitem', { name: /Cat A/ }))
})
it('the finding vanishing closes it, the active tab button holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
act(() => {
@@ -214,97 +377,11 @@ describe('citations panel opening', () => {
},
})
})
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(
screen.getByRole('tab', { name: 'Constats' }),
)
})
})
describe('closing and layout', () => {
it('Escape, ✕ and the scrim close it, the focus goes back to the trigger', async () => {
const user = await mount()
await openFromFinding(user)
await user.keyboard('{Escape}')
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(trigger())
await user.click(trigger())
await user.click(
within(panel()).getByRole('button', { name: 'Fermer les références' }),
)
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(trigger())
await user.click(trigger())
fireEvent.click(screen.getByTestId('references-scrim'))
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(trigger())
await closed()
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
})
it('selecting a tab closes it, the new tab button takes the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(
screen.getByRole('tab', { name: 'Vérification' }),
)
})
it('makes the tab panels inert while it is open, the header stays usable', async () => {
const user = await mount()
const tabPanel = () => screen.getAllByRole('tabpanel', { hidden: true })[0]
act(() => void commitMove(40))
await openFromFinding(user)
expect(tabPanel().parentElement).toHaveAttribute('inert')
expect(screen.getByRole('button', { name: /Enregistrer/ })).toBeEnabled()
expect(panel().closest('header')).toBeNull()
await user.keyboard('{Escape}')
expect(tabPanel().parentElement).not.toHaveAttribute('inert')
})
it('Ctrl+Z reverts a reference edit while open', async () => {
const user = await mount()
await openFromFinding(user)
const field = within(panel()).getByLabelText('Citation', {
selector: '#panel-reference-0-ref-a-citation',
})
await user.clear(field)
await user.type(field, 'Neuf')
fireEvent.blur(field)
const doc = () => JSON.parse(store.getState().documentText)
expect(doc().references[0].citation).toBe('Neuf')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
})
describe('read-only modes', () => {
it('show the citations with no edit control', async () => {
const user = await mount(800)
await openFromFinding(user)
expect(
within(panel()).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
expect(within(panel()).queryByRole('textbox')).toBeNull()
})
})
describe('ids', () => {
it('stay unique with the Références tab mounted and the panel open (P14)', async () => {
const user = await mount()
await user.click(screen.getByRole('tab', { name: 'Références' }))
await user.click(screen.getByRole('button', { name: /^Barone/ }))
await user.click(screen.getByRole('button', { name: 'Modifier' }))
await openFromFinding(user)
const ids = [...document.querySelectorAll('[id]')].map((e) => e.id)
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([])
expect(ids).toContain('tab-reference-0-ref-a-citation')
expect(ids).toContain('panel-reference-0-ref-a-citation')
})
})
describe('focus fallbacks (P6)', () => {
it('below 640 px the active tab sits under « Plus »: the finding vanishing gives it the focus', async () => {
it('below 640 px the active tab sits under « Plus »: it holds the focus', async () => {
const user = await mount(375)
await user.click(screen.getByRole('button', { name: 'Plus' }))
await user.click(screen.getByRole('button', { name: 'Constats' }))
@@ -312,6 +389,7 @@ describe('focus fallbacks (P6)', () => {
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await user.click(trigger())
await focusIs(heading)
act(() => {
store.getState().commit({
op: 'remove',
@@ -322,9 +400,308 @@ describe('focus fallbacks (P6)', () => {
},
})
})
expect(screen.queryByTestId('editor-citations-panel')).toBeNull()
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Plus' }),
await closed()
await focusIs(() => screen.getByRole('button', { name: 'Plus' }))
})
})
describe('the exit', () => {
it('keeps the page and the panel inert until it is over, then lifts it', async () => {
const user = await mount()
const page = () =>
screen.getAllByRole('tabpanel', { hidden: true })[0].parentElement
await openFromFinding(user)
expect(page()).toHaveAttribute('inert')
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(layer()).toHaveAttribute('inert')
expect(page()).toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
await closed()
expect(page()).not.toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('a second close is a no-op, a tab choice replaces the pending move', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
fireEvent.keyDown(layer(), { key: 'Escape' })
fireEvent.click(screen.getByTestId('references-scrim'))
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
await focusIs(() => screen.getByRole('tab', { name: 'Vérification' }))
})
it('leaves a focus the user placed elsewhere during the exit alone', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
await user.click(closeButton())
const save = screen.getByRole('button', { name: /Enregistrer/ })
act(() => save.focus())
await closed()
await new Promise((resolve) => setTimeout(resolve, 50))
expect(document.activeElement).toBe(save)
})
it('Défaire and Refaire stay usable while it is open', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
const undo = screen.getByRole('button', { name: /Défaire/ })
await waitFor(() => expect(undo).toBeEnabled())
await user.click(undo)
expect(hasPanel()).toBe(true)
expect(screen.getByRole('button', { name: /Refaire/ })).toBeEnabled()
})
})
describe('the library and the history around the panel', () => {
it('« Tout afficher » resets the search and the sort of the tab, open tiles kept (P4)', async () => {
const user = await mount()
await user.click(screen.getByRole('tab', { name: 'Références' }))
const tab = () => screen.getByRole('tabpanel', { name: 'Références' })
await user.type(within(tab()).getByRole('searchbox'), 'Barone')
await user.click(within(tab()).getByRole('button', { name: /^Barone/ }))
await user.selectOptions(
within(tab()).getByLabelText('Trier par'),
'citation',
)
await openFromFinding(user)
await user.click(link())
await closed()
expect(within(tab()).getByRole('searchbox')).toHaveValue('')
expect(within(tab()).getByLabelText('Trier par')).toHaveValue('sheet')
expect(within(tab()).getAllByRole('listitem').length).toBeGreaterThan(2)
expect(
within(tab()).getByRole('button', { name: /^Barone/ }),
).toHaveAttribute('aria-expanded', 'true')
await focusIs(() =>
within(tab()).getByRole('heading', { name: 'Références' }),
)
})
it('an undo that removes the finding closes it: the active tab button holds the focus (P6)', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
element: {
kind: 'finding_node',
value: {
id: 'fnode-b',
name: name('Node B'),
description: {},
reference_ids: ['ref-b'],
requires_vet_referral: false,
review_status: 'to_confirm',
children: [],
},
},
})
})
await select(user, /Node B/)
await user.click(trigger('1 référence'))
await focusIs(heading)
act(() => void store.getState().undoStep())
await closed()
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
})
})
describe('« Retirer de ce constat »', () => {
const retire = (user: User, at = 0) =>
user.click(
within(panel()).getAllByRole('button', { name: 'Retirer de ce constat' })[
at
],
)
async function openTile(user: User, citation: RegExp) {
await user.click(within(panel()).getByRole('button', { name: citation }))
}
it('removes only that id, the reference stays, one undo restores it with the status', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'set_status',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
status: 'reviewed',
})
})
expect(nodeA().review_status).toBe('reviewed')
await openFromFinding(user)
const history = store.getState().undo.length
await openTile(user, /^Barone/)
await retire(user)
expect(nodeA().reference_ids).toEqual(['ref-c'])
expect(nodeA().review_status).toBe('to_confirm')
expect(doc().references).toHaveLength(3)
expect(store.getState().undo.length).toBe(history + 1)
expect(tiles()).toHaveLength(1)
expect(panel()).toHaveTextContent('1 référence citée par ce constat')
act(() => void store.getState().undoStep())
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(nodeA().review_status).toBe('reviewed')
expect(tiles()).toHaveLength(2)
})
it('the focus goes to the next tile, else the previous, else the heading', async () => {
const ids = ['ref-a', 'ref-b', 'ref-c']
const user = await mount(1280, nodeText(ids))
await openFromFinding(user, '3 références')
const header = (at: number) => () =>
tiles()[at].querySelector('button') as HTMLElement
await openTile(user, /^Barone/)
await retire(user)
await focusIs(header(0))
expect(header(0)().textContent).toContain('Denoix')
await openTile(user, /^Code rural/)
await retire(user, 0)
await focusIs(header(0))
expect(tiles()).toHaveLength(1)
await openTile(user, /^Denoix/)
await retire(user)
await focusIs(heading)
})
it('the last citation gone: the panel stays with its line and « Tout afficher »', async () => {
const user = await mount(1280, nodeText(['ref-a']))
await openFromFinding(user, '1 référence')
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await retire(user)
expect(panel()).toHaveTextContent(
'Ce constat ne cite plus aucune référence.',
)
expect(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
).toBeVisible()
expect(hasPanel()).toBe(true)
await user.click(closeButton())
await closed()
// the trigger is gone with its count: the active tab button takes the focus (P6)
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
})
it('a dangling id is a « Référence introuvable » row with Retirer, counted like the rest', async () => {
const user = await mount(1280, nodeText(['ref-a', 'ref-gone']))
await openFromFinding(user)
expect(panel()).toHaveTextContent('2 références citées par ce constat')
expect(tiles()).toHaveLength(2)
expect(tiles()[1]).toHaveTextContent('Référence introuvable')
await user.click(
within(tiles()[1] as HTMLElement).getByRole('button', {
name: /^Retirer/,
}),
)
expect(nodeA().reference_ids).toEqual(['ref-a'])
expect(tiles()).toHaveLength(1)
await focusIs(() => tiles()[0].querySelector('button')!)
})
})
describe("a tile in edit when the panel closes (P22'')", () => {
async function edit(user: User) {
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
return panel().querySelector(
'#panel-reference-0-ref-a-citation',
) as HTMLTextAreaElement
}
it('a valid draft is committed before the close, then the panel closes', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
await user.click(closeButton())
expect(doc().references[0].citation).toBe('Neuf')
await closed()
await focusIs(() => trigger())
})
it('a refused draft cancels a user close: panel open, field focused, message shown', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(layer()).not.toHaveAttribute('inert')
expect(document.activeElement).toBe(field)
expect(within(panel()).getByRole('alert')).toBeVisible()
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('a refused draft cancels a tab switch and « Tout afficher »', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
await user.click(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
)
expect(hasPanel()).toBe(true)
})
it('a forced close (finding vanished) drops a refused draft and says so', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await closed()
expect(
screen.getByText(/Saisie non appliquée : Citation/),
).toBeInTheDocument()
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('Escape in a field of the tile neither closes nor commits', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
await user.keyboard('{Escape}')
expect(hasPanel()).toBe(true)
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('Ctrl+Z reverts a reference edit while the panel is open', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
fireEvent.blur(field)
expect(doc().references[0].citation).toBe('Neuf')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
})
@@ -9,7 +9,7 @@ import {
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ReferenceFacts from '@/components/editor/references/ReferenceFacts'
import ReferenceLibrary from '@/components/editor/references/ReferenceLibrary'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import { useLocaleStore } from '@/state/localeStore'
import { targetOfKey } from '@/editor/navigation'
import { edit, insert } from '../helpers/editorFixtures'
@@ -228,7 +228,11 @@ describe('« Aller à » a reference', () => {
await openReady({ text: sheetText() })
const user = userEvent.setup()
const view = render(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} />,
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
/>,
)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
@@ -240,7 +244,12 @@ describe('« Aller à » a reference', () => {
serial: 1,
}
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} focus={focus} />,
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
focus={focus}
/>,
)
expect(box).toHaveValue('')
expect(document.querySelectorAll('button[aria-controls]')).toHaveLength(3)
@@ -256,23 +265,43 @@ describe('the reset signal', () => {
await openReady({ text: sheetText() })
const user = userEvent.setup()
const view = render(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={0} />,
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={0}
/>,
)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
await user.type(box, 'Code')
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={0} />,
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={0}
/>,
)
expect(box).toHaveValue('Code')
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={1} />,
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={1}
/>,
)
expect(box).toHaveValue('')
await user.type(box, 'a')
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={1} />,
<ReferencesTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
libraryReset={1}
/>,
)
expect(box).toHaveValue('a')
})
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ReferenceLibrary from '@/components/editor/references/ReferenceLibrary'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
@@ -86,7 +86,12 @@ function sortText(): string {
type User = ReturnType<typeof userEvent.setup>
const doc = () => JSON.parse(store.getState().documentText)
const lib = (readOnly = false, extra = {}) => (
<ReferenceLibrary readOnly={readOnly} navigate={vi.fn()} {...extra} />
<ReferencesTab
readOnly={readOnly}
navigate={vi.fn()}
reloadSheet={vi.fn()}
{...extra}
/>
)
async function mount(readOnly = false) {
await openReady({ text: sortText() })
@@ -420,12 +425,12 @@ describe('the reset path (« Tout afficher »)', () => {
it('empties the search and the sort, keeping open tiles and the tile in edit', async () => {
await openReady({ text: sortText() })
const user = userEvent.setup()
const view = render(lib(false, { resetSignal: 0 }))
const view = render(lib(false, { libraryReset: 0 }))
await user.click(header('r2'))
const item = await startEdit(user, 'r1')
await user.selectOptions(sortBox(), 'citation')
await user.type(search(), 'e')
view.rerender(lib(false, { resetSignal: 1 }))
view.rerender(lib(false, { libraryReset: 1 }))
expect(search()).toHaveValue('')
expect(sortBox()).toHaveValue('sheet')
expect(order()).toHaveLength(5)