feat(editor): search, sort, count and add in the Références tab

Search (citation, DOI, URL) with « Effacer la recherche » and Escape;
« Trier par » sheet order, citation (locale collator), citation count,
type (business order); every sort stable on stored order, display only:
document, stored order, ids and history unchanged (unit + e2e). Count
« {n} références » / « {n} sur {total} » counts matching references
only. « Monter » / « Descendre » only in sheet order without search
(A1). « Ajouter une référence » resets search and sort and appends a
draft tile in edit; a tile in edit stays pinned while sorted or
searched; tile state pruned of absent ids. Reset path ready for « Tout
afficher » (R2.4).

Gates: typecheck, lint, test:run (app 1452), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (editor-equine never listed): 115
passed / 102 skipped / 2 failed: editor-structures (test-side, fixed,
rerun with editor-references 12 passed / 11 skipped) and admin.spec A0
« Target crashed » during axe on the rights screen (not R2: that
screen renders every grant, 1 282 accumulated e2e fixtures; reported as
an open risk); full-row guard: no pre-existing row changed in any table.

## R-24 (removed or rewritten assertions)
| file | old | new |
|---|---|---|
| editor-references-tab.test.tsx | `#tab-reference-new-citation` present on load | null until « Ajouter une référence » |
| same | no match text « Aucune référence ne correspond. » | notice « Aucune référence ne contient « zzz ». » |
| same | add: form always visible, add clears the search, `getByText('Nouvelle source')` | click « Ajouter une référence » first; new tile header open, focused, search empty, 4 tiles |
| same | « a refused add keeps the search » | REMOVED (P24: add resets the search at once); replaced by « draft opens with citation focused, refused add keeps the draft, no write » |
| editor-tabs-lists.test.tsx | add form directly | click « Ajouter une référence » before the form assertions (same assertions after) |
| editor-keep-alive.test.tsx | form survives tab round trip | same, after opening the draft |
| editor-no-loss.test.tsx | reference form keeps typed text | same, after opening the draft |
| e2e editor-shell.spec (2), editor-shell-crossing.spec, editor-structures.spec | fill `#tab-reference-new-*` directly; `getByText(citation)` visible | open the draft first; structures asserts the new header is focused |
| e2e editor-references.spec keyboard walk | focus search, Tab reaches header 0 | focus « Ajouter une référence » (search, sort, add precede the headers) |
Other readers of `editor.reference.add`/new ids: grep of src, tests, e2e incl. editor-equine found none left unlisted. editor-equine is not affected ("updated, not run": nothing to update).

## i18n (fr / en)
Added: `editor.references.add` Ajouter une référence / Add a reference; `add_help` Type et citation obligatoires. / Type and citation required.; `clear_search` Effacer la recherche / Clear the search; `sort_by` Trier par / Sort by; `sort.sheet|citation|count|type` Ordre de la fiche, Citation (A → Z), Nombre de citations, Type / Sheet order, Citation (A → Z), Number of citations, Type; `count_one|other` {count} référence(s) / reference(s); `count_of_one|other` {count} référence(s) sur {total} / {count} reference(s) of {total}; `reorder_hint` Pour réorganiser, affichez l'ordre de la fiche sans recherche. / To reorder, show the sheet order without a search.; `no_result` Aucune référence ne contient « {q} ». / No reference contains “{q}”.; `no_result_scope` La recherche porte sur la citation, le DOI et l'URL. / The search covers the citation, the DOI and the URL. (REVUE sentence split in two keys so the first half is bold).
Changed: none. Removed: none (`editor.references.no_match` kept, the panel's EmptyLine still uses it).
This commit is contained in:
bchanot committed 2026-11-12 21:18:56 +01:00
1 parent c21995b3fb
commit 3baac4dbb5
26 files changed
+1544 -219

No files matched your search

+240 -3
View File
@@ -13,7 +13,10 @@ import {
openEditor, openEditor,
openTab, openTab,
place, place,
saveDraft,
seedDraft, seedDraft,
serverDocument,
serverRevision,
standardShape, standardShape,
} from '../support/editor' } from '../support/editor'
@@ -59,9 +62,9 @@ function shape(document: Record<string, unknown>) {
family.reference_ids = ['ref-doi'] family.reference_ids = ['ref-doi']
} }
async function open(page: Page) { async function open(page: Page, seedShape = shape) {
const actor = await editorActor('fr') 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) await openEditor(page, dict, actor, seed.sheetId)
return { actor, seed } return { actor, seed }
} }
@@ -187,8 +190,9 @@ test.describe('reference tiles, edit mode', () => {
test.setTimeout(120_000) test.setTimeout(120_000)
await open(page) await open(page)
await openTab(page, dict, 'references') await openTab(page, dict, 'references')
// The toolbar's last stop (search, sort, add) precedes the first header.
await page await page
.getByRole('searchbox', { name: dict['editor.references.search'] }) .getByRole('button', { name: dict['editor.references.add'] })
.focus() .focus()
for (let at = 0; at < 3; at++) { for (let at = 0; at < 3; at++) {
await page.keyboard.press('Tab') 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<string, unknown>) {
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.describe('reference tiles, read-only at 375 px', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => { test.beforeEach(async ({ context }, info) => {
@@ -242,6 +456,29 @@ test.describe('reference tiles, read-only at 375 px', () => {
await expect(headers(page)).toHaveCount(3) await expect(headers(page)).toHaveCount(3)
const box = await headers(page).first().boundingBox() const box = await headers(page).first().boundingBox()
expect(box?.height ?? 0).toBeGreaterThanOrEqual(44) 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 expectNoHorizontalOverflow(page, 'the closed tiles at 375 px')
await expectAccessible(page, 'the closed tiles at 375 px') await expectAccessible(page, 'the closed tiles at 375 px')
await headers(page).nth(1).click() await headers(page).nth(1).click()
@@ -196,6 +196,9 @@ test.describe('editor shell, width crossing (H)', () => {
}) => { }) => {
await open(page) await open(page)
await openTab(page, dict, 'references') await openTab(page, dict, 'references')
await page
.getByRole('button', { name: dict['editor.references.add'] })
.click()
await keepsTypedValue( await keepsTypedValue(
page, page,
page.locator('#tab-reference-new-citation'), page.locator('#tab-reference-new-citation'),
+6
View File
@@ -98,6 +98,9 @@ test.describe('editor shell, kept places (B2a)', () => {
}) => { }) => {
await open(page) await open(page)
await openTab(page, dict, 'references') 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 page.locator('#tab-reference-new-citation').fill('Smith 1999')
await openTab(page, dict, 'general') await openTab(page, dict, 'general')
await openTab(page, dict, 'references') await openTab(page, dict, 'references')
@@ -128,6 +131,9 @@ test.describe('editor shell, kept places (B2a)', () => {
await open(page) await open(page)
// An edit first, so « Enregistrer » is enabled: a reference added in its tab. // An edit first, so « Enregistrer » is enabled: a reference added in its tab.
await openTab(page, dict, 'references') 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-type').selectOption('book')
await page.locator('#tab-reference-new-citation').fill('Smith 1999') await page.locator('#tab-reference-new-citation').fill('Smith 1999')
await page await page
+13 -3
View File
@@ -80,12 +80,17 @@ test.describe('editor structures (A4)', () => {
// « Référence A » stays first: it is cited by « Constat A »). // « Référence A » stays first: it is cited by « Constat A »).
await openTab(page, dict, 'references') await openTab(page, dict, 'references')
for (const citation of ['Première référence', 'Seconde référence']) { 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-type').selectOption('book')
await page.locator('#tab-reference-new-citation').fill(citation) await page.locator('#tab-reference-new-citation').fill(citation)
await page await page
.getByRole('button', { name: dict['editor.reference.add'] }) .getByRole('button', { name: dict['editor.reference.add'] })
.click() .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 tiles = page.locator('[id^="tab-reference-"][id$="-header"]')
const tileOf = (citation: string) => const tileOf = (citation: string) =>
@@ -102,12 +107,17 @@ test.describe('editor structures (A4)', () => {
await expect(tiles).toHaveCount(1) await expect(tiles).toHaveCount(1)
await search.fill('') await search.fill('')
await expect(tiles).toHaveCount(3) 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') await tileOf('Seconde référence')
.getByRole('button', { name: dict['editor.action.move_up'] }) .getByRole('button', { name: dict['editor.action.move_up'] })
.click() .click()
await expect(tiles.nth(1)).toContainText('Seconde référence') 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') await tileOf('Première référence')
.getByRole('button', { name: dict['editor.action.delete'] }) .getByRole('button', { name: dict['editor.action.delete'] })
.click() .click()
@@ -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<typeof EMPTY>) => 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 (
<section
aria-label={t('editor.reference.new')}
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
>
<div className="flex items-center gap-3 p-3">
<Icon name="chevron-down" size={18} />
<h3 className="text-sm font-semibold">{t('editor.reference.new')}</h3>
</div>
<div className="space-y-3 border-t border-[var(--color-border)] p-3">
<div className="grid gap-3 sm:grid-cols-2">
<SelectField
id={`${ID}-type`}
label={t('editor.reference.type')}
value={form.type}
options={options}
onCommit={(type) => set({ type })}
/>
<DraftField
id={`${ID}-doi`}
label={t('editor.reference.doi')}
value={form.doi}
onChange={(doi) => set({ doi })}
/>
</div>
<DraftField
id={`${ID}-citation`}
label={t('editor.reference.citation')}
value={form.citation}
onChange={(citation) => set({ citation })}
multiline
/>
<DraftField
id={`${ID}-url`}
label={t('editor.reference.url')}
value={form.url}
onChange={(url) => set({ url })}
/>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<div className="flex flex-wrap items-center gap-3">
<ActionButton readOnly={false} variant="primary" onClick={create}>
{t('editor.reference.add')}
</ActionButton>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.add_help')}
</p>
</div>
</div>
</section>
)
}
@@ -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 (
<div
role="status"
className="space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3 text-sm"
>
<p>
<strong>
{t('editor.references.no_result').replace('{q}', query.trim())}
</strong>{' '}
{t('editor.references.no_result_scope')}
</p>
<Button type="button" variant="secondary" size="sm" onClick={onClear}>
<Icon name="close" size={14} className="mr-1" />
{t('editor.references.clear_search')}
</Button>
</div>
)
}
@@ -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<typeof EMPTY>) => 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 (
<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">
<SelectField
id={`${host}-reference-new-type`}
label={t('editor.reference.type')}
value={form.type}
options={options}
onCommit={(type) => set({ type })}
/>
<DraftField
id={`${host}-reference-new-citation`}
label={t('editor.reference.citation')}
value={form.citation}
onChange={(citation) => set({ citation })}
multiline
/>
<DraftField
id={`${host}-reference-new-url`}
label={t('editor.reference.url')}
value={form.url}
onChange={(url) => set({ url })}
/>
<DraftField
id={`${host}-reference-new-doi`}
label={t('editor.reference.doi')}
value={form.doi}
onChange={(doi) => set({ doi })}
/>
</div>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.reference.add')}
</ActionButton>
</div>
)
}
@@ -1,113 +1,77 @@
import { useEffect, useState } from 'react' import { useRef, useState } from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import DeleteDialog, { import DeleteDialog, {
type DeleteTarget, type DeleteTarget,
} from '@/components/editor/DeleteDialog' } from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly' import EditOnly from '@/components/editor/EditOnly'
import Input from '@/components/ui/Input' import type { FocusRequest } from '@/editor/focusRequest'
import {
focusRow,
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
import type { EditorTarget } from '@/editor/navigation' import type { EditorTarget } from '@/editor/navigation'
import { citersOf } from '@/editor/references/citations' import { isSheetView } from '@/editor/references/view'
import { visibleReferences } from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import ReferenceForm from './ReferenceForm' import NewReferenceTile from './NewReferenceTile'
import NoResult from './NoResult'
import { EmptyLine } from './ReferenceList' import { EmptyLine } from './ReferenceList'
import ReferenceTiles from './ReferenceTiles' import ReferenceTiles from './ReferenceTiles'
import { tileKeys, useTileState } from './useTileState' import ReferenceToolbar from './ReferenceToolbar'
import { useReferenceActions, useReferenceLibrary } from './useReferenceLibrary'
interface Props { interface Props {
readOnly: boolean readOnly: boolean
/** « Aller à » a citing finding or family. */ /** « Aller à » a citing finding or family. */
navigate: (target: EditorTarget) => void navigate: (target: EditorTarget) => void
focus?: FocusRequest 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 resetSignal?: number
} }
/** /**
* « Aller à » a reference: its tile is opened, the search is cleared first when it may * The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
* hide the tile, and the tile's button is focused after the commit that shows it. * reference, the draft tile and the delete dialog. Lives in the Références tab (ids
*/ * prefixed `tab-`).
function useReferenceFocus(
focus: FocusRequest | undefined,
query: string,
actions: { clearQuery: () => void; reveal: (key: ElementKey) => 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'
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-`).
*/ */
export default function ReferenceLibrary(props: Props) { export default function ReferenceLibrary(props: Props) {
const { readOnly, navigate, focus, resetSignal = 0 } = props const { readOnly, navigate, focus, resetSignal = 0 } = props
const t = useT() const t = useT()
const doc = useSheetDocument() const lib = useReferenceLibrary(readOnly, resetSignal)
const tiles = useTileState() const searchRef = useRef<HTMLInputElement>(null)
const [query, setQuery] = useSearchQuery(resetSignal) const act = useReferenceActions(lib, focus, searchRef)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null) const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const all: readonly Reference[] = doc?.references ?? [] const { all, shown } = lib
const keys = tileKeys(all) const sheetView = isSheetView(shown.view)
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()
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<Input <ReferenceToolbar
type="search" query={shown.view.query}
aria-label={t('editor.references.search')} onQuery={(query) => shown.update({ query })}
placeholder={t('editor.references.search')} onClear={act.clearSearch}
value={query} searchRef={searchRef}
onChange={(event) => setQuery(event.target.value)} sort={shown.view.sort}
onSort={(sort) => shown.update({ sort })}
shown={shown.matchCount}
total={all.length}
canAdd={!readOnly}
onAdd={act.startAdd}
/> />
{doc && ( {lib.loaded && (
<> <>
<EmptyLine total={all.length} shown={shown.length} /> {all.length === 0 && <EmptyLine />}
{all.length > 0 && shown.matchCount === 0 && (
<NoResult query={shown.view.query} onClear={act.clearSearch} />
)}
{!readOnly && !sheetView && shown.positions.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.reorder_hint')}
</p>
)}
<ReferenceTiles <ReferenceTiles
shown={shown} positions={shown.positions}
all={all} all={all}
keys={keys} keys={lib.keys}
citers={citers} citers={lib.citers}
tiles={tiles} tiles={lib.tiles}
readOnly={readOnly} readOnly={readOnly}
movable={query.trim() === ''} movable={sheetView}
navigate={navigate} navigate={navigate}
onEdit={act.edit}
onDelete={(reference) => onDelete={(reference) =>
setDeleting({ setDeleting({
key: { kind: 'reference', id: reference.id }, key: { kind: 'reference', id: reference.id },
@@ -116,7 +80,9 @@ export default function ReferenceLibrary(props: Props) {
} }
/> />
<EditOnly readOnly={readOnly}> <EditOnly readOnly={readOnly}>
<ReferenceForm host="tab" onAdded={() => setQuery('')} /> {act.draft !== null && (
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
)}
</EditOnly> </EditOnly>
</> </>
)} )}
@@ -35,11 +35,12 @@ export function ReferenceList({ shown, all, citers, ...rest }: ListProps) {
) )
} }
/** The empty line: no reference at all, or none that matches. */ /** The empty line: the sheet has no reference at all. */
export function EmptyLine({ total, shown }: { total: number; shown: number }) { export function EmptyLine() {
const t = useT() const t = useT()
if (shown > 0) return null return (
const key = <p className="text-sm text-[var(--color-ink-muted)]">
total === 0 ? 'editor.reference.empty' : 'editor.references.no_match' {t('editor.reference.empty')}
return <p className="text-sm text-[var(--color-ink-muted)]">{t(key)}</p> </p>
)
} }
@@ -6,8 +6,8 @@ import ReferenceTile from './ReferenceTile'
import type { useTileState } from './useTileState' import type { useTileState } from './useTileState'
interface Props { interface Props {
/** The tiles to list, each placed by its index in the whole bibliography `all`. */ /** The tiles to list, in display order, as positions in the whole bibliography `all`. */
shown: readonly Reference[] positions: readonly number[]
all: readonly Reference[] all: readonly Reference[]
/** One key per position of `all` (`tileKeys`). */ /** One key per position of `all` (`tileKeys`). */
keys: readonly string[] keys: readonly string[]
@@ -16,12 +16,13 @@ interface Props {
readOnly: boolean readOnly: boolean
movable: boolean movable: boolean
navigate: (target: EditorTarget) => void navigate: (target: EditorTarget) => void
onEdit: (position: number) => void
onDelete: (reference: Reference) => void onDelete: (reference: Reference) => void
} }
/** The tiles of the Références tab, wired to the library's open / edit state. */ /** The tiles of the Références tab, wired to the library's open / edit state. */
export default function ReferenceTiles(props: Props) { 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 edit = useEditCommand()
const move = (reference: Reference, position: number) => const move = (reference: Reference, position: number) =>
edit.run('move', { edit.run('move', {
@@ -33,8 +34,8 @@ export default function ReferenceTiles(props: Props) {
return ( return (
<> <>
<ul className="space-y-3"> <ul className="space-y-3">
{shown.map((reference) => { {positions.map((position) => {
const position = all.indexOf(reference) const reference = all[position]
const key = keys[position] const key = keys[position]
return ( return (
<ReferenceTile <ReferenceTile
@@ -50,7 +51,7 @@ export default function ReferenceTiles(props: Props) {
movable={props.movable} movable={props.movable}
on={{ on={{
toggle: () => tiles.toggle(key), toggle: () => tiles.toggle(key),
edit: () => tiles.startEdit(key), edit: () => props.onEdit(position),
done: tiles.finish, done: tiles.finish,
remove: () => props.onDelete(reference), remove: () => props.onDelete(reference),
move: (to) => move(reference, to), move: (to) => move(reference, to),
@@ -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<HTMLInputElement | null>
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 (
<p aria-live="polite" className="text-sm text-[var(--color-ink-muted)]">
{text.replace('{total}', String(total))}
</p>
)
}
/** 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 (
<div className="space-y-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<div className="relative flex-1">
<Input
ref={searchRef}
type="search"
aria-label={t('editor.references.search')}
placeholder={t('editor.references.search')}
value={query}
onChange={(event) => onQuery(event.target.value)}
onKeyDown={escape}
className="pr-11 max-sm:h-11 [&::-webkit-search-cancel-button]:appearance-none"
/>
{query !== '' && (
<button
type="button"
aria-label={t('editor.references.clear_search')}
onClick={onClear}
className="absolute right-0 top-0 flex size-10 max-sm:size-11 items-center justify-center rounded-lg text-[var(--color-ink-muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name="close" size={16} />
</button>
)}
</div>
<div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
<label htmlFor="tab-reference-sort" className="text-sm">
{t('editor.references.sort_by')}
</label>
<Select
id="tab-reference-sort"
value={sort}
onChange={(event) => onSort(event.target.value as ReferenceSort)}
className="max-sm:h-11 sm:w-52"
>
{REFERENCE_SORTS.map((value) => (
<option key={value} value={value}>
{t(`editor.references.sort.${value}`)}
</option>
))}
</Select>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<CountLine shown={props.shown} total={props.total} />
<ActionButton
readOnly={!props.canAdd}
variant="secondary"
size="sm"
onClick={props.onAdd}
>
{t('editor.references.add')}
</ActionButton>
</div>
</div>
)
}
@@ -1,13 +1,4 @@
import type { ReferenceType } from '@faunosteo/core-wasm/types' export { REFERENCE_TYPES } from '@/editor/references/referenceTypes'
export const REFERENCE_TYPES: readonly ReferenceType[] = [
'book',
'journal',
'standard',
'legal',
'web',
'manual',
]
/** Where reference cards are shown: the Références tab or a finding's citations panel. */ /** Where reference cards are shown: the Références tab or a finding's citations panel. */
export type ReferenceHost = 'tab' | 'panel' export type ReferenceHost = 'tab' | 'panel'
@@ -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<string, never[]>()
/** 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<typeof useReferenceLibrary>
/** Focuses a row after the commit that shows it (the request ran before it rendered). */
function useLateFocus() {
const [late, setLate] = useState<ElementKey | null>(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<HTMLInputElement | null>,
) {
const { keys, tiles, shown } = lib
const [draft, setDraft] = useState<number | null>(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)
},
}
}
@@ -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<string, readonly CiterItem[]>,
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<ReferenceView>) => {
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)),
}
}
@@ -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 * 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. * 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<ReadonlySet<string>>(() => new Set()) const [openKeys, setOpenKeys] = useState<ReadonlySet<string>>(() => new Set())
const [editingKey, setEditingKey] = useState<string | null>(null) const [editingKey, setEditingKey] = useState<string | null>(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<LeaveGuard | null>(null) const guard = useRef<LeaveGuard | null>(null)
const leave = () => guard.current?.() ?? true const leave = () => guard.current?.() ?? true
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key)) const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
@@ -40,9 +49,10 @@ export function useTileState() {
}) })
} }
const startEdit = (key: string) => { const startEdit = (key: string) => {
if (editingKey !== null && editingKey !== key && !leave()) return if (editingKey !== null && editingKey !== key && !leave()) return false
setEditingKey(key) setEditingKey(key)
open(key) open(key)
return true
} }
return { return {
openKeys, openKeys,
@@ -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',
]
+57
View File
@@ -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)
}
+38
View File
@@ -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
}
+15 -1
View File
@@ -1232,7 +1232,6 @@ export const en: Dict = {
'editor.references.search': 'Search a reference', 'editor.references.search': 'Search a reference',
'editor.references.cited_by': 'Cited by « {name} » ({count})', 'editor.references.cited_by': 'Cited by « {name} » ({count})',
'editor.references.show_all': 'Show all ({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_one': 'Cited {count} time',
'editor.references.cited_other': 'Cited {count} times', 'editor.references.cited_other': 'Cited {count} times',
'editor.references.uncited': 'Not cited', 'editor.references.uncited': 'Not cited',
@@ -1249,6 +1248,21 @@ export const en: Dict = {
'editor.references.none_url': 'None', 'editor.references.none_url': 'None',
'editor.references.new_tab': '(new tab)', '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.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_one': '{count} reference',
'editor.findings.references_open_other': '{count} references', 'editor.findings.references_open_other': '{count} references',
'editor.draft.loading': 'Loading the draft…', 'editor.draft.loading': 'Loading the draft…',
+15 -1
View File
@@ -1263,7 +1263,6 @@ export const fr: Dict = {
'editor.references.search': 'Rechercher une référence', 'editor.references.search': 'Rechercher une référence',
'editor.references.cited_by': 'Citées par « {name} » ({count})', 'editor.references.cited_by': 'Citées par « {name} » ({count})',
'editor.references.show_all': 'Tout afficher ({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_one': 'Citée {count} fois',
'editor.references.cited_other': 'Citée {count} fois', 'editor.references.cited_other': 'Citée {count} fois',
'editor.references.uncited': 'Non citée', 'editor.references.uncited': 'Non citée',
@@ -1280,6 +1279,21 @@ export const fr: Dict = {
'editor.references.none_url': 'Aucune', 'editor.references.none_url': 'Aucune',
'editor.references.new_tab': '(nouvel onglet)', '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.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_one': '{count} référence',
'editor.findings.references_open_other': '{count} références', 'editor.findings.references_open_other': '{count} références',
'editor.draft.loading': 'Chargement du brouillon…', 'editor.draft.loading': 'Chargement du brouillon…',
@@ -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 () => { it('the reference add form survives leaving and returning to the Références tab', async () => {
const user = await mount() const user = await mount()
await user.click(tab('Références')) 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', { const field = inPlace('references').getByLabelText('Citation', {
selector: '#tab-reference-new-citation', selector: '#tab-reference-new-citation',
}) })
@@ -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 () => { it('the reference creation form, in the Références tab', async () => {
const user = await mount() const user = await mount()
await user.click(tab('Références')) await user.click(tab('Références'))
await user.click(button('Ajouter une référence'))
await keepsTypedValue( await keepsTypedValue(
user, user,
'tab-reference-new-citation', 'tab-reference-new-citation',
@@ -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<string, number> = { 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<T>(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'])
})
})
@@ -155,9 +155,7 @@ describe('the Références tab', () => {
expect( expect(
tabPanel().querySelector('#tab-reference-0-ref-a-header'), tabPanel().querySelector('#tab-reference-0-ref-a-header'),
).not.toBeNull() ).not.toBeNull()
expect( expect(tabPanel().querySelector('#tab-reference-new-citation')).toBeNull()
tabPanel().querySelector('#tab-reference-new-citation'),
).not.toBeNull()
}) })
it('matches the citation, the DOI and the URL, ignoring case and accents', async () => { 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.clear(search())
await user.type(search(), 'zzz') await user.type(search(), 'zzz')
expect( expect(
within(tabPanel()).getByText('Aucune référence ne correspond.'), within(tabPanel()).getByText('Aucune référence ne contient « zzz ».'),
).toBeInTheDocument() ).toBeInTheDocument()
}) })
@@ -281,7 +279,10 @@ describe('the reset signal', () => {
}) })
describe('adding a reference', () => { describe('adding a reference', () => {
const addButton = () =>
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' })
async function add(user: User) { async function add(user: User) {
await user.click(addButton())
const byId = (id: string) => tabPanel().querySelector<HTMLElement>(id)! const byId = (id: string) => tabPanel().querySelector<HTMLElement>(id)!
await user.selectOptions(byId('#tab-reference-new-type'), 'book') await user.selectOptions(byId('#tab-reference-new-type'), 'book')
await user.type(byId('#tab-reference-new-citation'), 'Nouvelle source') 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() const user = await mount()
await user.type(search(), 'Barone') await user.type(search(), 'Barone')
expect(cards()).toHaveLength(1) expect(cards()).toHaveLength(1)
await add(user) await add(user)
expect(search()).toHaveValue('') expect(search()).toHaveValue('')
expect(cards()).toHaveLength(4) 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() const user = await mount()
await user.type(search(), 'Barone') 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( await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }), 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)
}) })
}) })
@@ -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<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()
})
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<typeof userEvent.setup>
const doc = () => JSON.parse(store.getState().documentText)
const lib = (readOnly = false, extra = {}) => (
<ReferenceLibrary readOnly={readOnly} navigate={vi.fn()} {...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-<position>-<id>-header`). */
const order = () =>
[...document.querySelectorAll('button[id$="-header"]')].map((button) =>
button.id.replace(/^tab-reference-\d+-(.*)-header$/, '$1'),
)
const header = (id: string) =>
document.querySelector<HTMLElement>(`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<HTMLElement>(
'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<HTMLElement>('#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()
})
})
@@ -45,6 +45,9 @@ describe('Références', () => {
await openReady() await openReady()
const user = userEvent.setup() const user = userEvent.setup()
render(<ReferencesTab {...props} />) render(<ReferencesTab {...props} />)
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
await user.click( await user.click(
screen.getByRole('button', { name: 'Ajouter la référence' }), screen.getByRole('button', { name: 'Ajouter la référence' }),
) )