From 18085cecf810f240f2a648cf1c256003037575c7 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 13 Nov 2026 18:51:35 +0100 Subject: [PATCH] feat(editor): finding dialog and citations side sheet in the history Constats opens each element in one modal dialog (view, edit with a local draft, creation) driven by the editor view layer of the browser history. The citations panel becomes a modal side sheet stacked over it; its geometry, exit machinery and page inertness are removed. Back and Forward restore the layers, a dirty form asks first. --- .../src/components/editor/EditorWorkspace.tsx | 141 ++---- .../components/editor/fields/DraftField.tsx | 7 +- .../src/components/editor/findings/AddBar.tsx | 3 + .../editor/findings/DiscardConfirm.tsx | 41 ++ .../{FindingDetail.tsx => FindingActions.tsx} | 158 +++---- .../editor/findings/FindingCitations.tsx | 138 ++++++ .../editor/findings/FindingContent.tsx | 211 --------- .../editor/findings/FindingCreateForm.tsx | 111 +++-- .../editor/findings/FindingDialog.tsx | 133 ++++++ .../editor/findings/FindingEditForm.tsx | 209 +++++++++ .../editor/findings/FindingTree.tsx | 21 +- .../editor/findings/FindingView.tsx | 94 ++++ .../editor/findings/ReadOnlyNotice.tsx | 14 + .../editor/findings/useDirtyGuard.ts | 32 ++ .../editor/references/CitationsLayer.tsx | 122 ----- .../editor/references/CitationsPanel.tsx | 28 +- .../editor/references/CitationsSheet.tsx | 86 ++++ .../editor/references/useCitationsPanel.ts | 52 +-- .../editor/references/useReferenceLibrary.ts | 3 +- .../components/editor/tabs/FindingsTab.tsx | 198 +++++++-- apps/app/src/components/ui/Dialog.tsx | 4 + apps/app/src/components/ui/ModalDialog.tsx | 43 +- apps/app/src/editor/annotations/deselect.ts | 4 +- apps/app/src/editor/editingContext.ts | 23 +- apps/app/src/editor/findingLayer.ts | 16 + apps/app/src/editor/findings/tree.ts | 11 + apps/app/src/editor/focusRequest.ts | 52 ++- apps/app/src/editor/history/entry.ts | 68 ++- .../src/editor/history/useEditorHistory.ts | 102 +++-- apps/app/src/editor/navigation.ts | 62 ++- apps/app/src/editor/tabs.ts | 22 +- apps/app/src/editor/useCitationsExit.ts | 61 --- apps/app/src/editor/useEditorNavigation.ts | 289 +++++------- apps/app/src/i18n/en.ts | 10 +- apps/app/src/i18n/fr.ts | 10 +- apps/app/tests/helpers/findingDialog.ts | 35 ++ apps/app/tests/helpers/findingsHost.tsx | 38 ++ .../tests/unit/editor-citations-exit.test.tsx | 124 ------ .../unit/editor-citations-layer.test.tsx | 53 --- apps/app/tests/unit/editor-escape.test.tsx | 25 +- .../tests/unit/editor-finding-dialog.test.tsx | 415 ++++++++++++++++++ apps/app/tests/unit/editor-findings.test.tsx | 348 ++++++++++----- .../tests/unit/editor-history-entry.test.ts | 80 +++- .../tests/unit/editor-history-guards.test.tsx | 63 ++- apps/app/tests/unit/editor-history.test.tsx | 14 + .../app/tests/unit/editor-keep-alive.test.tsx | 9 +- apps/app/tests/unit/editor-navigation.test.ts | 66 ++- apps/app/tests/unit/editor-no-loss.test.tsx | 29 +- .../unit/editor-references-flip.test.tsx | 49 ++- .../unit/editor-references-panel.test.tsx | 219 +++------ 50 files changed, 2642 insertions(+), 1504 deletions(-) create mode 100644 apps/app/src/components/editor/findings/DiscardConfirm.tsx rename apps/app/src/components/editor/findings/{FindingDetail.tsx => FindingActions.tsx} (51%) create mode 100644 apps/app/src/components/editor/findings/FindingCitations.tsx delete mode 100644 apps/app/src/components/editor/findings/FindingContent.tsx create mode 100644 apps/app/src/components/editor/findings/FindingDialog.tsx create mode 100644 apps/app/src/components/editor/findings/FindingEditForm.tsx create mode 100644 apps/app/src/components/editor/findings/FindingView.tsx create mode 100644 apps/app/src/components/editor/findings/ReadOnlyNotice.tsx create mode 100644 apps/app/src/components/editor/findings/useDirtyGuard.ts delete mode 100644 apps/app/src/components/editor/references/CitationsLayer.tsx create mode 100644 apps/app/src/components/editor/references/CitationsSheet.tsx create mode 100644 apps/app/src/editor/findingLayer.ts delete mode 100644 apps/app/src/editor/useCitationsExit.ts create mode 100644 apps/app/tests/helpers/findingDialog.ts create mode 100644 apps/app/tests/helpers/findingsHost.tsx delete mode 100644 apps/app/tests/unit/editor-citations-exit.test.tsx delete mode 100644 apps/app/tests/unit/editor-citations-layer.test.tsx create mode 100644 apps/app/tests/unit/editor-finding-dialog.test.tsx diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx index ed0f8a8c..0e9348cc 100644 --- a/apps/app/src/components/editor/EditorWorkspace.tsx +++ b/apps/app/src/components/editor/EditorWorkspace.tsx @@ -1,21 +1,16 @@ -import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { useMemo, useState, type ReactNode } from 'react' import { useLocation } from 'react-router-dom' -import { AnimatePresence } from 'motion/react' -import type { ElementKey } from '@faunosteo/core-wasm/types' import type { OfficialSheetAdmin } from '@faunosteo/supabase' import Notice from '@/components/ui/Notice' -import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext' -import { - AnnounceContext, - FocusConsumedContext, - isTextField, -} from '@/editor/focusRequest' +import { EditorModeContext, ReadOnlyContext } from '@/editor/editingContext' +import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest' import { saveFailureMessage } from '@/editor/messages' import type { EditorMode } from '@/editor/mode' import { useEditorStore } from '@/editor/state/editorStore' -import { ownedEntry } from '@/editor/history/entry' +import { ownedEntry, withoutForms } from '@/editor/history/entry' import useEditorHistory from '@/editor/history/useEditorHistory' -import { defaultView } from '@/editor/navigation' +import { citationsOfView, defaultView } from '@/editor/navigation' +import { findingLayerOf } from '@/editor/findingLayer' import { initialTab } from '@/editor/tabs' import { useEditorNavigation, @@ -31,7 +26,7 @@ import EditorTabBody from './EditorTabBody' import EditorTabs from './EditorTabs' import ModeNotice from './ModeNotice' import RecoveryNotice from './RecoveryNotice' -import CitationsLayer from './references/CitationsLayer' +import CitationsSheet from './references/CitationsSheet' interface Props { sheet: OfficialSheetAdmin @@ -61,18 +56,16 @@ function SaveFailureNotice() { /** What dialogs and edit-only parts below need of the editor's state. */ function EditingState({ readOnly, - citationsOf, + mode, children, }: { readOnly: boolean - citationsOf: ElementKey | null + mode: EditorMode children: ReactNode }) { return ( - - {children} - + {children} ) } @@ -84,75 +77,42 @@ interface PlacesProps { } /** - * Under the tab row: the tab panels and the citations panel of a finding beside them. The - * container starts after the tab row, so the panel and its scrim never cover the header or - * the tabs; from the opening to the end of the exit the tab panels are inert. Its minimum - * height is permanent (never toggled): the panel and the scrim reach the bottom of the - * window and the document never changes size when the panel opens or closes (P16'). + * The tab panels, then the citations sheet: the sheet comes after the tab body (which + * holds the finding dialog) so it is shown after it and lies over it. */ function Places({ nav, readOnly, reloadSheet }: PlacesProps) { const { state } = nav - const open = state.citationsOf !== null return ( -
- - {state.citationsOf && !nav.exiting && ( - - )} - -
- -
-
+ <> + + + ) } -/** - * A keydown aimed at `body` (nothing focused) never reaches the workspace's own handler: - * while the citations panel is open, Escape there closes it all the same, unless a - * modal dialog is open or the key was already handled. - */ -function useBodyEscape(open: boolean, close: () => void) { - const closeRef = useRef(close) - closeRef.current = close - useEffect(() => { - if (!open) return - const onKey = (event: KeyboardEvent) => { - if (event.key !== 'Escape' || event.defaultPrevented) return - if (event.isComposing || event.target !== document.body) return - if (document.querySelector('dialog[open]')) return - event.preventDefault() - closeRef.current() - } - document.addEventListener('keydown', onKey) - return () => document.removeEventListener('keydown', onKey) - }, [open]) -} - /** * The draft page once the version is ready: header, notices, tab row, the citations * panel and the shown place. Owns the navigation state, so the first tab is known at @@ -169,24 +129,15 @@ export default function EditorWorkspace(props: Props) { ) // A reload or a reopened entry shows the view the history kept, never a layer. const { state } = useLocation() - const [entry] = useState(() => ownedEntry(state, owner)) - const nav = useEditorNavigation(tab, entry?.view) + const [view] = useState(() => { + const entry = ownedEntry(state, owner) + return entry && withoutForms(entry.view) + }) + const nav = useEditorNavigation(tab, view) useEditorHistory(nav, owner, defaultView(tab)) - const open = nav.state.citationsOf !== null - useBodyEscape(open, nav.closeCitations) return ( - -
{ - if (event.key !== 'Escape' || event.defaultPrevented) return - if (event.nativeEvent.isComposing || !open) return - if (isTextField(event.target)) return - event.preventDefault() - nav.closeCitations() - }} - > + +
diff --git a/apps/app/src/components/editor/fields/DraftField.tsx b/apps/app/src/components/editor/fields/DraftField.tsx index 42f4db58..0dd17528 100644 --- a/apps/app/src/components/editor/fields/DraftField.tsx +++ b/apps/app/src/components/editor/fields/DraftField.tsx @@ -3,7 +3,7 @@ import Input from '@/components/ui/Input' import Textarea from '@/components/ui/Textarea' /** - * A controlled field of a creation form: it never commits, the form's own button does + * A controlled field of a form: it never commits, the form's own button does * (BDR-050). The committed fields of existing elements are `TextField`. */ export default function DraftField({ @@ -13,6 +13,7 @@ export default function DraftField({ onChange, onBlur, multiline, + readOnly, hint, error, }: { @@ -23,6 +24,8 @@ export default function DraftField({ /** Optional: a form field that applies its text when it loses the focus. */ onBlur?: () => void multiline?: boolean + /** Shown but not editable (the editor turned read-only under a form that is kept). */ + readOnly?: boolean hint?: string error?: string }) { @@ -31,6 +34,8 @@ export default function DraftField({ value, onChange: (e: { target: { value: string } }) => onChange(e.target.value), onBlur, + readOnly, + 'aria-readonly': readOnly || undefined, 'aria-invalid': Boolean(error), 'aria-describedby': fieldDescribedBy(id, hint, error), } diff --git a/apps/app/src/components/editor/findings/AddBar.tsx b/apps/app/src/components/editor/findings/AddBar.tsx index ad81b971..5f78fc06 100644 --- a/apps/app/src/components/editor/findings/AddBar.tsx +++ b/apps/app/src/components/editor/findings/AddBar.tsx @@ -22,6 +22,7 @@ export default function AddBar({ return (
void + onDiscard: () => void +}) { + const t = useT() + const keep = useRef(null) + useEffect(() => keep.current?.focus(), []) + return ( +
+

{t('editor.findings.discard_ask')}

+
+ + +
+
+ ) +} diff --git a/apps/app/src/components/editor/findings/FindingDetail.tsx b/apps/app/src/components/editor/findings/FindingActions.tsx similarity index 51% rename from apps/app/src/components/editor/findings/FindingDetail.tsx rename to apps/app/src/components/editor/findings/FindingActions.tsx index ec8682c1..1ceadc8c 100644 --- a/apps/app/src/components/editor/findings/FindingDetail.tsx +++ b/apps/app/src/components/editor/findings/FindingActions.tsx @@ -1,113 +1,10 @@ import type { EditCommand } from '@faunosteo/core-wasm/types' import ActionButton from '@/components/editor/fields/ActionButton' import MoveButtons from '@/components/editor/fields/MoveButtons' -import TextField from '@/components/editor/fields/TextField' -import FindingContent from '@/components/editor/findings/FindingContent' -import StatusBadge from '@/components/editor/findings/StatusBadge' -import { patchElement, type FindingItem } from '@/editor/findings/tree' -import { isBlank } from '@/editor/sheetDocument' -import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand' -import type { Locale } from '@/i18n/types' +import type { FindingItem } from '@/editor/findings/tree' +import type { EditCommandApi } from '@/editor/useEditCommand' import { useT } from '@/i18n/useT' -export interface FindingDetailProps { - item: FindingItem - readOnly: boolean - onDelete: () => void - /** Opens the citations panel of this finding (a family has none). */ - onShowReferences?: (opener: HTMLElement) => void -} - -/** The selected element: its names, its review state and the actions on it. */ -export default function FindingDetail({ - item, - readOnly, - onDelete, - onShowReferences, -}: FindingDetailProps) { - const t = useT() - const edit = useEditCommand() - return ( -
-
-

- {t(`editor.findings.type.${item.kind}`)} -

- {item.status && } -
- - -
- - - edit.run('actions', { op: 'move', key: item.key, position }) - } - /> - - {t('editor.action.delete')} - -
- {edit.fieldError('actions') && ( -

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

- )} -
- ) -} - -function Names({ - item, - readOnly, - edit, -}: { - item: FindingItem - readOnly: boolean - edit: EditCommandApi -}) { - const t = useT() - const rename = (locale: Locale) => (value: string) => - isBlank(value) - ? edit.reject(locale, 'editor.field.required') - : edit.run(locale, { - op: 'update', - key: item.key, - element: patchElement(item, { - name: { ...item.name, [locale]: value }, - }), - }) - return ( -
- {(['fr', 'en'] as const).map((locale) => ( - - ))} -
- ) -} - function statusCommand( item: FindingItem, status: 'reviewed' | 'to_confirm', @@ -155,3 +52,54 @@ function ReviewActions({ ) } + +interface ActionsProps { + item: FindingItem + readOnly: boolean + edit: EditCommandApi + onEdit: () => void + onDelete: () => void +} + +/** The view mode's actions (edit tier only): « Modifier », review, order, « Supprimer ». */ +export default function FindingActions(props: ActionsProps) { + const { item, readOnly, edit, onEdit, onDelete } = props + const t = useT() + return ( + <> +
+ + {t('editor.findings.edit')} + + + + edit.run('actions', { op: 'move', key: item.key, position }) + } + /> + + {t('editor.action.delete')} + +
+ {edit.fieldError('actions') && ( +

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

+ )} + + ) +} diff --git a/apps/app/src/components/editor/findings/FindingCitations.tsx b/apps/app/src/components/editor/findings/FindingCitations.tsx new file mode 100644 index 00000000..97d8f3bd --- /dev/null +++ b/apps/app/src/components/editor/findings/FindingCitations.tsx @@ -0,0 +1,138 @@ +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 { 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). */ + onShowReferences: (opener: HTMLElement) => void +} + +const RING = + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]' + +/** « X références »: the way to the sheet of a finding node's citations. */ +function SheetTrigger({ + item, + count, + sheetOpen, + onShowReferences, +}: Pick & { + count: number +}) { + const plural = usePlural() + return ( + + ) +} + +/** A family's inline list of cited references, each removable (« Retirer »). */ +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 ( +
    + {ids.map((id) => ( +
  • + {citation(id)} + remove(id)} + > + {t('editor.action.remove')} + +
  • + ))} +
+ ) +} + +/** + * « 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 doc = useSheetDocument() + const { element } = item + if (element.kind === 'zone') return null + const ids = element.value.reference_ids + const patch = (reference_ids: string[]) => + edit.run('references', { + op: 'update', + key: item.key, + element: patchElement(item, { reference_ids }), + }) + const options = [ + { value: '', label: t('editor.field.choose') }, + ...(doc?.references ?? []) + .filter((r) => !ids.includes(r.id)) + .map((r) => ({ value: r.id, label: r.citation })), + ] + return ( +
+
+

{t('editor.findings.references')}

+ {ids.length > 0 && element.kind === 'finding_node' && ( + + )} +
+ {ids.length === 0 && ( +

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

+ )} + {element.kind === 'finding_category' && ( + patch(ids.filter((other) => other !== id))} + /> + )} + {!readOnly && ( + id !== '' && patch([...ids, id])} + error={edit.fieldError('references')} + /> + )} +
+ ) +} diff --git a/apps/app/src/components/editor/findings/FindingContent.tsx b/apps/app/src/components/editor/findings/FindingContent.tsx deleted file mode 100644 index 1b8d46e0..00000000 --- a/apps/app/src/components/editor/findings/FindingContent.tsx +++ /dev/null @@ -1,211 +0,0 @@ -import { useContext } from 'react' -import ActionButton from '@/components/editor/fields/ActionButton' -import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue' -import SelectField from '@/components/editor/fields/SelectField' -import TextField from '@/components/editor/fields/TextField' -import Icon from '@/components/ui/Icon' -import { ReferencesOpenContext } from '@/editor/editingContext' -import { - patchElement, - sameKey, - type FindingItem, - type FindingPatch, -} from '@/editor/findings/tree' -import { usePlural } from '@/editor/plural' -import { optionalText, useSheetDocument } from '@/editor/sheetDocument' -import type { EditCommandApi } from '@/editor/useEditCommand' -import type { Locale } from '@/i18n/types' -import { useT } from '@/i18n/useT' - -interface ContentProps { - item: FindingItem - readOnly: boolean - edit: EditCommandApi - /** Opens the citations panel; given for a finding only, a family has no panel. */ - onShowReferences?: (opener: HTMLElement) => void -} - -/** The content of a category or a node: descriptions, vet referral, cited references. */ -export default function FindingContent(props: ContentProps) { - const { element } = props.item - if (element.kind === 'zone') return null - const patch = (field: string, change: FindingPatch) => - props.edit.run(field, { - op: 'update', - key: props.item.key, - element: patchElement(props.item, change), - }) - return ( -
- - {element.kind === 'finding_node' && ( - - )} - -
- ) -} - -type Patch = (field: string, change: FindingPatch) => boolean - -function Descriptions({ - item, - readOnly, - edit, - current, - patch, -}: ContentProps & { - current: { fr?: string; en?: string } - patch: Patch -}) { - const t = useT() - const commit = (locale: Locale) => (value: string) => - patch(`description-${locale}`, { - description: optionalText(current, locale, value), - }) - return ( -
- {(['fr', 'en'] as const).map((locale) => ( - - ))} -
- ) -} - -function VetFlag({ - readOnly, - edit, - value, - patch, -}: ContentProps & { value: boolean; patch: Patch }) { - const t = useT() - const label = t('editor.findings.vet_referral') - if (readOnly) { - const answer = t(value ? 'editor.findings.yes' : 'editor.findings.no') - return - } - return ( -
- - {edit.fieldError('vet') && ( -

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

- )} -
- ) -} - -function Citations({ - item, - readOnly, - edit, - ids, - patch, - onShowReferences, -}: ContentProps & { ids: readonly string[]; patch: Patch }) { - const t = useT() - const plural = usePlural() - const doc = useSheetDocument() - const citationsOf = useContext(ReferencesOpenContext) - const panelOpen = citationsOf !== null && sameKey(citationsOf, item.key) - const references = doc?.references ?? [] - const citation = (id: string) => - references.find((r) => r.id === id)?.citation ?? id - const options = [ - { value: '', label: t('editor.field.choose') }, - ...references - .filter((r) => !ids.includes(r.id)) - .map((r) => ({ value: r.id, label: r.citation })), - ] - return ( -
-
-

{t('editor.findings.references')}

- {ids.length > 0 && onShowReferences && ( - - )} -
- {ids.length === 0 && ( -

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

- )} -
    - {ids.map((id) => ( -
  • - {citation(id)} - - patch('references', { - reference_ids: ids.filter((other) => other !== id), - }) - } - > - {t('editor.action.remove')} - -
  • - ))} -
- {!readOnly && ( - - id !== '' && patch('references', { reference_ids: [...ids, id] }) - } - error={edit.fieldError('references')} - /> - )} -
- ) -} diff --git a/apps/app/src/components/editor/findings/FindingCreateForm.tsx b/apps/app/src/components/editor/findings/FindingCreateForm.tsx index 04ce911e..7b6eca17 100644 --- a/apps/app/src/components/editor/findings/FindingCreateForm.tsx +++ b/apps/app/src/components/editor/findings/FindingCreateForm.tsx @@ -4,9 +4,12 @@ import type { FindingCategoryKind, FindingNode, } from '@faunosteo/core-wasm/types' -import ActionButton from '@/components/editor/fields/ActionButton' import DraftField from '@/components/editor/fields/DraftField' import SelectField from '@/components/editor/fields/SelectField' +import DiscardConfirm from '@/components/editor/findings/DiscardConfirm' +import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice' +import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard' +import Button from '@/components/ui/Button' import { buildItems, type FindingItem, @@ -15,6 +18,7 @@ import { import type { IdPrefix } from '@/editor/ids' import { isBlank, useSheetDocument } from '@/editor/sheetDocument' import { useEditCommand } from '@/editor/useEditCommand' +import type { Guards } from '@/editor/useEditorNavigation' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' @@ -31,26 +35,30 @@ export interface PendingFinding { parent: FindingItem | null } +export interface FindingCreateFormProps { + pending: PendingFinding + readOnly: boolean + guards: Guards + /** `created` is the new element's id, `parent` the element it went under. */ + onCreated: (id: string, parent: FindingItem | null) => void + /** A close of the dialog; forced after « Abandonner ». */ + onClose: (forced: boolean) => void +} + /** * Collects what the core requires (names FR/EN, the kind of a category), then one - * `insert`: no element exists with default labels. + * `insert`: no element exists with default labels. The fields are a local draft: nothing + * is written before « Créer », a close or a move never creates (R2F-3). */ -export default function FindingCreateForm({ - pending, - onCreated, - onCancel, -}: { - pending: PendingFinding - onCreated: (id: string, parent: FindingItem | null) => void - onCancel: () => void -}) { +export default function FindingCreateForm(props: FindingCreateFormProps) { + const { pending, readOnly, guards, onCreated, onClose } = props const t = useT() const edit = useEditCommand() const zones = useZoneChoice() - const title = useFormTitle(pending, zones.chosen) const [fr, setFr] = useState('') const [en, setEn] = useState('') const [kind, setKind] = useState('') + const guard = useDirtyGuard(guards, fr !== '' || en !== '' || kind !== '') const create = () => { const parent = pending.kind === 'category' ? zones.chosen : pending.parent const missingParent = pending.kind === 'category' && !parent @@ -71,16 +79,27 @@ export default function FindingCreateForm({ }) if (added) onCreated(createdId, parent) } + const category = pending.kind === 'category' return ( -
-

{title}

+
{ + event.preventDefault() + create() + }} + > + {readOnly && } + {category && zones.chosen && }
- {pending.kind === 'category' && } - {pending.kind === 'category' && ( + {category && } + {category && ( ({ @@ -96,12 +115,14 @@ export default function FindingCreateForm({ label={t('editor.general.name_fr')} value={fr} onChange={setFr} + readOnly={readOnly} />
{edit.fieldError('form') && ( @@ -109,15 +130,26 @@ export default function FindingCreateForm({ {edit.fieldError('form')}

)} -
- - {t('editor.findings.create')} - - - {t('editor.findings.cancel')} - -
-
+ {guard.confirming ? ( + onClose(true)} + /> + ) : ( +
+ + +
+ )} + ) } @@ -139,7 +171,13 @@ function useZoneChoice(): ZoneChoice { return { zones, zoneId, setZoneId, chosen } } -function ZoneSelect({ zones }: { zones: ZoneChoice }) { +function ZoneSelect({ + zones, + readOnly, +}: { + zones: ZoneChoice + readOnly: boolean +}) { const t = useT() const locale = useLocaleStore((s) => s.locale) return ( @@ -147,6 +185,7 @@ function ZoneSelect({ zones }: { zones: ZoneChoice }) { id="finding-new-zone" label={t('editor.findings.zone')} value={zones.zoneId} + readOnly={readOnly} options={[ { value: '', label: t('editor.field.choose') }, ...zones.zones.map((zone) => ({ @@ -159,19 +198,17 @@ function ZoneSelect({ zones }: { zones: ZoneChoice }) { ) } -/** A category lands at zone level: its title names the zone chosen in the form. */ -function useFormTitle( - pending: PendingFinding, - zone: FindingItem | null, -): string { +/** A category lands at zone level: the line under the dialog's title names the zone chosen. */ +function ZoneTitle({ zone }: { zone: FindingItem }) { const t = useT() const locale = useLocaleStore((s) => s.locale) - if (pending.kind !== 'category') - return t(`editor.findings.new.${pending.kind}`) - if (!zone) return t('editor.findings.add_category') - return t('editor.findings.new.category_in_zone').replace( - '{zone}', - zone.name[locale], + return ( +

+ {t('editor.findings.new.category_in_zone').replace( + '{zone}', + zone.name[locale], + )} +

) } diff --git a/apps/app/src/components/editor/findings/FindingDialog.tsx b/apps/app/src/components/editor/findings/FindingDialog.tsx new file mode 100644 index 00000000..8a8499bd --- /dev/null +++ b/apps/app/src/components/editor/findings/FindingDialog.tsx @@ -0,0 +1,133 @@ +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 Dialog from '@/components/ui/Dialog' +import { usePlaceVisible } from '@/lib/placeVisibility' +import type { FindingItem, FindingKind } from '@/editor/findings/tree' +import type { FindingLayer } from '@/editor/tabs' +import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' + +export interface FindingDialogProps { + layer: FindingLayer + /** The element the dialog shows; null while it creates one or is closed. */ + item: FindingItem | null + /** The creation the dialog holds, null for the view of an element. */ + pending: PendingFinding | null + readOnly: boolean + /** Where the focus goes once the dialog is closed (the tree row, the add button). */ + returnFocus: () => HTMLElement | null + onDelete: (item: FindingItem) => void + onCreated: (id: string, parent: FindingItem | null, kind: FindingKind) => void +} + +interface ItemBodyProps { + item: FindingItem + layer: FindingLayer + readOnly: boolean + onDelete: (item: FindingItem) => void +} + +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 + } +} + +/** View mode, or the edit form: a local mode of the one dialog, no history entry. */ +function ItemBody({ item, layer, readOnly, onDelete }: ItemBodyProps) { + const t = useT() + const [editing, setEditing] = useState(false) + const [saved, setSaved] = useState(false) + const returnToEdit = useFocusEditButton(editing) + const { view } = layer + const sheetOpen = view !== null && 'key' in view && view.citations + return ( +
+ {editing ? ( + { + returnToEdit() + setSaved(wrote) + setEditing(false) + }} + onDiscardClose={() => layer.close(true)} + /> + ) : ( + { + setSaved(false) + setEditing(true) + }} + onDelete={() => onDelete(item)} + onShowReferences={(opener) => layer.openCitations(item.key, opener)} + /> + )} +

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

+
+ ) +} + +/** + * The finding dialog (R2F-3): one `ModalDialog` kept across its modes (view, edit, + * creation). The view layer of the browser history drives it; it opens only while its + * place is shown (no native modal inside a hidden part). + */ +export default function FindingDialog(props: FindingDialogProps) { + const { layer, item, pending, readOnly } = props + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const visible = usePlaceVisible() + const title = pending + ? t(`editor.findings.new.${pending.kind}`) + : (item?.name[locale] ?? '') + return ( + (layer.close() ? undefined : 'kept')} + > + {pending && ( + props.onCreated(id, parent, pending.kind)} + onClose={(forced) => layer.close(forced)} + /> + )} + {item && ( + + )} + + ) +} diff --git a/apps/app/src/components/editor/findings/FindingEditForm.tsx b/apps/app/src/components/editor/findings/FindingEditForm.tsx new file mode 100644 index 00000000..9dc27a74 --- /dev/null +++ b/apps/app/src/components/editor/findings/FindingEditForm.tsx @@ -0,0 +1,209 @@ +import { useRef, useState } from 'react' +import DraftField from '@/components/editor/fields/DraftField' +import DiscardConfirm from '@/components/editor/findings/DiscardConfirm' +import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard' +import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice' +import Button from '@/components/ui/Button' +import { patchElement, type FindingItem } from '@/editor/findings/tree' +import { isBlank, optionalText } from '@/editor/sheetDocument' +import { useEditCommand } from '@/editor/useEditCommand' +import type { Guards } from '@/editor/useEditorNavigation' +import { useT } from '@/i18n/useT' + +/** What the form edits, as plain strings: nothing is written before « Enregistrer ». */ +interface Draft { + fr: string + en: string + descriptionFr: string + descriptionEn: string + vet: boolean +} + +function draftOf(item: FindingItem): Draft { + const { element } = item + const described = element.kind === 'zone' ? {} : element.value.description + return { + fr: item.name.fr, + en: item.name.en, + descriptionFr: described.fr ?? '', + descriptionEn: described.en ?? '', + vet: element.kind === 'finding_node' && element.value.requires_vet_referral, + } +} + +/** The draft as it would be saved: names trimmed, a blank description absent. */ +function normalized(draft: Draft): Draft { + return { + ...draft, + fr: draft.fr.trim(), + en: draft.en.trim(), + descriptionFr: isBlank(draft.descriptionFr) ? '' : draft.descriptionFr, + descriptionEn: isBlank(draft.descriptionEn) ? '' : draft.descriptionEn, + } +} + +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. */ +function patchOf(item: FindingItem, draft: Draft) { + const now = normalized(draft) + const { element } = item + const name = { fr: now.fr, en: now.en } + if (element.kind === 'zone') return patchElement(item, { name }) + let description = optionalText( + element.value.description, + 'fr', + now.descriptionFr, + ) + description = optionalText(description, 'en', now.descriptionEn) + const vet = { requires_vet_referral: now.vet } + return patchElement(item, { + name, + description, + ...(element.kind === 'finding_node' ? vet : {}), + }) +} + +export interface FindingEditFormProps { + item: FindingItem + readOnly: boolean + guards: Guards + /** 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 +} + +function VetCheckbox({ + checked, + readOnly, + onChange, +}: { + checked: boolean + readOnly: boolean + onChange: (value: boolean) => void +}) { + const t = useT() + return ( + + ) +} + +/** + * 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 + * editor turns read-only the draft stays, its fields read-only, and only « Abandonner » + * is left. + */ +export default function FindingEditForm(props: FindingEditFormProps) { + const { item, readOnly, guards, onDone, onDiscardClose } = props + const t = useT() + const edit = useEditCommand() + const initial = useRef(draftOf(item)).current + const [draft, setDraft] = useState(initial) + const [blank, setBlank] = useState([]) + const dirty = !sameDraft(draft, initial) + const guard = useDirtyGuard(guards, dirty) + const set = (change: Partial) => setDraft({ ...draft, ...change }) + const save = () => { + const missing = (['fr', 'en'] as const).filter((l) => isBlank(draft[l])) + setBlank(missing) + if (missing.length > 0) { + document.getElementById(`finding-edit-name-${missing[0]}`)?.focus() + return + } + if (!dirty) return onDone(false) + const command = { + op: 'update', + key: item.key, + element: patchOf(item, draft), + } as const + if (edit.run('save', command)) onDone(true) + } + const cancel = () => (dirty && !readOnly ? guard.askToLeave() : onDone(false)) + const described = item.kind !== 'zone' + const fieldError = (l: 'fr' | 'en') => + blank.includes(l) ? t('editor.field.required') : undefined + return ( +
{ + event.preventDefault() + save() + }} + > + {readOnly && } +
+ {(['fr', 'en'] as const).map((l) => ( + set({ [l]: value })} + readOnly={readOnly} + error={fieldError(l)} + /> + ))} + {described && + (['fr', 'en'] as const).map((l) => ( + + set( + l === 'fr' + ? { descriptionFr: value } + : { descriptionEn: value }, + ) + } + readOnly={readOnly} + multiline + /> + ))} +
+ {item.element.kind === 'finding_node' && ( + set({ vet })} + /> + )} + {edit.fieldError('save') && ( +

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

+ )} + {guard.confirming ? ( + + guard.confirming === 'dialog' ? onDiscardClose() : onDone(false) + } + /> + ) : ( +
+ + +
+ )} + + ) +} diff --git a/apps/app/src/components/editor/findings/FindingTree.tsx b/apps/app/src/components/editor/findings/FindingTree.tsx index a0848200..a369abce 100644 --- a/apps/app/src/components/editor/findings/FindingTree.tsx +++ b/apps/app/src/components/editor/findings/FindingTree.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, type KeyboardEvent } from 'react' +import { afterModalsClosed } from '@/components/ui/afterModalsClosed' import StatusBadge from '@/components/editor/findings/StatusBadge' import { keyMove, type FindingItem } from '@/editor/findings/tree' import { useT } from '@/i18n/useT' @@ -9,6 +10,8 @@ export interface FindingTreeProps { selectedId: string | null expanded: ReadonlySet onSelect: (id: string) => void + /** Click, Enter or Space on a row: the row is selected and its dialog opens. */ + onActivate: (item: FindingItem) => void onToggle: (id: string, open: boolean) => void /** Moves focus to this item (after a deletion); null leaves focus alone. */ focusId: { id: string } | null @@ -26,6 +29,7 @@ export default function FindingTree(props: FindingTreeProps) { const refs = useRef(new Map()) const focusAfter = useRef(null) const { visible, selectedId, expanded, onSelect, onToggle } = props + const { onActivate } = props const { focusId, onFocused } = props useEffect(() => { if (focusAfter.current) refs.current.get(focusAfter.current)?.focus() @@ -33,11 +37,17 @@ export default function FindingTree(props: FindingTreeProps) { }) useEffect(() => { if (!focusId) return - refs.current.get(focusId.id)?.focus() + // After the dialogs a move closed: the page behind them is inert until then. + afterModalsClosed(() => refs.current.get(focusId.id)?.focus()) onFocused() }, [focusId, onFocused]) const current = visible.find((item) => item.id === selectedId) ?? visible[0] const onKeyDown = (event: KeyboardEvent, item: FindingItem) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + onActivate(item) + return + } const move = keyMove(visible, item, expanded, event.key) if (!move) return event.preventDefault() @@ -66,7 +76,7 @@ export default function FindingTree(props: FindingTreeProps) { else refs.current.delete(item.id) }} onKeyDown={onKeyDown} - onSelect={onSelect} + onActivate={onActivate} onToggle={onToggle} /> ))} @@ -81,7 +91,7 @@ interface TreeRowProps { open: boolean register: (el: HTMLElement | null) => void onKeyDown: (event: KeyboardEvent, item: FindingItem) => void - onSelect: (id: string) => void + onActivate: (item: FindingItem) => void onToggle: (id: string, open: boolean) => void } @@ -92,7 +102,7 @@ function TreeRow({ open, register, onKeyDown, - onSelect, + onActivate, onToggle, }: TreeRowProps) { const locale = useLocaleStore((s) => s.locale) @@ -107,10 +117,11 @@ function TreeRow({ aria-expanded={item.hasChildren ? open : undefined} tabIndex={tabbable ? 0 : -1} data-testid="finding-item" + data-finding-key={JSON.stringify(item.key)} onKeyDown={(event) => { if (event.target === event.currentTarget) onKeyDown(event, item) }} - onClick={() => onSelect(item.id)} + onClick={() => onActivate(item)} style={{ paddingLeft: `${(item.level - 1) * 1.25 + 0.5}rem` }} className={`flex cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-sm ${ selected diff --git a/apps/app/src/components/editor/findings/FindingView.tsx b/apps/app/src/components/editor/findings/FindingView.tsx new file mode 100644 index 00000000..4292d40d --- /dev/null +++ b/apps/app/src/components/editor/findings/FindingView.tsx @@ -0,0 +1,94 @@ +import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue' +import FindingActions from '@/components/editor/findings/FindingActions' +import FindingCitations from '@/components/editor/findings/FindingCitations' +import StatusBadge from '@/components/editor/findings/StatusBadge' +import type { FindingItem } from '@/editor/findings/tree' +import { useEditCommand } from '@/editor/useEditCommand' +import { useT } from '@/i18n/useT' + +export interface FindingViewProps { + item: FindingItem + readOnly: boolean + sheetOpen: boolean + onEdit: () => void + onDelete: () => void + onShowReferences: (opener: HTMLElement) => void +} + +/** The texts of a category or a node, read: descriptions, then the vet referral of a node. */ +function Texts({ item }: { item: FindingItem }) { + const t = useT() + const { element } = item + if (element.kind === 'zone') return null + return ( + <> +
+ {(['fr', 'en'] as const).map((locale) => ( + + ))} +
+ {element.kind === 'finding_node' && ( + + )} + + ) +} + +/** + * The element read in the finding dialog (R2F-3): type and status, names, texts, its + * citations, and the actions of the edit tier. Nothing here edits a field in place. + */ +export default function FindingView(props: FindingViewProps) { + const { item, readOnly, sheetOpen } = props + const t = useT() + const edit = useEditCommand() + return ( +
+
+

+ {t(`editor.findings.type.${item.kind}`)} +

+ {item.status && } +
+
+ {(['fr', 'en'] as const).map((locale) => ( + + ))} +
+ + + +
+ ) +} diff --git a/apps/app/src/components/editor/findings/ReadOnlyNotice.tsx b/apps/app/src/components/editor/findings/ReadOnlyNotice.tsx new file mode 100644 index 00000000..1f8fee73 --- /dev/null +++ b/apps/app/src/components/editor/findings/ReadOnlyNotice.tsx @@ -0,0 +1,14 @@ +import Notice from '@/components/ui/Notice' +import { useEditorMode } from '@/editor/editingContext' +import { useT } from '@/i18n/useT' + +/** + * The editor turned read-only under a form the dialog keeps: why, worded from the mode. + * A narrow window comes back on widening; any other mode leaves only « Abandonner ». + */ +export default function ReadOnlyNotice() { + const t = useT() + const mode = useEditorMode() + const key = mode === 'narrow' ? 'flip_narrow' : 'flip_blocked' + return {t(`editor.findings.${key}`)} +} diff --git a/apps/app/src/components/editor/findings/useDirtyGuard.ts b/apps/app/src/components/editor/findings/useDirtyGuard.ts new file mode 100644 index 00000000..458a8606 --- /dev/null +++ b/apps/app/src/components/editor/findings/useDirtyGuard.ts @@ -0,0 +1,32 @@ +import { useEffect, useRef, useState } from 'react' +import { useBeforeUnload } from '@/app/useLeaveGuard' +import type { Guards } from '@/editor/useEditorNavigation' + +/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */ +export type DiscardTarget = 'form' | 'dialog' + +/** + * The finding layer's guard while a form holds changes (R2F-3): a user close that reaches + * the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les + * modifications ? » (`confirming`). A forced close, or a form with nothing typed, goes + * ahead. `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too. + */ +export function useDirtyGuard(guards: Guards, dirty: boolean) { + const [confirming, setConfirming] = useState(null) + const latest = useRef(dirty) + latest.current = dirty + useBeforeUnload(dirty) + useEffect(() => { + guards.register('finding', (forced) => { + if (forced || !latest.current) return { allowed: true } + setConfirming('dialog') + return { allowed: false } + }) + return () => guards.register('finding', null) + }, [guards]) + return { + confirming, + askToLeave: () => setConfirming('form'), + keepTyping: () => setConfirming(null), + } +} diff --git a/apps/app/src/components/editor/references/CitationsLayer.tsx b/apps/app/src/components/editor/references/CitationsLayer.tsx deleted file mode 100644 index 2e974c80..00000000 --- a/apps/app/src/components/editor/references/CitationsLayer.tsx +++ /dev/null @@ -1,122 +0,0 @@ -import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react' -import { motion, useIsPresent, useReducedMotion } from 'motion/react' -import { PANEL_ENTER_S, PANEL_EXIT_S } from '@/editor/useCitationsExit' -import KeptPlace from '../KeptPlace' -import CitationsPanel from './CitationsPanel' - -type Props = Parameters[0] - -/** The top bar (`h-14`): the panel sticks right under it. */ -const TOP_BAR_REM = 3.5 - -/** - * The panel's visible height: from its top (under the top bar once the page has scrolled) - * to the nearer of the container's bottom and the viewport's bottom. Kept right on scroll, - * resize and visual-viewport changes (mobile URL bar, keyboard); only the panel's own - * height is written, so the document never changes size. - */ -function useFitToViewport(panel: RefObject) { - useLayoutEffect(() => { - const element = panel.current - const container = element?.parentElement - if (!element || !container) return - const bar = - TOP_BAR_REM * - parseFloat(getComputedStyle(document.documentElement).fontSize) - const fit = () => { - const box = container.getBoundingClientRect() - const viewport = window.visualViewport?.height ?? window.innerHeight - const visible = Math.min(box.bottom, viewport) - Math.max(box.top, bar) - element.style.height = `${Math.max(visible, 0)}px` - } - fit() - const watched: EventTarget[] = [window] - if (window.visualViewport) watched.push(window.visualViewport) - for (const target of watched) { - target.addEventListener('scroll', fit, { passive: true }) - target.addEventListener('resize', fit) - } - const observer = - typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(fit) - // Content above the container reflowing moves its top without resizing it. - observer?.observe(container) - observer?.observe(document.documentElement) - return () => { - for (const target of watched) { - target.removeEventListener('scroll', fit) - target.removeEventListener('resize', fit) - } - observer?.disconnect() - } - }, [panel]) -} - -/** - * The citations panel and its scrim over the places (board 25). The panel slides in from - * the right (translateX only), the scrim fades on the same timings; under reduced motion - * both change at once, the callbacks still fire (P29). While it exits, the panel is inert - * (the page behind stays inert until the workspace lifts it, P9). - * - * Geometry (P16, P16'): the wrapper fills the Places container, clips the slide on the x - * axis only (`clip`, never `hidden`) and is 34 rem at most; the panel inside sticks under - * the top bar, is exactly as tall as what is visible (`useFitToViewport`) and scrolls its - * own list, so the page's size never changes. - */ -export default function CitationsLayer(props: Props) { - const reduced = useReducedMotion() - const present = useIsPresent() - const layer = useRef(null) - const focused = useRef(false) - useFitToViewport(layer) - // A reopen during a slow exit reuses this instance: it focuses its heading again. - useEffect(() => { - if (!present) focused.current = false - }, [present]) - const slide = { x: reduced ? 0 : '100%' } - const enter = { - duration: reduced ? 0 : PANEL_ENTER_S, - ease: 'easeOut', - } as const - const leave = { - duration: reduced ? 0 : PANEL_EXIT_S, - ease: 'easeIn', - } as const - // The heading takes the focus once the panel is in place (P9, P29). - const entered = () => { - if (!present || focused.current) return - focused.current = true - layer.current - ?.querySelector('[data-place-heading]') - ?.focus({ preventScroll: true }) - } - return ( - <> -