diff --git a/apps/app/e2e/shell/editor-references.spec.ts b/apps/app/e2e/shell/editor-references.spec.ts index 9b46e585..4934fd7e 100644 --- a/apps/app/e2e/shell/editor-references.spec.ts +++ b/apps/app/e2e/shell/editor-references.spec.ts @@ -13,7 +13,10 @@ import { openEditor, openTab, place, + saveDraft, seedDraft, + serverDocument, + serverRevision, standardShape, } from '../support/editor' @@ -59,9 +62,9 @@ function shape(document: Record) { family.reference_ids = ['ref-doi'] } -async function open(page: Page) { +async function open(page: Page, seedShape = shape) { const actor = await editorActor('fr') - const seed = await seedDraft(actor, { shape: shape }) + const seed = await seedDraft(actor, { shape: seedShape }) await openEditor(page, dict, actor, seed.sheetId) return { actor, seed } } @@ -187,8 +190,9 @@ test.describe('reference tiles, edit mode', () => { test.setTimeout(120_000) await open(page) await openTab(page, dict, 'references') + // The toolbar's last stop (search, sort, add) precedes the first header. await page - .getByRole('searchbox', { name: dict['editor.references.search'] }) + .getByRole('button', { name: dict['editor.references.add'] }) .focus() for (let at = 0; at < 3; at++) { await page.keyboard.press('Tab') @@ -223,6 +227,216 @@ test.describe('reference tiles, edit mode', () => { }) }) +/** + * Four references with distinct orders. Stored: Zèbre 10, zebre 9, Alpha, Étude. + * Citation A → Z: Alpha, Étude, zebre 9, Zèbre 10. Citations: zebre 9 two (family and + * node), Alpha one, the others none. Types: book, journal, legal, web. + */ +function sortShape(document: Record) { + standardShape(document) + const reference = (id: string, type: string, citation: string) => ({ + id, + type, + citation, + url: null, + doi: null, + }) + document.references = [ + reference('ref-z', 'web', 'Zèbre 10'), + reference('ref-y', 'journal', 'zebre 9'), + reference('ref-a', 'book', 'Alpha'), + reference('ref-e', 'legal', 'Étude'), + ] + 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-y'] + family.children[0].reference_ids = ['ref-y', 'ref-a'] +} + +const SORTED = { + sheet: ['Zèbre 10', 'zebre 9', 'Alpha', 'Étude'], + citation: ['Alpha', 'Étude', 'zebre 9', 'Zèbre 10'], + count: ['zebre 9', 'Alpha', 'Zèbre 10', 'Étude'], + type: ['Alpha', 'zebre 9', 'Étude', 'Zèbre 10'], +} as const + +/** The citations of the tiles in display order (the header's first text node). */ +const shownCitations = (page: Page) => + headers(page).evaluateAll((buttons) => + buttons.map((button) => button.querySelector('span')?.textContent ?? ''), + ) + +test.describe('reference tiles, search, sort and add', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip( + isPhone(info), + 'editing needs >= 1 024 px; the phone twin 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) + }) + + const toolbar = (page: Page) => ({ + search: libraryRoot(page).getByRole('searchbox', { + name: dict['editor.references.search'], + }), + sort: libraryRoot(page).getByLabel(dict['editor.references.sort_by']), + clear: libraryRoot(page).getByRole('button', { + name: dict['editor.references.clear_search'], + }), + }) + + test('four sorts, search, clear, no result, move buttons; the server never changes', async ({ + page, + requests, + }) => { + test.setTimeout(150_000) + const { actor, seed } = await open(page, sortShape) + requests.forbid(actor.account.email, actor.account.password) + const before = await serverDocument(seed.draftId) + const revision = await serverRevision(seed.draftId) + await openTab(page, dict, 'references') + const bar = toolbar(page) + await expect( + libraryRoot(page).getByText('4 références', { exact: true }), + ).toBeVisible() + for (const [sort, expected] of Object.entries(SORTED)) { + await bar.sort.selectOption(sort) + await expect.poll(() => shownCitations(page)).toEqual(expected) + } + await expectAccessible(page, 'the type sort') + + // Search: count line, hint instead of the move buttons, clear, Escape. + await bar.sort.selectOption('sheet') + await headers(page).first().click() + const down = libraryRoot(page).getByRole('button', { + name: dict['editor.action.move_down'], + }) + await expect(down).toBeVisible() + await bar.search.fill('zebre') + await expect( + libraryRoot(page).getByText('2 références sur 4', { exact: true }), + ).toBeVisible() + await expect(down).toHaveCount(0) + await expect( + libraryRoot(page).getByText(dict['editor.references.reorder_hint']), + ).toBeVisible() + await expectAccessible(page, 'a search in progress') + await bar.clear.click() + await expect(bar.search).toHaveValue('') + await expect(bar.search).toBeFocused() + await expect(down).toBeVisible() + await bar.search.fill('alpha') + await page.keyboard.press('Escape') + await expect(bar.search).toHaveValue('') + + // No result, then the notice's own clear button. + await bar.search.fill('radiographie') + const notice = libraryRoot(page).getByRole('status').filter({ + hasText: 'radiographie', + }) + await expect(notice).toContainText('Aucune référence ne contient') + await expectAccessible(page, 'the no result notice') + await notice + .getByRole('button', { name: dict['editor.references.clear_search'] }) + .click() + await expect(bar.search).toBeFocused() + await expect(headers(page)).toHaveCount(4) + + // Display only: nothing was saved, the server holds the same document and revision. + expect(await serverDocument(seed.draftId)).toEqual(before) + expect(await serverRevision(seed.draftId)).toBe(revision) + }) + + test('add a reference, save it, then delete an uncited one', async ({ + page, + requests, + }) => { + test.setTimeout(150_000) + const { actor, seed } = await open(page, sortShape) + requests.forbid(actor.account.email, actor.account.password) + await openTab(page, dict, 'references') + const bar = toolbar(page) + await bar.sort.selectOption('count') + await bar.search.fill('alpha') + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.add'] }) + .click() + await expect(bar.search).toHaveValue('') + await expect(bar.sort).toHaveValue('sheet') + const citation = libraryRoot(page).getByLabel( + dict['editor.reference.citation'], + ) + await expect(citation).toBeFocused() + // The focus scrolled the toolbar under the sticky header: axe judges what is covered. + await libraryRoot(page).getByRole('searchbox').scrollIntoViewIfNeeded() + await expectAccessible(page, 'the draft tile') + await libraryRoot(page) + .getByLabel(dict['editor.reference.type']) + .selectOption('manual') + await citation.fill('Nouvelle source') + await libraryRoot(page) + .getByRole('button', { name: dict['editor.reference.add'] }) + .click() + await expect(headers(page)).toHaveCount(5) + const added = headers(page).last() + await expect(added).toContainText('Nouvelle source') + await expect(added).toHaveAttribute('aria-expanded', 'true') + await expect(added).toBeFocused() + await saveDraft(page, dict, seed.revision + 1) + const saved = await serverDocument<{ references: { citation: string }[] }>( + seed.draftId, + ) + expect(saved.references.map((r) => r.citation)).toEqual([ + ...SORTED.sheet, + 'Nouvelle source', + ]) + + // Delete an uncited reference (Étude): the dialog confirms, the tile goes. + await headers(page).nth(3).click() + await tileAt(page, 3) + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await page + .getByRole('dialog') + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await expect(headers(page)).toHaveCount(4) + await expect(libraryRoot(page).getByText('Étude')).toHaveCount(0) + }) + + test('a tile in edit keeps its place under a sort and under a search', async ({ + page, + requests, + }) => { + test.setTimeout(150_000) + const { actor } = await open(page, sortShape) + requests.forbid(actor.account.email, actor.account.password) + await openTab(page, dict, 'references') + const bar = toolbar(page) + await bar.sort.selectOption('citation') + await headers(page).nth(3).click() + await tileAt(page, 3) + .getByRole('button', { name: dict['editor.references.edit'] }) + .click() + await bar.sort.selectOption('count') + await expect( + tileAt(page, 3).getByLabel(dict['editor.reference.citation']), + ).toBeVisible() + await bar.search.fill('alpha') + await expect(headers(page)).toHaveCount(2) + await expect( + libraryRoot(page).getByLabel(dict['editor.reference.citation']), + ).toBeVisible() + }) +}) + test.describe('reference tiles, read-only at 375 px', () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context }, info) => { @@ -242,6 +456,29 @@ test.describe('reference tiles, read-only at 375 px', () => { await expect(headers(page)).toHaveCount(3) const box = await headers(page).first().boundingBox() expect(box?.height ?? 0).toBeGreaterThanOrEqual(44) + // Board 27: search and sort are 44 px targets, there is no « Ajouter » and no hint. + const root = libraryRoot(page) + const search = root.getByRole('searchbox') + const sort = root.getByLabel(dict['editor.references.sort_by']) + for (const control of [search, sort]) { + expect((await control.boundingBox())?.height ?? 0).toBeGreaterThanOrEqual( + 44, + ) + } + await expect( + root.getByRole('button', { name: dict['editor.references.add'] }), + ).toHaveCount(0) + await sort.selectOption('citation') + await search.fill('source') + await expect(headers(page)).toHaveCount(1) + await expect( + root.getByText(dict['editor.references.reorder_hint']), + ).toHaveCount(0) + await root + .getByRole('button', { name: dict['editor.references.clear_search'] }) + .click() + await sort.selectOption('sheet') + await expect(headers(page)).toHaveCount(3) await expectNoHorizontalOverflow(page, 'the closed tiles at 375 px') await expectAccessible(page, 'the closed tiles at 375 px') await headers(page).nth(1).click() diff --git a/apps/app/e2e/shell/editor-shell-crossing.spec.ts b/apps/app/e2e/shell/editor-shell-crossing.spec.ts index 6fdb8c34..a4787f01 100644 --- a/apps/app/e2e/shell/editor-shell-crossing.spec.ts +++ b/apps/app/e2e/shell/editor-shell-crossing.spec.ts @@ -196,6 +196,9 @@ test.describe('editor shell, width crossing (H)', () => { }) => { await open(page) await openTab(page, dict, 'references') + await page + .getByRole('button', { name: dict['editor.references.add'] }) + .click() await keepsTypedValue( page, page.locator('#tab-reference-new-citation'), diff --git a/apps/app/e2e/shell/editor-shell.spec.ts b/apps/app/e2e/shell/editor-shell.spec.ts index d3376872..43c02ad3 100644 --- a/apps/app/e2e/shell/editor-shell.spec.ts +++ b/apps/app/e2e/shell/editor-shell.spec.ts @@ -98,6 +98,9 @@ test.describe('editor shell, kept places (B2a)', () => { }) => { await open(page) await openTab(page, dict, 'references') + await page + .getByRole('button', { name: dict['editor.references.add'] }) + .click() await page.locator('#tab-reference-new-citation').fill('Smith 1999') await openTab(page, dict, 'general') await openTab(page, dict, 'references') @@ -128,6 +131,9 @@ test.describe('editor shell, kept places (B2a)', () => { await open(page) // An edit first, so « Enregistrer » is enabled: a reference added in its tab. await openTab(page, dict, 'references') + await page + .getByRole('button', { name: dict['editor.references.add'] }) + .click() await page.locator('#tab-reference-new-type').selectOption('book') await page.locator('#tab-reference-new-citation').fill('Smith 1999') await page diff --git a/apps/app/e2e/shell/editor-structures.spec.ts b/apps/app/e2e/shell/editor-structures.spec.ts index 75c13761..7f5e5670 100644 --- a/apps/app/e2e/shell/editor-structures.spec.ts +++ b/apps/app/e2e/shell/editor-structures.spec.ts @@ -80,12 +80,17 @@ test.describe('editor structures (A4)', () => { // « Référence A » stays first: it is cited by « Constat A »). await openTab(page, dict, 'references') for (const citation of ['Première référence', 'Seconde référence']) { + await page + .getByRole('button', { name: dict['editor.references.add'] }) + .click() await page.locator('#tab-reference-new-type').selectOption('book') await page.locator('#tab-reference-new-citation').fill(citation) await page .getByRole('button', { name: dict['editor.reference.add'] }) .click() - await expect(page.getByText(citation)).toBeVisible() + await expect( + page.getByRole('button', { name: new RegExp(`^${citation}`) }), + ).toBeFocused() } const tiles = page.locator('[id^="tab-reference-"][id$="-header"]') const tileOf = (citation: string) => @@ -102,12 +107,17 @@ test.describe('editor structures (A4)', () => { await expect(tiles).toHaveCount(1) await search.fill('') await expect(tiles).toHaveCount(3) - await tiles.filter({ hasText: 'Seconde référence' }).click() + // An added tile stays open (P24): no click, a click would close it. + await expect( + tiles.filter({ hasText: 'Seconde référence' }), + ).toHaveAttribute('aria-expanded', 'true') await tileOf('Seconde référence') .getByRole('button', { name: dict['editor.action.move_up'] }) .click() await expect(tiles.nth(1)).toContainText('Seconde référence') - await tiles.filter({ hasText: 'Première référence' }).click() + await expect( + tiles.filter({ hasText: 'Première référence' }), + ).toHaveAttribute('aria-expanded', 'true') await tileOf('Première référence') .getByRole('button', { name: dict['editor.action.delete'] }) .click() diff --git a/apps/app/src/components/editor/references/NewReferenceTile.tsx b/apps/app/src/components/editor/references/NewReferenceTile.tsx new file mode 100644 index 00000000..2663fc4f --- /dev/null +++ b/apps/app/src/components/editor/references/NewReferenceTile.tsx @@ -0,0 +1,120 @@ +import { useEffect, useState } from 'react' +import type { ReferenceType } from '@faunosteo/core-wasm/types' +import ActionButton from '@/components/editor/fields/ActionButton' +import DraftField from '@/components/editor/fields/DraftField' +import SelectField from '@/components/editor/fields/SelectField' +import Icon from '@/components/ui/Icon' +import { isBlank, nullable } from '@/editor/sheetDocument' +import { useEditCommand } from '@/editor/useEditCommand' +import { useT } from '@/i18n/useT' +import { REFERENCE_TYPES } from './referenceTypes' + +const EMPTY = { type: '', citation: '', url: '', doi: '' } +const ID = 'tab-reference-new' + +interface Props { + /** Bumped by each « Ajouter une référence »: the citation takes the focus again. */ + focusSerial: number + /** The reference was created in one modification, under this id. */ + onAdded: (id: string) => void +} + +/** + * The draft tile of « Ajouter une référence » (board 24 E): type « Choisir… » and citation + * required, DOI and URL optional. Nothing reaches the document before « Ajouter la + * référence », which inserts the reference as one modification. + */ +export default function NewReferenceTile({ focusSerial, onAdded }: Props) { + const t = useT() + const edit = useEditCommand() + const [form, setForm] = useState(EMPTY) + const set = (patch: Partial) => setForm({ ...form, ...patch }) + useEffect(() => { + document.getElementById(`${ID}-citation`)?.focus() + }, [focusSerial]) + const options = [ + { value: '', label: t('editor.field.choose') }, + ...REFERENCE_TYPES.map((type) => ({ + value: type, + label: t(`editor.reference.type.${type}`), + })), + ] + const create = () => { + if (form.type === '' || isBlank(form.citation)) { + edit.reject('form', 'editor.reference.required') + return + } + let created = '' + const added = edit.runNew('form', 'ref', (id) => { + created = id + return { + op: 'insert', + element: { + kind: 'reference', + value: { + id, + type: form.type as ReferenceType, + citation: form.citation, + url: nullable(form.url), + doi: nullable(form.doi), + }, + }, + } + }) + if (added) onAdded(created) + } + return ( +
+
+ +

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

+
+
+
+ set({ type })} + /> + set({ doi })} + /> +
+ set({ citation })} + multiline + /> + set({ url })} + /> + {edit.fieldError('form') && ( +

+ {edit.fieldError('form')} +

+ )} +
+ + {t('editor.reference.add')} + +

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

+
+
+
+ ) +} diff --git a/apps/app/src/components/editor/references/NoResult.tsx b/apps/app/src/components/editor/references/NoResult.tsx new file mode 100644 index 00000000..99b31d17 --- /dev/null +++ b/apps/app/src/components/editor/references/NoResult.tsx @@ -0,0 +1,31 @@ +import Button from '@/components/ui/Button' +import Icon from '@/components/ui/Icon' +import { useT } from '@/i18n/useT' + +/** Board 24 B: nothing contains the search; the notice offers to clear it. */ +export default function NoResult({ + query, + onClear, +}: { + query: string + onClear: () => void +}) { + const t = useT() + return ( +
+

+ + {t('editor.references.no_result').replace('{q}', query.trim())} + {' '} + {t('editor.references.no_result_scope')} +

+ +
+ ) +} diff --git a/apps/app/src/components/editor/references/ReferenceForm.tsx b/apps/app/src/components/editor/references/ReferenceForm.tsx deleted file mode 100644 index 31ab1fd3..00000000 --- a/apps/app/src/components/editor/references/ReferenceForm.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import { useState } from 'react' -import type { ReferenceType } from '@faunosteo/core-wasm/types' -import ActionButton from '@/components/editor/fields/ActionButton' -import DraftField from '@/components/editor/fields/DraftField' -import SelectField from '@/components/editor/fields/SelectField' -import { isBlank, nullable } from '@/editor/sheetDocument' -import { useEditCommand } from '@/editor/useEditCommand' -import { useT } from '@/i18n/useT' -import { REFERENCE_TYPES, type ReferenceHost } from './referenceTypes' - -const EMPTY = { type: '', citation: '', url: '', doi: '' } - -/** - * Adds a reference: the type and the citation are required, URL and DOI optional. - * `onAdded` runs after a successful add, so the list can show the new reference. - */ -export default function ReferenceForm({ - host, - onAdded, -}: { - host: ReferenceHost - onAdded?: () => void -}) { - const t = useT() - const edit = useEditCommand() - const [form, setForm] = useState(EMPTY) - const set = (patch: Partial) => setForm({ ...form, ...patch }) - const options = [ - { value: '', label: t('editor.field.choose') }, - ...REFERENCE_TYPES.map((type) => ({ - value: type, - label: t(`editor.reference.type.${type}`), - })), - ] - const create = () => { - if (form.type === '' || isBlank(form.citation)) { - edit.reject('form', 'editor.reference.required') - return - } - const added = edit.runNew('form', 'ref', (id) => ({ - op: 'insert', - element: { - kind: 'reference', - value: { - id, - type: form.type as ReferenceType, - citation: form.citation, - url: nullable(form.url), - doi: nullable(form.doi), - }, - }, - })) - if (!added) return - setForm(EMPTY) - onAdded?.() - } - return ( -
-

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

-
- set({ type })} - /> - set({ citation })} - multiline - /> - set({ url })} - /> - set({ doi })} - /> -
- {edit.fieldError('form') && ( -

- {edit.fieldError('form')} -

- )} - - {t('editor.reference.add')} - -
- ) -} diff --git a/apps/app/src/components/editor/references/ReferenceLibrary.tsx b/apps/app/src/components/editor/references/ReferenceLibrary.tsx index 224c8581..d0e91bcd 100644 --- a/apps/app/src/components/editor/references/ReferenceLibrary.tsx +++ b/apps/app/src/components/editor/references/ReferenceLibrary.tsx @@ -1,113 +1,77 @@ -import { useEffect, useState } from 'react' -import type { ElementKey, Reference } from '@faunosteo/core-wasm/types' +import { useRef, useState } from 'react' import DeleteDialog, { type DeleteTarget, } from '@/components/editor/DeleteDialog' import EditOnly from '@/components/editor/EditOnly' -import Input from '@/components/ui/Input' -import { - focusRow, - useFocusRequest, - type FocusRequest, -} from '@/editor/focusRequest' +import type { FocusRequest } from '@/editor/focusRequest' import type { EditorTarget } from '@/editor/navigation' -import { citersOf } from '@/editor/references/citations' -import { visibleReferences } from '@/editor/references/filter' -import { useSheetDocument } from '@/editor/sheetDocument' +import { isSheetView } from '@/editor/references/view' import { useT } from '@/i18n/useT' -import ReferenceForm from './ReferenceForm' +import NewReferenceTile from './NewReferenceTile' +import NoResult from './NoResult' import { EmptyLine } from './ReferenceList' import ReferenceTiles from './ReferenceTiles' -import { tileKeys, useTileState } from './useTileState' +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 is emptied once per bump. */ + /** Bumped by « Tout afficher »: the search and the sort are reset once per bump. */ resetSignal?: number } /** - * « Aller à » a reference: its tile is opened, the search is cleared first when it may - * hide the tile, and the tile's button is focused after the commit that shows it. - */ -function useReferenceFocus( - focus: FocusRequest | undefined, - query: string, - actions: { clearQuery: () => void; reveal: (key: ElementKey) => 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' - actions.reveal(target.key) - if (query === '') return focusRow(target.key) ? 'found' : 'none' - actions.clearQuery() - setLate(target.key) - return 'found' - }) -} - -/** The search text, emptied each time `resetSignal` changes (the tab stays mounted). */ -function useSearchQuery(resetSignal: number) { - const [query, setQuery] = useState('') - const [seen, setSeen] = useState(resetSignal) - if (seen !== resetSignal) { - setSeen(resetSignal) - setQuery('') - } - return [query, setQuery] as const -} - -/** - * The sheet's bibliography: a search, one collapsible tile per reference, the add form - * and the delete dialog. Lives in the Références tab (ids prefixed `tab-`). + * 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 doc = useSheetDocument() - const tiles = useTileState() - const [query, setQuery] = useSearchQuery(resetSignal) + const lib = useReferenceLibrary(readOnly, resetSignal) + const searchRef = useRef(null) + const act = useReferenceActions(lib, focus, searchRef) const [deleting, setDeleting] = useState(null) - const all: readonly Reference[] = doc?.references ?? [] - const keys = tileKeys(all) - const reveal = (key: ElementKey) => { - const at = all.findIndex( - (reference) => key.kind === 'reference' && reference.id === key.id, - ) - if (at >= 0) tiles.reveal(keys[at]) - } - useReferenceFocus(focus, query, { clearQuery: () => setQuery(''), reveal }) - const shown = visibleReferences(all, null, query) - const citers = doc ? citersOf(doc) : new Map() + const { all, shown } = lib + const sheetView = isSheetView(shown.view) return (
- setQuery(event.target.value)} + 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} /> - {doc && ( + {lib.loaded && ( <> - + {all.length === 0 && } + {all.length > 0 && shown.matchCount === 0 && ( + + )} + {!readOnly && !sheetView && shown.positions.length > 0 && ( +

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

+ )} setDeleting({ key: { kind: 'reference', id: reference.id }, @@ -116,7 +80,9 @@ export default function ReferenceLibrary(props: Props) { } /> - setQuery('')} /> + {act.draft !== null && ( + + )} )} diff --git a/apps/app/src/components/editor/references/ReferenceList.tsx b/apps/app/src/components/editor/references/ReferenceList.tsx index c90bdc5e..68541314 100644 --- a/apps/app/src/components/editor/references/ReferenceList.tsx +++ b/apps/app/src/components/editor/references/ReferenceList.tsx @@ -35,11 +35,12 @@ export function ReferenceList({ shown, all, citers, ...rest }: ListProps) { ) } -/** The empty line: no reference at all, or none that matches. */ -export function EmptyLine({ total, shown }: { total: number; shown: number }) { +/** The empty line: the sheet has no reference at all. */ +export function EmptyLine() { const t = useT() - if (shown > 0) return null - const key = - total === 0 ? 'editor.reference.empty' : 'editor.references.no_match' - return

{t(key)}

+ return ( +

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

+ ) } diff --git a/apps/app/src/components/editor/references/ReferenceTiles.tsx b/apps/app/src/components/editor/references/ReferenceTiles.tsx index 5937a3c6..485de7ec 100644 --- a/apps/app/src/components/editor/references/ReferenceTiles.tsx +++ b/apps/app/src/components/editor/references/ReferenceTiles.tsx @@ -6,8 +6,8 @@ import ReferenceTile from './ReferenceTile' import type { useTileState } from './useTileState' interface Props { - /** The tiles to list, each placed by its index in the whole bibliography `all`. */ - shown: readonly Reference[] + /** The tiles to list, in display order, as positions in the whole bibliography `all`. */ + positions: readonly number[] all: readonly Reference[] /** One key per position of `all` (`tileKeys`). */ keys: readonly string[] @@ -16,12 +16,13 @@ interface Props { readOnly: boolean movable: boolean navigate: (target: EditorTarget) => void + onEdit: (position: number) => void onDelete: (reference: Reference) => void } /** The tiles of the Références tab, wired to the library's open / edit state. */ export default function ReferenceTiles(props: Props) { - const { shown, all, keys, citers, tiles, navigate } = props + const { positions, all, keys, citers, tiles, navigate } = props const edit = useEditCommand() const move = (reference: Reference, position: number) => edit.run('move', { @@ -33,8 +34,8 @@ export default function ReferenceTiles(props: Props) { return ( <>
    - {shown.map((reference) => { - const position = all.indexOf(reference) + {positions.map((position) => { + const reference = all[position] const key = keys[position] return ( tiles.toggle(key), - edit: () => tiles.startEdit(key), + edit: () => props.onEdit(position), done: tiles.finish, remove: () => props.onDelete(reference), move: (to) => move(reference, to), diff --git a/apps/app/src/components/editor/references/ReferenceToolbar.tsx b/apps/app/src/components/editor/references/ReferenceToolbar.tsx new file mode 100644 index 00000000..ec92cc3b --- /dev/null +++ b/apps/app/src/components/editor/references/ReferenceToolbar.tsx @@ -0,0 +1,103 @@ +import type { KeyboardEvent, RefObject } from 'react' +import ActionButton from '@/components/editor/fields/ActionButton' +import Icon from '@/components/ui/Icon' +import Input from '@/components/ui/Input' +import Select from '@/components/ui/Select' +import { usePlural } from '@/editor/plural' +import { REFERENCE_SORTS, type ReferenceSort } from '@/editor/references/sort' +import { useT } from '@/i18n/useT' + +interface Props { + query: string + onQuery: (query: string) => void + /** Empties the search and gives the focus back to its field. */ + onClear: () => void + searchRef: RefObject + sort: ReferenceSort + onSort: (sort: ReferenceSort) => void + shown: number + total: number + /** « Ajouter une référence »: absent while the editor is read-only. */ + canAdd: boolean + onAdd: () => void +} + +/** The count line: « {n} références » or « {n} références sur {total} ». */ +function CountLine({ shown, total }: { shown: number; total: number }) { + const plural = usePlural() + const key = shown === total ? 'count' : 'count_of' + const text = plural(`editor.references.${key}`, shown) + return ( +

    + {text.replace('{total}', String(total))} +

    + ) +} + +/** Search with its clear button, the sort, the count and the add button (boards 23, 24). */ +export default function ReferenceToolbar(props: Props) { + const { query, onQuery, onClear, searchRef, sort, onSort } = props + const t = useT() + // P12: Escape empties a non-empty search; an empty one lets the event bubble (A5). + const escape = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || query === '') return + event.preventDefault() + onClear() + } + return ( +
    +
    +
    + onQuery(event.target.value)} + onKeyDown={escape} + className="pr-11 max-sm:h-11 [&::-webkit-search-cancel-button]:appearance-none" + /> + {query !== '' && ( + + )} +
    +
    + + +
    +
    +
    + + + {t('editor.references.add')} + +
    +
    + ) +} diff --git a/apps/app/src/components/editor/references/referenceTypes.ts b/apps/app/src/components/editor/references/referenceTypes.ts index 0a0aed42..230b3090 100644 --- a/apps/app/src/components/editor/references/referenceTypes.ts +++ b/apps/app/src/components/editor/references/referenceTypes.ts @@ -1,13 +1,4 @@ -import type { ReferenceType } from '@faunosteo/core-wasm/types' - -export const REFERENCE_TYPES: readonly ReferenceType[] = [ - 'book', - 'journal', - 'standard', - 'legal', - 'web', - 'manual', -] +export { REFERENCE_TYPES } from '@/editor/references/referenceTypes' /** Where reference cards are shown: the Références tab or a finding's citations panel. */ export type ReferenceHost = 'tab' | 'panel' diff --git a/apps/app/src/components/editor/references/useReferenceLibrary.ts b/apps/app/src/components/editor/references/useReferenceLibrary.ts new file mode 100644 index 00000000..176b75a2 --- /dev/null +++ b/apps/app/src/components/editor/references/useReferenceLibrary.ts @@ -0,0 +1,97 @@ +import { useEffect, useState, type RefObject } from 'react' +import type { ElementKey, Reference } from '@faunosteo/core-wasm/types' +import { + focusRow, + useFocusRequest, + type FocusRequest, +} from '@/editor/focusRequest' +import { citersOf } from '@/editor/references/citations' +import { referenceMatches } from '@/editor/references/filter' +import { useSheetDocument } from '@/editor/sheetDocument' +import { tileKeys, useTileState } from './useTileState' +import { useReferenceView } from './useReferenceView' + +const NO_CITERS = new Map() + +/** The document's references with the tab's tile state and display order. */ +export function useReferenceLibrary(readOnly: boolean, resetSignal: number) { + const doc = useSheetDocument() + const all: readonly Reference[] = doc?.references ?? [] + const keys = tileKeys(all) + const tiles = useTileState(doc ? keys : null) + const citers = doc ? citersOf(doc) : NO_CITERS + const editedAt = readOnly ? -1 : keys.indexOf(tiles.editingKey ?? '') + const shown = useReferenceView(all, citers, editedAt, resetSignal) + return { loaded: doc !== null, all, keys, tiles, citers, shown } +} +export type ReferenceLibraryState = ReturnType + +/** Focuses a row after the commit that shows it (the request ran before it rendered). */ +function useLateFocus() { + const [late, setLate] = useState(null) + useEffect(() => { + if (late === null) return + focusRow(late) + setLate(null) + }, [late]) + return setLate +} + +const positionOf = (all: readonly Reference[], key: ElementKey) => + all.findIndex((r) => key.kind === 'reference' && r.id === key.id) + +/** + * « Aller à » a reference: its tile is opened, the search is cleared (only it, P3) when it + * hides the tile, and the tile's button is focused after the commit that shows it (P8). + */ +function useReferenceFocus( + focus: FocusRequest | undefined, + lib: ReferenceLibraryState, + later: (key: ElementKey) => void, +) { + const { all, keys, tiles, shown } = lib + useFocusRequest(focus, (target) => { + const at = target.key === null ? -1 : positionOf(all, target.key) + if (target.key === null || at < 0) return 'none' + tiles.reveal(keys[at]) + if (referenceMatches(all[at], shown.view.query)) { + return focusRow(target.key) ? 'found' : 'none' + } + shown.update({ query: '' }) + later(target.key) + return 'found' + }) +} + +/** What the library's controls do: search, « Ajouter une référence », edit and « Aller à ». */ +export function useReferenceActions( + lib: ReferenceLibraryState, + focus: FocusRequest | undefined, + searchRef: RefObject, +) { + const { keys, tiles, shown } = lib + const [draft, setDraft] = useState(null) + const later = useLateFocus() + useReferenceFocus(focus, lib, later) + return { + draft, + clearSearch: () => { + shown.update({ query: '' }) + searchRef.current?.focus() + }, + // P24 (and P22): leave the tile in edit first, then a clean view and the draft. + startAdd: () => { + if (!tiles.finish()) return + shown.reset() + setDraft((serial) => (serial ?? 0) + 1) + }, + added: (id: string) => { + setDraft(null) + tiles.reveal(`${id}#0`) + later({ kind: 'reference', id }) + }, + edit: (position: number) => { + if (tiles.startEdit(keys[position])) shown.markEdited(position) + }, + } +} diff --git a/apps/app/src/components/editor/references/useReferenceView.ts b/apps/app/src/components/editor/references/useReferenceView.ts new file mode 100644 index 00000000..8ee733c9 --- /dev/null +++ b/apps/app/src/components/editor/references/useReferenceView.ts @@ -0,0 +1,59 @@ +import { useState } from 'react' +import { referenceMatches } from '@/editor/references/filter' +import type { Reference } from '@faunosteo/core-wasm/types' +import type { CiterItem } from '@/editor/references/citations' +import { + isSheetView, + shownPositions, + type ReferenceView, +} from '@/editor/references/view' +import { useLocaleStore } from '@/state/localeStore' + +const INITIAL: ReferenceView = { query: '', sort: 'sheet' } + +/** + * The search, the sort and the resulting tile order of the Références tab. All three are + * display state: nothing here reaches the document (BDR-114). `resetSignal` (« Tout + * afficher ») empties the search and the sort once per bump; the tab stays mounted (A2). + * `editedAt` is the position of the tile in edit: while the view is not the sheet view it + * keeps the index it had when the view last changed (P23). + */ +export function useReferenceView( + all: readonly Reference[], + citers: ReadonlyMap, + editedAt: number, + resetSignal: number, +) { + const locale = useLocaleStore((state) => state.locale) + const [view, setView] = useState(INITIAL) + const [seen, setSeen] = useState(resetSignal) + const [pinIndex, setPinIndex] = useState(0) + if (seen !== resetSignal) { + setSeen(resetSignal) + setView(INITIAL) + } + const pin = + editedAt >= 0 && !isSheetView(view) + ? { position: editedAt, index: pinIndex } + : null + const context = { + locale, + citedCount: (id: string) => citers.get(id)?.length ?? 0, + } + const positions = shownPositions(all, view, context, pin) + // The count is the matches: a pinned tile the search misses is shown, not counted. + const matchCount = all.filter((r) => referenceMatches(r, view.query)).length + return { + view, + positions, + matchCount, + /** A new search or sort: the tile in edit stays where it is shown now. */ + update: (patch: Partial) => { + setPinIndex(positions.indexOf(editedAt)) + setView((current) => ({ ...current, ...patch })) + }, + reset: () => setView(INITIAL), + /** The tile at `position` enters edit: remember where it is shown. */ + markEdited: (position: number) => setPinIndex(positions.indexOf(position)), + } +} diff --git a/apps/app/src/components/editor/references/useTileState.ts b/apps/app/src/components/editor/references/useTileState.ts index b04d81e8..fbc6c15a 100644 --- a/apps/app/src/components/editor/references/useTileState.ts +++ b/apps/app/src/components/editor/references/useTileState.ts @@ -18,11 +18,20 @@ export function tileKeys(all: readonly Reference[]): string[] { /** * Which tiles are open and which one is in edit. Lives in the library, which the tab keeps * mounted (A2), so both survive a tab change and reset when the editor is reopened. - * Leaving the edit view asks the tile's guard first: a refusal keeps it (P22). + * Leaving the edit view asks the tile's guard first: a refusal keeps it (P22). `keys` are + * the tiles the document has (null while it is not loaded): state of a tile that is gone + * is dropped at once (P23'). */ -export function useTileState() { +export function useTileState(keys: readonly string[] | null) { const [openKeys, setOpenKeys] = useState>(() => new Set()) const [editingKey, setEditingKey] = useState(null) + if (keys !== null) { + const live = new Set(keys) + if ([...openKeys].some((key) => !live.has(key))) { + setOpenKeys(new Set([...openKeys].filter((key) => live.has(key)))) + } + if (editingKey !== null && !live.has(editingKey)) setEditingKey(null) + } const guard = useRef(null) const leave = () => guard.current?.() ?? true const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key)) @@ -40,9 +49,10 @@ export function useTileState() { }) } const startEdit = (key: string) => { - if (editingKey !== null && editingKey !== key && !leave()) return + if (editingKey !== null && editingKey !== key && !leave()) return false setEditingKey(key) open(key) + return true } return { openKeys, diff --git a/apps/app/src/editor/references/referenceTypes.ts b/apps/app/src/editor/references/referenceTypes.ts new file mode 100644 index 00000000..b4fef380 --- /dev/null +++ b/apps/app/src/editor/references/referenceTypes.ts @@ -0,0 +1,11 @@ +import type { ReferenceType } from '@faunosteo/core-wasm/types' + +/** The reference types in business order (the « Type » sort and the pickers). */ +export const REFERENCE_TYPES: readonly ReferenceType[] = [ + 'book', + 'journal', + 'standard', + 'legal', + 'web', + 'manual', +] diff --git a/apps/app/src/editor/references/sort.ts b/apps/app/src/editor/references/sort.ts new file mode 100644 index 00000000..880b59d0 --- /dev/null +++ b/apps/app/src/editor/references/sort.ts @@ -0,0 +1,57 @@ +import type { Reference } from '@faunosteo/core-wasm/types' +import { REFERENCE_TYPES } from './referenceTypes' +import type { Locale } from '@/i18n/types' + +/** The four display orders of the Références tab; `sheet` is the stored order. */ +export const REFERENCE_SORTS = ['sheet', 'citation', 'count', 'type'] as const +export type ReferenceSort = (typeof REFERENCE_SORTS)[number] + +export interface SortContext { + locale: Locale + /** How many findings and families cite each reference id. */ + citedCount: (id: string) => number +} + +/** A type outside the list sorts after the listed ones. */ +const typeRank = (reference: Reference) => { + const rank = REFERENCE_TYPES.indexOf(reference.type) + return rank < 0 ? REFERENCE_TYPES.length : rank +} + +function comparator( + references: readonly Reference[], + sort: ReferenceSort, + context: SortContext, +): (a: number, b: number) => number { + const collator = new Intl.Collator(context.locale, { + sensitivity: 'base', + numeric: true, + }) + const count = (at: number) => context.citedCount(references[at].id) + switch (sort) { + case 'citation': + return (a, b) => + collator.compare(references[a].citation, references[b].citation) + case 'count': + return (a, b) => count(b) - count(a) + case 'type': + return (a, b) => typeRank(references[a]) - typeRank(references[b]) + case 'sheet': + return () => 0 + } +} + +/** + * The positions (indexes into `references`, P31) in display order. Display only: the + * inputs are not touched and a new array is returned. Equal keys keep the stored order, + * so the result never depends on the order of `positions`. + */ +export function sortReferenceIds( + references: readonly Reference[], + positions: readonly number[], + sort: ReferenceSort, + context: SortContext, +): number[] { + const compare = comparator(references, sort, context) + return [...positions].sort((a, b) => compare(a, b) || a - b) +} diff --git a/apps/app/src/editor/references/view.ts b/apps/app/src/editor/references/view.ts new file mode 100644 index 00000000..e2bdc8ca --- /dev/null +++ b/apps/app/src/editor/references/view.ts @@ -0,0 +1,38 @@ +import type { Reference } from '@faunosteo/core-wasm/types' +import { referenceMatches } from './filter' +import { sortReferenceIds, type ReferenceSort, type SortContext } from './sort' + +export interface ReferenceView { + query: string + sort: ReferenceSort +} + +/** Stored order, no search: the only view where ↑ / ↓ mean something (A1). */ +export const isSheetView = (view: ReferenceView) => + view.sort === 'sheet' && view.query.trim() === '' + +/** + * The tile in edit, kept in the shown set at `index` whatever the search or the sort + * (P23); only worth passing when the view is not the sheet view. + */ +export interface Pin { + position: number + index: number +} + +/** The positions to show: the search, then the sort, then the pinned tile put back. */ +export function shownPositions( + references: readonly Reference[], + view: ReferenceView, + context: SortContext, + pin: Pin | null, +): number[] { + const matching = references.flatMap((reference, position) => + referenceMatches(reference, view.query) ? [position] : [], + ) + const sorted = sortReferenceIds(references, matching, view.sort, context) + if (pin === null) return sorted + const rest = sorted.filter((position) => position !== pin.position) + rest.splice(Math.min(pin.index, rest.length), 0, pin.position) + return rest +} diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 07a12a90..21baa199 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1232,7 +1232,6 @@ export const en: Dict = { '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.references.uncited': 'Not cited', @@ -1249,6 +1248,21 @@ export const en: Dict = { 'editor.references.none_url': 'None', 'editor.references.new_tab': '(new tab)', 'editor.references.delete_hint': "To delete this reference, first remove each of its citations: “Go to”, then “Remove” in the finding's or family's detail.", + 'editor.references.add': 'Add a reference', + 'editor.references.add_help': 'Type and citation required.', + 'editor.references.clear_search': 'Clear the search', + 'editor.references.sort_by': 'Sort by', + 'editor.references.sort.sheet': 'Sheet order', + 'editor.references.sort.citation': 'Citation (A → Z)', + 'editor.references.sort.count': 'Number of citations', + 'editor.references.sort.type': 'Type', + 'editor.references.count_one': '{count} reference', + 'editor.references.count_other': '{count} references', + 'editor.references.count_of_one': '{count} reference of {total}', + 'editor.references.count_of_other': '{count} references of {total}', + 'editor.references.reorder_hint': 'To reorder, show the sheet order without a search.', + 'editor.references.no_result': 'No reference contains “{q}”.', + 'editor.references.no_result_scope': 'The search covers the citation, the DOI and the URL.', 'editor.findings.references_open_one': '{count} reference', 'editor.findings.references_open_other': '{count} references', 'editor.draft.loading': 'Loading the draft…', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index fbb2bc09..9eff4c54 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1263,7 +1263,6 @@ export const fr: Dict = { '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.references.uncited': 'Non citée', @@ -1280,6 +1279,21 @@ export const fr: Dict = { 'editor.references.none_url': 'Aucune', 'editor.references.new_tab': '(nouvel onglet)', 'editor.references.delete_hint': 'Pour supprimer cette référence, retirez d\'abord chacune de ses citations : « Aller à », puis « Retirer » dans le détail du constat ou de la famille.', + 'editor.references.add': 'Ajouter une référence', + 'editor.references.add_help': 'Type et citation obligatoires.', + 'editor.references.clear_search': 'Effacer la recherche', + 'editor.references.sort_by': 'Trier par', + 'editor.references.sort.sheet': 'Ordre de la fiche', + 'editor.references.sort.citation': 'Citation (A → Z)', + 'editor.references.sort.count': 'Nombre de citations', + 'editor.references.sort.type': 'Type', + 'editor.references.count_one': '{count} référence', + 'editor.references.count_other': '{count} références', + 'editor.references.count_of_one': '{count} référence sur {total}', + 'editor.references.count_of_other': '{count} références sur {total}', + 'editor.references.reorder_hint': 'Pour réorganiser, affichez l\'ordre de la fiche sans recherche.', + 'editor.references.no_result': 'Aucune référence ne contient « {q} ».', + 'editor.references.no_result_scope': 'La recherche porte sur la citation, le DOI et l\'URL.', 'editor.findings.references_open_one': '{count} référence', 'editor.findings.references_open_other': '{count} références', 'editor.draft.loading': 'Chargement du brouillon…', diff --git a/apps/app/tests/unit/editor-keep-alive.test.tsx b/apps/app/tests/unit/editor-keep-alive.test.tsx index d0cc5a7b..d00a783d 100644 --- a/apps/app/tests/unit/editor-keep-alive.test.tsx +++ b/apps/app/tests/unit/editor-keep-alive.test.tsx @@ -202,6 +202,9 @@ describe('text typed in a place that is left', () => { it('the reference add form survives leaving and returning to the Références tab', async () => { const user = await mount() await user.click(tab('Références')) + await user.click( + inPlace('references').getByRole('button', { name: 'Ajouter une référence' }), + ) const field = inPlace('references').getByLabelText('Citation', { selector: '#tab-reference-new-citation', }) diff --git a/apps/app/tests/unit/editor-no-loss.test.tsx b/apps/app/tests/unit/editor-no-loss.test.tsx index ae1cb4d6..e15c3af0 100644 --- a/apps/app/tests/unit/editor-no-loss.test.tsx +++ b/apps/app/tests/unit/editor-no-loss.test.tsx @@ -146,6 +146,7 @@ describe('typed values come back after a 1 024 px crossing', () => { it('the reference creation form, in the Références tab', async () => { const user = await mount() await user.click(tab('Références')) + await user.click(button('Ajouter une référence')) await keepsTypedValue( user, 'tab-reference-new-citation', diff --git a/apps/app/tests/unit/editor-reference-sort.test.ts b/apps/app/tests/unit/editor-reference-sort.test.ts new file mode 100644 index 00000000..bc4e144c --- /dev/null +++ b/apps/app/tests/unit/editor-reference-sort.test.ts @@ -0,0 +1,147 @@ +/** R2.3: the four display orders and the shown set are pure and never touch their inputs. */ +import { describe, expect, it } from 'vitest' +import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types' +import { sortReferenceIds } from '@/editor/references/sort' +import { shownPositions } from '@/editor/references/view' + +const ref = (id: string, citation: string, type: ReferenceType): Reference => ({ + id, + type, + citation, + url: null, + doi: null, +}) + +// Accents, case, numbers, equal citations and mixed types, in stored order r1..r5. +const refs: readonly Reference[] = [ + ref('r1', 'Zèbre 10', 'web'), + ref('r2', 'zebre 9', 'journal'), + ref('r3', 'Étude', 'book'), + ref('r4', 'etude', 'book'), + ref('r5', 'Alpha', 'legal'), +] +const COUNTS: Record = { r1: 1, r2: 2, r5: 1 } +const context = { + locale: 'fr' as const, + citedCount: (id: string) => COUNTS[id] ?? 0, +} +const all = [0, 1, 2, 3, 4] +const ids = (positions: number[]) => positions.map((at) => refs[at].id) + +function permutations(items: readonly T[]): T[][] { + if (items.length < 2) return [[...items]] + return items.flatMap((item, at) => + permutations([...items.slice(0, at), ...items.slice(at + 1)]).map( + (rest) => [item, ...rest], + ), + ) +} + +describe('sortReferenceIds', () => { + it('sheet keeps the stored order', () => { + expect(ids(sortReferenceIds(refs, all, 'sheet', context))).toEqual([ + 'r1', + 'r2', + 'r3', + 'r4', + 'r5', + ]) + }) + + it('citation: collator, accents and case ignored, numbers by value, ties stored', () => { + expect(ids(sortReferenceIds(refs, all, 'citation', context))).toEqual([ + 'r5', + 'r3', + 'r4', + 'r2', + 'r1', + ]) + }) + + it('count: most cited first, ties in sheet order', () => { + expect(ids(sortReferenceIds(refs, all, 'count', context))).toEqual([ + 'r2', + 'r1', + 'r5', + 'r3', + 'r4', + ]) + }) + + it('type: REFERENCE_TYPES order, ties in sheet order', () => { + expect(ids(sortReferenceIds(refs, all, 'type', context))).toEqual([ + 'r3', + 'r4', + 'r2', + 'r5', + 'r1', + ]) + }) + + it('a type outside the list sorts after the listed ones, stored order among them', () => { + const odd = [ + ref('x1', 'a', 'unknown' as ReferenceType), + ref('x2', 'b', 'web'), + ref('x3', 'c', 'other' as ReferenceType), + ] + expect( + sortReferenceIds(odd, [0, 1, 2], 'type', context).map((at) => odd[at].id), + ).toEqual(['x2', 'x1', 'x3']) + }) + + it('every permutation of the input gives the same output', () => { + for (const sort of ['sheet', 'citation', 'count', 'type'] as const) { + const expected = sortReferenceIds(refs, all, sort, context) + for (const input of permutations(all)) { + expect(sortReferenceIds(refs, input, sort, context)).toEqual(expected) + } + } + }) + + it('returns a new array and leaves frozen inputs untouched', () => { + const frozen = Object.freeze([...refs.map((r) => Object.freeze({ ...r }))]) + const positions = Object.freeze([4, 3, 2, 1, 0]) + const out = sortReferenceIds(frozen, positions, 'citation', context) + expect(out).not.toBe(positions) + expect(positions).toEqual([4, 3, 2, 1, 0]) + expect(frozen.map((r) => r.id)).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']) + }) + + it('numbers in English too', () => { + const en = { ...context, locale: 'en' as const } + expect(ids(sortReferenceIds(refs, all, 'citation', en))[3]).toBe('r2') + }) +}) + +describe('shownPositions', () => { + const view = { query: '', sort: 'citation' } as const + + it('searches, then sorts', () => { + expect( + ids( + shownPositions( + refs, + { query: 'ZEBRE', sort: 'citation' }, + context, + null, + ), + ), + ).toEqual(['r2', 'r1']) + }) + + it('puts the pinned tile back at its index, hidden by the search or not', () => { + const search = { query: 'etude', sort: 'citation' } as const + const pinned = shownPositions(refs, search, context, { + position: 0, + index: 1, + }) + expect(ids(pinned)).toEqual(['r3', 'r1', 'r4']) + const clamped = shownPositions(refs, view, context, { + position: 0, + index: 99, + }) + expect(ids(clamped)).toEqual(['r5', 'r3', 'r4', 'r2', 'r1']) + const first = shownPositions(refs, view, context, { position: 1, index: 0 }) + expect(ids(first)).toEqual(['r2', 'r5', 'r3', 'r4', 'r1']) + }) +}) diff --git a/apps/app/tests/unit/editor-references-tab.test.tsx b/apps/app/tests/unit/editor-references-tab.test.tsx index 4b512c1a..625cd5a4 100644 --- a/apps/app/tests/unit/editor-references-tab.test.tsx +++ b/apps/app/tests/unit/editor-references-tab.test.tsx @@ -155,9 +155,7 @@ describe('the Références tab', () => { expect( tabPanel().querySelector('#tab-reference-0-ref-a-header'), ).not.toBeNull() - expect( - tabPanel().querySelector('#tab-reference-new-citation'), - ).not.toBeNull() + expect(tabPanel().querySelector('#tab-reference-new-citation')).toBeNull() }) it('matches the citation, the DOI and the URL, ignoring case and accents', async () => { @@ -173,7 +171,7 @@ describe('the Références tab', () => { await user.clear(search()) await user.type(search(), 'zzz') expect( - within(tabPanel()).getByText('Aucune référence ne correspond.'), + within(tabPanel()).getByText('Aucune référence ne contient « zzz ».'), ).toBeInTheDocument() }) @@ -281,7 +279,10 @@ describe('the reset signal', () => { }) describe('adding a reference', () => { + const addButton = () => + within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' }) async function add(user: User) { + await user.click(addButton()) const byId = (id: string) => tabPanel().querySelector(id)! await user.selectOptions(byId('#tab-reference-new-type'), 'book') await user.type(byId('#tab-reference-new-citation'), 'Nouvelle source') @@ -290,23 +291,33 @@ describe('adding a reference', () => { ) } - it('clears the search so the new reference shows', async () => { + it('resets the search, shows the new tile open and focuses its button', async () => { const user = await mount() await user.type(search(), 'Barone') expect(cards()).toHaveLength(1) await add(user) expect(search()).toHaveValue('') expect(cards()).toHaveLength(4) - expect(header('Nouvelle source')).toBeInTheDocument() + expect(header('Nouvelle source')).toHaveAttribute('aria-expanded', 'true') + expect(document.activeElement).toBe(header('Nouvelle source')) + expect(within(tabPanel()).queryByLabelText('Citation')).toBeNull() }) - it('a refused add keeps the search', async () => { + it('opens a draft tile with the citation focused, and a refused add keeps it', async () => { const user = await mount() await user.type(search(), 'Barone') + await user.click(addButton()) + expect(search()).toHaveValue('') + expect(document.activeElement).toBe( + tabPanel().querySelector('#tab-reference-new-citation'), + ) await user.click( within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }), ) - expect(search()).toHaveValue('Barone') + expect(within(tabPanel()).getByRole('alert')).toHaveTextContent( + 'Choisissez un type', + ) + expect(doc().references).toHaveLength(3) }) }) diff --git a/apps/app/tests/unit/editor-references-view.test.tsx b/apps/app/tests/unit/editor-references-view.test.tsx new file mode 100644 index 00000000..5886297c --- /dev/null +++ b/apps/app/tests/unit/editor-references-view.test.tsx @@ -0,0 +1,489 @@ +/** R2.3: search, sort, count, no-result notice, A1, the add flow, the pin and the reset. */ +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 { targetOfKey } from '@/editor/navigation' +import { useLocaleStore } from '@/state/localeStore' +import { edit, insert } from '../helpers/editorFixtures' +import { + baseText, + openReady, + resetStore, + store, +} from '../helpers/editorHarness' + +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() +}) + +const name = (n: string) => ({ fr: n, en: n }) +const ref = (id: string, citation: string, type: ReferenceType) => + ({ + kind: 'reference', + value: { id, type, citation, url: null, doi: null }, + }) as const + +/** Stored order r1..r5; counts r2: 2, r1: 1, r5: 1, r3: 0, r4: 0. */ +function sortText(): string { + let text = baseText() + text = insert(text, ref('r1', 'Zèbre 10', 'web')) + text = insert(text, ref('r2', 'zebre 9', 'journal')) + text = insert(text, ref('r3', 'Étude', 'book')) + text = insert(text, ref('r4', 'etude', 'book')) + text = insert(text, ref('r5', 'Alpha', 'legal')) + text = insert(text, { + kind: 'zone', + value: { id: 'zone-a', name: name('Zone A'), 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 A'), + description: {}, + reference_ids: ['r1', 'r2', 'r5'], + review_status: 'to_confirm', + children: [], + }, + }, + }) + return 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 A'), + description: {}, + requires_vet_referral: false, + reference_ids: ['r2'], + review_status: 'to_confirm', + children: [], + }, + }, + }) +} + +type User = ReturnType +const doc = () => JSON.parse(store.getState().documentText) +const lib = (readOnly = false, extra = {}) => ( + +) +async function mount(readOnly = false) { + await openReady({ text: sortText() }) + const user = userEvent.setup() + const view = render(lib(readOnly)) + return { user, view } +} + +const search = () => + screen.getByRole('searchbox', { name: 'Rechercher une référence' }) +const sortBox = () => screen.getByLabelText('Trier par') +/** The ids shown, in display order (header ids `tab-reference---header`). */ +const order = () => + [...document.querySelectorAll('button[id$="-header"]')].map((button) => + button.id.replace(/^tab-reference-\d+-(.*)-header$/, '$1'), + ) +const header = (id: string) => + document.querySelector(`button[id$="-${id}-header"]`)! +const snapshot = () => ({ + text: store.getState().documentText, + history: store.getState().undo.length, + unsaved: store.getState().unsaved, +}) + +describe('the four sorts', () => { + it('reorder the tiles for display, each stable on ties', async () => { + const { user } = await mount() + expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']) + await user.selectOptions(sortBox(), 'citation') + expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1']) + await user.selectOptions(sortBox(), 'count') + expect(order()).toEqual(['r2', 'r1', 'r5', 'r3', 'r4']) + await user.selectOptions(sortBox(), 'type') + expect(order()).toEqual(['r3', 'r4', 'r2', 'r5', 'r1']) + await user.selectOptions(sortBox(), 'sheet') + expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']) + }) + + it('offers the four labelled options', async () => { + await mount() + const labels = within(sortBox()) + .getAllByRole('option') + .map((option) => option.textContent) + expect(labels).toEqual([ + 'Ordre de la fiche', + 'Citation (A → Z)', + 'Nombre de citations', + 'Type', + ]) + }) + + it('keep the document, its stored order and the history untouched (BDR-114)', async () => { + const { user } = await mount() + const before = snapshot() + for (const sort of ['citation', 'count', 'type', 'sheet']) { + await user.selectOptions(sortBox(), sort) + } + await user.type(search(), 'zebre') + await user.selectOptions(sortBox(), 'citation') + await user.clear(search()) + await user.type(search(), 'zzz') + await user.click( + screen.getAllByRole('button', { name: 'Effacer la recherche' })[0], + ) + expect(snapshot()).toEqual(before) + expect(doc().references.map((r: { id: string }) => r.id)).toEqual([ + 'r1', + 'r2', + 'r3', + 'r4', + 'r5', + ]) + }) +}) + +describe('the count line', () => { + it('says « {n} références », then « {n} références sur {total} »', async () => { + const { user } = await mount() + expect(screen.getByText('5 références')).toBeInTheDocument() + await user.type(search(), 'zebre') + expect(screen.getByText('2 références sur 5')).toBeInTheDocument() + await user.clear(search()) + await user.type(search(), 'alpha') + expect(screen.getByText('1 référence sur 5')).toBeInTheDocument() + await user.clear(search()) + await user.type(search(), 'zzz') + expect(screen.getByText('0 référence sur 5')).toBeInTheDocument() + }) +}) + +describe('the count with a pinned tile', () => { + it('counts the matches only, the pinned tile stays shown', async () => { + const { user } = await mount() + await startEdit(user, 'r1') + await user.type(search(), 'alpha') + expect(order()).toEqual(['r1', 'r5']) + expect(screen.getByText('1 référence sur 5')).toBeInTheDocument() + }) +}) + +describe('clearing the search', () => { + it('the button appears with a query, empties it and refocuses the field', async () => { + const { user } = await mount() + expect( + screen.queryByRole('button', { name: 'Effacer la recherche' }), + ).toBeNull() + await user.type(search(), 'etude') + expect(order()).toEqual(['r3', 'r4']) + await user.click( + screen.getByRole('button', { name: 'Effacer la recherche' }), + ) + expect(search()).toHaveValue('') + expect(document.activeElement).toBe(search()) + expect(order()).toHaveLength(5) + }) + + it('Escape empties a non-empty search and stops there (P12)', async () => { + const { user } = await mount() + const bubbled = vi.fn() + document.body.addEventListener('keydown', bubbled) + await user.type(search(), 'etude') + await user.keyboard('{Escape}') + expect(search()).toHaveValue('') + expect(bubbled.mock.calls.at(-1)?.[0].defaultPrevented).toBe(true) + bubbled.mockClear() + await user.keyboard('{Escape}') + expect(bubbled).toHaveBeenCalledTimes(1) + expect(bubbled.mock.calls[0][0].defaultPrevented).toBe(false) + document.body.removeEventListener('keydown', bubbled) + }) +}) + +describe('no result (board 24 B)', () => { + it('shows the notice with its own clear button, and no reorder hint', async () => { + const { user } = await mount() + await user.type(search(), 'radiographie') + expect(order()).toEqual([]) + const notice = screen.getByRole('status', { + name: '', + }) + expect(notice).toHaveTextContent( + "Aucune référence ne contient « radiographie ». La recherche porte sur la citation, le DOI et l'URL.", + ) + expect(screen.queryByText(/Pour réorganiser/)).toBeNull() + await user.click( + within(notice).getByRole('button', { name: 'Effacer la recherche' }), + ) + expect(search()).toHaveValue('') + expect(document.activeElement).toBe(search()) + expect(order()).toHaveLength(5) + }) +}) + +describe('the move buttons (A1)', () => { + const movers = () => screen.queryAllByRole('button', { name: 'Descendre' }) + const hint = () => screen.queryByText(/Pour réorganiser, affichez/) + const openAll = async (user: User) => { + for (const button of document.querySelectorAll( + 'button[id$="-header"]', + )) { + await user.click(button) + } + } + + it('exist only in sheet order without a search', async () => { + const { user } = await mount() + await openAll(user) + expect(movers()).toHaveLength(5) + expect(hint()).toBeNull() + await user.selectOptions(sortBox(), 'citation') + expect(movers()).toHaveLength(0) + expect(hint()).not.toBeNull() + await user.selectOptions(sortBox(), 'sheet') + expect(movers()).toHaveLength(5) + await user.type(search(), 'e') + expect(movers()).toHaveLength(0) + expect(hint()).not.toBeNull() + await user.selectOptions(sortBox(), 'type') + expect(movers()).toHaveLength(0) + await user.clear(search()) + expect(movers()).toHaveLength(0) + expect(hint()).not.toBeNull() + }) + + it('are absent in read-only, and so is the hint', async () => { + const { user } = await mount(true) + await openAll(user) + await user.selectOptions(sortBox(), 'count') + expect(movers()).toHaveLength(0) + expect(hint()).toBeNull() + expect( + screen.queryByRole('button', { name: 'Ajouter une référence' }), + ).toBeNull() + }) +}) + +/** Opens the tile of `id` and enters edit. */ +async function startEdit(user: User, id: string) { + await user.click(header(id)) + const item = header(id).closest('li')! + await user.click(within(item).getByRole('button', { name: 'Modifier' })) + return item +} + +describe('the tile in edit is pinned (P23)', () => { + it('keeps its index when the sort changes', async () => { + const { user } = await mount() + await user.selectOptions(sortBox(), 'citation') + await startEdit(user, 'r1') + expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1']) + await user.selectOptions(sortBox(), 'count') + expect(order()).toEqual(['r2', 'r5', 'r3', 'r4', 'r1']) + await user.selectOptions(sortBox(), 'sheet') + expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']) + }) + + it('starts in sheet order and holds its place under a later sort', async () => { + const { user } = await mount() + await startEdit(user, 'r3') + await user.selectOptions(sortBox(), 'citation') + expect(order()).toEqual(['r5', 'r4', 'r3', 'r2', 'r1']) + }) + + it('stays shown under a search that does not match it, until it leaves edit', async () => { + const { user } = await mount() + const item = await startEdit(user, 'r1') + await user.type(search(), 'alpha') + expect(order()).toEqual(['r1', 'r5']) + expect(within(item).getByLabelText('Citation')).toBeInTheDocument() + await user.click(within(item).getByRole('button', { name: 'Terminer' })) + expect(order()).toEqual(['r5']) + }) + + it('is suspended in read-only: the tile renders its read view', async () => { + const { user, view } = await mount() + await startEdit(user, 'r1') + await user.selectOptions(sortBox(), 'citation') + view.rerender(lib(true)) + expect(screen.queryByLabelText('Citation')).toBeNull() + expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1']) + await user.type(search(), 'alpha') + expect(order()).toEqual(['r5']) + }) +}) + +describe('adding (P24)', () => { + const add = () => + screen.getByRole('button', { name: 'Ajouter une référence' }) + const draftCitation = () => + document.querySelector('#tab-reference-new-citation') + + it('resets search and sort, appends a draft tile in edit, citation focused', async () => { + const { user } = await mount() + await user.selectOptions(sortBox(), 'count') + await user.type(search(), 'e') + await user.click(add()) + expect(search()).toHaveValue('') + expect(sortBox()).toHaveValue('sheet') + expect(order()).toHaveLength(5) + expect(document.activeElement).toBe(draftCitation()) + expect(screen.getByLabelText('Type')).toHaveValue('') + expect( + within(screen.getByLabelText('Type')).getByText('Choisir…'), + ).toBeInTheDocument() + expect( + screen.getByText('Type et citation obligatoires.'), + ).toBeInTheDocument() + expect(snapshot().history).toBe(0) + }) + + it('creates the reference in one modification; the tile stays open, out of edit, focused', async () => { + const { user } = await mount() + await user.click(add()) + await user.selectOptions(screen.getByLabelText('Type'), 'book') + await user.type(draftCitation()!, 'Nouvelle source') + await user.click( + screen.getByRole('button', { name: 'Ajouter la référence' }), + ) + expect(store.getState().undo.length).toBe(1) + expect(doc().references).toHaveLength(6) + const id = doc().references[5].id + expect(order()).toHaveLength(6) + expect(header(id)).toHaveAttribute('aria-expanded', 'true') + expect(document.activeElement).toBe(header(id)) + expect(draftCitation()).toBeNull() + expect( + within(header(id).closest('li')!).getByRole('button', { + name: 'Modifier', + }), + ).toBeInTheDocument() + }) + + it('a second click on the button takes the focus back to the citation', async () => { + const { user } = await mount() + await user.click(add()) + await user.click(search()) + await user.click(add()) + expect(document.activeElement).toBe(draftCitation()) + expect( + document.querySelectorAll('#tab-reference-new-citation'), + ).toHaveLength(1) + }) + + it('leaves the tile in edit first: a refused field cancels the add (P22)', async () => { + const { user } = await mount() + const item = await startEdit(user, 'r1') + const url = within(item).getByLabelText('Adresse web (URL)') + await user.type(url, 'exemple.org') + await user.click(add()) + expect(draftCitation()).toBeNull() + expect(document.activeElement).toBe(url) + await user.clear(url) + await user.click(add()) + expect(draftCitation()).not.toBeNull() + expect(within(item).queryByLabelText('Citation')).toBeNull() + }) + + it('keeps the draft hidden in read-only and resumes it when editable again', async () => { + const { user, view } = await mount() + await user.click(add()) + await user.type(draftCitation()!, 'En cours') + view.rerender(lib(true)) + expect(draftCitation()).not.toBeVisible() + view.rerender(lib(false)) + expect(draftCitation()).toBeVisible() + expect(draftCitation()).toHaveValue('En cours') + }) +}) + +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 })) + 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 })) + expect(search()).toHaveValue('') + expect(sortBox()).toHaveValue('sheet') + expect(order()).toHaveLength(5) + expect(header('r2')).toHaveAttribute('aria-expanded', 'true') + expect(within(item).getByLabelText('Citation')).toBeInTheDocument() + }) +}) + +describe('« Aller à » a reference hidden by the search (P3, P8)', () => { + const request = (id: string, serial: number) => ({ + target: targetOfKey({ kind: 'reference', id }), + serial, + }) + + it('clears the search only, opens the tile, focuses its button, keeps other tiles open', async () => { + const { user, view } = await mount() + await user.click(header('r2')) + await user.selectOptions(sortBox(), 'citation') + await user.type(search(), 'alpha') + await act(async () => + view.rerender(lib(false, { focus: request('r3', 1) })), + ) + expect(search()).toHaveValue('') + expect(sortBox()).toHaveValue('citation') + expect(header('r3')).toHaveAttribute('aria-expanded', 'true') + expect(header('r2')).toHaveAttribute('aria-expanded', 'true') + expect(document.activeElement).toBe(header('r3')) + }) + + it('keeps a search that does not hide it', async () => { + const { user, view } = await mount() + await user.type(search(), 'etude') + await act(async () => + view.rerender(lib(false, { focus: request('r4', 1) })), + ) + expect(search()).toHaveValue('etude') + expect(document.activeElement).toBe(header('r4')) + expect(header('r4')).toHaveAttribute('aria-expanded', 'true') + }) +}) + +describe('state of a reference that left the document (P23-prime)', () => { + it('is dropped: undoing the removal brings the tile back closed and out of edit', async () => { + const { user } = await mount() + await startEdit(user, 'r4') + act(() => { + store + .getState() + .commit({ op: 'remove', key: { kind: 'reference', id: 'r4' } }) + }) + expect(order()).toEqual(['r1', 'r2', 'r3', 'r5']) + act(() => { + store.getState().undoStep() + }) + expect(order()).toContain('r4') + expect(header('r4')).toHaveAttribute('aria-expanded', 'false') + expect( + within(header('r4').closest('li')!).queryByLabelText('Citation'), + ).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/editor-tabs-lists.test.tsx b/apps/app/tests/unit/editor-tabs-lists.test.tsx index 7ecb0b6a..a7be5998 100644 --- a/apps/app/tests/unit/editor-tabs-lists.test.tsx +++ b/apps/app/tests/unit/editor-tabs-lists.test.tsx @@ -45,6 +45,9 @@ describe('Références', () => { await openReady() const user = userEvent.setup() render() + await user.click( + screen.getByRole('button', { name: 'Ajouter une référence' }), + ) await user.click( screen.getByRole('button', { name: 'Ajouter la référence' }), )