diff --git a/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md b/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md index 49841d31..29ae2392 100644 --- a/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md +++ b/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md @@ -44,3 +44,14 @@ Reworded prose (no new key): `admin.failure.view.asset.unknown`, `editor.annotat | `editor.annotations.show_all` | Toutes les annotations | All annotations | Properties panel, back to the card | plan wording | Reused: `editor.annotations.list` (« Annotations de la vue », card title and list name), `editor.annotations.list_empty`. + +## Lot D (references side panel) + +| Key | FR | EN | Where | Status | +|---|---|---|---|---| +| `editor.references.search` | Rechercher une référence | Search a reference | Panel field (name and placeholder) | board text | +| `editor.references.cited_by` | Citées par « {name} » ({count}) | Cited by « {name} » ({count}) | Panel chip, opened from a finding | board text | +| `editor.references.show_all` | Tout afficher ({count}) | Show all ({count}) | Panel link clearing the chip | board text | +| `editor.references.no_match` | Aucune référence ne correspond. | No reference matches. | Panel, search or filter without result | proposal | +| `editor.references.cited_one` / `_other` | citée {count} fois | cited {count} time / times | Each reference card | board text | +| `editor.findings.references_open_one` / `_other` | {count} référence / {count} références | {count} reference / references | Finding detail, Citations block, opens the panel filtered | plan wording | diff --git a/apps/app/e2e/shell/editor-shell.spec.ts b/apps/app/e2e/shell/editor-shell.spec.ts index c1c734a0..75c9e3a0 100644 --- a/apps/app/e2e/shell/editor-shell.spec.ts +++ b/apps/app/e2e/shell/editor-shell.spec.ts @@ -90,6 +90,8 @@ test.describe('editor shell, kept places (B2a)', () => { await expect(page.locator('#reference-new-citation')).toHaveValue( 'Smith 1999', ) + // The tab panels are inert while the panel is open (AC3): close it to reach them. + await closeReferences(page, dict) for (const tab of ['general', 'findings', 'verification']) { await selectTab(page, dict, tab) } @@ -103,6 +105,43 @@ test.describe('editor shell, kept places (B2a)', () => { expect(repeated).toEqual([]) }) + for (const width of [1024, 1280]) { + test(`the open references panel leaves the header and the tab row clickable at ${width} px`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 800 }) + await open(page) + await openReferences(page, dict) + await page.locator('#reference-new-type').selectOption('book') + await page.locator('#reference-new-citation').fill('Smith 1999') + await page + .getByRole('button', { name: dict['editor.reference.add'] }) + .click() + const header = page.locator('main header').first() + const tabs = page.getByRole('tablist') + const panel = place(page, 'references') + const targets = [ + page.getByRole('button', { name: dict['common.save'], exact: true }), + page.getByRole('button', { + name: dict['editor.references.open'], + exact: true, + }), + page.getByRole('tab', { + name: new RegExp(`^${dict['editor.tab.findings']}`), + }), + ] + for (const scrolled of [false, true]) { + await page.evaluate((y) => window.scrollTo(0, y), scrolled ? 400 : 0) + for (const target of targets) await target.click({ trial: true }) + const box = await panel.boundingBox() + for (const above of [header, tabs]) { + const other = await above.boundingBox() + expect(box!.y).toBeGreaterThanOrEqual(other!.y + other!.height - 1) + } + } + }) + } + test('focus lands on a named element after a tab click, « Retour au dessin » and « Aller à »', async ({ page, }) => { diff --git a/apps/app/e2e/shell/editor-structures.spec.ts b/apps/app/e2e/shell/editor-structures.spec.ts index 69e3f8c9..64a8b758 100644 --- a/apps/app/e2e/shell/editor-structures.spec.ts +++ b/apps/app/e2e/shell/editor-structures.spec.ts @@ -8,6 +8,7 @@ import { editorActor, openEditor, openReferences, + place, openSection, pickAnnotation, pointOf, @@ -88,6 +89,17 @@ test.describe('editor structures (A4)', () => { '[id^="reference-"][id$="-citation"]:not(#reference-new-citation)', ) await expect(citations).toHaveCount(2) + await expect( + place(page, 'references').getByText('citée 0 fois'), + ).toHaveCount(2) + await page + .getByRole('searchbox', { name: dict['editor.references.search'] }) + .fill('seconde') + await expect(citations).toHaveCount(1) + await page + .getByRole('searchbox', { name: dict['editor.references.search'] }) + .fill('') + await expect(citations).toHaveCount(2) await page .getByRole('listitem') .filter({ hasText: 'Seconde référence' }) diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx index 3bdc5404..d0333b71 100644 --- a/apps/app/src/components/editor/EditorWorkspace.tsx +++ b/apps/app/src/components/editor/EditorWorkspace.tsx @@ -11,7 +11,10 @@ import { saveFailureMessage } from '@/editor/messages' import type { EditorMode } from '@/editor/mode' import { useEditorStore } from '@/editor/state/editorStore' import { initialTab } from '@/editor/tabs' -import { useEditorNavigation } from '@/editor/useEditorNavigation' +import { + useEditorNavigation, + type EditorNavigation, +} from '@/editor/useEditorNavigation' import type { TabTier } from '@/editor/useViewport' import { useT } from '@/i18n/useT' import ConflictDialog from './ConflictDialog' @@ -68,6 +71,65 @@ function EditingState({ ) } +interface PlacesProps { + nav: EditorNavigation + readOnly: boolean + reloadSheet: () => void +} + +/** + * Under the tab row: the tab panels and the references panel 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). + */ +function Places({ nav, readOnly, reloadSheet }: PlacesProps) { + const { state } = nav + const open = state.references.open + return ( +
+ {state.referencesMounted && ( + + + + )} + {open && ( + + ) +} + /** * The draft page once the version is ready: header, notices, tab row, the references * panel and the shown place. Owns the navigation state, so the first tab is known at @@ -100,29 +162,7 @@ export default function EditorWorkspace(props: Props) { - {state.referencesMounted && ( - - - - )} - +

diff --git a/apps/app/src/components/editor/findings/FindingContent.tsx b/apps/app/src/components/editor/findings/FindingContent.tsx index 14bc8ba6..9a21eb2a 100644 --- a/apps/app/src/components/editor/findings/FindingContent.tsx +++ b/apps/app/src/components/editor/findings/FindingContent.tsx @@ -2,11 +2,13 @@ import ActionButton from '@/components/editor/fields/ActionButton' import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue' import SelectField from '@/components/editor/fields/SelectField' import TextField from '@/components/editor/fields/TextField' +import Icon from '@/components/ui/Icon' import { patchElement, type FindingItem, type FindingPatch, } from '@/editor/findings/tree' +import { usePlural } from '@/editor/plural' import { optionalText, useSheetDocument } from '@/editor/sheetDocument' import type { EditCommandApi } from '@/editor/useEditCommand' import type { Locale } from '@/i18n/types' @@ -16,6 +18,7 @@ interface ContentProps { item: FindingItem readOnly: boolean edit: EditCommandApi + onShowReferences?: (opener: HTMLElement) => void } /** The content of a category or a node: descriptions, vet referral, cited references. */ @@ -120,8 +123,10 @@ function Citations({ edit, ids, patch, + onShowReferences, }: ContentProps & { ids: readonly string[]; patch: Patch }) { const t = useT() + const plural = usePlural() const doc = useSheetDocument() const references = doc?.references ?? [] const citation = (id: string) => @@ -134,7 +139,19 @@ function Citations({ ] return (

-

{t('editor.findings.references')}

+
+

{t('editor.findings.references')}

+ {ids.length > 0 && onShowReferences && ( + + )} +
{ids.length === 0 && (

{t('editor.findings.references_none')} diff --git a/apps/app/src/components/editor/findings/FindingDetail.tsx b/apps/app/src/components/editor/findings/FindingDetail.tsx index 04046a1f..3f8c9444 100644 --- a/apps/app/src/components/editor/findings/FindingDetail.tsx +++ b/apps/app/src/components/editor/findings/FindingDetail.tsx @@ -14,6 +14,8 @@ export interface FindingDetailProps { item: FindingItem readOnly: boolean onDelete: () => void + /** Opens the references panel filtered to this element. */ + onShowReferences?: (opener: HTMLElement) => void } /** The selected element: its names, its review state and the actions on it. */ @@ -21,6 +23,7 @@ export default function FindingDetail({ item, readOnly, onDelete, + onShowReferences, }: FindingDetailProps) { const t = useT() const edit = useEditCommand() @@ -33,7 +36,12 @@ export default function FindingDetail({ {item.status && }

- +

{t('editor.reference.new')}

-
+
void }) { + const plural = usePlural() const t = useT() const edit = useEditCommand() const key = { kind: 'reference', id: reference.id } as const @@ -41,7 +50,10 @@ export default function ReferenceRow({ const prefix = `reference-${reference.id}` return (
  • -
    +

    + {plural('editor.references.cited', cited)} +

    +
    - edit.run('move', { op: 'move', key, position })} - /> + {movable && ( + + edit.run('move', { op: 'move', key, position }) + } + /> + )} { +interface Props { + readOnly: boolean + focus?: FocusRequest onClose: () => void + /** The finding the list is filtered to (opened from its detail), if any. */ + citedBy?: ElementKey | null + /** « Tout afficher »: drops the filter. */ + onShowAll?: () => void } /** - * The references side panel, minimal until Lot D: the sheet's bibliography, cited by id - * from the findings, opened by the header button. Not a dialog: it keeps the page usable. - * The workspace mounts it at the first opening and keeps it (hidden) afterwards. + * « Aller à » a reference: the search is cleared first when it may hide the card, and the + * card is focused after the commit that shows it (it does not exist while hidden). */ -export default function ReferencesPanel({ readOnly, focus, onClose }: Props) { +function useReferenceFocus( + focus: FocusRequest | undefined, + query: string, + clearQuery: () => void, +) { + const [late, setLate] = useState(null) + useEffect(() => { + if (late === null) return + focusRow(late) + setLate(null) + }, [late]) + useFocusRequest(focus, (target) => { + if (target.key === null) return 'none' + if (query === '') return focusRow(target.key) ? 'found' : 'none' + clearQuery() + setLate(target.key) + return 'found' + }) +} + +function PanelHeader({ onClose }: { onClose: () => void }) { const t = useT() - useRowFocus(focus) + return ( +
    +

    + + {t('editor.place.references')} +

    + +
    + ) +} + +/** The finding filter: « 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 ( +
    + + {text} + + +
    + ) +} + +function SearchField({ + value, + onChange, + inputRef, +}: { + value: string + onChange: (value: string) => void + inputRef: RefObject +}) { + const t = useT() + return ( + onChange(event.target.value)} + /> + ) +} + +interface ListProps { + shown: readonly Reference[] + all: readonly Reference[] + counts: ReadonlyMap + movable: boolean + readOnly: boolean + onDelete: (reference: Reference) => void +} + +function ReferenceList({ shown, all, counts, ...rest }: ListProps) { + return ( +
      + {shown.map((reference) => ( + rest.onDelete(reference)} + /> + ))} +
    + ) +} + +/** What the list shows: the finding filter (dropped once the finding is gone) and the query. */ +function useShownReferences( + citedBy: ElementKey | null, + query: string, + onShowAll: (() => void) | undefined, +) { const doc = useSheetDocument() + const finding = useMemo( + () => (doc ? citingFinding(doc, citedBy) : null), + [doc, citedBy], + ) + const gone = doc !== null && citedBy !== null && finding === null + useEffect(() => { + if (gone) onShowAll?.() + }, [gone, onShowAll]) + const all = doc?.references ?? [] + const cited = finding ? citedIds(finding) : null + const shown = visibleReferences(all, cited, query) + return { doc, finding, all, cited, shown } +} + +/** The empty line: no reference at all, or none that matches. */ +function EmptyLine({ total, shown }: { total: number; shown: number }) { + const t = useT() + if (shown > 0) return null + const key = + total === 0 ? 'editor.reference.empty' : 'editor.references.no_match' + return

    {t(key)}

    +} + +/** + * The references side panel: the sheet's bibliography, filtered to the finding that opened + * it or searched, each reference with how often it is cited. Not a dialog: the page stays + * usable. The workspace mounts it at the first opening and keeps it (hidden) afterwards. + */ +export default function ReferencesPanel(props: Props) { + const { readOnly, focus, onClose, citedBy = null, onShowAll } = props + const locale = useLocaleStore((s) => s.locale) + const searchRef = useRef(null) + const [query, setQuery] = useState('') const [deleting, setDeleting] = useState(null) - const references = doc?.references ?? [] + useReferenceFocus(focus, query, () => setQuery('')) + const { doc, finding, all, cited, shown } = useShownReferences( + citedBy, + query, + onShowAll, + ) + const showAll = () => { + onShowAll?.() + searchRef.current?.focus() + } const onKeyDown = (event: KeyboardEvent) => { if (event.key !== 'Escape' || event.defaultPrevented) return event.stopPropagation() @@ -37,52 +236,38 @@ export default function ReferencesPanel({ readOnly, focus, onClose }: Props) { data-testid="editor-references-panel" aria-labelledby="editor-references-title" onKeyDown={onKeyDown} - className="space-y-3 rounded-xl border border-[var(--color-border)] p-4" + 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" > -
    -

    - {t('editor.place.references')} -

    - -
    - {doc && references.length === 0 && ( -

    - {t('editor.reference.empty')} -

    + + {finding && cited && ( + )} -
      - {references.map((reference, index) => ( - + {doc && ( + <> + + + onDelete={(reference) => setDeleting({ key: { kind: 'reference', id: reference.id }, label: reference.citation, }) } /> - ))} -
    - {doc && ( - - - + + + + )} setDeleting(null)} /> diff --git a/apps/app/src/components/editor/tabs/FindingsTab.tsx b/apps/app/src/components/editor/tabs/FindingsTab.tsx index ba7e61cb..cd756615 100644 --- a/apps/app/src/components/editor/tabs/FindingsTab.tsx +++ b/apps/app/src/components/editor/tabs/FindingsTab.tsx @@ -61,7 +61,11 @@ function useFindingDeletion( } /** Constats: the tree zones → categories → nodes, edited one command at a time. */ -export default function FindingsTab({ readOnly, focus }: EditorPlaceProps) { +export default function FindingsTab({ + readOnly, + focus, + navigate, +}: EditorPlaceProps) { const t = useT() const doc = useSheetDocument() const [selectedId, setSelectedId] = useState(null) @@ -151,6 +155,12 @@ export default function FindingsTab({ readOnly, focus }: EditorPlaceProps) { item={selected} readOnly={readOnly} onDelete={() => askDelete(selected)} + onShowReferences={(opener) => + navigate( + { place: 'references', key: null, citedBy: selected.key }, + opener, + ) + } /> )} diff --git a/apps/app/src/editor/navigation.ts b/apps/app/src/editor/navigation.ts index 0f53dea3..f0000e6e 100644 --- a/apps/app/src/editor/navigation.ts +++ b/apps/app/src/editor/navigation.ts @@ -44,6 +44,7 @@ export type NavigationAction = | { type: 'back_to_drawing' } | { type: 'open_references'; citedBy: ElementKey | null } | { type: 'close_references' } + | { type: 'clear_cited_by' } | { type: 'go_to'; target: EditorTarget } | { type: 'focus_consumed'; serial: number } @@ -146,6 +147,8 @@ export function navigationReducer( return openReferences(state, action.citedBy) case 'close_references': return { ...state, references: { open: false, citedBy: null } } + case 'clear_cited_by': + return { ...state, references: { ...state.references, citedBy: null } } case 'go_to': return goTo(state, action.target) case 'focus_consumed': diff --git a/apps/app/src/editor/references/citations.ts b/apps/app/src/editor/references/citations.ts new file mode 100644 index 00000000..ba9b1144 --- /dev/null +++ b/apps/app/src/editor/references/citations.ts @@ -0,0 +1,25 @@ +import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' +import { buildItems } from '@/editor/findings/tree' + +const memo = new WeakMap>() + +/** + * How many findings (categories and nodes, at any depth) cite each reference. A display + * count read from the document, no rule: the core's `sheet.dependents` stays the authority + * for a refused deletion. Memoised on the parsed document. + */ +export function citationCounts( + doc: AnatomicalSheetDocument, +): ReadonlyMap { + const known = memo.get(doc) + if (known) return known + const counts = new Map() + for (const { element } of buildItems(doc)) { + if (element.kind === 'zone') continue + for (const id of element.value.reference_ids) { + counts.set(id, (counts.get(id) ?? 0) + 1) + } + } + memo.set(doc, counts) + return counts +} diff --git a/apps/app/src/editor/references/filter.ts b/apps/app/src/editor/references/filter.ts new file mode 100644 index 00000000..be20307a --- /dev/null +++ b/apps/app/src/editor/references/filter.ts @@ -0,0 +1,47 @@ +import type { + AnatomicalSheetDocument, + ElementKey, + Reference, +} from '@faunosteo/core-wasm/types' +import { folded } from '@/catalogue/useCatalogue' +import { + buildItems, + itemForKey, + type FindingItem, +} from '@/editor/findings/tree' + +/** The finding a filter names, read from the current document; null once it is gone. */ +export function citingFinding( + doc: AnatomicalSheetDocument, + key: ElementKey | null, +): FindingItem | null { + if (key === null) return null + return itemForKey(buildItems(doc), key)?.item ?? null +} + +/** The ids a finding cites; a zone cites none. */ +export function citedIds(item: FindingItem): readonly string[] { + return item.element.kind === 'zone' ? [] : item.element.value.reference_ids +} + +/** Case- and accent-insensitive match on the citation, the DOI and the URL. */ +export function referenceMatches(reference: Reference, query: string): boolean { + const term = folded(query.trim()) + if (term === '') return true + return [reference.citation, reference.doi ?? '', reference.url ?? ''].some( + (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), + ) +} diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index 9dea2266..683927a9 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -55,6 +55,8 @@ export interface EditorNavigation { backToDrawing: () => void openReferences: (citedBy: ElementKey | null, opener?: Opener) => void closeReferences: () => void + /** « Tout afficher »: drops the finding filter; no move, no announcement. */ + showAllReferences: () => void consumed: (serial: number, outcome: FocusOutcome) => void announce: (text: string) => void } @@ -155,7 +157,11 @@ function useSectionMoves(go: Go, openers: Openers) { } /** The references panel moves: open (optionally filtered) and close. */ -function useReferenceMoves(go: Go, openers: Openers) { +function useReferenceMoves( + go: Go, + openers: Openers, + dispatch: Dispatch, +) { const t = useT() const openReferences = useCallback( (citedBy: ElementKey | null, opener?: Opener) => { @@ -169,7 +175,11 @@ function useReferenceMoves(go: Go, openers: Openers) { const text = t('editor.live.references_closed') go({ type: 'close_references' }, 'references_closed', text) }, [go, t]) - return { openReferences, closeReferences } + const showAllReferences = useCallback( + () => dispatch({ type: 'clear_cited_by' }), + [dispatch], + ) + return { openReferences, closeReferences, showAllReferences } } /** « Retour au dessin »: the entry that opened the section, else the canvas box. */ @@ -265,6 +275,6 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation { consumed: receipts.consumed, selectTab: receipts.selectTab, ...useSectionMoves(go, openers), - ...useReferenceMoves(go, openers), + ...useReferenceMoves(go, openers, dispatch), } } diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index ffbd4364..7f14b08e 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1227,6 +1227,14 @@ export const en: Dict = { 'editor.annotations.show_all': 'All annotations', 'editor.references.open': 'References', '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.no_match': 'No reference matches.', + 'editor.references.cited_one': 'cited {count} time', + 'editor.references.cited_other': 'cited {count} times', + 'editor.findings.references_open_one': '{count} reference', + 'editor.findings.references_open_other': '{count} references', 'editor.draft.loading': 'Loading the draft…', 'editor.draft.none': 'This sheet has no draft.', 'editor.draft.overview_link': 'View the sheet', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 6849e8bc..78464729 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1258,6 +1258,14 @@ export const fr: Dict = { 'editor.annotations.show_all': 'Toutes les annotations', 'editor.references.open': 'Références', '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.no_match': 'Aucune référence ne correspond.', + 'editor.references.cited_one': 'citée {count} fois', + 'editor.references.cited_other': 'citée {count} fois', + 'editor.findings.references_open_one': '{count} référence', + 'editor.findings.references_open_other': '{count} références', 'editor.draft.loading': 'Chargement du brouillon…', 'editor.draft.none': "Cette fiche n'a pas de brouillon.", 'editor.draft.overview_link': 'Voir la fiche', diff --git a/apps/app/tests/unit/editor-citations.test.ts b/apps/app/tests/unit/editor-citations.test.ts new file mode 100644 index 00000000..12b639ed --- /dev/null +++ b/apps/app/tests/unit/editor-citations.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' +import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' +import { citationCounts } from '@/editor/references/citations' +import { edit, insert } from '../helpers/editorFixtures' +import { baseText } from '../helpers/editorHarness' + +const name = (n: string) => ({ fr: n, en: n }) +const reference = (id: string) => + ({ + kind: 'reference', + value: { id, type: 'book', citation: id, url: null, doi: null }, + }) as const + +function citing(): AnatomicalSheetDocument { + let text = insert(baseText(), reference('ref-a')) + text = insert(text, reference('ref-b')) + text = insert(text, reference('ref-none')) + text = insert(text, { + kind: 'zone', + value: { id: 'zone-a', name: name('Zone'), categories: [] }, + }) + text = edit(text, { + op: 'insert', + parent: { kind: 'zone', id: 'zone-a' }, + element: { + kind: 'finding_category', + value: { + id: 'fcat-a', + kind: 'dysfunction', + name: name('Cat'), + description: {}, + reference_ids: ['ref-a', 'ref-b'], + review_status: 'to_confirm', + children: [], + }, + }, + }) + text = edit(text, { + op: 'insert', + parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] }, + element: { + kind: 'finding_node', + value: { + id: 'fnode-a', + name: name('Node'), + description: {}, + requires_vet_referral: false, + reference_ids: ['ref-a'], + review_status: 'to_confirm', + children: [], + }, + }, + }) + return JSON.parse(text) +} + +describe('citationCounts', () => { + it('counts the citers of a category and of nested nodes, zero when uncited', () => { + const counts = citationCounts(citing()) + expect(counts.get('ref-a')).toBe(2) + expect(counts.get('ref-b')).toBe(1) + expect(counts.get('ref-none') ?? 0).toBe(0) + }) + + it('is memoised on the parsed document', () => { + const doc = citing() + expect(citationCounts(doc)).toBe(citationCounts(doc)) + }) + + it('is empty without findings', () => { + expect(citationCounts(JSON.parse(baseText())).size).toBe(0) + }) +}) diff --git a/apps/app/tests/unit/editor-navigation.test.ts b/apps/app/tests/unit/editor-navigation.test.ts index 18245182..db3fde39 100644 --- a/apps/app/tests/unit/editor-navigation.test.ts +++ b/apps/app/tests/unit/editor-navigation.test.ts @@ -135,6 +135,16 @@ describe('navigationReducer', () => { expect(state.references).toEqual({ open: true, citedBy: view }) }) + it('clear_cited_by drops the filter and keeps the panel open', () => { + const state = run( + initialNavigation('annotations'), + { type: 'open_references', citedBy: view }, + { type: 'clear_cited_by' }, + ) + expect(state.references).toEqual({ open: true, citedBy: null }) + expect(state.focus).toBeUndefined() + }) + it('opens a section and goes back to the drawing', () => { const state = run(initialNavigation('annotations'), { type: 'open_section', diff --git a/apps/app/tests/unit/editor-references-panel.test.tsx b/apps/app/tests/unit/editor-references-panel.test.tsx new file mode 100644 index 00000000..2a0add0a --- /dev/null +++ b/apps/app/tests/unit/editor-references-panel.test.tsx @@ -0,0 +1,284 @@ +/** U1 Lot D: the references side panel, filter, search, counts, non-modal layout. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import ReferencesPanel from '@/components/editor/references/ReferencesPanel' +import { targetOfKey } from '@/editor/navigation' +import { useLocaleStore } from '@/state/localeStore' +import { edit, insert } from '../helpers/editorFixtures' +import { + baseText, + commitMove, + openReady, + resetStore, + serverHas, + store, +} from '../helpers/editorHarness' +import { mountDraft, setWidth } from '../helpers/editorRoute' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +beforeEach(() => useLocaleStore.setState({ locale: 'fr' })) +afterEach(() => { + cleanup() + resetStore() + setWidth(1024) +}) + +const name = (n: string) => ({ fr: n, en: n }) +const ref = (id: string, citation: string, url = '', doi = '') => + ({ + kind: 'reference', + value: { + id, + type: 'book', + citation, + url: url || null, + doi: doi || null, + }, + }) as const + +function sheetText(): string { + let text = baseText() + text = insert(text, ref('ref-a', 'Barone, Ostéologie')) + text = insert(text, ref('ref-b', 'Denoix', 'https://exemple.org/Épaule')) + text = insert(text, ref('ref-c', 'Code rural', '', '10.1000/ABC')) + text = insert(text, { + kind: 'zone', + value: { id: 'zone-a', name: name('Zone A'), categories: [] }, + }) + return edit(text, { + op: 'insert', + parent: { kind: 'zone', id: 'zone-a' }, + element: { + kind: 'finding_category', + value: { + id: 'fcat-a', + kind: 'dysfunction', + name: name('Cat A'), + description: {}, + reference_ids: ['ref-a', 'ref-b'], + review_status: 'to_confirm', + children: [], + }, + }, + }) +} + +const ready = () => + screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) +const header = () => screen.getByRole('button', { name: 'Références' }) +const panel = () => screen.getByTestId('editor-references-panel') +const cards = () => within(panel()).getAllByRole('listitem') +const search = () => + within(panel()).getByRole('searchbox', { name: 'Rechercher une référence' }) + +async function mount(width = 1280) { + serverHas(sheetText(), 3) + const user = userEvent.setup() + mountDraft({ width }) + await ready() + return user +} + +async function openFromFinding(user: ReturnType) { + await user.click(screen.getByRole('tab', { name: 'Constats' })) + await user.click(screen.getByRole('treeitem', { name: /Cat A/ })) + const tabPanel = screen.getByRole('tabpanel', { name: 'Constats' }) + await user.click( + within(tabPanel).getByRole('button', { name: '2 références' }), + ) +} + +describe('references panel opening', () => { + it('the header button opens it on its heading', async () => { + const user = await mount() + await user.click(header()) + expect(document.activeElement).toBe( + within(panel()).getByRole('heading', { name: 'Références' }), + ) + expect(cards()).toHaveLength(3) + }) + + it('a finding that cites references opens the panel filtered to it', async () => { + const user = await mount() + await openFromFinding(user) + const chip = within(panel()).getByTestId('references-filter-chip') + expect(chip).toHaveTextContent('Citées par « Cat A » (2)') + expect(cards()).toHaveLength(2) + await user.click( + within(panel()).getByRole('button', { name: 'Tout afficher (3)' }), + ) + expect(within(panel()).queryByTestId('references-filter-chip')).toBeNull() + expect(cards()).toHaveLength(3) + expect(document.activeElement).toBe(search()) + }) + + it('each card says how often it is cited', async () => { + const user = await mount() + await user.click(header()) + const texts = cards().map((card) => card.textContent) + expect(texts[0]).toContain('citée 1 fois') + expect(texts[2]).toContain('citée 0 fois') + }) + + it('undo removing the cited finding drops the filter', async () => { + const user = await mount() + await openFromFinding(user) + act(() => { + store.getState().commit({ + op: 'remove', + key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] }, + }) + }) + expect(within(panel()).queryByTestId('references-filter-chip')).toBeNull() + expect(cards()).toHaveLength(3) + }) +}) + +describe('search and order buttons', () => { + it('matches the citation, the DOI and the URL, ignoring case and accents', async () => { + const user = await mount() + await user.click(header()) + await user.type(search(), 'OSTEOLOGIE') + expect(cards()).toHaveLength(1) + await user.clear(search()) + await user.type(search(), '10.1000/abc') + expect(cards()).toHaveLength(1) + await user.clear(search()) + await user.type(search(), 'epaule') + expect(cards()).toHaveLength(1) + await user.clear(search()) + await user.type(search(), 'zzz') + expect( + within(panel()).getByText('Aucune référence ne correspond.'), + ).toBeInTheDocument() + }) + + it('shows ↑ / ↓ only with neither filter nor search', async () => { + const user = await mount() + await user.click(header()) + expect( + within(panel()).getAllByRole('button', { name: 'Descendre' }).length, + ).toBe(3) + await user.type(search(), 'a') + expect( + within(panel()).queryByRole('button', { name: 'Descendre' }), + ).toBeNull() + }) + + it('hides ↑ / ↓ while filtered to a finding', async () => { + const user = await mount() + await openFromFinding(user) + expect( + within(panel()).queryByRole('button', { name: 'Descendre' }), + ).toBeNull() + }) +}) + +describe('closing and layout', () => { + it('Escape, ✕ and the scrim close it, the focus goes back to the opener', async () => { + const user = await mount() + await user.click(header()) + await user.keyboard('{Escape}') + expect(panel()).not.toBeVisible() + expect(document.activeElement).toBe(header()) + await user.click(header()) + await user.click( + within(panel()).getByRole('button', { name: 'Fermer les références' }), + ) + expect(panel()).not.toBeVisible() + await user.click(header()) + fireEvent.click(screen.getByTestId('references-scrim')) + expect(panel()).not.toBeVisible() + expect(document.activeElement).toBe(header()) + }) + + it('the finding button gets the focus back when it is still shown', async () => { + const user = await mount() + await openFromFinding(user) + await user.keyboard('{Escape}') + expect(document.activeElement).toHaveTextContent('2 références') + }) + + 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 user.click(header()) + expect(tabPanel().parentElement).toHaveAttribute('inert') + expect(screen.getByRole('button', { name: /Enregistrer/ })).toBeEnabled() + expect(panel().closest('header')).toBeNull() + await user.click(header()) + expect(tabPanel().parentElement).not.toHaveAttribute('inert') + }) + + it('Ctrl+Z reverts a reference edit while open', async () => { + const user = await mount() + await user.click(header()) + const field = within(panel()).getByLabelText('Citation', { + selector: '#reference-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 no edit control, only the search', async () => { + const user = await mount(800) + await user.click(header()) + expect( + within(panel()).queryByRole('button', { name: 'Supprimer' }), + ).toBeNull() + expect( + within(panel()).queryByRole('button', { name: 'Ajouter la référence' }), + ).toBeNull() + expect(search()).toBeInTheDocument() + }) +}) + +describe('« Aller à » a reference', () => { + it('clears the search that hides it and focuses its card', async () => { + serverHas(sheetText(), 3) + await openReady({ text: sheetText() }) + const user = userEvent.setup() + const props = { readOnly: false, onClose: vi.fn() } + const view = render() + const box = screen.getByRole('searchbox', { + name: 'Rechercher une référence', + }) + await user.type(box, 'Code') + expect(screen.getAllByRole('listitem')).toHaveLength(1) + const focus = { + target: targetOfKey({ kind: 'reference', id: 'ref-a' }), + serial: 1, + } + view.rerender() + expect(box).toHaveValue('') + expect(screen.getAllByRole('listitem')).toHaveLength(3) + expect(document.activeElement?.getAttribute('data-focus-key')).toContain( + 'ref-a', + ) + }) +})