feat(editor): cite references from the finding edit form only

This commit is contained in:
bchanot committed 2026-11-14 14:11:13 +01:00
1 parent afc1051313
commit f0e49fd447
16 files changed
+519 -395

No files matched your search

+44 -29
View File
@@ -29,7 +29,7 @@ import {
} from '../support/editor'
// V1-2.6 R2 finish: the citations of one finding as a modal side sheet over its dialog
// (R2F-4): its contents, « Retirer de ce constat » and « Défaire », « Tout afficher »,
// (R2F-4): its contents (no removal: that is the edit form's), « Défaire », « Tout afficher »,
// every close path with the focus checked after the exit (motion and reduced motion),
// Escape in a tile field, the exiting sheet inert, the keyboard and touch proofs, axe open
// (edit, read-only at 375 px), Back and Forward over the layers. The spec seeds its own
@@ -100,8 +100,19 @@ const link = (page: Page) =>
name: dict['editor.references.panel_show_all'],
})
const undo = (page: Page) => page.getByRole('button', { name: /Défaire/ })
const retire = (tile: Locator) =>
tile.getByRole('button', { name: dict['editor.references.remove_citation'] })
/** The edit form's « Retirer » of a cited reference, by its citation. */
const retire = (page: Page, citation: string) =>
findingDialog(page).getByRole('button', {
name: `${dict['editor.action.remove']} ${citation}`,
})
const modify = (page: Page) =>
findingDialog(page).getByRole('button', {
name: dict['editor.findings.edit'],
})
const saveForm = (page: Page) =>
findingDialog(page).getByRole('button', {
name: dict['editor.findings.save'],
})
type Node = { reference_ids: string[]; review_status: string }
const nodeOf = (document: Record<string, unknown>) =>
@@ -124,7 +135,7 @@ test.describe('citations sheet, editing', () => {
await dropLateReplays(context)
})
test('opens over its finding dialog, « Retirer » then one « Défaire », saved status', async ({
test('opens over its finding dialog, read-only; the edit form removes, one « Défaire », saved status', async ({
page,
requests,
}) => {
@@ -152,31 +163,39 @@ test.describe('citations sheet, editing', () => {
await expect(
tile.getByText(dict['editor.references.this_finding'], { exact: true }),
).toBeVisible()
await expect(retire(tile)).toBeVisible()
await expect(
tile.getByRole('button', { name: dict['editor.references.edit'] }),
).toBeVisible()
for (const name of [
dict['editor.action.delete'],
dict['editor.action.move_up'],
dict['editor.action.remove'],
]) {
await expect(panel(page).getByRole('button', { name })).toHaveCount(0)
}
await expectAccessible(page, 'the citations sheet, an open tile')
// « Retirer » takes the citation out at once; the next tile takes the focus (P20).
await retire(tile).click()
await expect(heads(page)).toHaveCount(2)
await expect(heads(page).nth(1)).toBeFocused()
await expect(heads(page).nth(1)).toContainText('Source C')
// « Défaire » is out of reach under the dialogs: close them, then one undo restores
// the citation and the status together.
// The sheet removes nothing: « Modifier » on the dialog stages the removal, the sheet
// opened from the form lists the draft, and « Enregistrer » writes it as one entry.
await closeCitations(page, dict)
await modify(page).click()
await retire(page, 'Source B').click()
await expect(trigger(page)).toContainText('2')
await showCitations(page)
await expect(heads(page)).toHaveCount(2)
await closeCitations(page, dict)
await saveForm(page).click()
await expect(trigger(page)).toContainText('2')
await closeFinding(page, dict)
// one « Défaire » restores the citation and the status together
await undo(page).click()
await openCitations(page, dict, 'Constat A')
await expect(heads(page)).toHaveCount(3)
await heads(page).nth(1).click()
await retire(tile).click()
await expect(heads(page)).toHaveCount(2)
await closeCitations(page, dict)
await modify(page).click()
await retire(page, 'Source B').click()
await saveForm(page).click()
await expect(trigger(page)).toContainText('2')
await closeFinding(page, dict)
await saveDraft(page, dict, seed.revision + 1)
const saved = await serverDocument<Record<string, unknown>>(seed.draftId)
@@ -207,27 +226,23 @@ test.describe('citations sheet, editing', () => {
await expect(last).toHaveAttribute('aria-expanded', 'true')
})
test('the last citations gone: the sheet stays with its line, Escape closes it, the dialog stays', async ({
test('the form drops every citation: the trigger goes with the count, nothing is written before « Enregistrer »', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openCitations(page, dict, 'Constat A')
for (const remaining of [2, 1, 0]) {
await heads(page).first().click()
await retire(heads(page).first().locator('xpath=ancestor::li[1]')).click()
await expect(heads(page)).toHaveCount(remaining)
await openFinding(page, dict, 'Constat A')
await modify(page).click()
for (const citation of ['Référence A', 'Source B', 'Source C']) {
await retire(page, citation).click()
}
await expect(trigger(page)).toHaveCount(0)
await expect(
panel(page).getByText(dict['editor.references.panel_empty']),
findingDialog(page).getByText(dict['editor.findings.references_none']),
).toBeVisible()
await expect(link(page)).toBeVisible()
await expect(page.locator('#editor-citations-title')).toBeFocused()
await page.keyboard.press('Escape')
await expect(panel(page)).toHaveCount(0)
// The trigger went with the last citation: the focus stays in the dialog.
await saveForm(page).click()
await expect(trigger(page)).toHaveCount(0)
await expect(findingDialog(page)).toBeVisible()
await expect(findingDialog(page).locator(':focus')).toHaveCount(1)
})
test('« Tout afficher » closes both layers, clears the search, keeps the sort and the open tiles; Back returns to the sheet', async ({
@@ -568,7 +583,7 @@ test.describe('citations sheet, read-only at 375 px', () => {
await heads(page).first().click()
for (const name of [
dict['editor.references.edit'],
dict['editor.references.remove_citation'],
dict['editor.action.remove'],
]) {
await expect(panel(page).getByRole('button', { name })).toHaveCount(0)
}
@@ -1,16 +1,12 @@
import Icon from '@/components/ui/Icon'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import type { FindingItem } from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
interface CitationsProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
/** The citations sheet is open over the dialog (the trigger reads « expanded »). */
sheetOpen: boolean
/** Opens the citations sheet; a family has none (it lists its citations here). */
@@ -48,15 +44,15 @@ function SheetTrigger({
)
}
/** A family's inline list of cited references, each removable (« Retirer »). */
function CitationList({
/** A family's inline list of cited references; removable only where `remove` is given. */
export function CitationList({
ids,
readOnly,
remove,
}: {
ids: readonly string[]
readOnly: boolean
remove: (id: string) => void
remove?: (id: string) => void
}) {
const t = useT()
const doc = useSheetDocument()
@@ -67,85 +63,69 @@ function CitationList({
{ids.map((id) => (
<li key={id} className="flex items-center gap-2 text-sm">
<span className="min-w-0 flex-1">{citation(id)}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() => remove(id)}
>
{t('editor.action.remove')}
</ActionButton>
{remove && (
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() => remove(id)}
>
{t('editor.action.remove')}
</ActionButton>
)}
</li>
))}
</ul>
)
}
/** The finding's cited ids, the update that changes them and the references still citable. */
function useCitationEdit(item: FindingItem, edit: EditCommandApi) {
/** « Références citées » and « X références »: the heading row of both modes. */
export function CitationsHeader({
item,
count,
sheetOpen,
onShowReferences,
}: Pick<CitationsProps, 'item' | 'sheetOpen' | 'onShowReferences'> & {
count: number
}) {
const t = useT()
const doc = useSheetDocument()
const ids =
item.element.kind === 'zone' ? [] : item.element.value.reference_ids
const patch = (reference_ids: string[]) =>
edit.run('references', {
op: 'update',
key: item.key,
element: patchElement(item, { reference_ids }),
})
const options = (doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation }))
return {
ids,
patch,
options: [{ value: '', label: t('editor.field.choose') }, ...options],
}
}
/**
* « Références citées » of a category or a node. A finding node shows « X références »
* (the sheet), a family its list. « Citer une référence » acts at once, one entry in the
* document's history, in view mode too (it is no part of the transactional form).
*/
export default function FindingCitations(props: CitationsProps) {
const { item, readOnly, edit } = props
const t = useT()
const cited = useCitationEdit(item, edit)
if (item.element.kind === 'zone') return null
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{cited.ids.length > 0 && item.element.kind === 'finding_node' && (
<SheetTrigger {...props} count={cited.ids.length} />
)}
</div>
{cited.ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{item.element.kind === 'finding_category' && (
<CitationList
ids={cited.ids}
readOnly={readOnly}
remove={(id) =>
cited.patch(cited.ids.filter((other) => other !== id))
}
/>
)}
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={cited.options}
onCommit={(id) => id !== '' && cited.patch([...cited.ids, id])}
error={edit.fieldError('references')}
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{count > 0 && item.element.kind === 'finding_node' && (
<SheetTrigger
item={item}
count={count}
sheetOpen={sheetOpen}
onShowReferences={onShowReferences}
/>
)}
</div>
)
}
/**
* « Références citées » of a category or a node, read: a finding node shows « X références »
* (the sheet), a family its list. Nothing here cites or removes: that is the edit form's
* (FindingEditCitations).
*/
export default function FindingCitations(props: CitationsProps) {
const { item } = props
const t = useT()
if (item.element.kind === 'zone') return null
const ids = item.element.value.reference_ids
return (
<div className="space-y-2">
<CitationsHeader {...props} count={ids.length} />
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{item.element.kind === 'finding_category' && (
<CitationList ids={ids} readOnly />
)}
</div>
)
}
@@ -66,6 +66,8 @@ function ItemBody(props: ItemBodyProps) {
const t = useT()
const mode = useItemMode()
const sheetOpen = !!layer.view && 'key' in layer.view && layer.view.citations
const showReferences = (opener: HTMLElement) =>
layer.openCitations(props.item.key, opener)
return (
<div className="space-y-2">
{mode.editing ? (
@@ -75,6 +77,8 @@ function ItemBody(props: ItemBodyProps) {
guards={layer.guards}
onDone={mode.done}
onDiscardClose={() => layer.close(true)}
sheetOpen={sheetOpen}
onShowReferences={showReferences}
/>
) : (
<FindingView
@@ -83,9 +87,7 @@ function ItemBody(props: ItemBodyProps) {
sheetOpen={sheetOpen}
onEdit={mode.startEdit}
onDelete={() => props.onDelete(props.item)}
onShowReferences={(opener) =>
layer.openCitations(props.item.key, opener)
}
onShowReferences={showReferences}
/>
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
@@ -0,0 +1,63 @@
import SelectField from '@/components/editor/fields/SelectField'
import {
CitationList,
CitationsHeader,
} from '@/components/editor/findings/FindingCitations'
import type { FindingItem } from '@/editor/findings/tree'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
interface Props {
item: FindingItem
/** The draft's cited ids: what the form shows, counts and hands to the sheet. */
ids: readonly string[]
readOnly: boolean
sheetOpen: boolean
onChange: (ids: string[]) => void
onShowReferences: (opener: HTMLElement) => void
}
/** The references the draft does not cite yet, after the « choose » placeholder. */
function useCitableOptions(ids: readonly string[]) {
const t = useT()
const doc = useSheetDocument()
const options = (doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation }))
return [{ value: '', label: t('editor.field.choose') }, ...options]
}
/**
* « Références citées » in the edit form of a category or a node: the draft's list, each
* « Retirer », and « Citer une référence ». Nothing is written before « Enregistrer ».
*/
export default function FindingEditCitations(props: Props) {
const { ids, readOnly, onChange } = props
const t = useT()
const options = useCitableOptions(ids)
return (
<div className="space-y-2">
<CitationsHeader {...props} count={ids.length} />
{ids.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
) : (
<CitationList
ids={ids}
readOnly={readOnly}
remove={(id) => onChange(ids.filter((other) => other !== id))}
/>
)}
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) => id !== '' && onChange([...ids, id])}
/>
)}
</div>
)
}
@@ -1,8 +1,10 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import DraftField from '@/components/editor/fields/DraftField'
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
import FindingEditCitations from '@/components/editor/findings/FindingEditCitations'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useCitationDraft } from '@/editor/findings/citationDraft'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank, optionalText } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
@@ -16,6 +18,7 @@ interface Draft {
descriptionFr: string
descriptionEn: string
vet: boolean
referenceIds: string[]
}
function draftOf(item: FindingItem): Draft {
@@ -27,6 +30,8 @@ function draftOf(item: FindingItem): Draft {
descriptionFr: described.fr ?? '',
descriptionEn: described.en ?? '',
vet: element.kind === 'finding_node' && element.value.requires_vet_referral,
referenceIds:
element.kind === 'zone' ? [] : [...element.value.reference_ids],
}
}
@@ -44,7 +49,7 @@ function normalized(draft: Draft): Draft {
const sameDraft = (a: Draft, b: Draft) =>
JSON.stringify(normalized(a)) === JSON.stringify(normalized(b))
/** The one `update` the form makes: names, and for a family or a node the texts. */
/** The one `update` the form makes: names, and for a family or a node texts and citations. */
function patchOf(item: FindingItem, draft: Draft) {
const now = normalized(draft)
const { element } = item
@@ -60,6 +65,7 @@ function patchOf(item: FindingItem, draft: Draft) {
return patchElement(item, {
name,
description,
reference_ids: now.referenceIds,
...(element.kind === 'finding_node' ? vet : {}),
})
}
@@ -72,6 +78,10 @@ export interface FindingEditFormProps {
onDone: (saved: boolean) => void
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
onDiscardClose: () => void
/** The citations sheet is open over the dialog (the trigger reads « expanded »). */
sheetOpen: boolean
/** Opens the citations sheet, which then lists the draft's citations. */
onShowReferences: (opener: HTMLElement) => void
}
function VetCheckbox({
@@ -167,10 +177,20 @@ function useEditSave(props: FindingEditFormProps, form: EditDraft) {
type EditDraft = ReturnType<typeof useFormDraft<Draft>>
/** The sheet opened from the form lists the draft's citations: they are published there. */
function usePublishedCitations(item: FindingItem, ids: readonly string[]) {
const publish = useCitationDraft((s) => s.publish)
useEffect(() => {
publish({ key: item.key, ids })
return () => publish(null)
}, [publish, item.key, ids])
}
/** The form's state: draft, blank names, save and cancel. */
function useEditForm(props: FindingEditFormProps) {
const form = useFormDraft(draftOf(props.item), props.guards, sameDraft)
const saving = useEditSave(props, form)
usePublishedCitations(props.item, form.draft.referenceIds)
const cancel = () =>
form.dirty && !props.readOnly
? form.guard.askToLeave()
@@ -180,7 +200,7 @@ function useEditForm(props: FindingEditFormProps) {
/**
* The element edited in the finding dialog (R2F-3): a local draft, one `update` on
* « Enregistrer » (none when nothing changed), nothing on « Annuler » or a close. When the
* « Enregistrer », citations included (none when nothing changed), nothing on « Annuler » or a close. When the
* editor turns read-only the draft stays, its fields read-only, and only « Abandonner »
* is left.
*/
@@ -217,6 +237,16 @@ export default function FindingEditForm(props: FindingEditFormProps) {
onChange={(vet) => form.set({ vet })}
/>
)}
{props.item.kind !== 'zone' && (
<FindingEditCitations
item={props.item}
ids={form.draft.referenceIds}
readOnly={props.readOnly}
sheetOpen={props.sheetOpen}
onChange={(referenceIds) => form.set({ referenceIds })}
onShowReferences={props.onShowReferences}
/>
)}
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{form.error}
@@ -77,8 +77,6 @@ export default function FindingView(props: FindingViewProps) {
<Texts item={item} />
<FindingCitations
item={item}
readOnly={readOnly}
edit={edit}
sheetOpen={sheetOpen}
onShowReferences={props.onShowReferences}
/>
@@ -1,6 +1,5 @@
import type { RefObject } from 'react'
import type { LocalizedText, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import { usePlural } from '@/editor/plural'
@@ -103,40 +102,20 @@ function Summary({
)
}
/** A cited id the sheet no longer holds (P30): named, and removable like any citation. */
function MissingRow({
entry,
readOnly,
onRemove,
}: {
entry: CitationEntry
readOnly: boolean
onRemove: () => void
}) {
/** A cited id the sheet no longer holds (P30): named; only the edit form removes it. */
function MissingRow({ entry }: { entry: CitationEntry }) {
const t = useT()
const missing = t('editor.references.missing')
return (
<li className="flex items-center gap-2 rounded-lg border border-[var(--color-border)] p-3 text-sm">
<span className="min-w-0 flex-1">
{missing}
<span className="ml-2 text-[var(--color-ink-muted)]">{entry.id}</span>
</span>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
aria-label={`${t('editor.action.remove')} ${missing} ${entry.id}`}
onClick={onRemove}
>
{t('editor.action.remove')}
</ActionButton>
<li className="rounded-lg border border-[var(--color-border)] p-3 text-sm">
{t('editor.references.missing')}
<span className="ml-2 text-[var(--color-ink-muted)]">{entry.id}</span>
</li>
)
}
type Panel = ReturnType<typeof useCitationsPanel>
/** One cited reference as a tile (« Modifier », « Retirer de ce constat »). */
/** One cited reference as a tile (« Modifier »). */
function EntryTile({
entry,
reference,
@@ -148,13 +127,13 @@ function EntryTile({
panel: Panel
props: Props
}) {
const { tiles, keys, citers, entries, remove } = panel
const { tiles, keys, citers, entries } = panel
const { readOnly, citedBy, navigate } = props
const key = keys[entry.index]
return (
<ReferenceTile
host="panel"
panel={{ current: citedBy, onRemove: () => remove(entry.index) }}
panel={{ current: citedBy }}
reference={reference}
position={entry.index}
count={entries.length}
@@ -189,12 +168,7 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
props={props}
/>
) : (
<MissingRow
key={`${entry.index}-${entry.id}`}
entry={entry}
readOnly={props.readOnly}
onRemove={() => panel.remove(entry.index)}
/>
<MissingRow key={`${entry.index}-${entry.id}`} entry={entry} />
),
)}
</ul>
@@ -203,7 +177,7 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
/**
* The citations of one finding: the references it cites as tiles, « Tout afficher » for
* the whole library. No search, add, delete or order (P7). The content of the side sheet
* the whole library. No search, add, remove or order (P7): citing is the edit form's. The content of the side sheet
* (CitationsSheet), which is the modal; opens from a finding's trigger only.
*/
export default function CitationsPanel(props: Props) {
@@ -227,11 +201,6 @@ export default function CitationsPanel(props: Props) {
{t('editor.references.panel_empty')}
</p>
)}
{panel.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{panel.error}
</p>
)}
<Entries panel={panel} props={props} />
</div>
</section>
@@ -20,15 +20,14 @@ export interface TileHandlers {
goTo: (key: ElementKey) => void
}
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
/** What a tile of the citations panel adds: the finding it belongs to. */
export interface PanelTile {
current: ElementKey
onRemove: () => void
}
export interface TileProps {
host: ReferenceHost
/** Set for the citations panel: « ce constat » marks, « Retirer de ce constat ». */
/** Set for the citations panel: « ce constat » marks. */
panel?: PanelTile
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
@@ -99,34 +98,18 @@ function TileHeader({ base, props }: { base: string; props: TileProps }) {
)
}
/** The panel's actions (P7): « Modifier » and « Retirer de ce constat », nothing else. */
function PanelActions({
props,
panel,
}: {
props: TileProps
panel: PanelTile
}) {
/** The panel's one action (P7): « Modifier ». Removing a citation is the edit form's. */
function PanelActions({ props }: { props: TileProps }) {
const t = useT()
return (
<div className="flex flex-wrap items-center gap-2">
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={(event) => props.on.edit(event.currentTarget)}
>
{t('editor.references.edit')}
</ActionButton>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={panel.onRemove}
>
{t('editor.references.remove_citation')}
</ActionButton>
</div>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={(event) => props.on.edit(event.currentTarget)}
>
{t('editor.references.edit')}
</ActionButton>
)
}
@@ -135,7 +118,7 @@ function TileActions({ props }: { props: TileProps }) {
const t = useT()
const { position, count, citers, readOnly, movable, on } = props
if (readOnly) return null
if (props.panel) return <PanelActions props={props} panel={props.panel} />
if (props.panel) return <PanelActions props={props} />
return (
<>
<div className="flex flex-wrap items-center gap-2">
@@ -1,11 +1,11 @@
import { useEffect, useMemo, useRef, useState, type FocusEvent } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { draftIdsFor, useCitationDraft } from '@/editor/findings/citationDraft'
import type { FindingItem } from '@/editor/findings/tree'
import { citersOf } from '@/editor/references/citations'
import { citedIds, citingFinding } from '@/editor/references/filter'
import { citationEntries, findingPath } from '@/editor/references/panel'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
@@ -31,11 +31,11 @@ interface Held {
}
/**
* P20: when the row that holds the focus leaves the list (« Retirer de ce constat », an
* undo that removes the reference), the focus goes to the next row's button, else the
* P20: when the row that holds the focus leaves the list (an undo that removes the
* reference), the focus goes to the next row's button, else the
* previous row's, else the heading. A row swapped for another at the same index (a
* tile turned into « Référence introuvable ») counts as gone, so « next » is the one
* after it. `lost` registers a row that is about to go without having held the focus.
* after it.
*/
function useFocusRescue() {
const list = useRef<HTMLUListElement>(null)
@@ -65,29 +65,27 @@ function useFocusRescue() {
list,
heading,
track,
lost: (at: number) => {
const row = rowsOf()[at]
if (row) hold(row, at)
},
}
}
/**
* What the panel shows of the finding: its cited ids and its path. Once the finding is
* gone (the sheet is leaving) the last known answer stays, so the sheet does not empty
* while it slides out and a tile in edit can still be asked to apply its draft.
* while it slides out and a tile in edit can still be asked to apply its draft. Opened
* from the edit form, it lists the form's staged citations, not the document's.
*/
function useShownFinding(
doc: ReturnType<typeof useSheetDocument>,
item: FindingItem | null,
citedBy: ElementKey,
) {
const staged = useCitationDraft((s) => draftIdsFor(s.draft, citedBy))
const found = useMemo(
() =>
doc && item
? { ids: citedIds(item), path: findingPath(doc, citedBy) }
? { ids: staged ?? citedIds(item), path: findingPath(doc, citedBy) }
: null,
[doc, item, citedBy],
[doc, item, citedBy, staged],
)
const [last, setLast] = useState(found)
if (found !== null && found !== last) setLast(found)
@@ -99,25 +97,14 @@ function useCitedEntries(hooks: PanelHooks) {
const { doc, item } = useCitedFinding(hooks.citedBy)
const { ids, path } = useShownFinding(doc, item, hooks.citedBy)
const entries = citationEntries(doc?.references ?? [], ids)
return { doc, item, ids, path, entries, keys: tileKeys(entries) }
return { doc, path, entries, keys: tileKeys(entries) }
}
/** What the citations panel reads and does: the cited entries, tiles, « Retirer ». */
/** What the citations panel reads: the cited entries and their tiles. */
export function useCitationsPanel(hooks: PanelHooks) {
const { doc, item, ids, path, entries, keys } = useCitedEntries(hooks)
const edit = useEditCommand()
const { doc, path, entries, keys } = useCitedEntries(hooks)
const tiles = useTileState(doc ? keys : null)
const focus = useFocusRescue()
// « Retirer de ce constat » is the detail's « Retirer »: the same update of the finding's
// reference_ids, so the core marks the finding « À confirmer » (P15) and one « Défaire »
// restores the citation and the status together. The reference itself stays in the sheet.
const remove = (at: number) => {
if (!item) return
const rest = ids.filter((_, index) => index !== at)
const element = patchElement(item, { reference_ids: rest })
const command = { op: 'update', key: item.key, element } as const
if (edit.run('references', command)) focus.lost(at)
}
return {
doc,
entries,
@@ -125,8 +112,6 @@ export function useCitationsPanel(hooks: PanelHooks) {
keys,
citers: doc ? citersOf(doc) : new Map<string, never[]>(),
path,
error: edit.fieldError('references'),
remove,
list: focus.list,
heading: focus.heading,
trackFocus: focus.track,
@@ -0,0 +1,27 @@
import { create } from 'zustand'
import type { ElementKey } from '@faunosteo/core-wasm/types'
/** The citations an open edit form holds, for the side sheet opened from that form. */
interface CitationDraft {
key: ElementKey
ids: readonly string[]
}
interface CitationDraftStore {
draft: CitationDraft | null
publish: (draft: CitationDraft | null) => void
}
export const useCitationDraft = create<CitationDraftStore>((set) => ({
draft: null,
publish: (draft) => set({ draft }),
}))
/** The ids the sheet of `key` lists instead of the document's, null when none are staged. */
export function draftIdsFor(
draft: CitationDraft | null,
key: ElementKey,
): readonly string[] | null {
if (!draft || JSON.stringify(draft.key) !== JSON.stringify(key)) return null
return draft.ids
}
-1
View File
@@ -1234,7 +1234,6 @@ export const en: Dict = {
'editor.references.panel_count_other': '{count} references cited by this finding',
'editor.references.panel_show_all': 'Show all in the References tab',
'editor.references.panel_empty': 'This finding no longer cites any reference.',
'editor.references.remove_citation': 'Remove from this finding',
'editor.references.this_finding': 'this finding',
'editor.references.missing': 'Reference not found',
'editor.references.cited_one': 'Cited {count} time',
-1
View File
@@ -1265,7 +1265,6 @@ export const fr: Dict = {
'editor.references.panel_count_other': '{count} références citées par ce constat',
'editor.references.panel_show_all': 'Tout afficher dans l\'onglet Références',
'editor.references.panel_empty': 'Ce constat ne cite plus aucune référence.',
'editor.references.remove_citation': 'Retirer de ce constat',
'editor.references.this_finding': 'ce constat',
'editor.references.missing': 'Référence introuvable',
'editor.references.cited_one': 'Citée {count} fois',
@@ -102,8 +102,8 @@ function sheetText(): string {
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280): Promise<User> {
serverHas(sheetText(), 3)
async function mount(width = 1280, text = sheetText()): Promise<User> {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft({ width, probe })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
@@ -556,3 +556,134 @@ describe('final review: the category creation title', () => {
expect(title.textContent).not.toContain('editor.')
})
})
const reference = (id: string, citation: string) => ({
kind: 'reference' as const,
value: { id, type: 'book' as const, citation, url: null, doi: null },
})
/** Node A cites Alpha; Beta is cited by nobody. */
function citingText(): string {
let text = insert(sheetText(), reference('ref-a', 'Alpha'))
text = insert(text, reference('ref-b', 'Beta'))
const key = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
} as const
const node = JSON.parse(text).finding_zones[0].categories[0].children[0]
const element = {
kind: 'finding_node',
value: { ...node, reference_ids: ['ref-a'] },
}
return edit(text, { op: 'update', key, element } as never)
}
const nodeIds = () =>
doc().finding_zones[0].categories[0].children[0].reference_ids
const cite = (user: User, label: string) =>
user.selectOptions(inDialog().getByLabelText('Citer une référence'), label)
const save = (user: User) =>
user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
const panelOpen = () => screen.queryByTestId('editor-citations-panel')
describe('citing references lives in the edit form (owner item 1)', () => {
it('the view has no cite control and no remove; the trigger opens the sheet', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
expect(inDialog().queryByLabelText('Citer une référence')).toBeNull()
expect(inDialog().queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(
inDialog().getByRole('button', { name: '1 référence' }),
).toBeVisible()
})
it('a family view lists its citations read-only', async () => {
let text = insert(sheetText(), reference('ref-a', 'Alpha'))
const key = { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] }
const cat = JSON.parse(text).finding_zones[0].categories[0]
const element = {
kind: 'finding_category',
value: { ...cat, reference_ids: ['ref-a'] },
}
text = edit(text, { op: 'update', key, element } as never)
const user = await mount(1280, text)
await openFinding(user, /Cat A/)
expect(inDialog().getByText('Alpha')).toBeVisible()
expect(inDialog().queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(inDialog().queryByLabelText('Citer une référence')).toBeNull()
})
it('the form stages a cite and a remove, written only by « Enregistrer »', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
const before = entries()
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: 'Retirer Alpha' }))
expect(nodeIds()).toEqual(['ref-a'])
expect(entries()).toBe(before)
expect(
inDialog().getByRole('button', { name: '1 référence' }),
).toBeVisible()
await save(user)
expect(nodeIds()).toEqual(['ref-b'])
expect(entries()).toBe(before + 1)
})
it('one undo restores the names and the citations together', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await user.clear(nameField())
await user.type(nameField(), 'Renommé')
await cite(user, 'Beta')
await save(user)
expect(doc().finding_zones[0].categories[0].children[0].name.fr).toBe(
'Renommé',
)
expect(nodeIds()).toEqual(['ref-a', 'ref-b'])
act(() => void store.getState().undoStep())
expect(doc().finding_zones[0].categories[0].children[0].name.fr).toBe(
'Node A',
)
expect(nodeIds()).toEqual(['ref-a'])
})
it('a cite then its remove is pristine: « Enregistrer » writes nothing', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
const before = entries()
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: 'Retirer Beta' }))
await save(user)
expect(entries()).toBe(before)
})
it('« Annuler » with only a citation change asks, « Abandonner » writes nothing', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
const before = entries()
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(entries()).toBe(before)
expect(nodeIds()).toEqual(['ref-a'])
})
it('the sheet opened from the form lists the draft and cannot remove', async () => {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: '2 références' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
const sheet = within(panelOpen()!)
expect(sheet.getByText(/2 références citées/)).toBeVisible()
expect(sheet.queryByRole('button', { name: /^Retirer/ })).toBeNull()
expect(nodeIds()).toEqual(['ref-a'])
})
})
+23 -9
View File
@@ -590,7 +590,7 @@ describe('Constats tab', () => {
)
})
it('edits descriptions (blank side omitted) and the vet flag in one save, cites at once', async () => {
it('edits descriptions (blank side omitted), the vet flag and the citations in one save', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
@@ -628,22 +628,22 @@ describe('Constats tab', () => {
await user.clear(inFindingDialog().getByLabelText('Description (FR)'))
await save()
expect(node().description).toEqual({})
// « Citer une référence » is no part of the form: it acts at once, in view mode
// the view cites nothing: « Citer une référence » is the edit form's
expect(inFindingDialog().queryByLabelText('Citer une référence')).toBeNull()
await startEdit(user)
await user.selectOptions(
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(node().reference_ids).toEqual([])
await save()
expect(node().reference_ids).toEqual(['ref-a'])
// a finding node lists its citations in the sheet, not inline
expect(
inFindingDialog().queryByRole('button', { name: /Retirer Alpha/ }),
).toBeNull()
expect(
inFindingDialog().getByRole('button', { name: '1 référence' }),
).toBeInTheDocument()
})
it('a family keeps its inline list of citations with « Retirer »', async () => {
it('a family cites and removes in its edit form, one save writes both', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
@@ -660,18 +660,32 @@ describe('Constats tab', () => {
render(<FindingsHost />)
await user.click(items()[1])
const family = () => doc().finding_zones[0].categories[0]
await startEdit(user)
await user.selectOptions(
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(family().reference_ids).toEqual(['ref-a'])
expect(
inFindingDialog().getByRole('button', { name: /Retirer Alpha/ }),
).toBeInTheDocument()
await user.click(
inFindingDialog().getByRole('button', { name: /Retirer Alpha/ }),
)
expect(family().reference_ids).toEqual([])
expect(
inFindingDialog().getByText('Aucune référence citée.'),
).toBeInTheDocument()
await user.selectOptions(
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(family().reference_ids).toEqual([])
await user.click(
inFindingDialog().getByRole('button', { name: 'Enregistrer' }),
)
expect(family().reference_ids).toEqual(['ref-a'])
expect(
inFindingDialog().queryByRole('button', { name: /Retirer/ }),
).toBeNull()
})
it('the trigger shows exactly for the keys open_citations accepts', async () => {
@@ -178,16 +178,17 @@ describe('opening', () => {
expect(panel()).toHaveAttribute('aria-labelledby', 'editor-citations-title')
})
it('a family keeps its inline list: no trigger, no panel', async () => {
it('a family lists its citations read-only: no trigger, no Retirer, no panel', async () => {
const user = await mount()
await select(user, /Cat A/)
const detail = screen.getByRole('tabpanel', { name: 'Constats' })
expect(
within(detail).queryByRole('button', { name: /références?$/ }),
).toBeNull()
expect(within(detail).getByText('Barone, Ostéologie')).toBeVisible()
expect(
within(detail).getAllByRole('button', { name: /^Retirer / }),
).toHaveLength(2)
within(detail).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
expect(hasPanel()).toBe(false)
})
@@ -204,7 +205,7 @@ describe('opening', () => {
expect(panel()).not.toHaveTextContent('Denoix')
})
it('an open tile marks the current finding and offers Modifier and « Retirer de ce constat »', async () => {
it('an open tile marks the current finding and offers Modifier only', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
@@ -214,10 +215,12 @@ describe('opening', () => {
within(tile).getAllByRole('button', { name: /^Aller à / }),
).toHaveLength(2)
expect(within(tile).getByRole('button', { name: 'Modifier' })).toBeVisible()
expect(
within(tile).getByRole('button', { name: 'Retirer de ce constat' }),
).toBeVisible()
for (const absent of ['Supprimer', 'Monter', 'Descendre']) {
for (const absent of [
'Retirer de ce constat',
'Supprimer',
'Monter',
'Descendre',
]) {
expect(within(panel()).queryByRole('button', { name: absent })).toBeNull()
}
})
@@ -486,101 +489,26 @@ describe('the library and the history around the panel', () => {
})
})
describe('« Retirer de ce constat »', () => {
const retire = (user: User, at = 0) =>
user.click(
within(panel()).getAllByRole('button', { name: 'Retirer de ce constat' })[
at
],
)
async function openTile(user: User, citation: RegExp) {
await user.click(within(panel()).getByRole('button', { name: citation }))
}
it('removes only that id, the reference stays, one undo restores it with the status', async () => {
describe('the sheet cannot remove a citation (the edit form does)', () => {
it('no tile offers « Retirer de ce constat »', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'set_status',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
status: 'reviewed',
})
})
expect(nodeA().review_status).toBe('reviewed')
await openFromFinding(user)
const history = store.getState().undo.length
await openTile(user, /^Barone/)
await retire(user)
expect(nodeA().reference_ids).toEqual(['ref-c'])
expect(nodeA().review_status).toBe('to_confirm')
expect(doc().references).toHaveLength(3)
expect(store.getState().undo.length).toBe(history + 1)
expect(tiles()).toHaveLength(1)
expect(panel()).toHaveTextContent('1 référence citée par ce constat')
act(() => void store.getState().undoStep())
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
expect(nodeA().review_status).toBe('reviewed')
expect(tiles()).toHaveLength(2)
})
it('the focus goes to the next tile, else the previous, else the heading', async () => {
const ids = ['ref-a', 'ref-b', 'ref-c']
const user = await mount(1280, nodeText(ids))
await openFromFinding(user, '3 références')
const header = (at: number) => () =>
tiles()[at].querySelector('button') as HTMLElement
await openTile(user, /^Barone/)
await retire(user)
await focusIs(header(0))
expect(header(0)().textContent).toContain('Denoix')
await openTile(user, /^Code rural/)
await retire(user, 0)
await focusIs(header(0))
expect(tiles()).toHaveLength(1)
await openTile(user, /^Denoix/)
await retire(user)
await focusIs(heading)
})
it('the last citation gone: the panel stays with its line and « Tout afficher »', async () => {
const user = await mount(1280, nodeText(['ref-a']))
await openFromFinding(user, '1 référence')
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await retire(user)
expect(panel()).toHaveTextContent(
'Ce constat ne cite plus aucune référence.',
)
expect(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
}),
).toBeVisible()
expect(hasPanel()).toBe(true)
await user.click(closeButton())
await closed()
// the trigger is gone with its count: the focus stays inside the finding dialog
expect(findingDialog()!.contains(document.activeElement)).toBe(true)
within(panel()).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
})
it('a dangling id is a « Référence introuvable » row with Retirer, counted like the rest', async () => {
it('a dangling id is a « Référence introuvable » row, counted, without Retirer', async () => {
const user = await mount(1280, nodeText(['ref-a', 'ref-gone']))
await openFromFinding(user)
expect(panel()).toHaveTextContent('2 références citées par ce constat')
expect(tiles()).toHaveLength(2)
expect(tiles()[1]).toHaveTextContent('Référence introuvable')
await user.click(
within(tiles()[1] as HTMLElement).getByRole('button', {
name: /^Retirer/,
}),
)
expect(nodeA().reference_ids).toEqual(['ref-a'])
expect(tiles()).toHaveLength(1)
await focusIs(() => tiles()[0].querySelector('button')!)
expect(
within(panel()).queryByRole('button', { name: /^Retirer/ }),
).toBeNull()
})
})