feat(editor): references side panel with filter, search and counts

Non-modal panel in a relative container after the tab row (scrim over the
tab panels, which are inert while it is open). Chip "Citées par" opened
from a finding's Citations block, "Tout afficher (N)", accent- and
case-insensitive search on citation, DOI and URL, "citée n fois" per card
(citationCounts, memoised TS read; the core stays the authority for
refused deletions). Up/down only without filter or search. "Aller à" a
reference clears a hiding search then focuses the card.

Rewritten assertions (R-24): editor-shell "the references panel keeps its
form text and no id repeats" closes the panel before reaching the inert
tab panels. Added: Chromium clickability at 1 024 and 1 280 px (top and
scrolled), editor-structures count and search, unit
editor-references-panel, editor-citations, navigation clear_cited_by.
This commit is contained in:
bchanot committed 2026-11-08 17:33:26 +01:00
1 parent cf9c300c80
commit ab51ea764d
19 files changed
+891 -85

No files matched your search

@@ -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 |
+39
View File
@@ -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,
}) => {
@@ -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' })
@@ -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 (
<div className={`relative ${open ? 'min-h-[calc(100dvh-3.5rem)]' : ''}`}>
{state.referencesMounted && (
<KeptPlace
name="references"
visible={open}
className="absolute bottom-0 right-0 top-0 z-20 w-[min(27rem,100%)]"
>
<ReferencesPanel
readOnly={readOnly}
focus={ownedBy(state.focus, 'references')}
onClose={nav.closeReferences}
citedBy={state.references.citedBy}
onShowAll={nav.showAllReferences}
/>
</KeptPlace>
)}
{open && (
<div
aria-hidden="true"
data-testid="references-scrim"
onClick={nav.closeReferences}
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
/>
)}
<div inert={open}>
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
readOnly={readOnly}
navigate={nav.navigate}
focus={state.focus}
reloadSheet={reloadSheet}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
</div>
</div>
)
}
/**
* 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) {
<EditorTabs active={state.tab} tier={tier} onSelect={nav.selectTab} />
<FocusConsumedContext value={nav.consumed}>
<AnnounceContext value={nav.announce}>
{state.referencesMounted && (
<KeptPlace name="references" visible={state.references.open}>
<ReferencesPanel
readOnly={readOnly}
focus={ownedBy(state.focus, 'references')}
onClose={nav.closeReferences}
/>
</KeptPlace>
)}
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
readOnly={readOnly}
navigate={nav.navigate}
focus={state.focus}
reloadSheet={reloadSheet}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
<Places nav={nav} readOnly={readOnly} reloadSheet={reloadSheet} />
</AnnounceContext>
</FocusConsumedContext>
<p aria-live="polite" className="sr-only">
@@ -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 (
<div className="space-y-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length > 0 && onShowReferences && (
<button
type="button"
onClick={(event) => onShowReferences(event.currentTarget)}
className="inline-flex min-h-11 items-center gap-1 rounded-full border border-[var(--color-border)] px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name="book" size={16} />
{plural('editor.findings.references_open', ids.length)}
</button>
)}
</div>
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
@@ -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 && <StatusBadge status={item.status} />}
</div>
<Names item={item} readOnly={readOnly} edit={edit} />
<FindingContent item={item} readOnly={readOnly} edit={edit} />
<FindingContent
item={item}
readOnly={readOnly}
edit={edit}
onShowReferences={onShowReferences}
/>
<div className="flex flex-wrap items-center justify-end gap-1">
<ReviewActions item={item} readOnly={readOnly} edit={edit} />
<MoveButtons
@@ -46,7 +46,7 @@ export default function ReferenceForm() {
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{t('editor.reference.new')}</p>
<div className="grid gap-3 md:grid-cols-2">
<div className="grid gap-3">
<SelectField
id="reference-new-type"
label={t('editor.reference.type')}
@@ -6,6 +6,7 @@ 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 } from './referenceTypes'
@@ -16,15 +17,23 @@ export default function ReferenceRow({
reference,
index,
count,
cited,
movable,
readOnly,
onDelete,
}: {
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
index: number
count: number
/** How many findings cite it. */
cited: number
/** ↑ / ↓ only while neither the finding filter nor the search narrows the list. */
movable: boolean
readOnly: boolean
onDelete: () => 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 (
<li {...focusAttrs(key)} className={`${CARD} ${FOCUS_CLASS}`}>
<div className="grid gap-3 md:grid-cols-2">
<p className="text-right text-sm text-[var(--color-ink-muted)]">
{plural('editor.references.cited', cited)}
</p>
<div className="grid gap-3">
<SelectField
id={`${prefix}-type`}
label={t('editor.reference.type')}
@@ -82,12 +94,16 @@ export default function ReferenceRow({
/>
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
<MoveButtons
index={index}
count={count}
readOnly={readOnly}
onMove={(position) => edit.run('move', { op: 'move', key, position })}
/>
{movable && (
<MoveButtons
index={index}
count={count}
readOnly={readOnly}
onMove={(position) =>
edit.run('move', { op: 'move', key, position })
}
/>
)}
<ActionButton
readOnly={readOnly}
variant="danger"
@@ -1,4 +1,12 @@
import { useState, type KeyboardEvent } from 'react'
import {
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type RefObject,
} from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
@@ -6,26 +14,217 @@ import EditOnly from '@/components/editor/EditOnly'
import ReferenceForm from '@/components/editor/references/ReferenceForm'
import ReferenceRow from '@/components/editor/references/ReferenceRow'
import Icon from '@/components/ui/Icon'
import { useRowFocus } from '@/editor/focusRequest'
import Input from '@/components/ui/Input'
import {
focusRow,
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorPlaceProps } from '@/editor/tabs'
import { citationCounts } from '@/editor/references/citations'
import {
citedIds,
citingFinding,
visibleReferences,
} from '@/editor/references/filter'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
interface Props extends Pick<EditorPlaceProps, 'readOnly' | 'focus'> {
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<ElementKey | null>(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 (
<div className="flex items-center justify-between gap-2">
<h2
id="editor-references-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>
)
}
/** 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 (
<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>
)
}
function SearchField({
value,
onChange,
inputRef,
}: {
value: string
onChange: (value: string) => void
inputRef: RefObject<HTMLInputElement | null>
}) {
const t = useT()
return (
<Input
ref={inputRef}
type="search"
aria-label={t('editor.references.search')}
placeholder={t('editor.references.search')}
value={value}
onChange={(event) => onChange(event.target.value)}
/>
)
}
interface ListProps {
shown: readonly Reference[]
all: readonly Reference[]
counts: ReadonlyMap<string, number>
movable: boolean
readOnly: boolean
onDelete: (reference: Reference) => void
}
function ReferenceList({ shown, all, counts, ...rest }: ListProps) {
return (
<ul className="space-y-3">
{shown.map((reference) => (
<ReferenceRow
key={reference.id}
reference={reference}
index={all.indexOf(reference)}
count={all.length}
cited={counts.get(reference.id) ?? 0}
movable={rest.movable}
readOnly={rest.readOnly}
onDelete={() => rest.onDelete(reference)}
/>
))}
</ul>
)
}
/** 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 <p className="text-sm text-[var(--color-ink-muted)]">{t(key)}</p>
}
/**
* 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<HTMLInputElement>(null)
const [query, setQuery] = useState('')
const [deleting, setDeleting] = useState<DeleteTarget | null>(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"
>
<div className="flex items-center justify-between gap-2">
<h2
id="editor-references-title"
tabIndex={-1}
data-place-heading
className="outline-none text-xl font-semibold"
>
{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>
{doc && references.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.reference.empty')}
</p>
<PanelHeader onClose={onClose} />
{finding && cited && (
<FilterChip
name={finding.name[locale]}
cited={cited.length}
total={all.length}
onShowAll={showAll}
/>
)}
<ul className="space-y-3">
{references.map((reference, index) => (
<ReferenceRow
key={reference.id}
reference={reference}
index={index}
count={references.length}
<SearchField value={query} onChange={setQuery} inputRef={searchRef} />
{doc && (
<>
<EmptyLine total={all.length} shown={shown.length} />
<ReferenceList
shown={shown}
all={all}
counts={citationCounts(doc)}
movable={cited === null && query.trim() === ''}
readOnly={readOnly}
onDelete={() =>
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
))}
</ul>
{doc && (
<EditOnly readOnly={readOnly}>
<ReferenceForm />
</EditOnly>
<EditOnly readOnly={readOnly}>
<ReferenceForm />
</EditOnly>
</>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
@@ -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<string | null>(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,
)
}
/>
)}
<DeleteDialog target={deleting} onClose={closeDelete} />
+3
View File
@@ -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':
@@ -0,0 +1,25 @@
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import { buildItems } from '@/editor/findings/tree'
const memo = new WeakMap<AnatomicalSheetDocument, ReadonlyMap<string, number>>()
/**
* 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<string, number> {
const known = memo.get(doc)
if (known) return known
const counts = new Map<string, number>()
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
}
+47
View File
@@ -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),
)
}
+13 -3
View File
@@ -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<NavigationAction>,
) {
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),
}
}
+8
View File
@@ -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',
+8
View File
@@ -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',
@@ -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)
})
})
@@ -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',
@@ -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<typeof import('@faunosteo/supabase')>()),
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<typeof userEvent.setup>) {
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(<ReferencesPanel {...props} />)
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(<ReferencesPanel {...props} focus={focus} />)
expect(box).toHaveValue('')
expect(screen.getAllByRole('listitem')).toHaveLength(3)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
)
})
})