From 3dc5820e3a47e7fba5d95d109259ef000da00b80 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 15 Nov 2026 16:39:43 +0100 Subject: [PATCH] feat(editor): edit mode of the references dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit « Modifier » turns the references dialog into a draft of adds and removes, saved as one update on the current citations. A new layer, citations, guards it between the finding and the reference dialogs: close, Back, POP refusal and the leave cascade ask it. « Modifier la référence » and « Nouvelle référence » stack the reference dialog over it; a creation it started joins its draft. --- .../src/components/editor/EditorWorkspace.tsx | 2 + .../editor/findings/DiscardConfirm.tsx | 13 +- .../editor/findings/FindingCitations.tsx | 38 -- .../editor/findings/FindingDialog.tsx | 31 +- .../editor/findings/FindingEditCitations.tsx | 56 -- .../components/editor/findings/useItemMode.ts | 33 + .../editor/references/CitationsDialog.tsx | 124 +++- .../editor/references/CitationsDraftList.tsx | 154 +++++ .../editor/references/CitationsEditForm.tsx | 145 +++++ .../editor/references/CitationsPanel.tsx | 24 +- .../editor/references/ReferenceDialog.tsx | 14 +- .../src/editor/history/useEditorHistory.ts | 45 +- .../app/src/editor/history/useLeaveConfirm.ts | 46 +- apps/app/src/editor/leftDraft.ts | 10 +- apps/app/src/editor/navigation.ts | 9 +- .../src/editor/references/citationEdits.ts | 41 ++ apps/app/src/editor/useEditorNavigation.ts | 58 +- apps/app/src/editor/useReferenceMoves.ts | 53 +- apps/app/src/i18n/en.ts | 4 + apps/app/src/i18n/fr.ts | 4 + apps/app/tests/helpers/findingsHost.tsx | 2 + .../tests/unit/editor-citation-edits.test.ts | 29 + .../tests/unit/editor-citations-edit.test.tsx | 581 ++++++++++++++++++ .../unit/editor-citations-guards.test.tsx | 172 ++++++ apps/app/tests/unit/editor-escape.test.tsx | 4 +- .../tests/unit/editor-history-entry.test.ts | 4 + .../tests/unit/editor-leave-cascade.test.tsx | 13 +- apps/app/tests/unit/editor-navigation.test.ts | 14 + .../unit/editor-references-panel.test.tsx | 9 +- 29 files changed, 1489 insertions(+), 243 deletions(-) delete mode 100644 apps/app/src/components/editor/findings/FindingEditCitations.tsx create mode 100644 apps/app/src/components/editor/findings/useItemMode.ts create mode 100644 apps/app/src/components/editor/references/CitationsDraftList.tsx create mode 100644 apps/app/src/components/editor/references/CitationsEditForm.tsx create mode 100644 apps/app/src/editor/references/citationEdits.ts create mode 100644 apps/app/tests/unit/editor-citation-edits.test.ts create mode 100644 apps/app/tests/unit/editor-citations-edit.test.tsx create mode 100644 apps/app/tests/unit/editor-citations-guards.test.tsx diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx index 6b5adbdb..f49873fc 100644 --- a/apps/app/src/components/editor/EditorWorkspace.tsx +++ b/apps/app/src/components/editor/EditorWorkspace.tsx @@ -118,6 +118,8 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) { onShowAll={() => cited && nav.showAllReferences(cited)} navigate={nav.navigate} returnFocus={nav.citationsTrigger} + guards={nav.guards} + references={nav.references} /> diff --git a/apps/app/src/components/editor/findings/DiscardConfirm.tsx b/apps/app/src/components/editor/findings/DiscardConfirm.tsx index 83558357..c87f427f 100644 --- a/apps/app/src/components/editor/findings/DiscardConfirm.tsx +++ b/apps/app/src/components/editor/findings/DiscardConfirm.tsx @@ -10,10 +10,19 @@ import { useT } from '@/i18n/useT' const BOX = 'space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3' -/** True when no open dialog lies over `host`: each open one is `host` or holds it. */ +/** + * True when no open dialog lies over `host`: each open one is `host`, holds it, or comes + * before it in the page (the editor's layers are stacked in tree order: the references + * dialog after the finding dialog, the reference dialog after both). + */ const onTop = (host: Element) => [...document.querySelectorAll('dialog[open]')].every( - (dialog) => dialog === host || dialog.contains(host), + (dialog) => + dialog === host || + dialog.contains(host) || + !!( + host.compareDocumentPosition(dialog) & Node.DOCUMENT_POSITION_PRECEDING + ), ) /** diff --git a/apps/app/src/components/editor/findings/FindingCitations.tsx b/apps/app/src/components/editor/findings/FindingCitations.tsx index 5c5bce25..c805398c 100644 --- a/apps/app/src/components/editor/findings/FindingCitations.tsx +++ b/apps/app/src/components/editor/findings/FindingCitations.tsx @@ -1,8 +1,6 @@ import Icon from '@/components/ui/Icon' -import ActionButton from '@/components/editor/fields/ActionButton' import type { FindingItem } from '@/editor/findings/tree' import { usePlural } from '@/editor/plural' -import { useSheetDocument } from '@/editor/sheetDocument' import { useT } from '@/i18n/useT' interface CitationsProps { @@ -38,42 +36,6 @@ function CitationsTrigger({ ) } -/** A 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 -}) { - const t = useT() - const doc = useSheetDocument() - const citation = (id: string) => - doc?.references.find((r) => r.id === id)?.citation ?? id - return ( - - ) -} - /** * « Références citées » and « X références » of a family or a node, the same in the view * and the edit mode (Rev 5): the count is the document's, the citations are read and diff --git a/apps/app/src/components/editor/findings/FindingDialog.tsx b/apps/app/src/components/editor/findings/FindingDialog.tsx index 7f29afc2..61b908b7 100644 --- a/apps/app/src/components/editor/findings/FindingDialog.tsx +++ b/apps/app/src/components/editor/findings/FindingDialog.tsx @@ -1,9 +1,9 @@ -import { useEffect, useRef, useState } from 'react' import FindingCreateForm, { type PendingFinding, } from '@/components/editor/findings/FindingCreateForm' import FindingEditForm from '@/components/editor/findings/FindingEditForm' import FindingView from '@/components/editor/findings/FindingView' +import { useItemMode } from '@/components/editor/findings/useItemMode' import Dialog from '@/components/ui/Dialog' import { usePlaceVisible } from '@/lib/placeVisibility' import type { FindingItem, FindingKind } from '@/editor/findings/tree' @@ -33,38 +33,11 @@ interface ItemBodyProps { const EDIT_BUTTON_ID = 'finding-edit-button' -/** After the form closes its button is gone: « Modifier » takes the focus back. */ -function useFocusEditButton(editing: boolean) { - const wanted = useRef(false) - useEffect(() => { - if (editing || !wanted.current) return - wanted.current = false - document.getElementById(EDIT_BUTTON_ID)?.focus() - }, [editing]) - return () => { - wanted.current = true - } -} - -/** The local mode of the one dialog: view or edit, and whether a save was just made. */ -function useItemMode() { - const [mode, setMode] = useState({ editing: false, saved: false }) - const returnToEdit = useFocusEditButton(mode.editing) - return { - ...mode, - startEdit: () => setMode({ editing: true, saved: false }), - done: (saved: boolean) => { - returnToEdit() - setMode({ editing: false, saved }) - }, - } -} - /** View mode, or the edit form: a local mode of the one dialog, no history entry. */ function ItemBody(props: ItemBodyProps) { const { layer } = props const t = useT() - const mode = useItemMode() + const mode = useItemMode(EDIT_BUTTON_ID) const showReferences = (opener: HTMLElement) => layer.openCitations(props.item.key, opener) return ( diff --git a/apps/app/src/components/editor/findings/FindingEditCitations.tsx b/apps/app/src/components/editor/findings/FindingEditCitations.tsx deleted file mode 100644 index c9074c10..00000000 --- a/apps/app/src/components/editor/findings/FindingEditCitations.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import SelectField from '@/components/editor/fields/SelectField' -import { CitationList } from '@/components/editor/findings/FindingCitations' -import { useSheetDocument } from '@/editor/sheetDocument' -import { useT } from '@/i18n/useT' - -interface Props { - /** The draft's cited ids: what the form shows. */ - ids: readonly string[] - readOnly: boolean - onChange: (ids: string[]) => 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] -} - -/** - * The cited references of a draft: the list, each « Retirer », and « Citer une référence ». - * Nothing is written before « Enregistrer ». Mounted by no form since Rev 5 Task 11: the - * references dialog's edit mode (Task 12) takes it over. - */ -export default function FindingEditCitations(props: Props) { - const { ids, readOnly, onChange } = props - const t = useT() - const options = useCitableOptions(ids) - return ( -
- {ids.length === 0 ? ( -

- {t('editor.findings.references_none')} -

- ) : ( - onChange(ids.filter((other) => other !== id))} - /> - )} - {!readOnly && ( - id !== '' && onChange([...ids, id])} - /> - )} -
- ) -} diff --git a/apps/app/src/components/editor/findings/useItemMode.ts b/apps/app/src/components/editor/findings/useItemMode.ts new file mode 100644 index 00000000..e935ae67 --- /dev/null +++ b/apps/app/src/components/editor/findings/useItemMode.ts @@ -0,0 +1,33 @@ +import { useEffect, useRef, useState } from 'react' + +/** After the form closes its button is gone: « Modifier » (`buttonId`) takes the focus back. */ +function useFocusEditButton(editing: boolean, buttonId: string) { + const wanted = useRef(false) + useEffect(() => { + if (editing || !wanted.current) return + wanted.current = false + document.getElementById(buttonId)?.focus() + }, [editing, buttonId]) + return () => { + wanted.current = true + } +} + +/** + * The local mode of a dialog (the finding dialog, the references dialog): view or edit, + * and whether a save was just made. No history entry. `buttonId` is its « Modifier ». + */ +export function useItemMode(buttonId: string) { + const [mode, setMode] = useState({ editing: false, saved: false }) + const returnToEdit = useFocusEditButton(mode.editing, buttonId) + return { + ...mode, + startEdit: () => setMode({ editing: true, saved: false }), + done: (saved: boolean) => { + returnToEdit() + setMode({ editing: false, saved }) + }, + /** Back to the view mode, nothing said: the dialog shows another element. */ + reset: () => setMode({ editing: false, saved: false }), + } +} diff --git a/apps/app/src/components/editor/references/CitationsDialog.tsx b/apps/app/src/components/editor/references/CitationsDialog.tsx index 120c1bb7..75147b57 100644 --- a/apps/app/src/components/editor/references/CitationsDialog.tsx +++ b/apps/app/src/components/editor/references/CitationsDialog.tsx @@ -1,49 +1,149 @@ +import { useState } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' +import ActionButton from '@/components/editor/fields/ActionButton' +import { useItemMode } from '@/components/editor/findings/useItemMode' import Dialog from '@/components/ui/Dialog' +import { useEditorReadOnly } from '@/editor/editingContext' import type { EditorTarget } from '@/editor/navigation' +import { findingPath } from '@/editor/references/panel' +import { useSheetDocument } from '@/editor/sheetDocument' +import type { Guards } from '@/editor/useEditorNavigation' +import type { ReferenceMoves } from '@/editor/useReferenceMoves' import { useT } from '@/i18n/useT' -import CitationsPanel from './CitationsPanel' +import CitationsEditForm from './CitationsEditForm' +import CitationsPanel, { FindingPath } from './CitationsPanel' import { CITATIONS_TITLE_ID } from './useCitationsPanel' export interface CitationsDialogProps { /** The family or finding node whose citations it shows; null while it is closed. */ citedBy: ElementKey | null - /** A user close (✕, Escape, the backdrop). */ - onClose: () => boolean + /** A close: a user one (✕, Escape, the backdrop) is refused by a draft; forced goes. */ + onClose: (forced?: boolean) => boolean /** « Tout afficher dans l'onglet Références ». */ onShowAll: () => void /** « Aller à » a citing finding or a reference. */ navigate: (target: EditorTarget) => void /** « X références » of the finding dialog under it, where the focus returns. */ returnFocus: () => HTMLElement | null + guards: Guards + /** The reference dialog over this one (the edit mode's edit and creation). */ + references: Pick +} + +/** The dialog's « Modifier »: the focus comes back to it after the edit mode. */ +const EDIT_BUTTON_ID = 'citations-edit-button' + +/** The local mode, back to the view for each element the dialog shows (no history entry). */ +function useCitationsMode(citedBy: ElementKey | null) { + const shownFor = citedBy && JSON.stringify(citedBy) + const mode = useItemMode(EDIT_BUTTON_ID) + const [modeFor, setModeFor] = useState(shownFor) + if (modeFor !== shownFor) { + setModeFor(shownFor) + mode.reset() + } + return { ...mode, shownFor } +} + +type Mode = ReturnType + +interface BodyProps { + citedBy: ElementKey + mode: Mode + props: CitationsDialogProps +} + +/** The edit mode: where the finding sits, then the draft form. */ +function EditBody({ citedBy, mode, props }: BodyProps) { + const doc = useSheetDocument() + const readOnly = useEditorReadOnly() + return ( + <> + + props.onClose(true)} + /> + + ) +} + +/** The view mode: the cited references, then « Modifier » (edit tier only). */ +function ViewBody({ citedBy, mode, props }: BodyProps) { + const t = useT() + const readOnly = useEditorReadOnly() + return ( + <> + +
+ + {t('editor.citations.edit')} + +
+ + ) +} + +/** The place of the dialog's content, in both modes, then what a save says. */ +function Body(body: BodyProps) { + const t = useT() + const { mode } = body + return ( +
+ {mode.editing ? : } +

+ {mode.saved ? t('editor.findings.saved') : ''} +

+
+ ) } /** * The references dialog of a family or a finding node (Rev 5): a modal layer over the * finding dialog. The host sits after the tab body in the tree, so it is shown after the * finding dialog and lies on top of it; Escape, ✕ and the backdrop close it only. The - * view mode reads the cited references. + * view mode reads the cited references; its « Modifier » turns it into a form (local + * mode, no history entry) whose draft the layer `citations` guards. */ export default function CitationsDialog(props: CitationsDialogProps) { const { citedBy, onClose } = props const t = useT() + const mode = useCitationsMode(citedBy) + const title = mode.editing + ? 'editor.citations.edit_title' + : 'editor.references.dialog_title' return ( (onClose() ? undefined : 'kept')} > - {citedBy && ( - - )} + {citedBy && } ) } diff --git a/apps/app/src/components/editor/references/CitationsDraftList.tsx b/apps/app/src/components/editor/references/CitationsDraftList.tsx new file mode 100644 index 00000000..8af671e9 --- /dev/null +++ b/apps/app/src/components/editor/references/CitationsDraftList.tsx @@ -0,0 +1,154 @@ +import { useEffect, useRef } from 'react' +import SelectField from '@/components/editor/fields/SelectField' +import Button from '@/components/ui/Button' +import { useSheetDocument } from '@/editor/sheetDocument' +import { useT } from '@/i18n/useT' + +export interface DraftListProps { + /** The draft's cited ids, in the order they will be saved. */ + ids: readonly string[] + readOnly: boolean + onAdd: (id: string) => void + onRemove: (id: string) => void + /** « Modifier la référence »: the reference dialog over this one. */ + onEditReference: (id: string, opener: HTMLElement) => void + /** « Nouvelle référence »: the creation dialog over this one. */ + onNew: (opener: HTMLElement) => void +} + +/** The add choice: its id, so the focus can land on it once the last row is removed. */ +const ADD_ID = 'citations-add-reference' + +/** 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] +} + +/** + * A removed row takes its buttons with it: the focus goes to the row now at its place, + * else the one before, else the add choice. + */ +function useRemovalFocus(ids: readonly string[]) { + const list = useRef(null) + const removedAt = useRef(null) + useEffect(() => { + const at = removedAt.current + if (at === null) return + removedAt.current = null + const rows = [...(list.current?.children ?? [])] + const row = rows[at] ?? rows[at - 1] + const target = + row?.querySelector('button') ?? document.getElementById(ADD_ID) + target?.focus() + }, [ids]) + return { list, removing: (at: number) => (removedAt.current = at) } +} + +interface RowProps { + id: string + props: DraftListProps + onRemove: () => void +} + +/** One cited id: its citation (or « Référence introuvable »), its edit and its removal. */ +function DraftRow({ id, props, onRemove }: RowProps) { + const t = useT() + const doc = useSheetDocument() + const citation = doc?.references.find((r) => r.id === id)?.citation + const shown = citation ?? `${t('editor.references.missing')} ${id}` + return ( +
  • + {shown} + {citation !== undefined && ( + + )} + +
  • + ) +} + +/** « Citer une référence » among those not cited yet, and « Nouvelle référence ». */ +function AddRow({ props }: { props: DraftListProps }) { + const t = useT() + const options = useCitableOptions(props.ids) + return ( +
    + {!props.readOnly && ( +
    + id !== '' && props.onAdd(id)} + /> +
    + )} + +
    + ) +} + +/** + * The cited references of the draft (the references dialog's edit mode, Rev 5): each with + * « Modifier la référence » and « Retirer » (a dangling id too), then the ways to cite one. + * Nothing is written before « Enregistrer ». Read only: every control off. + */ +export default function CitationsDraftList(props: DraftListProps) { + const { ids } = props + const t = useT() + const focus = useRemovalFocus(ids) + return ( +
    + {ids.length === 0 && ( +

    + {t('editor.findings.references_none')} +

    + )} +
      + {ids.map((id, at) => ( + { + focus.removing(at) + props.onRemove(id) + }} + /> + ))} +
    + +
    + ) +} diff --git a/apps/app/src/components/editor/references/CitationsEditForm.tsx b/apps/app/src/components/editor/references/CitationsEditForm.tsx new file mode 100644 index 00000000..0b5fdfd9 --- /dev/null +++ b/apps/app/src/components/editor/references/CitationsEditForm.tsx @@ -0,0 +1,145 @@ +import { useEffect, useRef } from 'react' +import type { ElementKey } from '@faunosteo/core-wasm/types' +import { FormActions } from '@/components/editor/findings/DiscardConfirm' +import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice' +import { useFormDraft } from '@/components/editor/findings/useDirtyGuard' +import { patchElement } from '@/editor/findings/tree' +import { + addId, + applyEdits, + NO_EDITS, + removeId, + sameEdits, + type CitationEdits, +} from '@/editor/references/citationEdits' +import { citedIds, citingFinding } from '@/editor/references/filter' +import { useSheetDocument } from '@/editor/sheetDocument' +import { useEditCommand } from '@/editor/useEditCommand' +import type { Guards } from '@/editor/useEditorNavigation' +import type { ReferenceMoves } from '@/editor/useReferenceMoves' +import { useT } from '@/i18n/useT' +import CitationsDraftList from './CitationsDraftList' + +export interface CitationsEditFormProps { + citedBy: ElementKey + readOnly: boolean + guards: Guards + /** The reference dialog over this one: an edit, or a creation cited in the draft. */ + references: Pick + /** Back to the view mode; `saved` is true when a command was written. */ + onDone: (saved: boolean) => void + /** « Abandonner » after a close request: the draft goes, so does the dialog. */ + onDiscardClose: () => void +} + +/** The family or node as the document holds it now, and the ids it cites now. */ +function useCurrent(citedBy: ElementKey) { + const doc = useSheetDocument() + const item = doc ? citingFinding(doc, citedBy) : null + return { item, ids: item ? citedIds(item) : [] } +} + +const sameIds = (a: readonly string[], b: readonly string[]) => + a.length === b.length && a.every((id, at) => id === b[at]) + +type Draft = ReturnType> + +/** The save: the draft applied to the current citations, one `update`, none unchanged. */ +function useCitationsSave(props: CitationsEditFormProps, form: Draft) { + const { item, ids } = useCurrent(props.citedBy) + const edit = useEditCommand() + const save = () => { + const next = applyEdits(ids, form.draft) + if (!item || sameIds(next, ids)) return props.onDone(false) + const element = patchElement(item, { reference_ids: next }) + const command = { op: 'update', key: item.key, element } as const + if (edit.run('save', command)) props.onDone(true) + } + return { + shown: applyEdits(ids, form.draft), + save, + error: edit.fieldError('save'), + } +} + +/** + * « Nouvelle référence »: the creation dialog over this one; the new id joins the draft, + * only while this form is still there (an abandoned draft cites nothing). + */ +function useCreation(props: CitationsEditFormProps, form: Draft) { + const latest = useRef(form) + latest.current = form + const alive = useRef(true) + useEffect(() => { + alive.current = true + return () => { + alive.current = false + } + }, []) + return (opener: HTMLElement) => + props.references.start(opener, (id) => { + const now = latest.current + if (alive.current) now.set(addId(now.draft, id)) + }) +} + +/** The form's state: the draft, its guard, its save, its cancel and its creation. */ +function useCitationsForm(props: CitationsEditFormProps) { + const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations') + const saving = useCitationsSave(props, form) + const cancel = () => + form.dirty && !props.readOnly + ? form.guard.askToLeave() + : props.onDone(false) + return { ...form, ...saving, cancel, create: useCreation(props, form) } +} + +/** + * The references dialog's edit mode (Rev 5): a draft of the citations (cite, remove, a new + * reference cited), one `update` on « Enregistrer » (none when nothing changed), nothing on + * « Annuler » or a close. The draft's layer is `citations`: a dirty one is asked before a + * close, a Back or a leave. Read only: the draft stays, only « Abandonner » is left. + */ +export default function CitationsEditForm(props: CitationsEditFormProps) { + const t = useT() + const form = useCitationsForm(props) + const { guard } = form + const discard = + guard.confirming === 'dialog' + ? props.onDiscardClose + : () => props.onDone(false) + return ( +
    { + event.preventDefault() + form.save() + }} + > + {props.readOnly && } + form.set(addId(form.draft, id))} + onRemove={(id) => form.set(removeId(form.draft, id))} + onEditReference={props.references.open} + onNew={form.create} + /> + {form.error && ( +

    + {form.error} +

    + )} + + + ) +} diff --git a/apps/app/src/components/editor/references/CitationsPanel.tsx b/apps/app/src/components/editor/references/CitationsPanel.tsx index 72e6ea3a..9ff65aa0 100644 --- a/apps/app/src/components/editor/references/CitationsPanel.tsx +++ b/apps/app/src/components/editor/references/CitationsPanel.tsx @@ -6,11 +6,7 @@ import type { CitationEntry } from '@/editor/references/panel' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' import ReferenceTile from './ReferenceTile' -import { - CITATIONS_TITLE_ID, - useCitationsPanel, - type PanelHooks, -} from './useCitationsPanel' +import { useCitationsPanel, type PanelHooks } from './useCitationsPanel' interface Props extends PanelHooks { /** « Tout afficher dans l'onglet Références ». */ @@ -23,7 +19,7 @@ const RING = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]' /** « Zone › Famille › **Constat** »: where the finding sits, the finding itself in bold. */ -function FindingPath({ path }: { path: readonly LocalizedText[] }) { +export function FindingPath({ path }: { path: readonly LocalizedText[] }) { const locale = useLocaleStore((s) => s.locale) const names = path.map((name) => name[locale]) const own = names.pop() @@ -143,10 +139,10 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) { } /** - * The citations of one family or finding node, the body of the references dialog + * The citations of one family or finding node, the view mode of the references dialog * (CitationsDialog): where it sits, the references it cites as tiles, the dangling ids - * named, « Tout afficher » for the whole library. The view mode: no search, add, remove, - * order or « Modifier » (P7). + * named, « Tout afficher » for the whole library. No search, add, remove, order or + * « Modifier » on a tile (P7): the dialog's own « Modifier » opens the edit mode. */ export default function CitationsPanel(props: Props) { const { onShowAll } = props @@ -154,13 +150,7 @@ export default function CitationsPanel(props: Props) { const panel = useCitationsPanel(props) const count = panel.entries.length return ( -
    + <> {count === 0 && ( @@ -169,6 +159,6 @@ export default function CitationsPanel(props: Props) {

    )} -
    + ) } diff --git a/apps/app/src/components/editor/references/ReferenceDialog.tsx b/apps/app/src/components/editor/references/ReferenceDialog.tsx index b2f5b315..b55d474b 100644 --- a/apps/app/src/components/editor/references/ReferenceDialog.tsx +++ b/apps/app/src/components/editor/references/ReferenceDialog.tsx @@ -41,7 +41,7 @@ function useGoneRule(layer: ReferenceLayer) { }, [view, doc, layer, t]) } -/** Where a closed dialog returns the focus: the tile's header, or the add button. */ +/** Where a closed dialog returns the focus: its opener, else the tile header or « Ajouter ». */ function useReturnTarget(layer: ReferenceLayer) { const last = useRef(layer.view) if (layer.view) last.current = layer.view @@ -49,7 +49,9 @@ function useReturnTarget(layer: ReferenceLayer) { return useCallback((): HTMLElement | null => { const shown = last.current if (!shown) return null - if ('create' in shown) return document.getElementById(ADD_BUTTON_ID) + // A creation over the citations dialog returns to its « Nouvelle référence ». + if ('create' in shown) + return opener() ?? document.getElementById(ADD_BUTTON_ID) const wanted = JSON.stringify({ kind: 'reference', id: shown.edit }) return ( opener() ?? @@ -104,10 +106,10 @@ function useOnSaved( } /** - * The reference dialog (R2F-5): one `Dialog` over the References tab or the citations - * sheet, a form for a reference's type, DOI, citation and URL, or for a new one. The view - * layer of the browser history drives it; it is no part of a kept place, so it is never a - * native modal inside a hidden one. + * The reference dialog (R2F-5): one `Dialog` over the References tab or the references + * dialog's edit mode (Rev 5), a form for a reference's type, DOI, citation and URL, or for + * a new one. The view layer of the browser history drives it; it is no part of a kept + * place, so it is never a native modal inside a hidden one. */ export default function ReferenceDialog({ layer, diff --git a/apps/app/src/editor/history/useEditorHistory.ts b/apps/app/src/editor/history/useEditorHistory.ts index 77e903b7..0d9fd817 100644 --- a/apps/app/src/editor/history/useEditorHistory.ts +++ b/apps/app/src/editor/history/useEditorHistory.ts @@ -11,9 +11,10 @@ import { } from '@/components/ui/afterModalsClosed' import { focusActiveTab } from '../focusRequest' import { LAYERS_TOP_DOWN } from '../leftDraft' -import { sameView, type EditorView } from '../navigation' +import { citationsOfView, sameView, type EditorView } from '../navigation' import { headingOf, + layersAbove, shownPlace, useMoveText, type EditorNavigation, @@ -211,23 +212,26 @@ function sameLayers(a: EditorView, b: EditorView): boolean { ) } -/** The finding dialog a view shows, without its citations dialog: that one holds no form. */ +/** The finding dialog a view shows, without its citations dialog (a layer of its own). */ function dialogOf({ finding }: EditorView): unknown { return finding && 'key' in finding ? { key: finding.key } : finding } +const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b) + /** - * The layers holding a form that a POP from `from` to `to` takes away, top down: the - * citations dialog alone is no such layer, so a Back that only closes it asks nothing. + * The layers that a POP from `from` to `to` takes away, top down: the reference dialog + * changed, the citations dialog closed or shown for another finding, the finding dialog + * changed. Each is asked; one holding no draft (no guard, or a clean one) lets it go. */ function leavingLayers(from: EditorView, to: EditorView): LayerName[] { - const same = (a: unknown, b: unknown) => - JSON.stringify(a) === JSON.stringify(b) - const reference = from.reference && !same(from.reference, to.reference) - const finding = from.finding && !same(dialogOf(from), dialogOf(to)) - return LAYERS_TOP_DOWN.filter((l) => - l === 'reference' ? reference : finding, - ) + const cited = citationsOfView(from) + const leaving = { + reference: !!from.reference && !same(from.reference, to.reference), + citations: !!cited && !same(cited, citationsOfView(to)), + finding: !!from.finding && !same(dialogOf(from), dialogOf(to)), + } + return LAYERS_TOP_DOWN.filter((layer) => leaving[layer]) } /** @@ -249,12 +253,14 @@ function refusal( return leaving.find((layer) => !nav.guards.ask(layer, false).allowed) ?? null } -/** The finding dialog alone: the clean citations and reference dialogs over it go. */ -function bareFinding(view: EditorView): EditorView { +/** `view` without the dialogs over `layer`: the clean layers above the one that asks. */ +function upTo(view: EditorView, layer: LayerName): EditorView { + const above = layersAbove(layer) const { finding } = view - const shown = - finding && 'key' in finding ? { ...finding, citations: false } : finding - return { ...view, finding: shown, reference: null } + const closes = above.includes('citations') && finding && 'key' in finding + const shown = closes ? { ...finding, citations: false } : finding + const reference = above.includes('reference') ? null : view.reference + return { ...view, finding: shown, reference } } interface PopContext { @@ -278,15 +284,16 @@ function landOnForeign(ctx: PopContext): Landing | null { /** * A POP refused (see `refusal`): the view stays, pushed again above the entry landed on. - * When the finding dialog refused, the clean citations and reference dialogs over it close - * first, so its question is not hidden under them. True when refused. + * The clean dialogs over the layer that refused close first (the reference dialog over a + * citations draft; both over a finding draft), so its question is not hidden under them. + * True when refused. */ function refusePop(ctx: PopContext, landed: HistoryEntry | null): boolean { const refused = refusal(ctx, landed) if (!refused) return false const { book, writer, view } = ctx if (landed) adopt(book, landed) - const kept = refused === 'finding' ? bareFinding(view) : view + const kept = refused === 'modal' ? view : upTo(view, refused) if (!sameView(kept, view)) ctx.nav.restoreView(kept) writer.push(kept) return true diff --git a/apps/app/src/editor/history/useLeaveConfirm.ts b/apps/app/src/editor/history/useLeaveConfirm.ts index 8b9c88e5..4921cb9a 100644 --- a/apps/app/src/editor/history/useLeaveConfirm.ts +++ b/apps/app/src/editor/history/useLeaveConfirm.ts @@ -1,11 +1,13 @@ import { useCallback, useEffect, useRef } from 'react' import { useLocation } from 'react-router-dom' import { topDirtyLayer } from '../leftDraft' -import type { - EditorNavigation, - Guards, - LayerExit, - LayerName, +import { citationsOfView } from '../navigation' +import { + layersAbove, + type EditorNavigation, + type Guards, + type LayerExit, + type LayerName, } from '../useEditorNavigation' /** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */ @@ -41,10 +43,11 @@ function leavesEditor(event: NavigateEventLike, path: string): boolean { interface Watch { guards: Guards /** - * Closes the citations dialog and a reference dialog over it: they lie over the finding - * dialog, so its question would be hidden under them. + * Closes the dialogs over `layer` (clean: it is the top dirty one), so its question is + * not hidden under them: the reference dialog over the citations dialog, both over the + * finding dialog. */ - clearAbove: () => void + clearAbove: (layer: LayerName) => void path: string /** The key of the jump the user confirmed: it passes, and leaves no flag. */ passing: { current: string | null } @@ -72,15 +75,14 @@ function jumpTo({ api, key, watch }: Jump, keep: () => void): void { } /** - * `layer` asks « Abandonner les modifications ? » and holds the jump. Its « Abandonner » - * closes it, with the citations dialog it may have been opened from (so the next question - * is not hidden under the citations dialog), and the next dirty layer under it asks in turn; the - * last one lets the jump go. Any « Continuer la saisie » drops the jump. The finding - * dialog asks once the layers over it are closed (they are clean: it is the top dirty one). + * `layer` asks « Abandonner les modifications ? » and holds the jump, once the layers over + * it are closed (they are clean: it is the top dirty one). Its « Abandonner » closes it, + * and the next dirty layer under it asks in turn; the last one lets the jump go. Any + * « Continuer la saisie » drops the jump. */ function askLeave(jump: Jump, layer: LayerName): void { const { guards, clearAbove } = jump.watch - if (layer === 'finding') clearAbove() + clearAbove(layer) guards.ask(layer, false) guards.holdLeave({ layer, @@ -113,13 +115,17 @@ type LeaveNav = Pick< 'guards' | 'state' | 'closeCitations' | 'references' > -/** Closes the citations and reference dialogs of the navigation `latest` holds, if open. */ -function clearerOf(latest: { current: LeaveNav }): () => void { - return () => { +/** + * Closes the open dialogs over `layer` of the navigation `latest` holds. Forced: they hold + * no draft, or one just abandoned (the state read may still show it, one commit behind). + */ +function clearerOf(latest: { current: LeaveNav }): (layer: LayerName) => void { + return (layer) => { const { state, closeCitations, references } = latest.current - const { finding } = state - if (finding && 'key' in finding && finding.citations) closeCitations() - if (state.reference) references.close(true) + const above = layersAbove(layer) + if (above.includes('reference') && state.reference) references.close(true) + const cited = above.includes('citations') && citationsOfView(state) + if (cited) closeCitations(true) } } diff --git a/apps/app/src/editor/leftDraft.ts b/apps/app/src/editor/leftDraft.ts index 8e8ef150..4b0bc193 100644 --- a/apps/app/src/editor/leftDraft.ts +++ b/apps/app/src/editor/leftDraft.ts @@ -2,7 +2,12 @@ import { useEffect, useRef, useState } from 'react' import type { HistoryOwner } from './history/entry' import { fingerprintOf, randomHex } from './history/fingerprint' import type { NavigationState } from './navigation' -import type { EditorNavigation, Guards, LayerName } from './useEditorNavigation' +import { + LAYERS, + type EditorNavigation, + type Guards, + type LayerName, +} from './useEditorNavigation' /** * A dirty dialog lost when the editor goes (a Back of several entries the browser does @@ -24,7 +29,7 @@ export const leftDraftKey = ({ sheetId, tag }: HistoryOwner) => `${PREFIX}${sheetId}:${tag}` /** The top layer first: the dialog the user was typing in when they left. */ -export const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding'] +export const LAYERS_TOP_DOWN: readonly LayerName[] = [...LAYERS].reverse() /** * The top layer whose form holds changes, or the first one under `below`; a forced ask @@ -55,6 +60,7 @@ function elementOf(state: NavigationState, layer: LayerName): unknown { ? { kind: 'reference', id: reference.edit } : null } + // The citations dialog's element is the finding whose citations it edits. const { finding } = state if (!finding) return null return 'key' in finding ? finding.key : finding.create.parent diff --git a/apps/app/src/editor/navigation.ts b/apps/app/src/editor/navigation.ts index 27bb1a62..0341e15b 100644 --- a/apps/app/src/editor/navigation.ts +++ b/apps/app/src/editor/navigation.ts @@ -291,9 +291,14 @@ function openReference(state: NavigationState, id: string): NavigationState { return shown({ ...state, reference: { edit: id } }) } -/** The creation form of a reference: only the References tab adds one. */ +/** + * The creation form of a reference: over the References tab, or over the citations dialog + * (its edit mode cites the new reference, Rev 5), which keeps its tab. + */ function createReference(state: NavigationState): NavigationState { - return shown({ ...state, tab: 'references', reference: { create: true } }) + const reference = { create: true } as const + if (citationsOfView(state)) return shown({ ...state, reference }) + return shown({ ...state, tab: 'references', reference }) } export function navigationReducer( diff --git a/apps/app/src/editor/references/citationEdits.ts b/apps/app/src/editor/references/citationEdits.ts new file mode 100644 index 00000000..7129a215 --- /dev/null +++ b/apps/app/src/editor/references/citationEdits.ts @@ -0,0 +1,41 @@ +/** + * The draft of the references dialog's edit mode (Rev 5): what the user added and removed, + * never a whole list. It is applied to the element's CURRENT citations at save, so a + * change made elsewhere meanwhile (an undo, a reload) is kept, never overwritten. + */ +export interface CitationEdits { + added: readonly string[] + removed: readonly string[] +} + +export const NO_EDITS: CitationEdits = { added: [], removed: [] } + +export const sameEdits = (a: CitationEdits, b: CitationEdits) => + JSON.stringify(a) === JSON.stringify(b) + +/** `current` with the removals dropped and the additions appended, each id once. */ +export function applyEdits( + current: readonly string[], + edits: CitationEdits, +): string[] { + const kept = current.filter((id) => !edits.removed.includes(id)) + return [...kept, ...edits.added.filter((id) => !kept.includes(id))] +} + +/** Cites `id`: undoes its removal, else adds it. */ +export function addId(edits: CitationEdits, id: string): CitationEdits { + if (edits.removed.includes(id)) { + return { ...edits, removed: edits.removed.filter((other) => other !== id) } + } + if (edits.added.includes(id)) return edits + return { ...edits, added: [...edits.added, id] } +} + +/** Removes `id`: undoes its addition, else records the removal. */ +export function removeId(edits: CitationEdits, id: string): CitationEdits { + if (edits.added.includes(id)) { + return { ...edits, added: edits.added.filter((other) => other !== id) } + } + if (edits.removed.includes(id)) return edits + return { ...edits, removed: [...edits.removed, id] } +} diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index e857619c..3f938d7c 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -53,8 +53,12 @@ export interface LeaveAnswer { } export type CanLeave = (forced: boolean) => LeaveAnswer -/** The layers that can hold a form the user must settle before leaving, top one last. */ -const LAYERS = ['finding', 'reference'] as const +/** + * The layers that can hold a form the user must settle before leaving, in stacking order + * (top one last): the finding dialog, the citations dialog over it (its edit mode, Rev 5), + * the reference dialog over either. + */ +export const LAYERS = ['finding', 'citations', 'reference'] as const export type LayerName = (typeof LAYERS)[number] /** One guard per layer (R2F-1): each layer registers its own check while it is mounted. */ @@ -132,8 +136,11 @@ export interface EditorNavigation { replaceFinding: (key: ElementKey | null, text?: string) => void /** Opens the citations dialog of a family or a node; any other key is ignored. */ openCitations: (citedBy: ElementKey, opener?: Opener) => void - /** A user close of the citations dialog. */ - closeCitations: () => boolean + /** + * A close of the citations dialog: a user one is refused by its draft (it asks first), + * a forced one goes (the draft is dropped). + */ + closeCitations: (forced?: boolean) => boolean /** « X références », where the focus returns once the citations dialog is closed. */ citationsTrigger: () => HTMLElement | null /** @@ -386,7 +393,7 @@ function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) { /** The citations dialog over the finding dialog: opened for a family or a node only. */ function useCitationsLayer(ctx: LayerContext, openers: Openers) { - const { dispatch, mark } = ctx + const { dispatch, guards, mark } = ctx const openCitations = useCallback( (citedBy: ElementKey, opener?: Opener) => { if (!isCitable(citedBy)) return @@ -397,35 +404,48 @@ function useCitationsLayer(ctx: LayerContext, openers: Openers) { }, [openers, dispatch, mark], ) - const closeCitations = useCallback(() => { - mark() - dispatch({ type: 'close_citations' }) - return true - }, [dispatch, mark]) + const closeCitations = useCallback( + (forced = false) => { + if (!guards.ask('citations', forced).allowed) return false + mark() + dispatch({ type: 'close_citations' }) + return true + }, + [guards, dispatch, mark], + ) return { openCitations, closeCitations } } +/** The layers stacked over `layer`, top one last. */ +export const layersAbove = (layer: LayerName): LayerName[] => + LAYERS.slice(LAYERS.indexOf(layer) + 1) + /** * Asks every layer, top down, before a move that leaves them all; true when none refused. - * When the finding dialog is the top one to refuse, the clean dialogs over it close first - * so its question is the one in view (as a refused Back, `bareFinding`). + * The clean dialogs over the top one to refuse close first so its question is the one in + * view (as a refused Back, `refusePop`). */ function useAskLeaving(ctx: LayerContext, state: NavigationState) { const { guards, dispatch, mark } = ctx - const cited = citationsOfView(state) !== null + const citations = citationsOfView(state) !== null const reference = state.reference !== null return useCallback((): boolean => { const refused = [...LAYERS] .reverse() .filter((layer) => !guards.ask(layer, false).allowed) - if (refused[0] !== 'finding' || !(cited || reference)) { - return refused.length === 0 - } + if (refused.length === 0) return true + const above = layersAbove(refused[0]) + const shown = { finding: false, citations, reference } + if (!above.some((layer) => shown[layer])) return false mark() - if (reference) dispatch({ type: 'close_reference' }) - if (cited) dispatch({ type: 'close_citations' }) + if (above.includes('reference') && reference) { + dispatch({ type: 'close_reference' }) + } + if (above.includes('citations') && citations) { + dispatch({ type: 'close_citations' }) + } return false - }, [guards, dispatch, mark, cited, reference]) + }, [guards, dispatch, mark, citations, reference]) } /** « Aller à » and « Tout afficher » leave every layer: a layer in edit may refuse. */ diff --git a/apps/app/src/editor/useReferenceMoves.ts b/apps/app/src/editor/useReferenceMoves.ts index 6fed7874..5d448fb6 100644 --- a/apps/app/src/editor/useReferenceMoves.ts +++ b/apps/app/src/editor/useReferenceMoves.ts @@ -1,4 +1,4 @@ -import { useCallback, useRef, useState, type RefObject } from 'react' +import { useCallback, useRef, useState } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' import type { LayerContext, MoveTrace } from './useEditorNavigation' @@ -10,12 +10,19 @@ export interface AddedReference { type Opener = HTMLElement | null | undefined +/** What a creation started from the citations dialog's edit form does with the new id. */ +export type CiteCreated = (id: string) => void + /** What the reference dialog (R2F-5) and the References tab's filter (R2F-6) do to the view. */ export interface ReferenceMoves { /** The dialog of reference `id`, over the place the view shows. */ open: (id: string, opener?: Opener) => void - /** The creation dialog, over the References tab. */ - start: (opener?: Opener) => void + /** + * The creation dialog, over the References tab or the citations dialog. `cite` is the + * citations edit form that started it (Rev 5): the new id goes to its draft, and the + * library shows no « added » notice for it. + */ + start: (opener?: Opener, cite?: CiteCreated) => void /** A user close; false when the form refused it (a dirty draft asks first). */ close: (forced?: boolean) => boolean /** @@ -35,19 +42,27 @@ export interface ReferenceMoves { backToFinding: (key: ElementKey) => void } +/** What the open dialog was started from: its opener, and a citing form for a creation. */ +interface Held { + opener: Opener + cite: CiteCreated | null +} + /** The moves that add the dialog: an edit of a reference, a creation. */ -function useOpening({ dispatch, mark }: LayerContext, held: RefObject) { +function useOpening({ dispatch, mark }: LayerContext, held: Held) { const open = useCallback( (id: string, opener?: Opener) => { - held.current = opener + held.opener = opener + held.cite = null mark() dispatch({ type: 'open_reference', id }) }, [dispatch, mark, held], ) const start = useCallback( - (opener?: Opener) => { - held.current = opener + (opener?: Opener, cite?: CiteCreated) => { + held.opener = opener + held.cite = cite ?? null mark() dispatch({ type: 'create_reference' }) }, @@ -89,14 +104,24 @@ function useClosing(ctx: LayerContext) { return { close: useClose(ctx), replace: useReplace(ctx) } } -/** A creation that succeeded: its entry becomes the reference's own, then it closes. */ -function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) { +/** + * A creation that succeeded: its entry becomes the reference's own, then it closes. The + * citing form that started it takes the id (no notice); else the library says it. + */ +function useCreated( + ctx: LayerContext, + replace: ReferenceMoves['replace'], + held: Held, +) { const { dispatch, mark } = ctx const [added, setAdded] = useState(null) const created = useCallback( (id: string) => { + const citing = held.cite + held.cite = null replace(id) - setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 })) + if (citing) citing(id) + else setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 })) // Precondition: the caller is a discrete event (the form's submit). React then // renders the replace and runs the history effect before this microtask, so the // entry is the reference's own before the close goes back over it and a Forward @@ -108,7 +133,7 @@ function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) { dispatch({ type: 'close_reference' }) }) }, - [replace, mark, dispatch], + [replace, mark, dispatch, held], ) return { created, added } } @@ -139,16 +164,16 @@ export function useReferenceMoves( ctx: LayerContext, trace: MoveTrace, ): ReferenceMoves { - const held = useRef(null) + const held = useRef({ opener: null, cite: null }).current const opener = useCallback((): HTMLElement | null => { - const element = held.current + const element = held.opener return element?.isConnected && !element.closest('[hidden]') ? element : null }, [held]) const closing = useClosing(ctx) return { ...useOpening(ctx, held), ...closing, - ...useCreated(ctx, closing.replace), + ...useCreated(ctx, closing.replace, held), ...useFilter(ctx, trace), opener, } diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index f01f5df6..7f063a91 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1229,6 +1229,10 @@ export const en: Dict = { 'editor.annotations.deselected': 'No annotation selected.', 'editor.references.search': 'Search a reference', 'editor.references.dialog_title': 'References of the finding', + 'editor.citations.edit': 'Edit', + 'editor.citations.edit_title': 'Edit the references of the finding', + 'editor.citations.edit_reference': 'Edit the reference', + 'editor.citations.new_reference': 'New reference', 'editor.references.panel_count_one': '{count} reference cited by this finding', 'editor.references.panel_count_other': '{count} references cited by this finding', 'editor.references.panel_show_all': 'Show all in the References tab', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 0b37b236..489bd77e 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1260,6 +1260,10 @@ export const fr: Dict = { 'editor.annotations.deselected': 'Aucune annotation sélectionnée.', 'editor.references.search': 'Rechercher une référence', 'editor.references.dialog_title': 'Références du constat', + 'editor.citations.edit': 'Modifier', + 'editor.citations.edit_title': 'Modifier les références du constat', + 'editor.citations.edit_reference': 'Modifier la référence', + 'editor.citations.new_reference': 'Nouvelle référence', 'editor.references.panel_count_one': '{count} référence citée par ce constat', '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', diff --git a/apps/app/tests/helpers/findingsHost.tsx b/apps/app/tests/helpers/findingsHost.tsx index df7265b7..2db7ec67 100644 --- a/apps/app/tests/helpers/findingsHost.tsx +++ b/apps/app/tests/helpers/findingsHost.tsx @@ -31,6 +31,8 @@ export default function FindingsHost({ onShowAll={() => undefined} navigate={nav.navigate} returnFocus={nav.citationsTrigger} + guards={nav.guards} + references={nav.references} /> ) diff --git a/apps/app/tests/unit/editor-citation-edits.test.ts b/apps/app/tests/unit/editor-citation-edits.test.ts new file mode 100644 index 00000000..d7d3fa6d --- /dev/null +++ b/apps/app/tests/unit/editor-citation-edits.test.ts @@ -0,0 +1,29 @@ +/** Rev 5 Task 12: the citations draft, held as additions and removals. */ +import { describe, expect, it } from 'vitest' +import { + addId, + applyEdits, + NO_EDITS, + removeId, +} from '@/editor/references/citationEdits' + +describe('citation edits', () => { + it('applies removals and additions to the current list, each id once', () => { + const edits = addId(removeId(NO_EDITS, 'a'), 'b') + expect(applyEdits(['a', 'c'], edits)).toEqual(['c', 'b']) + expect(applyEdits(['a', 'b'], edits)).toEqual(['b']) + expect(applyEdits([], edits)).toEqual(['b']) + }) + + it('a removal then a citation of the same id is no change at all', () => { + expect(addId(removeId(NO_EDITS, 'a'), 'a')).toEqual(NO_EDITS) + expect(removeId(addId(NO_EDITS, 'n'), 'n')).toEqual(NO_EDITS) + }) + + it('a repeat is ignored', () => { + const once = addId(NO_EDITS, 'b') + expect(addId(once, 'b')).toBe(once) + const gone = removeId(NO_EDITS, 'a') + expect(removeId(gone, 'a')).toBe(gone) + }) +}) diff --git a/apps/app/tests/unit/editor-citations-edit.test.tsx b/apps/app/tests/unit/editor-citations-edit.test.tsx new file mode 100644 index 00000000..28968bcd --- /dev/null +++ b/apps/app/tests/unit/editor-citations-edit.test.tsx @@ -0,0 +1,581 @@ +/** Rev 5 Task 12: the references dialog's edit mode (draft, save, guards, stacked dialogs). */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { Location, NavigateFunction } from 'react-router-dom' +import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry' +import { + forgetSessionTag, + resolveSessionTag, +} from '@/editor/history/sessionTag' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { edit, insert } from '../helpers/editorFixtures' +import { + baseText, + resetStore, + serverHas, + SHEET, + store, + USER, +} from '../helpers/editorHarness' +import { mountDraft, setWidth } from '../helpers/editorRoute' +import { + findingDialog, + inFindingDialog, + openFinding, +} from '../helpers/findingDialog' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +let navigate: NavigateFunction +let location: Location +const probe = (n: NavigateFunction, l: Location) => { + navigate = n + location = l +} +const written = () => + (location.state as Record | null)?.[ENTRY_KEY] + +let TAG: string +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + TAG = resolveSessionTag(USER) +}) +afterEach(() => { + cleanup() + resetStore() + setWidth(1024) +}) + +const name = (n: string) => ({ fr: n, en: n }) +const ref = (id: string, citation: string) => + ({ + kind: 'reference', + value: { id, type: 'book', citation, url: null, doi: null }, + }) as const + +/** Barone (ref-a), Denoix (ref-b), Code rural (ref-c); Node A cites `ids`. */ +function sheetText(ids = ['ref-a', 'ref-c']): string { + let text = baseText() + text = insert(text, ref('ref-a', 'Barone, Ostéologie')) + text = insert(text, ref('ref-b', 'Denoix')) + text = insert(text, ref('ref-c', 'Code rural')) + 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: [], + 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: {}, + reference_ids: ids, + requires_vet_referral: false, + review_status: 'to_confirm', + children: [], + }, + }, + }) +} + +const nodeKey = { + kind: 'finding' as const, + zone_id: 'zone-a', + path: ['fcat-a', 'fnode-a'], +} + +type User = ReturnType + +async function mount(width = 1280, text = sheetText()): Promise { + serverHas(text, 3) + const user = userEvent.setup() + mountDraft({ width, probe }) + await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) + await user.click(screen.getByRole('tab', { name: 'Constats' })) + await waitFor(() => expect(written()?.view.tab).toBe('findings')) + return user +} + +const doc = () => JSON.parse(store.getState().documentText) +const nodeA = () => + doc().finding_zones[0].categories[0].children[0] as { + name: { fr: string } + reference_ids: string[] + } +const library = () => + (doc().references as { id: string; citation: string }[]).map( + (r) => r.citation, + ) +const undos = () => store.getState().undo.length +const back = (steps = 1) => act(async () => navigate(-steps)) +const question = 'Abandonner les modifications ?' + +const openDialogs = () => [ + ...document.querySelectorAll('dialog[open][data-layer]'), +] +const citations = () => + openDialogs().find((d) => d.querySelector('[data-place="citations"]')) +const inCitations = () => within(citations()!) +const referenceDialog = () => + openDialogs().find((d) => d.querySelector('#reference-form-citation')) +const inReference = () => within(referenceDialog()!) +const button = (label: string | RegExp) => + inCitations().getByRole('button', { name: label }) +const rows = () => + [...citations()!.querySelectorAll('[data-citation-row]')].map((row) => + row.getAttribute('data-citation-row'), + ) + +/** Node A's dialog, then its references dialog. */ +async function openCitations(user: User, trigger = '2 références') { + await openFinding(user, /Node A/) + await user.click(inFindingDialog().getByRole('button', { name: trigger })) + await waitFor(() => expect(citations()).toBeDefined()) +} + +/** The references dialog of Node A, in its edit mode. */ +async function editCitations(user: User, trigger?: string) { + await openCitations(user, trigger) + await user.click(button('Modifier')) + await waitFor(() => + expect( + inCitations().getByRole('heading', { + name: 'Modifier les références du constat', + }), + ).toBeVisible(), + ) +} + +const removeRow = (user: User, citation: RegExp) => + user.click( + inCitations().getByRole('button', { + name: new RegExp(`^Retirer ${citation.source}`), + }), + ) +const cite = (user: User, id: string) => + user.selectOptions(inCitations().getByLabelText('Citer une référence'), id) + +describe('the « Modifier » of the references dialog', () => { + it('switches to the edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => { + const user = await mount() + await openCitations(user) + const before = written()!.id + await user.click(button('Modifier')) + expect(written()!.id).toBe(before) + expect(rows()).toEqual(['ref-a', 'ref-c']) + expect( + inCitations().queryByRole('button', { name: /Tout afficher/ }), + ).toBeNull() + expect(inCitations().queryByRole('button', { name: 'Aller à' })).toBeNull() + }) + + it('is not offered read only (below 1 024 px)', async () => { + const user = await mount(900) + await openCitations(user) + expect(inCitations().queryByRole('button', { name: 'Modifier' })).toBeNull() + }) +}) + +describe('the draft', () => { + it('stages a removal and a citation, writes nothing until « Enregistrer »', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + await cite(user, 'ref-b') + expect(rows()).toEqual(['ref-c', 'ref-b']) + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c']) + expect(undos()).toBe(0) + }) + + it('one save is one update, one undo; back to the view mode, focus on « Modifier »', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + await cite(user, 'ref-b') + await user.click(button('Enregistrer')) + expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b']) + expect(undos()).toBe(1) + await waitFor(() => expect(button('Modifier')).toHaveFocus()) + expect( + inCitations().getByText('Modifications enregistrées'), + ).toBeInTheDocument() + act(() => { + store.getState().undoStep() + }) + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c']) + }) + + it('a pristine save writes nothing', async () => { + const user = await mount() + await editCitations(user) + await user.click(button('Enregistrer')) + expect(undos()).toBe(0) + await waitFor(() => expect(button('Modifier')).toHaveFocus()) + expect(inCitations().queryByText('Modifications enregistrées')).toBeNull() + }) + + it('a dangling id is named and removable', async () => { + const user = await mount(1280, sheetText(['ref-a', 'ref-x'])) + await editCitations(user) + expect(inCitations().getByText(/^Référence introuvable/)).toBeVisible() + await removeRow(user, /ref-x/) + await user.click(button('Enregistrer')) + expect(nodeA().reference_ids).toEqual(['ref-a']) + }) + + it('a save keeps citations changed elsewhere: removals and additions on the current list', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + act(() => { + const node = doc().finding_zones[0].categories[0].children[0] + store.getState().commit({ + op: 'update', + key: nodeKey, + element: { + kind: 'finding_node', + value: { ...node, reference_ids: ['ref-a', 'ref-c', 'ref-b'] }, + }, + }) + }) + await user.click(button('Enregistrer')) + expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b']) + }) +}) + +describe('leaving the edit mode with changes', () => { + it('« Annuler » asks; « Abandonner » goes back to the view, nothing written', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + await user.click(button('Annuler')) + expect(inCitations().getByText(question)).toBeVisible() + await user.click(button('Abandonner')) + await waitFor(() => expect(button('Modifier')).toHaveFocus()) + expect(citations()).toBeDefined() + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c']) + }) + + it('« Annuler » without changes goes back at once', async () => { + const user = await mount() + await editCitations(user) + await user.click(button('Annuler')) + await waitFor(() => expect(button('Modifier')).toHaveFocus()) + }) + + it('Escape and ✕ ask; the dialog stays', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + await user.click(button('Fermer')) + expect(citations()).toBeDefined() + expect(inCitations().getByText(question)).toBeVisible() + await user.click(button('Continuer la saisie')) + act(() => button('Annuler').focus()) + await user.keyboard('{Escape}') + expect(citations()).toBeDefined() + expect(inCitations().getByText(question)).toBeVisible() + }) + + it('a Back that closes only the references dialog asks; the draft stays', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + await back() + expect(citations()).toBeDefined() + expect(inCitations().getByText(question)).toBeVisible() + expect(rows()).toEqual(['ref-c']) + expect(written()!.view.finding).toMatchObject({ citations: true }) + }) + + it('a flip to read only keeps the draft, every control off, only « Abandonner »', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + act(() => { + setWidth(900) + window.dispatchEvent(new Event('resize')) + }) + expect(rows()).toEqual(['ref-c']) + expect(inCitations().getByText(/Élargissez la fenêtre/)).toBeVisible() + expect(button('Enregistrer')).toBeDisabled() + expect(button(/^Retirer/)).toBeDisabled() + expect(button(/^Modifier la référence/)).toBeDisabled() + expect(button('Nouvelle référence')).toBeDisabled() + expect(inCitations().queryByLabelText('Citer une référence')).toBeNull() + expect(inCitations().queryByRole('button', { name: 'Annuler' })).toBeNull() + await user.click(button('Abandonner')) + await waitFor(() => + expect( + inCitations().getByRole('heading', { name: 'Références du constat' }), + ).toBeVisible(), + ) + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c']) + }) +}) + +describe('the reference dialog over the edit mode', () => { + it('« Modifier la référence » stacks it; closed, the draft and the focus are back', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Code rural/) + const opener = button(/^Modifier la référence Barone/) + await user.click(opener) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + expect(openDialogs()).toHaveLength(3) + expect( + inReference().getByRole('heading', { name: 'Modifier la référence' }), + ).toBeVisible() + await user.click(inReference().getByRole('button', { name: 'Fermer' })) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + await waitFor(() => expect(opener).toHaveFocus()) + expect(rows()).toEqual(['ref-a']) + }) + + it('« Nouvelle référence » creates it and cites it in the draft only', async () => { + const user = await mount() + await editCitations(user) + await user.click(button('Nouvelle référence')) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute( + 'aria-selected', + 'true', + ) + await user.selectOptions(inReference().getByLabelText('Type'), 'book') + await user.type(inReference().getByLabelText('Citation'), 'Neuf') + await user.click( + inReference().getByRole('button', { name: 'Ajouter la référence' }), + ) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + expect(library()).toContain('Neuf') + const id = doc().references.find( + (r: { citation: string }) => r.citation === 'Neuf', + ).id + expect(rows()).toEqual(['ref-a', 'ref-c', id]) + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c']) + await user.click(button('Enregistrer')) + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', id]) + expect(undos()).toBe(2) + }) + + it('a reference created, then the draft abandoned, stays in the library uncited', async () => { + const user = await mount() + await editCitations(user) + await user.click(button('Nouvelle référence')) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + await user.selectOptions(inReference().getByLabelText('Type'), 'book') + await user.type(inReference().getByLabelText('Citation'), 'Neuf') + await user.click( + inReference().getByRole('button', { name: 'Ajouter la référence' }), + ) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + await user.click(button('Annuler')) + await user.click(button('Abandonner')) + expect(library()).toContain('Neuf') + expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c']) + expect(undos()).toBe(1) + }) +}) + +describe('a finding draft and a references draft on the same element', () => { + it('are both saved; neither overwrites the other', async () => { + const user = await mount() + await openFinding(user, /Node A/) + await user.click( + inFindingDialog().getByRole('button', { name: 'Modifier' }), + ) + await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis') + await user.click( + inFindingDialog().getByRole('button', { name: '2 références' }), + ) + await waitFor(() => expect(citations()).toBeDefined()) + await user.click(button('Modifier')) + await removeRow(user, /Barone/) + await user.click(button('Enregistrer')) + await user.click(button('Fermer')) + await waitFor(() => expect(citations()).toBeUndefined()) + await user.click( + inFindingDialog().getByRole('button', { name: 'Enregistrer' }), + ) + expect(nodeA().name.fr).toBe('Node A bis') + expect(nodeA().reference_ids).toEqual(['ref-c']) + expect(undos()).toBe(2) + }) +}) + +describe('leaving the editor with a citations draft', () => { + it('a sign-out leaves the account flag of the citations layer', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + act(() => { + forgetSessionTag() + useAuthStore.setState({ user: null }) + }) + await waitFor(() => expect(citations()).toBeUndefined()) + const flags = Object.keys(sessionStorage) + .filter((k) => k.startsWith('faunosteo:editor:left-draft-account:')) + .map((k) => JSON.parse(sessionStorage.getItem(k)!)) + expect(flags).toHaveLength(1) + expect(flags[0]).toMatchObject({ kind: 'citations', key: nodeKey }) + expect(JSON.stringify(flags)).not.toContain('Barone') + }) + + it('a plain leave flags the citations layer', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Barone/) + cleanup() + const flag = sessionStorage.getItem( + `faunosteo:editor:left-draft:${SHEET}:${TAG}`, + ) + expect(JSON.parse(flag!)).toEqual({ kind: 'citations', key: nodeKey }) + }) +}) + +/** The Navigation API as the leave guard reads it: `navigate` events and `traverseTo`. */ +class NavigationStub extends EventTarget { + traverseTo = vi.fn((key: string) => { + void key + return { committed: Promise.resolve(), finished: Promise.resolve() } + }) +} + +describe('a reference over the references dialog of a dirty finding (criterion 23)', () => { + let api: NavigationStub + beforeEach(() => { + api = new NavigationStub() + Object.defineProperty(window, 'navigation', { + value: api, + configurable: true, + }) + }) + afterEach(() => { + Reflect.deleteProperty(window, 'navigation') + }) + + function jump() { + const url = new URL('/app/admin/sheets', window.location.origin).href + const event = Object.assign(new Event('navigate', { cancelable: true }), { + navigationType: 'traverse', + destination: { url, key: 'list', sameDocument: true }, + }) + act(() => { + api.dispatchEvent(event) + }) + return event + } + + /** Node A in edit with a typed name, its references in edit, Barone in edit, typed. */ + async function stacked(user: User) { + await openFinding(user, /Node A/) + await user.click( + inFindingDialog().getByRole('button', { name: 'Modifier' }), + ) + await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis') + await user.click( + inFindingDialog().getByRole('button', { name: '2 références' }), + ) + await waitFor(() => expect(citations()).toBeDefined()) + await user.click(button('Modifier')) + await user.click(button(/^Modifier la référence Barone/)) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + await user.type(inReference().getByLabelText('Citation'), ' x') + } + + it('the finding asks next with the references dialog closed, focused; the jump goes after it', async () => { + const user = await mount() + await stacked(user) + expect(jump().defaultPrevented).toBe(true) + expect(inReference().getByText(question)).toBeVisible() + await user.click(inReference().getByRole('button', { name: 'Abandonner' })) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + await waitFor(() => expect(citations()).toBeUndefined()) + const finding = within(findingDialog()!) + expect(finding.getByText(question)).toBeVisible() + const keep = finding.getByRole('button', { name: 'Continuer la saisie' }) + await waitFor(() => expect(keep).toHaveFocus()) + expect(api.traverseTo).not.toHaveBeenCalled() + await user.click(finding.getByRole('button', { name: 'Abandonner' })) + expect(api.traverseTo).toHaveBeenCalledWith('list') + }) + + it('« Continuer la saisie » there keeps the finding draft and drops the jump', async () => { + const user = await mount() + await stacked(user) + jump() + await user.click(inReference().getByRole('button', { name: 'Abandonner' })) + await waitFor(() => expect(citations()).toBeUndefined()) + const finding = within(findingDialog()!) + await user.click( + finding.getByRole('button', { name: 'Continuer la saisie' }), + ) + expect(finding.getByLabelText('Nom (FR)')).toHaveValue('Node A bis') + expect(api.traverseTo).not.toHaveBeenCalled() + }) + + it('a citations draft under a clean reference dialog asks once the reference is closed', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Code rural/) + await user.click(button(/^Modifier la référence Barone/)) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + expect(jump().defaultPrevented).toBe(true) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + expect(inCitations().getByText(question)).toBeVisible() + const keep = inCitations().getByRole('button', { + name: 'Continuer la saisie', + }) + await waitFor(() => expect(keep).toHaveFocus()) + await user.click(button('Abandonner')) + expect(api.traverseTo).toHaveBeenCalledWith('list') + }) +}) + +describe('a Back over a citations draft under a clean reference dialog', () => { + it('the reference dialog closes, the draft asks, the view is pushed again', async () => { + const user = await mount() + await editCitations(user) + await removeRow(user, /Code rural/) + await user.click(button(/^Modifier la référence Barone/)) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + await back(2) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + expect(citations()).toBeDefined() + expect(inCitations().getByText(question)).toBeVisible() + expect(rows()).toEqual(['ref-a']) + expect(written()!.view).toMatchObject({ + reference: null, + finding: { citations: true }, + }) + }) +}) diff --git a/apps/app/tests/unit/editor-citations-guards.test.tsx b/apps/app/tests/unit/editor-citations-guards.test.tsx new file mode 100644 index 00000000..56dc5836 --- /dev/null +++ b/apps/app/tests/unit/editor-citations-guards.test.tsx @@ -0,0 +1,172 @@ +/** Rev 5 Task 12: the citations layer's guard (Back, refusal, close, order, creation). */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, render } from '@testing-library/react' +import type { ElementKey } from '@faunosteo/core-wasm/types' +import { + MemoryRouter, + useLocation, + useNavigate, + type Location, + type NavigateFunction, +} from 'react-router-dom' +import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry' +import useEditorHistory from '@/editor/history/useEditorHistory' +import { LAYERS_TOP_DOWN, topDirtyLayer } from '@/editor/leftDraft' +import { defaultView } from '@/editor/navigation' +import { + useEditorNavigation, + type EditorNavigation, + type LayerName, +} from '@/editor/useEditorNavigation' + +afterEach(cleanup) + +const owner = { sheetId: 'S', tag: 'T' } +const node: ElementKey = { + kind: 'finding', + zone_id: 'zone', + path: ['family', 'node'], +} + +let nav: EditorNavigation +let navigate: NavigateFunction +let location: Location +const entry = () => (location.state as Record)[ENTRY_KEY] + +function Page() { + nav = useEditorNavigation('findings') + navigate = useNavigate() + location = useLocation() + useEditorHistory(nav, owner, defaultView('findings')) + return null +} + +function mount() { + render( + + + , + ) +} + +/** A layer whose form holds changes: a user ask refuses, a forced one says the note. */ +const dirty = vi.fn((forced: boolean) => + forced ? { allowed: true, note: 'dropped' } : { allowed: false }, +) +const register = (layer: LayerName) => + act(() => nav.guards.register(layer, dirty)) + +/** Node's finding dialog, then its citations dialog: two entries. */ +function cited() { + mount() + act(() => nav.openFinding(node)) + act(() => nav.openCitations(node)) +} + +describe('the layer order', () => { + it('reference, citations, finding: asked top down', () => { + expect(LAYERS_TOP_DOWN).toEqual(['reference', 'citations', 'finding']) + mount() + const order: string[] = [] + for (const layer of ['finding', 'citations', 'reference'] as const) { + nav.guards.register(layer, () => { + order.push(layer) + return { allowed: true } + }) + } + nav.guards.askAll(false) + expect(order).toEqual(['reference', 'citations', 'finding']) + }) + + it('topDirtyLayer: citations over finding, reference over both', () => { + mount() + register('finding') + register('citations') + expect(topDirtyLayer(nav.guards)).toBe('citations') + expect(topDirtyLayer(nav.guards, 'citations')).toBe('finding') + register('reference') + expect(topDirtyLayer(nav.guards)).toBe('reference') + expect(topDirtyLayer(nav.guards, 'reference')).toBe('citations') + }) +}) + +describe('a Back over a citations draft', () => { + it('closing only the citations dialog asks; the view and the entry stay', () => { + cited() + register('citations') + dirty.mockClear() + act(() => navigate(-1)) + expect(dirty).toHaveBeenCalledWith(false) + expect(nav.state.finding).toMatchObject({ citations: true }) + expect(entry().view.finding).toMatchObject({ citations: true }) + }) + + it('a clean citations layer lets it close', () => { + cited() + act(() => nav.guards.register('citations', () => ({ allowed: true }))) + act(() => navigate(-1)) + expect(nav.state.finding).toMatchObject({ citations: false }) + }) + + it('under a clean reference dialog: the reference closes, the draft asks', () => { + cited() + act(() => nav.references.open('ref-a')) + register('citations') + dirty.mockClear() + act(() => navigate(-2)) + expect(dirty).toHaveBeenCalledWith(false) + expect(nav.state.reference).toBeNull() + expect(nav.state.finding).toMatchObject({ citations: true }) + expect(entry().view).toMatchObject({ + reference: null, + finding: { citations: true }, + }) + }) +}) + +describe('closeCitations', () => { + it('a user close is refused by a draft; a forced one goes', () => { + cited() + register('citations') + let closed = true + act(() => { + closed = nav.closeCitations() + }) + expect(closed).toBe(false) + expect(nav.state.finding).toMatchObject({ citations: true }) + act(() => { + closed = nav.closeCitations(true) + }) + expect(closed).toBe(true) + expect(nav.state.finding).toMatchObject({ citations: false }) + }) +}) + +describe('a creation started over the citations dialog', () => { + it('hands its id to the form that started it; no « added » notice', async () => { + cited() + const cite = vi.fn() + act(() => nav.references.start(null, cite)) + expect(nav.state).toMatchObject({ + tab: 'findings', + reference: { create: true }, + }) + await act(async () => nav.references.created('ref-new')) + expect(cite).toHaveBeenCalledWith('ref-new') + expect(nav.references.added).toBeNull() + expect(nav.state.reference).toBeNull() + expect(nav.state.finding).toMatchObject({ citations: true }) + }) + + it('a later creation from the library sets the notice, cites nothing', async () => { + cited() + const cite = vi.fn() + act(() => nav.references.start(null, cite)) + act(() => nav.references.close(true)) + act(() => nav.selectTab('references')) + act(() => nav.references.start(null)) + await act(async () => nav.references.created('ref-lib')) + expect(cite).not.toHaveBeenCalled() + expect(nav.references.added).toMatchObject({ id: 'ref-lib' }) + }) +}) diff --git a/apps/app/tests/unit/editor-escape.test.tsx b/apps/app/tests/unit/editor-escape.test.tsx index d7416b3b..d8d394ab 100644 --- a/apps/app/tests/unit/editor-escape.test.tsx +++ b/apps/app/tests/unit/editor-escape.test.tsx @@ -281,10 +281,10 @@ describe('Escape with the focus on the page', () => { await select(user) await openCitations(user) const trigger = screen.getByRole('button', { name: '1 référence' }) - expect(trigger).toHaveAttribute('aria-expanded', 'true') + expect(trigger).toHaveAttribute('aria-haspopup', 'dialog') await user.keyboard('{Escape}') await waitFor(() => expect(citations()).toBeNull()) - expect(trigger).toHaveAttribute('aria-expanded', 'false') + await waitFor(() => expect(trigger).toHaveFocus()) // the finding dialog under the sheet is still there: a second Escape closes it expect(document.querySelector('dialog[open]')).not.toBeNull() await user.keyboard('{Escape}') diff --git a/apps/app/tests/unit/editor-history-entry.test.ts b/apps/app/tests/unit/editor-history-entry.test.ts index e3fe4168..d373ab64 100644 --- a/apps/app/tests/unit/editor-history-entry.test.ts +++ b/apps/app/tests/unit/editor-history-entry.test.ts @@ -109,6 +109,10 @@ describe('sanitizeView', () => { expect(sanitizeView(creation)?.reference).toEqual({ create: true }) const elsewhere = { ...view('general'), reference: { create: true } } expect(sanitizeView(elsewhere)?.reference).toBeNull() + // Rev 5: a creation over the citations dialog is never read back (POP, reload). + const overCitations = { ...sheet, reference: { create: true } } + expect(sanitizeView(overCitations)?.reference).toBeNull() + expect(sanitizeView(overCitations)?.finding).toEqual(sheet.finding) expect( sanitizeView({ ...tab, reference: { edit: '' } })?.reference, ).toBeNull() diff --git a/apps/app/tests/unit/editor-leave-cascade.test.tsx b/apps/app/tests/unit/editor-leave-cascade.test.tsx index 4635c72f..82836071 100644 --- a/apps/app/tests/unit/editor-leave-cascade.test.tsx +++ b/apps/app/tests/unit/editor-leave-cascade.test.tsx @@ -46,6 +46,7 @@ function Editor() { return ( <> + ) @@ -93,23 +94,28 @@ const layer = (name: LayerName) => screen.queryByTestId(name) const button = (name: LayerName, label: string) => within(layer(name)!).getByRole('button', { name: label }) -describe('a reference dialog over a finding dialog, both dirty', () => { - it('asks the reference, then the finding, then the jump goes', async () => { +describe('reference, citations and finding dialogs, all dirty', () => { + it('asks the reference, the citations, then the finding, then the jump goes', async () => { const user = userEvent.setup() expect(jump().defaultPrevented).toBe(true) expect(within(layer('finding')!).queryByRole('group')).toBeNull() + expect(within(layer('citations')!).queryByRole('group')).toBeNull() await user.click(button('reference', 'Abandonner')) expect(layer('reference')).toBeNull() + expect(within(layer('finding')!).queryByRole('group')).toBeNull() + await user.click(button('citations', 'Abandonner')) + expect(layer('citations')).toBeNull() expect(api.traverseTo).not.toHaveBeenCalled() await user.click(button('finding', 'Abandonner')) expect(api.traverseTo).toHaveBeenCalledTimes(1) expect(api.traverseTo).toHaveBeenCalledWith('list') }) - it('« Continuer la saisie » on the second keeps the finding, no jump', async () => { + it('« Continuer la saisie » on the last keeps the finding, no jump', async () => { const user = userEvent.setup() jump() await user.click(button('reference', 'Abandonner')) + await user.click(button('citations', 'Abandonner')) await user.click(button('finding', 'Continuer la saisie')) expect(layer('finding')).not.toBeNull() expect(within(layer('finding')!).queryByRole('group')).toBeNull() @@ -121,6 +127,7 @@ describe('a reference dialog over a finding dialog, both dirty', () => { jump() await user.click(button('reference', 'Continuer la saisie')) expect(layer('reference')).not.toBeNull() + expect(layer('citations')).not.toBeNull() expect(layer('finding')).not.toBeNull() expect(api.traverseTo).not.toHaveBeenCalled() }) diff --git a/apps/app/tests/unit/editor-navigation.test.ts b/apps/app/tests/unit/editor-navigation.test.ts index 46eb98c0..74b2e02d 100644 --- a/apps/app/tests/unit/editor-navigation.test.ts +++ b/apps/app/tests/unit/editor-navigation.test.ts @@ -180,6 +180,20 @@ describe('navigationReducer', () => { }) }) + it('a creation over the citations dialog keeps the tab and both dialogs under it', () => { + const created = run( + initialNavigation('findings'), + { type: 'open_finding', key: node }, + { type: 'open_citations', citedBy: node }, + { type: 'create_reference' }, + ) + expect(created).toMatchObject({ + tab: 'findings', + finding: { key: node, citations: true }, + reference: { create: true }, + }) + }) + it('the filter belongs to the References tab: any move to another tab drops it', () => { const filtered = run(initialNavigation('findings'), { type: 'show_all_references', diff --git a/apps/app/tests/unit/editor-references-panel.test.tsx b/apps/app/tests/unit/editor-references-panel.test.tsx index 59eb8db6..81fb4181 100644 --- a/apps/app/tests/unit/editor-references-panel.test.tsx +++ b/apps/app/tests/unit/editor-references-panel.test.tsx @@ -223,7 +223,7 @@ describe('opening', () => { expect(panel()).not.toHaveTextContent('Denoix') }) - it('view mode: an open tile marks the current finding, « Aller à » only, no edit control', async () => { + it('view mode: an open tile marks the current finding, « Aller à » only; « Modifier » is the dialog’s', async () => { const user = await mount() await openFromFinding(user) await user.click(within(panel()).getByRole('button', { name: /^Barone/ })) @@ -239,9 +239,14 @@ describe('opening', () => { 'Monter', 'Descendre', ]) { + expect(within(tile).queryByRole('button', { name: absent })).toBeNull() expect( within(citationsDialog()).queryByRole('button', { name: absent }), - ).toBeNull() + ).toBe( + absent === 'Modifier' + ? document.getElementById('citations-edit-button') + : null, + ) } expect(within(citationsDialog()).queryByRole('searchbox')).toBeNull() expect(within(citationsDialog()).queryByRole('textbox')).toBeNull()