feat(editor): reference dialog, reading tiles and finding filter in the history

R2F-5 and R2F-6: the reference dialog is a view layer above the References tab or the citations sheet (local draft, one command per changed save, creation entry becomes the reference's own). Tiles only read. « Tout afficher » filters the library by the finding, « Revenir au constat » pops or pushes. Inline tile edit, draft tile and their guards removed.
This commit is contained in:
bchanot committed 2026-11-13 20:27:00 +01:00
1 parent e2d020bd3d
commit 8031e0078f
28 files changed
+1072 -1512

No files matched your search

@@ -10,7 +10,7 @@ import { useEditorStore } from '@/editor/state/editorStore'
import { ownedEntry, withoutForms } from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import { citationsOfView, defaultView } from '@/editor/navigation'
import { findingLayerOf } from '@/editor/findingLayer'
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
import { initialTab } from '@/editor/tabs'
import {
useEditorNavigation,
@@ -27,6 +27,7 @@ import EditorTabs from './EditorTabs'
import ModeNotice from './ModeNotice'
import RecoveryNotice from './RecoveryNotice'
import CitationsSheet from './references/CitationsSheet'
import ReferenceDialog from './references/ReferenceDialog'
interface Props {
sheet: OfficialSheetAdmin
@@ -77,11 +78,14 @@ interface PlacesProps {
}
/**
* 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.
* The tab panels, then the citations sheet and the reference dialog: each comes after the
* one under it in the tree (the tab body holds the finding dialog), so it is shown after
* it and lies over it.
*/
function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
const { state } = nav
const references = referenceLayerOf(nav)
const cited = citationsOfView(state)
return (
<>
<EditorTabBody
@@ -90,6 +94,7 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
readOnly={readOnly}
navigate={nav.navigate}
layer={findingLayerOf(nav)}
references={references}
libraryReset={state.libraryReset}
focus={state.focus}
reloadSheet={reloadSheet}
@@ -101,14 +106,15 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
}}
/>
<CitationsSheet
citedBy={citationsOfView(state)}
citedBy={cited}
readOnly={readOnly}
guards={nav.guards}
onClose={nav.closeCitations}
onShowAll={nav.showAllReferences}
onShowAll={() => cited && nav.showAllReferences(cited)}
navigate={nav.navigate}
onEdit={nav.references.open}
returnFocus={nav.citationsTrigger}
/>
<ReferenceDialog layer={references} readOnly={readOnly} />
</>
)
}
@@ -1,34 +1,38 @@
import { useEffect, useRef, useState } from 'react'
import { useBeforeUnload } from '@/app/useLeaveGuard'
import type { Guards } from '@/editor/useEditorNavigation'
import type { Guards, LayerName } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
/** 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
* The layer's guard (the finding dialog's, or the reference dialog's) while a form holds
* changes (R2F-3, R2F-5): a user close that reaches the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
* modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and
* says the draft was dropped (BDR-115); a form with nothing typed says nothing.
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
*/
export function useDirtyGuard(guards: Guards, dirty: boolean) {
export function useDirtyGuard(
guards: Guards,
dirty: boolean,
layer: LayerName,
) {
const t = useT()
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
const latest = useRef({ dirty, dropped: t('editor.findings.draft_dropped') })
latest.current = { dirty, dropped: t('editor.findings.draft_dropped') }
useBeforeUnload(dirty)
useEffect(() => {
guards.register('finding', (forced) => {
guards.register(layer, (forced) => {
const { dirty: held, dropped } = latest.current
if (!held) return { allowed: true }
if (forced) return { allowed: true, note: dropped }
setConfirming('dialog')
return { allowed: false }
})
return () => guards.register('finding', null)
}, [guards])
return () => guards.register(layer, null)
}, [guards, layer])
return {
confirming,
askToLeave: () => setConfirming('form'),
@@ -44,11 +48,12 @@ export function useFormDraft<T extends object>(
initial: T,
guards: Guards,
same: (a: T, b: T) => boolean,
layer: LayerName = 'finding',
) {
const first = useRef(initial).current
const [draft, setDraft] = useState(first)
const dirty = !same(draft, first)
const guard = useDirtyGuard(guards, dirty)
const guard = useDirtyGuard(guards, dirty, layer)
return {
draft,
dirty,
@@ -1,4 +1,4 @@
import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'
import type { RefObject } from 'react'
import type { LocalizedText, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
@@ -17,6 +17,8 @@ interface Props extends PanelHooks {
onShowAll: () => void
/** « Aller à » a citing finding or family: closes the panel, then moves. */
navigate: (target: EditorTarget) => void
/** « Modifier »: the reference dialog over the sheet, `opener` is where the focus returns. */
onEdit: (id: string, opener: HTMLElement) => void
}
const RING =
@@ -134,35 +136,17 @@ function MissingRow({
type Panel = ReturnType<typeof useCitationsPanel>
/**
* True once the panel unmounts (its list with it). It only unmounts after a close its leave check allowed,
* which already said any refused draft (`note`). React runs a deleted parent's layout
* cleanups before its children's, so a tile's edit view reads true when it drops then.
*/
function useLeaving() {
const leaving = useRef(false)
useLayoutEffect(() => {
leaving.current = false
return () => {
leaving.current = true
}
}, [])
return useCallback(() => leaving.current, [])
}
/** One cited reference as a tile (« Modifier », « Retirer de ce constat »). */
function EntryTile({
entry,
reference,
panel,
props,
leaving,
}: {
entry: CitationEntry
reference: Reference
panel: Panel
props: Props
leaving: () => boolean
}) {
const { tiles, keys, citers, entries, remove } = panel
const { readOnly, citedBy, navigate } = props
@@ -176,17 +160,12 @@ function EntryTile({
count={entries.length}
citers={citers.get(reference.id) ?? []}
open={tiles.openKeys.has(key)}
editing={!readOnly && tiles.editingKey === key}
readOnly={readOnly}
movable={false}
on={{
toggle: () => tiles.toggle(key, readOnly),
edit: () => void tiles.startEdit(key),
done: tiles.finish,
toggle: () => tiles.toggle(key),
edit: (opener) => props.onEdit(reference.id, opener),
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
takeFocus: () => tiles.takeFocus(key),
hostLeaving: leaving,
}}
/>
)
@@ -194,7 +173,6 @@ function EntryTile({
/** The cited references as tiles, the dangling ids as rows. */
function Entries({ panel, props }: { panel: Panel; props: Props }) {
const leaving = useLeaving()
return (
<ul
ref={panel.list}
@@ -209,7 +187,6 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
reference={entry.reference}
panel={panel}
props={props}
leaving={leaving}
/>
) : (
<MissingRow
@@ -1,9 +1,7 @@
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import ModalDialog from '@/components/ui/ModalDialog'
import { isTextField } from '@/editor/focusRequest'
import type { EditorTarget } from '@/editor/navigation'
import type { Guards } from '@/editor/useEditorNavigation'
import CitationsPanel from './CitationsPanel'
/** Sheet motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
@@ -14,13 +12,14 @@ export interface CitationsSheetProps {
/** The finding whose citations the view shows; null while the sheet is closed. */
citedBy: ElementKey | null
readOnly: boolean
guards: Guards
/** A user close (✕, Escape, scrim): false when a tile in edit refused it. */
/** A user close (✕, Escape, scrim). */
onClose: () => boolean
/** « Tout afficher dans l'onglet Références ». */
onShowAll: () => void
/** « Aller à » a citing finding or a reference. */
navigate: (target: EditorTarget) => void
/** « Modifier » on a tile: the reference dialog over the sheet. */
onEdit: (id: string, opener: HTMLElement) => void
/** « X références » of the dialog under the sheet, where the focus returns. */
returnFocus: () => HTMLElement | null
}
@@ -38,8 +37,7 @@ function useSheetMotion() {
/**
* The citations of a finding as a modal side sheet at the right edge, over the finding
* dialog (R2F-4): the host sits after the tab body in the tree, so it is shown after the
* dialog and lies on top of it. Escape and the scrim close the sheet only. Interim until
* the tiles stop editing inline: an Escape typed in a tile's field is the field's.
* dialog and lies on top of it. Escape and the scrim close the sheet only.
*/
function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
const { citedBy, onClose } = props
@@ -50,7 +48,6 @@ function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
layer
onClose={close}
returnFocus={props.returnFocus}
ignoreEscape={isTextField}
labelledBy="editor-citations-title"
className="open:block"
>
@@ -73,10 +70,10 @@ function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
<CitationsPanel
readOnly={props.readOnly}
citedBy={citedBy}
guards={props.guards}
onClose={onClose}
onShowAll={props.onShowAll}
navigate={props.navigate}
onEdit={props.onEdit}
/>
</motion.div>
</ModalDialog>
@@ -1,145 +0,0 @@
import { useEffect, useState, type KeyboardEvent } from 'react'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import Icon from '@/components/ui/Icon'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
const EMPTY = { type: '', citation: '', url: '', doi: '' }
const ID = 'tab-reference-new'
interface Props {
/** Bumped by each « Ajouter une référence »: the citation takes the focus again. */
focusSerial: number
/** The reference was created in one modification, under this id. */
onAdded: (id: string) => void
/** « Annuler l'ajout »: the draft goes, nothing was written. */
onCancel: () => void
}
const isTextTarget = (target: EventTarget) =>
target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement
const isPristine = (form: typeof EMPTY) =>
Object.values(form).every((v) => v === '')
const isComposing = (event: KeyboardEvent) =>
event.nativeEvent.isComposing || event.keyCode === 229
/**
* The draft tile of « Ajouter une référence » (board 24 E): type « Choisir… » and citation
* required, DOI and URL optional. Nothing reaches the document before « Ajouter la
* référence », which inserts the reference as one modification.
*/
export default function NewReferenceTile({
focusSerial,
onAdded,
onCancel,
}: Props) {
const t = useT()
const edit = useEditCommand()
const [form, setForm] = useState(EMPTY)
const set = (patch: Partial<typeof EMPTY>) => setForm({ ...form, ...patch })
useEffect(() => {
document.getElementById(`${ID}-citation`)?.focus()
}, [focusSerial])
const options = [
{ value: '', label: t('editor.field.choose') },
...REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
})),
]
const create = () => {
if (form.type === '' || isBlank(form.citation)) {
edit.reject('form', 'editor.reference.required')
return
}
let created = ''
const added = edit.runNew('form', 'ref', (id) => {
created = id
return {
op: 'insert',
element: {
kind: 'reference',
value: {
id,
type: form.type as ReferenceType,
citation: form.citation,
url: nullable(form.url),
doi: nullable(form.doi),
},
},
}
})
if (added) onAdded(created)
}
// Escape cancels from anywhere in the tile; a text field with typed text keeps it.
const escape = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (isComposing(event)) return
if (isTextTarget(event.target) && !isPristine(form)) return
event.preventDefault()
onCancel()
}
return (
<section
aria-label={t('editor.reference.new')}
onKeyDown={escape}
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
>
<div className="flex items-center gap-3 p-3">
<Icon name="chevron-down" size={18} />
<h3 className="text-sm font-semibold">{t('editor.reference.new')}</h3>
</div>
<div className="space-y-3 border-t border-[var(--color-border)] p-3">
<div className="grid gap-3 sm:grid-cols-2">
<SelectField
id={`${ID}-type`}
label={t('editor.reference.type')}
value={form.type}
options={options}
onCommit={(type) => set({ type })}
/>
<DraftField
id={`${ID}-doi`}
label={t('editor.reference.doi')}
value={form.doi}
onChange={(doi) => set({ doi })}
/>
</div>
<DraftField
id={`${ID}-citation`}
label={t('editor.reference.citation')}
value={form.citation}
onChange={(citation) => set({ citation })}
multiline
/>
<DraftField
id={`${ID}-url`}
label={t('editor.reference.url')}
value={form.url}
onChange={(url) => set({ url })}
/>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<div className="flex flex-wrap items-center gap-3">
<ActionButton readOnly={false} variant="primary" onClick={create}>
{t('editor.reference.add')}
</ActionButton>
<ActionButton readOnly={false} variant="secondary" onClick={onCancel}>
{t('editor.references.add_cancel')}
</ActionButton>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.add_help')}
</p>
</div>
</div>
</section>
)
}
@@ -14,6 +14,17 @@ export default function NoResult({
onClear: () => void
}) {
const t = useT()
// A filtered finding that cites nothing: no search to clear, the chip has the way out.
if (query.trim() === '') {
return (
<p
data-testid="editor-references-no-result"
className="text-sm text-[var(--color-ink-muted)]"
>
{t('editor.references.panel_empty')}
</p>
)
}
return (
<div
data-testid="editor-references-no-result"
@@ -0,0 +1,118 @@
import { useCallback, useEffect, useRef } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import Dialog from '@/components/ui/Dialog'
import { visibleElement } from '@/editor/focusRequest'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { ReferenceLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { ADD_BUTTON_ID } from './addButton'
import ReferenceForm from './ReferenceForm'
export interface ReferenceDialogProps {
layer: ReferenceLayer
readOnly: boolean
}
type View = ReferenceLayer['view']
/** The reference the view edits, read from the current document; null once it is gone. */
function editedIn(view: View, references: readonly Reference[] | undefined) {
if (!view || !('edit' in view)) return null
return references?.find((reference) => reference.id === view.edit) ?? null
}
/**
* The reference the dialog edits vanished (a reload after a conflict, a Back onto a dead
* entry): the layer closes by replace and says so (R2F-5). After this commit's effects,
* as the finding dialog's rule: a form that registered a guard in them can still be asked.
*/
function useGoneRule(layer: ReferenceLayer) {
const t = useT()
const doc = useSheetDocument()
const handled = useRef<string | null>(null)
const { view } = layer
useEffect(() => {
if (!view) handled.current = null
if (!doc || !view || !('edit' in view)) return
const stamp = JSON.stringify(view)
if (editedIn(view, doc.references) || handled.current === stamp) return
handled.current = stamp
queueMicrotask(() => layer.replace(null, t('editor.references.gone')))
}, [view, doc, layer, t])
}
/** Where a closed dialog returns the focus: the tile's header, or the add button. */
function useReturnTarget(layer: ReferenceLayer) {
const last = useRef(layer.view)
if (layer.view) last.current = layer.view
const { opener } = layer
return useCallback((): HTMLElement | null => {
const shown = last.current
if (!shown) return null
if ('create' in shown) return document.getElementById(ADD_BUTTON_ID)
const wanted = JSON.stringify({ kind: 'reference', id: shown.edit })
return (
opener() ??
visibleElement('[data-tile-header]', (element) => {
return element.dataset.focusKey === wanted
})
)
}, [opener])
}
/** What the layer shows: a creation, or the reference it edits (null once it is gone). */
function useShownReference(layer: ReferenceLayer) {
const t = useT()
const doc = useSheetDocument()
const creating = !!layer.view && 'create' in layer.view
const edited = editedIn(layer.view, doc?.references)
const title = creating
? 'editor.reference.new'
: 'editor.references.edit_title'
return { creating, edited, title: t(title), open: creating || !!edited }
}
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
function useOnSaved(layer: ReferenceLayer, creating: boolean) {
const t = useT()
return (id: string, citation: string) => {
if (!creating) return void layer.close(true)
layer.announce(t('editor.references.added').replace('{citation}', citation))
layer.created(id)
}
}
/**
* 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.
*/
export default function ReferenceDialog({
layer,
readOnly,
}: ReferenceDialogProps) {
const shown = useShownReference(layer)
const returnFocus = useReturnTarget(layer)
const onSaved = useOnSaved(layer, shown.creating)
useGoneRule(layer)
return (
<Dialog
open={shown.open}
layer
size="lg"
title={shown.title}
returnFocus={returnFocus}
onClose={() => (layer.close() ? undefined : 'kept')}
>
<ReferenceForm
key={shown.edited?.id ?? 'new'}
reference={shown.edited}
readOnly={readOnly}
guards={layer.guards}
onSaved={onSaved}
onClose={(forced) => layer.close(forced)}
/>
</Dialog>
)
}
@@ -1,61 +0,0 @@
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
import {
useReferenceEdit,
type EditHooks,
type Field,
} from './useReferenceEdit'
interface Props {
reference: Reference
/** DOM id prefix of the tile (host, position and id): the fields' ids derive from it. */
base: string
/** The tile's leave guard (registered while mounted), focus ticket and dropped-draft slot. */
hooks: EditHooks
}
/** The edit view of one reference (board 24 D): type, DOI, citation and URL. */
export default function ReferenceEditor(props: Props) {
const { reference, base } = props
const t = useT()
const { edit, drafts, setDraft, commitField, setType } = useReferenceEdit(
reference,
base,
props.hooks,
)
const text = (field: Field, label: string, multiline = false) => (
<DraftField
id={`${base}-${field}`}
label={label}
value={drafts[field]}
onChange={(value) => setDraft(field, value)}
onBlur={() => commitField(field)}
multiline={multiline}
error={edit.fieldError(field)}
/>
)
const options = REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
}))
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<SelectField
id={`${base}-type`}
label={t('editor.reference.type')}
value={reference.type}
options={options}
onCommit={(type) => setType(type as ReferenceType)}
error={edit.fieldError('type')}
/>
{text('doi', t('editor.reference.doi'))}
</div>
{text('citation', t('editor.reference.citation'), true)}
{text('url', t('editor.reference.url'))}
</div>
)
}
@@ -0,0 +1,246 @@
import { useRef } from 'react'
import type {
EditCommand,
Reference,
ReferenceType,
} from '@faunosteo/core-wasm/types'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
import { webHref } from '@/editor/references/safeLink'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
/** What the form edits, as plain strings: nothing is written before « Enregistrer ». */
interface Draft {
type: string
citation: string
doi: string
url: string
}
const EMPTY: Draft = { type: '', citation: '', doi: '', url: '' }
const draftOf = (reference: Reference): Draft => ({
type: reference.type,
citation: reference.citation,
doi: reference.doi ?? '',
url: reference.url ?? '',
})
/** The draft as the document would hold it: a blank optional field is absent. */
const normalized = (draft: Draft): Draft => ({
...draft,
doi: nullable(draft.doi) ?? '',
url: nullable(draft.url) ?? '',
})
const sameDraft = (a: Draft, b: Draft) =>
JSON.stringify(normalized(a)) === JSON.stringify(normalized(b))
type Field = 'type' | 'citation' | 'url'
/** The first field the core would refuse, with the words for it; null when none. */
function refusalOf(
draft: Draft,
creating: boolean,
): { field: Field; key: string } | null {
const required = 'editor.field.required'
if (creating && draft.type === '') return { field: 'type', key: required }
if (isBlank(draft.citation)) return { field: 'citation', key: required }
const url = nullable(draft.url)
if (url !== null && webHref(url) === null) {
return { field: 'url', key: 'editor.reference.url_invalid' }
}
return null
}
/** The reference the draft makes under `id`. */
function valueOf(draft: Draft, id: string): Reference {
const now = normalized(draft)
return {
id,
type: now.type as ReferenceType,
citation: now.citation,
doi: nullable(now.doi),
url: nullable(now.url),
}
}
export interface ReferenceFormProps {
/** The reference edited; null for a creation. */
reference: Reference | null
readOnly: boolean
guards: Guards
/** One command was written; `id` and `citation` are the reference's. */
onSaved: (id: string, citation: string) => void
/** Nothing was written (pristine save, « Annuler », « Abandonner »); forced drops a draft. */
onClose: (forced: boolean) => void
}
type Form = ReturnType<typeof useFormDraft<Draft>>
/**
* The one command of a save: an `update` of the reference, or an `insert` under a new id.
* The dialog closes after a save: a second submit while it plays its exit writes nothing.
*/
function useWrite(reference: Reference | null, draft: Draft) {
const edit = useEditCommand()
const saved = useRef(false)
const run = (): string | null => {
if (reference) {
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
const key = { kind: 'reference', id: reference.id }
const command = { op: 'update', key, element } as EditCommand
return edit.run('form', command) ? reference.id : null
}
let id = ''
const added = edit.runNew('form', 'ref', (fresh) => {
id = fresh
const element = { kind: 'reference', value: valueOf(draft, fresh) }
return { op: 'insert', element } as EditCommand
})
return added ? id : null
}
const write = (): string | null => {
const id = saved.current ? null : run()
saved.current = saved.current || id !== null
return id
}
return { edit, write }
}
/** The save: refused on its field, nothing written when unchanged, else one command. */
function useReferenceSave(props: ReferenceFormProps, form: Form) {
const { edit, write } = useWrite(props.reference, form.draft)
const save = () => {
const refusal = refusalOf(form.draft, props.reference === null)
if (refusal) {
edit.reject(refusal.field, refusal.key)
document.getElementById(`reference-form-${refusal.field}`)?.focus()
return
}
if (!form.dirty) return props.onClose(false)
const id = write()
if (id !== null) props.onSaved(id, form.draft.citation)
}
return { save, edit }
}
/** The form's state: the local draft, its guard and its save. */
function useReferenceForm(props: ReferenceFormProps) {
const first = props.reference ? draftOf(props.reference) : EMPTY
const form = useFormDraft(first, props.guards, sameDraft, 'reference')
return { ...form, ...useReferenceSave(props, form) }
}
type ReferenceFormState = ReturnType<typeof useReferenceForm>
/** One of the three text fields of the form, a draft field with its own refusal. */
function Text(props: {
form: ReferenceFormState
field: 'doi' | 'citation' | 'url'
readOnly: boolean
multiline?: boolean
}) {
const t = useT()
const { form, field } = props
return (
<DraftField
id={`reference-form-${field}`}
label={t(`editor.reference.${field}`)}
value={form.draft[field]}
onChange={(value) => form.set({ [field]: value })}
readOnly={props.readOnly}
multiline={props.multiline}
error={form.edit.fieldError(field)}
/>
)
}
/** The type, then the three texts, as draft fields. */
function FormFields({
form,
readOnly,
}: {
form: ReferenceFormState
readOnly: boolean
}) {
const t = useT()
const options = [
{ value: '', label: t('editor.field.choose') },
...REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
})),
]
return (
<>
<div className="grid gap-3 sm:grid-cols-2">
<SelectField
id="reference-form-type"
label={t('editor.reference.type')}
value={form.draft.type}
options={options}
onCommit={(type) => form.set({ type })}
readOnly={readOnly}
error={form.edit.fieldError('type')}
/>
<Text form={form} field="doi" readOnly={readOnly} />
</div>
<Text form={form} field="citation" readOnly={readOnly} multiline />
<Text form={form} field="url" readOnly={readOnly} />
</>
)
}
/**
* A reference edited or created in the reference dialog (R2F-5): a local draft, one
* command on « Enregistrer » (none when nothing changed), nothing on « Annuler », a close
* or a move. When the editor turns read-only the draft stays, its fields read-only, and
* only « Abandonner » is left.
*/
export default function ReferenceForm(props: ReferenceFormProps) {
const t = useT()
const form = useReferenceForm(props)
const { guard } = form
const creating = props.reference === null
return (
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
form.save()
}}
>
{props.readOnly && <ReadOnlyNotice />}
<FormFields form={form} readOnly={props.readOnly} />
{form.edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{form.edit.fieldError('form')}
</p>
)}
<FormActions
confirming={guard.confirming}
readOnly={props.readOnly}
submitLabel={t(
creating ? 'editor.reference.add' : 'editor.findings.save',
)}
onCancel={() =>
form.dirty && !props.readOnly
? guard.askToLeave()
: props.onClose(props.readOnly)
}
onKeepTyping={guard.keepTyping}
onDiscard={() => props.onClose(true)}
/>
</form>
)
}
@@ -1,43 +1,23 @@
import {
useCallback,
useContext,
useLayoutEffect,
useRef,
useState,
type RefObject,
} from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { AnnounceContext } from '@/editor/focusRequest'
import { usePlural } from '@/editor/plural'
import type { CiterItem } from '@/editor/references/citations'
import { useT } from '@/i18n/useT'
import CitersList from './CitersList'
import ReferenceEditor from './ReferenceEditor'
import ReferenceFacts from './ReferenceFacts'
import type { ReferenceHost } from './referenceTypes'
import { useDroppedText, type Field, type LeaveGuard } from './useReferenceEdit'
/** What a tile asks of the library that owns its state. */
export interface TileHandlers {
toggle: () => void
edit: () => void
/** Leaves the edit view; false (the view stays) when a field refuses. */
done: () => boolean
/** « Modifier »: opens the reference dialog; `opener` is where the focus returns. */
edit: (opener: HTMLElement) => void
/** « Supprimer »: the Références tab only. */
remove?: () => void
/** « Monter » / « Descendre »: the Références tab only. */
move?: (position: number) => void
goTo: (key: ElementKey) => void
registerLeave: (guard: LeaveGuard | null) => void
/** True once after « Modifier »: the edit view then focuses its Citation field. */
takeFocus: () => boolean
/**
* True while the host itself unmounts: the leave that closed it already said the dropped
* drafts (the citations panel's forced close), so the tile does not say them again.
*/
hostLeaving?: () => boolean
}
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
@@ -56,7 +36,6 @@ export interface TileProps {
count: number
citers: readonly CiterItem[]
open: boolean
editing: boolean
readOnly: boolean
/** ↑ / ↓ only while neither the search nor a sort narrows or reorders the list. */
movable: boolean
@@ -82,58 +61,34 @@ const BUTTON_RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** The disclosure button: citation (two lines when closed), type and how often it is cited. */
function TileHeader({
base,
props,
headerRef,
onToggle,
}: {
base: string
props: TileProps
headerRef: RefObject<HTMLButtonElement | null>
onToggle: () => void
}) {
function TileHeader({ base, props }: { base: string; props: TileProps }) {
const t = useT()
const plural = usePlural()
const { reference, open, editing, citers } = props
const { reference, open, citers } = props
const cited = citers.length
const key = JSON.stringify({ kind: 'reference', id: reference.id })
return (
<button
ref={headerRef}
type="button"
id={`${base}-header`}
data-focus-key={key}
data-tile-header
aria-expanded={open || editing}
aria-expanded={open}
aria-controls={`${base}-body`}
aria-describedby={props.outsideSearch ? `${base}-outside` : undefined}
onClick={onToggle}
onClick={props.on.toggle}
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left ${META_COLUMN[props.host]} ${BUTTON_RING}`}
>
<Icon
name={open || editing ? 'chevron-down' : 'chevron-right'}
size={18}
/>
<Icon name={open ? 'chevron-down' : 'chevron-right'} size={18} />
<span
className={`min-w-0 break-words text-sm ${open || editing ? '' : 'line-clamp-2'} ${editing ? 'font-semibold' : ''}`}
className={`min-w-0 break-words text-sm ${open ? '' : 'line-clamp-2'}`}
>
{editing ? (
// In edit this button ends the edit: its name says so, the title stays visible (M7).
<>
<span className="sr-only">{t('editor.references.done')}. </span>
{t('editor.references.edit_title')}
</>
) : (
reference.citation
)}
{reference.citation}
</span>
<span className="col-start-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-ink-muted)] sm:col-start-3 sm:row-start-1 sm:flex-col sm:items-end">
{!editing && (
<span className="rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 font-medium text-[var(--color-ink)]">
{t(`editor.reference.type.${reference.type}`)}
</span>
)}
<span className="rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 font-medium text-[var(--color-ink)]">
{t(`editor.reference.type.${reference.type}`)}
</span>
<span>
{cited === 0
? t('editor.references.uncited')
@@ -159,7 +114,7 @@ function PanelActions({
readOnly={false}
variant="secondary"
size="sm"
onClick={props.on.edit}
onClick={(event) => props.on.edit(event.currentTarget)}
>
{t('editor.references.edit')}
</ActionButton>
@@ -188,7 +143,7 @@ function TileActions({ props }: { props: TileProps }) {
readOnly={false}
variant="secondary"
size="sm"
onClick={on.edit}
onClick={(event) => on.edit(event.currentTarget)}
>
{t('editor.references.edit')}
</ActionButton>
@@ -236,96 +191,21 @@ function TileActions({ props }: { props: TileProps }) {
}
/**
* The refused drafts an edit view was unmounted with (a read-only flip, an undo that removes
* the reference), as the tile keeps them: shown by the tile until its next action. The drop
* is said once in the polite live region from `onDrop` itself, not from an effect: an undo
* unmounts the tile with its view, and a dying tile runs no effect (V1). An edit view that
* ends on purpose (« Terminer », another tile's « Modifier ») ends the note; a flip does not.
*/
function useDroppedDrafts(
editing: boolean,
readOnly: boolean,
hostLeaving?: () => boolean,
) {
const droppedText = useDroppedText()
const announce = useContext(AnnounceContext)
const [dropped, setDropped] = useState<readonly Field[] | null>(null)
const [wasEditing, setWasEditing] = useState(editing)
if (wasEditing !== editing) {
setWasEditing(editing)
if (wasEditing && !readOnly) setDropped(null)
}
// `onDrop` must stay stable (the view's cleanup depends on it): it reads the latest
// render's words and host through this ref.
const latest = useRef({ droppedText, announce, hostLeaving })
useLayoutEffect(() => {
latest.current = { droppedText, announce, hostLeaving }
})
const onDrop = useCallback((fields: readonly Field[]) => {
setDropped(fields)
const now = latest.current
if (!now.hostLeaving?.()) now.announce(now.droppedText(fields))
}, [])
return { dropped, setDropped, onDrop }
}
/** The tile's own actions: « Terminer » refocuses the header, a toggle ends the note. */
function useTileActions(
props: TileProps,
headerRef: RefObject<HTMLButtonElement | null>,
) {
const { on, editing, readOnly } = props
const { dropped, setDropped, onDrop } = useDroppedDrafts(
editing,
readOnly,
on.hostLeaving,
)
return {
dropped,
onDrop,
done: () => {
if (on.done()) headerRef.current?.focus()
},
toggle: () => {
setDropped(null)
on.toggle()
},
}
}
/** « Saisie non appliquée : … »: plain text, the live region says it once elsewhere. */
function DroppedNote({ fields }: { fields: readonly Field[] }) {
const droppedText = useDroppedText()
return (
<p className="flex items-start gap-2 rounded-md bg-amber-50 p-2 text-sm text-amber-800">
<Icon name="alert" size={16} className="mt-0.5 shrink-0" />
{droppedText(fields)}
</p>
)
}
/**
* One reference as a collapsible tile (boards 23, 24): closed, open (facts, citers,
* actions), or in edit (fields, citers, « Terminer »). Read-only: the facts and the
* citers' « Aller à » only, no control that changes the draft.
* One reference as a collapsible tile (boards 23, 24): closed, or open (facts, citers,
* actions). « Modifier » opens the reference dialog; no field is edited in the tile
* (R2F-5). Read-only: the facts and the citers' « Aller à » only, no control that changes
* the document.
*/
export default function ReferenceTile(props: TileProps) {
const { host, reference, position, open, editing, on } = props
const { host, reference, position, open, on } = props
const t = useT()
const base = tileBase(host, position, reference)
const headerRef = useRef<HTMLButtonElement>(null)
const { dropped, onDrop, done, toggle } = useTileActions(props, headerRef)
return (
<li
data-reference-tile
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
>
<TileHeader
base={base}
props={props}
headerRef={headerRef}
onToggle={toggle}
/>
<TileHeader base={base} props={props} />
{props.outsideSearch && (
<p
id={`${base}-outside`}
@@ -334,45 +214,18 @@ export default function ReferenceTile(props: TileProps) {
{t('editor.references.outside_search')}
</p>
)}
{(open || editing) && (
{open && (
<div
id={`${base}-body`}
className="space-y-3 border-t border-[var(--color-border)] p-3"
>
{editing ? (
<ReferenceEditor
reference={reference}
base={base}
hooks={{
registerLeave: on.registerLeave,
takeFocus: on.takeFocus,
onDrop,
}}
/>
) : (
<ReferenceFacts reference={reference} />
)}
<ReferenceFacts reference={reference} />
<CitersList
citers={props.citers}
current={props.panel?.current}
onGoTo={on.goTo}
/>
{dropped && <DroppedNote fields={dropped} />}
{editing ? (
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
// A press keeps the focus in its field: a refusal shown on blur would move
// the button before the click lands. The click applies every field itself.
onMouseDown={(event) => event.preventDefault()}
onClick={done}
>
{t('editor.references.done')}
</ActionButton>
) : (
<TileActions props={props} />
)}
<TileActions props={props} />
</div>
)}
</li>
@@ -19,7 +19,7 @@ interface Props {
readOnly: boolean
movable: boolean
navigate: (target: EditorTarget) => void
onEdit: (position: number) => void
onEdit: (position: number, opener: HTMLElement) => void
onDelete: (reference: Reference) => void
}
@@ -49,19 +49,15 @@ export default function ReferenceTiles(props: Props) {
count={all.length}
citers={citers.get(reference.id) ?? []}
open={tiles.openKeys.has(key)}
editing={!props.readOnly && tiles.editingKey === key}
readOnly={props.readOnly}
movable={props.movable}
outsideSearch={!referenceMatches(reference, props.query)}
on={{
toggle: () => tiles.toggle(key, props.readOnly),
edit: () => props.onEdit(position),
done: tiles.finish,
toggle: () => tiles.toggle(key),
edit: (opener) => props.onEdit(position, opener),
remove: () => props.onDelete(reference),
move: (to) => move(reference, to),
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
takeFocus: () => tiles.takeFocus(key),
}}
/>
)
@@ -20,7 +20,51 @@ interface Props {
total: number
/** « Ajouter une référence »: absent while the editor is read-only. */
canAdd: boolean
onAdd: () => void
onAdd: (opener: HTMLElement) => void
/** The finding the list is filtered by (R2F-6), with the two ways out of the filter. */
filter: FilterChip | null
}
/** The finding filter: its name, « × » and « Revenir au constat ». */
export interface FilterChip {
name: string
onRemove: () => void
onBack: () => void
}
const BUTTON =
'inline-flex min-h-11 items-center justify-center rounded-md px-2 ' +
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** « Références du constat : X » with « × », and the way back to the finding. */
function FilterBar({ filter }: { filter: FilterChip }) {
const t = useT()
const fill = (key: string) => t(key).replace('{name}', () => filter.name)
return (
<div
data-testid="editor-references-filter"
className="flex flex-wrap items-center gap-x-3 gap-y-1"
>
<span className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border)] bg-[var(--color-surface-strong)] pl-3 text-sm">
{fill('editor.references.filter_chip')}
<button
type="button"
aria-label={fill('editor.references.filter_remove')}
onClick={filter.onRemove}
className={`${BUTTON} rounded-full`}
>
<Icon name="close" size={14} />
</button>
</span>
<button
type="button"
onClick={filter.onBack}
className={`${BUTTON} text-sm text-[var(--color-accent-strong)] underline`}
>
{t('editor.references.filter_back')}
</button>
</div>
)
}
/** The count line: « {n} références » or « {n} références sur {total} ». */
@@ -88,6 +132,7 @@ export default function ReferenceToolbar(props: Props) {
</Select>
</div>
</div>
{props.filter && <FilterBar filter={props.filter} />}
<div className="flex flex-wrap items-center justify-between gap-3">
<CountLine shown={props.shown} total={props.total} />
<ActionButton
@@ -95,7 +140,7 @@ export default function ReferenceToolbar(props: Props) {
readOnly={!props.canAdd}
variant="secondary"
size="sm"
onClick={props.onAdd}
onClick={(event) => props.onAdd(event.currentTarget)}
>
{t('editor.references.add')}
</ActionButton>
@@ -6,15 +6,11 @@ import { citedIds, citingFinding } from '@/editor/references/filter'
import { citationEntries, findingPath } from '@/editor/references/panel'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards, LeaveAnswer } from '@/editor/useEditorNavigation'
import { useDroppedText } from './useReferenceEdit'
import { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
readOnly: boolean
citedBy: ElementKey
/** The layers' guards: the tile in edit registers its own for the sheet. */
guards: Guards
}
/** The finding read from the current document; null once the document lacks it. */
@@ -27,29 +23,6 @@ function useCitedFinding(citedBy: ElementKey) {
return { doc, item }
}
/**
* P22'': a move that leaves the sheet asks the tile in edit first (a refusal cancels the
* move); a forced one (the finding vanished) drops a refused draft and says so. Interim
* until the reference dialog replaces the inline tile edit.
*/
function useLeaveCheck(tiles: ReturnType<typeof useTileState>, guards: Guards) {
const droppedText = useDroppedText()
const check = (forced: boolean): LeaveAnswer => {
const refused = tiles.leave()
if (refused.length === 0) return { allowed: true }
if (!forced) return { allowed: false }
return { allowed: true, note: droppedText(refused) }
}
// Registered once and kept: the layers' effects of one commit run cleanups first, so a
// guard re-registered on every render would be absent when another layer asks.
const latest = useRef(check)
latest.current = check
useEffect(() => {
guards.register('citations', (forced) => latest.current(forced))
return () => guards.register('citations', null)
}, [guards])
}
/** The row the focus is in: its element, its index in the list and the list's length. */
interface Held {
element: Element
@@ -135,12 +108,11 @@ export function useCitationsPanel(hooks: PanelHooks) {
const edit = useEditCommand()
const tiles = useTileState(doc ? keys : null)
const focus = useFocusRescue()
useLeaveCheck(tiles, hooks.guards)
// « Retirer de ce constat » is the detail's « Retirer »: the same update of the finding's
// reference_ids, so the core marks the finding « À confirmer » (P15) and one « Défaire »
// restores the citation and the status together. The reference itself stays in the sheet.
const remove = (at: number) => {
if (!item || !tiles.finish()) return
if (!item) return
const rest = ids.filter((_, index) => index !== at)
const element = patchElement(item, { reference_ids: rest })
const command = { op: 'update', key: item.key, element } as const
@@ -1,178 +0,0 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
/** The text fields of the edit view, in the order the leave guard tries them. */
export const FIELDS = ['citation', 'doi', 'url'] as const
export type Field = (typeof FIELDS)[number]
type Drafts = Record<Field, string>
/**
* What the guard calls on a leave: every pending field is tried; the fields that refused
* (their drafts stay, the first one is focused), empty when all were applied.
*/
export type LeaveGuard = () => Field[]
/** What the tile hands its edit view (the library owns the state). */
export interface EditHooks {
registerLeave: (guard: LeaveGuard | null) => void
/** True once per « Modifier »: the mount focuses Citation, a remount never does. */
takeFocus: () => boolean
/** The view unmounted with these refused drafts; stable (it runs from a cleanup). */
onDrop: (fields: readonly Field[]) => void
}
const committedOf = (reference: Reference): Drafts => ({
citation: reference.citation,
doi: reference.doi ?? '',
url: reference.url ?? '',
})
/** The document value a draft gives (a blank optional field is null, so ''). */
const normalized = (field: Field, draft: string) =>
field === 'citation' ? draft : (nullable(draft) ?? '')
const patched = (reference: Reference, field: Field, draft: string) =>
field === 'citation'
? { ...reference, citation: draft }
: { ...reference, [field]: nullable(draft) }
/** One draft per text field; a new committed value (undo, reload) replaces its draft. */
function useDrafts(reference: Reference) {
const committed = committedOf(reference)
const [drafts, setDrafts] = useState(committed)
const [seen, setSeen] = useState(committed)
const changed = FIELDS.filter((field) => seen[field] !== committed[field])
if (changed.length > 0) {
setSeen(committed)
const fresh = changed.map((field) => [field, committed[field]])
setDrafts({ ...drafts, ...Object.fromEntries(fresh) })
}
const setDraft = (field: Field, value: string) =>
setDrafts({ ...drafts, [field]: value })
return [drafts, setDraft] as const
}
/** The fields whose draft differs from `reference`, in `FIELDS` order. */
const pendingFields = (reference: Reference, drafts: Drafts) =>
FIELDS.filter(
(field) =>
normalized(field, drafts[field]) !== committedOf(reference)[field],
)
/**
* The reference as the document holds it now, and the drafts as typed. A blur right after
* an apply (« Terminer » focusing the header, a close) runs before the next render, so
* the rendered `reference` is stale there: `applied` advances with every apply and is
* replaced when the document hands a new reference (undo, reload) (C1).
*/
function useAppliedReference(reference: Reference, drafts: Drafts) {
const applied = useRef(reference)
const typed = useRef(drafts)
useLayoutEffect(() => {
applied.current = reference
}, [reference])
useLayoutEffect(() => {
typed.current = drafts
})
return { applied, typed }
}
/** What the view does to the document: `update`, `apply` a draft, which drafts are `pending`. */
function useWriter(reference: Reference, drafts: Drafts) {
const edit = useEditCommand()
const { applied, typed } = useAppliedReference(reference, drafts)
const update = (field: string, value: Reference) => {
const key = { kind: 'reference', id: reference.id } as const
const element = { kind: 'reference', value } as const
const done = edit.run(field, { op: 'update', key, element })
if (done) applied.current = value
return done
}
const apply = (field: Field): boolean => {
if (field === 'citation' && isBlank(drafts[field])) {
return edit.reject(field, 'editor.field.required')
}
return update(field, patched(applied.current, field, drafts[field]))
}
const pending = (field: Field) =>
normalized(field, drafts[field]) !== committedOf(applied.current)[field]
return { edit, applied, typed, update, apply, pending }
}
/** The view's three effects: its guard, the focus ticket and the dropped-draft report. */
function useEditLifecycle(
base: string,
hooks: EditHooks,
leave: LeaveGuard,
writer: Pick<ReturnType<typeof useWriter>, 'applied' | 'typed'>,
) {
const { registerLeave, takeFocus, onDrop } = hooks
const { applied, typed } = writer
useEffect(() => {
registerLeave(leave)
return () => registerLeave(null)
})
useEffect(() => {
if (takeFocus()) document.getElementById(`${base}-citation`)?.focus()
}, [base, takeFocus])
// Never clears a report (a StrictMode remount runs this cleanup with nothing pending).
useLayoutEffect(
() => () => {
const pending = pendingFields(applied.current, typed.current)
if (pending.length > 0) onDrop(pending)
},
[applied, typed, onDrop],
)
}
/**
* The write path of one reference's edit view. A field applies to the draft when it
* loses the focus (`commitField`); `leave` re-applies every field whose text differs from
* the document, focuses the first refused field and shows that field's refusal (the view
* has one error slot; the other refused drafts stay as typed) (P22, P22', I1).
* `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
* `takeFocus` says whether this mount is a user's « Modifier » (it focuses Citation) and
* `onDrop` receives the fields of the refused drafts the view is unmounted with (M1).
*/
export function useReferenceEdit(
reference: Reference,
base: string,
hooks: EditHooks,
) {
const [drafts, setDraft] = useDrafts(reference)
const writer = useWriter(reference, drafts)
const { edit, applied, apply, pending } = writer
const leave: LeaveGuard = () => {
const refused = FIELDS.filter(pending).filter((field) => !apply(field))
if (refused.length === 0) return refused
// The focus move runs the blur commit of the field that held it, which writes the
// one error slot; re-applying the first refusal last makes the focused field the
// one that shows its message (I1). Refused again, it writes nothing.
document.getElementById(`${base}-${refused[0]}`)?.focus()
apply(refused[0])
return refused
}
useEditLifecycle(base, hooks, leave, writer)
return {
edit,
drafts,
setDraft,
commitField: (field: Field) => pending(field) && apply(field),
setType: (type: ReferenceType) =>
writer.update('type', { ...applied.current, type }),
}
}
/** « Saisie non appliquée : Citation, Adresse web (URL) »: the words for dropped drafts. */
export function useDroppedText(): (fields: readonly Field[]) => string {
const t = useT()
return (fields) => {
const names = fields.map((field) => t(`editor.reference.${field}`))
return t('editor.references.draft_dropped').replace('{field}', () =>
names.join(', '),
)
}
}
@@ -7,27 +7,69 @@ import {
type FocusRequest,
} from '@/editor/focusRequest'
import { citersOf } from '@/editor/references/citations'
import { referenceMatches } from '@/editor/references/filter'
import {
citedIds,
citingFinding,
referenceMatches,
} from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { ReferenceLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { tileKeys, useTileState } from './useTileState'
import { useReferenceView } from './useReferenceView'
import { ADD_BUTTON_ID } from './addButton'
const NO_CITERS = new Map<string, never[]>()
/** The document's references with the tab's tile state and display order. */
export function useReferenceLibrary(resetSignal: number) {
/**
* The finding the filter names, read from the current document, with the ids it cites. A
* filter whose finding is gone (an undo, a reload, a Back onto a dead entry) is removed by
* replace and says so once (R2F-6).
*/
function useFilterFinding(layer: ReferenceLayer) {
const t = useT()
const doc = useSheetDocument()
const finding = doc ? citingFinding(doc, layer.filter) : null
const gone = doc !== null && layer.filter !== null && finding === null
useEffect(() => {
if (gone) layer.clearFilter(t('editor.references.filter_gone'))
// The wording and the move are stable per render; the vanished finding is the trigger.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [gone])
return { finding, cited: finding ? new Set(citedIds(finding)) : null }
}
/** The tile key of the reference the dialog edits, while this tab is the place shown. */
function useEditedKey(layer: ReferenceLayer): string | null {
const shown = usePlaceVisible()
const { view } = layer
return shown && view && 'edit' in view ? `${view.edit}#0` : null
}
/** The document's references, one tile key each, the tile state and who cites what. */
function useBibliography() {
const doc = useSheetDocument()
const all: readonly Reference[] = doc?.references ?? []
const keys = tileKeys(all)
const tiles = useTileState(doc ? keys : null)
const citers = doc ? citersOf(doc) : NO_CITERS
return { loaded: doc !== null, all, keys, tiles, citers }
}
/** The document's references with the tab's tile state and display order. */
export function useReferenceLibrary(
resetSignal: number,
layer: ReferenceLayer,
) {
const bibliography = useBibliography()
const filter = useFilterFinding(layer)
const shown = useReferenceView(
{ all, keys, citers },
tiles.editingKey,
bibliography,
useEditedKey(layer),
resetSignal,
filter.cited,
)
return { loaded: doc !== null, all, keys, tiles, citers, shown }
return { ...bibliography, shown, finding: filter.finding }
}
export type ReferenceLibraryState = ReturnType<typeof useReferenceLibrary>
@@ -45,65 +87,76 @@ function useLateFocus() {
const positionOf = (all: readonly Reference[], key: ElementKey) =>
all.findIndex((r) => key.kind === 'reference' && r.id === key.id)
type Show = (key: ElementKey) => 'found' | 'none'
/**
* « Aller à » a reference: its tile is opened, the search is cleared (only it, P3) when it
* hides the tile, and the tile's button is focused after the commit that shows it (P8).
* Shows a reference's tile: opened, the search cleared (only it, P3) and the finding
* filter removed when they hide it, its button focused after the commit that shows it
* (P8). `none` when the sheet holds no such reference.
*/
function useReferenceFocus(
focus: FocusRequest | undefined,
function useShowReference(
lib: ReferenceLibraryState,
later: (key: ElementKey) => void,
) {
const { all, keys, tiles, shown } = lib
useFocusRequest(focus, (target) => {
const at = target.key === null ? -1 : positionOf(all, target.key)
if (target.key === null || at < 0) return 'none'
tiles.reveal(keys[at])
if (referenceMatches(all[at], shown.view.query)) {
return focusRowLater(target.key) ? 'found' : 'none'
}
shown.update({ query: '' })
later(target.key)
layer: ReferenceLayer,
): Show {
const later = useLateFocus()
return (key) => {
const at = positionOf(lib.all, key)
if (at < 0) return 'none'
const reference = lib.all[at]
lib.tiles.reveal(lib.keys[at])
const cited = lib.finding && citedIds(lib.finding)
const filtered = !!cited && !cited.includes(reference.id)
const matches = referenceMatches(reference, lib.shown.view.query)
if (matches && !filtered) return focusRowLater(key) ? 'found' : 'none'
if (filtered) layer.clearFilter()
if (!matches) lib.shown.update({ query: '' })
later(key)
return 'found'
})
}
}
/** What the library's controls do: search, « Ajouter une référence », edit and « Aller à ». */
export function useReferenceActions(
lib: ReferenceLibraryState,
focus: FocusRequest | undefined,
searchRef: RefObject<HTMLInputElement | null>,
/** « Aller à » a reference: its tile is shown and focused. */
function useReferenceFocus(focus: FocusRequest | undefined, show: Show) {
useFocusRequest(focus, (target) =>
target.key === null ? 'none' : show(target.key),
)
}
/** The notice of a reference just added: shown until « Afficher », or until it is gone. */
function useAddedNotice(
all: readonly Reference[],
added: ReferenceLayer['added'],
show: Show,
) {
const { keys, tiles, shown } = lib
const [draft, setDraft] = useState<number | null>(null)
const later = useLateFocus()
useReferenceFocus(focus, lib, later)
const [dismissed, setDismissed] = useState(0)
const reference = added && all.find((r) => r.id === added.id)
if (!added || !reference || added.serial === dismissed) return null
return {
draft,
clearSearch: () => {
shown.update({ query: '' })
searchRef.current?.focus()
},
// P24 (and P22): leave the tile in edit first, then a clean view and the draft.
startAdd: () => {
if (!tiles.finish()) return
shown.reset(null)
setDraft((serial) => (serial ?? 0) + 1)
},
// P24: the new tile is shown whatever was typed meanwhile, so the view is reset.
added: (id: string) => {
setDraft(null)
shown.reset(tiles.editingKey)
tiles.reveal(`${id}#0`)
later({ kind: 'reference', id })
},
// C2: nothing was written; the search and sort reset by the add stay as they are.
cancelAdd: () => {
setDraft(null)
document.getElementById(ADD_BUTTON_ID)?.focus()
},
edit: (position: number) => {
if (tiles.startEdit(keys[position])) shown.markEdited(keys[position])
citation: reference.citation,
show: () => {
show({ kind: 'reference', id: added.id })
setDismissed(added.serial)
},
}
}
/** What the library's controls do: search, « Ajouter une référence », « Modifier », « Aller à ». */
export function useReferenceActions(
lib: ReferenceLibraryState,
focus: FocusRequest | undefined,
layer: ReferenceLayer,
searchRef: RefObject<HTMLInputElement | null>,
) {
const show = useShowReference(lib, layer)
useReferenceFocus(focus, show)
return {
notice: useAddedNotice(lib.all, layer.added, show),
clearSearch: () => {
lib.shown.update({ query: '' })
searchRef.current?.focus()
},
startAdd: (opener: HTMLElement) => layer.start(opener),
edit: (position: number, opener: HTMLElement) =>
layer.open(lib.all[position].id, opener),
}
}
@@ -26,70 +26,61 @@ interface Shown {
/**
* The search, the sort and the resulting tile order of the Références tab. All three are
* display state: nothing here reaches the document (BDR-114). `resetSignal` (« Tout
* afficher ») empties the search once per bump and keeps the sort (R2F-4); the tab stays
* mounted (A2).
* The tile that entered edit is pinned at the index it was shown at, whatever the search
* or the sort, and stays pinned after « Terminer » until the next search or sort change,
* so the tile the user just edited never vanishes under their focus (P23, I1). A
* read-only flip keeps the pin: the tile in edit stays shown across it, with its note.
* `editingKey` is the tile in edit, if any.
* display state: nothing here reaches the document (BDR-114), and the search is a personal
* search that never reaches the browser history. `resetSignal` (« Tout afficher ») empties
* the search once per bump and keeps the sort (R2F-4); the tab stays mounted (A2).
* `cited` (the ids one finding cites, null for none) narrows the list and the counts
* (R2F-6); it is navigation, held by the history.
* The tile the dialog edits (`editingKey`) is pinned at the index it was shown at, whatever
* the search or the sort, and stays pinned after the dialog closes until the next search
* or sort change, so the tile the user just edited never vanishes under their focus (P23,
* I1). With a filter nothing is pinned: a tile outside it never shows.
*/
export function useReferenceView(
{ all, keys, citers }: Shown,
editingKey: string | null,
resetSignal: number,
cited: ReadonlySet<string> | null,
) {
const locale = useLocaleStore((state) => state.locale)
const [view, setView] = useState(INITIAL)
const [seen, setSeen] = useState(resetSignal)
const [pinned, setPinned] = useState<Pinned | null>(null)
// The reset view is the sheet order: the tile in edit sits at its own position.
const pinEdited = (key: string | null): Pinned | null =>
key === null || !keys.includes(key)
? null
: { key, index: keys.indexOf(key) }
if (seen !== resetSignal) {
setSeen(resetSignal)
setView({ ...view, query: '' })
setPinned(pinEdited(editingKey))
setPinned(null)
}
const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
const pin =
pinned !== null && pinAt >= 0 && !isSheetView(view)
? { position: pinAt, index: pinned.index }
: null
const context = {
locale,
citedCount: (id: string) => citers.get(id)?.length ?? 0,
}
const positions = shownPositions(all, view, context, pin)
// The count is the matches: a pinned tile the search misses is shown, not counted.
const matchCount = all.filter((r) => referenceMatches(r, view.query)).length
const pinAtShown = (key: string) =>
Math.max(0, positions.indexOf(keys.indexOf(key)))
// A new search or sort: the tile in edit stays where it is shown, any other pin ends.
const pinAfterChange = (): Pinned | null => {
if (pinned === null || pinned.key !== editingKey) return null
return { key: pinned.key, index: pinAtShown(pinned.key) }
const plain = shownPositions(all, view, context, null, cited)
const editedAt = editingKey === null ? -1 : keys.indexOf(editingKey)
// Only a tile that is shown is pinned: a reference just created is not part of the list.
if (plain.includes(editedAt) && pinned?.key !== editingKey) {
setPinned({ key: editingKey as string, index: plain.indexOf(editedAt) })
}
const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
const pin =
pinned !== null && pinAt >= 0 && !isSheetView(view, cited !== null)
? { position: pinAt, index: Math.max(0, pinned.index) }
: null
const positions = shownPositions(all, view, context, pin, cited)
const inFilter = (r: Reference) => cited === null || cited.has(r.id)
// The count is the matches: a pinned tile the search misses is shown, not counted.
const matchCount = all.filter(
(r) => inFilter(r) && referenceMatches(r, view.query),
).length
return {
view,
positions,
matchCount,
total: all.filter(inFilter).length,
filtered: cited !== null,
update: (patch: Partial<ReferenceView>) => {
setPinned(pinAfterChange())
setPinned(null)
setView((current) => ({ ...current, ...patch }))
},
/**
* The clean view; `keep` is the tile still in edit, passed by the caller because a
* `finish()` in the same handler has not reached this render's `editingKey` (M3).
*/
reset: (keep: string | null) => {
setView(INITIAL)
setPinned(pinEdited(keep))
},
/** The tile `key` enters edit: remember where it is shown. */
markEdited: (key: string) => setPinned({ key, index: pinAtShown(key) }),
}
}
@@ -1,5 +1,4 @@
import { useRef, useState } from 'react'
import type { LeaveGuard, Field } from './useReferenceEdit'
import { useState } from 'react'
/**
* One key per tile: the id and its occurrence among equal ids, so a duplicated id stays
@@ -15,75 +14,25 @@ export function tileKeys(all: readonly { id: string }[]): string[] {
}
/**
* Which tiles are open and which one is in edit. Lives in the library, which the tab keeps
* mounted (A2), so both survive a tab change and reset when the editor is reopened.
* Leaving the edit view asks the tile's guard first: a refusal keeps it (P22). `keys` are
* the tiles the document has (null while it is not loaded): state of a tile that is gone
* is dropped at once (P23').
* Which tiles are open. Lives in the library, which the tab keeps mounted (A2), so it
* survives a tab change and resets when the editor is reopened. `keys` are the tiles the
* document has (null while it is not loaded): state of a tile that is gone is dropped at
* once (P23'). Nothing here edits a tile: « Modifier » opens the reference dialog.
*/
export function useTileState(keys: readonly string[] | null) {
const [openKeys, setOpenKeys] = useState<ReadonlySet<string>>(() => new Set())
const [editingKey, setEditingKey] = useState<string | null>(null)
if (keys !== null) {
const live = new Set(keys)
if ([...openKeys].some((key) => !live.has(key))) {
setOpenKeys(new Set([...openKeys].filter((key) => live.has(key))))
}
if (editingKey !== null && !live.has(editingKey)) setEditingKey(null)
}
const guard = useRef<LeaveGuard | null>(null)
// The tile a « Modifier » just opened: its edit view focuses Citation once, a remount
// after a read-only interval does not (M1).
const focusTicket = useRef<string | null>(null)
/** Applies the tile in edit; the fields that refused, none when nothing is left to apply. */
const leave = (): Field[] => guard.current?.() ?? []
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
const finish = () => {
if (leave().length > 0) return false
setEditingKey(null)
return true
}
// Read-only, the edit view is gone: a toggle ends the edit state and collapses.
const toggle = (key: string, readOnly = false) => {
if (editingKey === key) {
if (!readOnly) return void finish()
setEditingKey(null)
return setOpenKeys((prev) => {
const next = new Set(prev)
next.delete(key)
return next
})
}
const toggle = (key: string) =>
setOpenKeys((prev) => {
const next = new Set(prev)
if (!next.delete(key)) next.add(key)
return next
})
}
const startEdit = (key: string) => {
if (editingKey !== null && editingKey !== key && leave().length > 0)
return false
focusTicket.current = key
setEditingKey(key)
open(key)
return true
}
const takeFocus = (key: string) => {
const mine = focusTicket.current === key
if (mine) focusTicket.current = null
return mine
}
return {
openKeys,
editingKey,
toggle,
startEdit,
finish,
leave,
takeFocus,
reveal: open,
registerLeave: (next: LeaveGuard | null) => {
guard.current = next
},
}
return { openKeys, toggle, reveal: open }
}
@@ -2,18 +2,20 @@ import { useRef, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly'
import NewReferenceTile from '@/components/editor/references/NewReferenceTile'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import NoResult from '@/components/editor/references/NoResult'
import ReferenceTiles from '@/components/editor/references/ReferenceTiles'
import ReferenceToolbar from '@/components/editor/references/ReferenceToolbar'
import {
useReferenceActions,
useReferenceLibrary,
type ReferenceLibraryState,
} from '@/components/editor/references/useReferenceLibrary'
import { isSheetView } from '@/editor/references/view'
import type { EditorPlaceProps } from '@/editor/tabs'
import type { EditorPlaceProps, ReferenceLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** The empty line: the sheet has no reference at all. */
function EmptyLine() {
@@ -27,21 +29,106 @@ function EmptyLine() {
type Props = Pick<EditorPlaceProps, 'readOnly' | 'navigate' | 'focus'> & {
resetSignal: number
layer: ReferenceLayer
}
/** « Référence ajoutée : … » with « Afficher »: the list did not move. */
function AddedNotice({
citation,
onShow,
}: {
citation: string
onShow: () => void
}) {
const t = useT()
return (
<Notice tone="success" className="items-center">
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
{t('editor.references.added').replace('{citation}', () => citation)}
<Button type="button" variant="secondary" size="sm" onClick={onShow}>
{t('editor.references.added_show')}
</Button>
</span>
</Notice>
)
}
/** The chip of the finding the list is filtered by, null for the whole bibliography. */
function useFilterChip(lib: ReferenceLibraryState, layer: ReferenceLayer) {
const locale = useLocaleStore((s) => s.locale)
const { finding } = lib
if (!finding || !layer.filter) return null
const key = layer.filter
return {
name: finding.name[locale],
onRemove: () => layer.clearFilter(),
onBack: () => layer.backToFinding(key),
}
}
type Actions = ReturnType<typeof useReferenceActions>
interface BodyProps {
lib: ReferenceLibraryState
act: Actions
props: Props
}
/** The notice, the empty and no-result lines, the hint and the tiles. */
function LibraryBody({ lib, act, props }: BodyProps) {
const t = useT()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const { all, shown } = lib
const sheetView = isSheetView(shown.view, shown.filtered)
return (
<>
{act.notice && (
<AddedNotice citation={act.notice.citation} onShow={act.notice.show} />
)}
{all.length === 0 && <EmptyLine />}
{all.length > 0 && shown.positions.length === 0 && (
<NoResult query={shown.view.query} onClear={act.clearSearch} />
)}
{!props.readOnly && !sheetView && shown.positions.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.reorder_hint')}
</p>
)}
<ReferenceTiles
positions={shown.positions}
all={all}
keys={lib.keys}
citers={lib.citers}
tiles={lib.tiles}
query={shown.view.query}
readOnly={props.readOnly}
movable={sheetView}
navigate={props.navigate}
onEdit={act.edit}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</>
)
}
/**
* The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
* reference, the draft tile and the delete dialog. Ids carry the `tab-` prefix. The
* citations panel shares only the tile (R2.4).
* The sheet's bibliography: toolbar (search, sort, filter, count, add), one collapsible
* tile per reference and the delete dialog. « Modifier » and « Ajouter » open the
* reference dialog (a layer of the workspace). Ids carry the `tab-` prefix. The citations
* panel shares only the tile (R2.4).
*/
function Library({ readOnly, navigate, focus, resetSignal }: Props) {
const t = useT()
const lib = useReferenceLibrary(resetSignal)
function Library(props: Props) {
const lib = useReferenceLibrary(props.resetSignal, props.layer)
const searchRef = useRef<HTMLInputElement>(null)
const act = useReferenceActions(lib, focus, searchRef)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const { all, shown } = lib
const sheetView = isSheetView(shown.view)
const act = useReferenceActions(lib, props.focus, props.layer, searchRef)
const chip = useFilterChip(lib, props.layer)
const { shown } = lib
return (
<div className="space-y-3">
<ReferenceToolbar
@@ -52,51 +139,12 @@ function Library({ readOnly, navigate, focus, resetSignal }: Props) {
sort={shown.view.sort}
onSort={(sort) => shown.update({ sort })}
shown={shown.matchCount}
total={all.length}
canAdd={!readOnly}
total={shown.total}
canAdd={!props.readOnly}
onAdd={act.startAdd}
filter={chip}
/>
{lib.loaded && (
<>
{all.length === 0 && <EmptyLine />}
{all.length > 0 && shown.positions.length === 0 && (
<NoResult query={shown.view.query} onClear={act.clearSearch} />
)}
{!readOnly && !sheetView && shown.positions.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.reorder_hint')}
</p>
)}
<ReferenceTiles
positions={shown.positions}
all={all}
keys={lib.keys}
citers={lib.citers}
tiles={lib.tiles}
query={shown.view.query}
readOnly={readOnly}
movable={sheetView}
navigate={navigate}
onEdit={act.edit}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
label: reference.citation,
})
}
/>
<EditOnly readOnly={readOnly}>
{act.draft !== null && (
<NewReferenceTile
focusSerial={act.draft}
onAdded={act.added}
onCancel={act.cancelAdd}
/>
)}
</EditOnly>
</>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
{lib.loaded && <LibraryBody lib={lib} act={act} props={props} />}
</div>
)
}
@@ -107,8 +155,11 @@ export default function ReferencesTab({
navigate,
focus,
libraryReset = 0,
references,
}: EditorPlaceProps) {
const t = useT()
if (!references)
throw new Error('Références needs the reference layer of the workspace')
return (
<section
data-testid="editor-tab-references"
@@ -128,6 +179,7 @@ export default function ReferencesTab({
navigate={navigate}
focus={focus}
resetSignal={libraryReset}
layer={references}
/>
</section>
)
+12 -1
View File
@@ -1,4 +1,4 @@
import type { FindingLayer } from './tabs'
import type { FindingLayer, ReferenceLayer } from './tabs'
import type { EditorNavigation } from './useEditorNavigation'
/** What Constats needs of the navigation for its dialog and the sheet over it. */
@@ -14,3 +14,14 @@ export function findingLayerOf(nav: EditorNavigation): FindingLayer {
announce: nav.announce,
}
}
/** What the References tab and the reference dialog need of the navigation. */
export function referenceLayerOf(nav: EditorNavigation): ReferenceLayer {
return {
view: nav.state.reference,
filter: nav.state.referenceFilter,
guards: nav.guards,
announce: nav.announce,
...nav.references,
}
}
+1 -2
View File
@@ -174,8 +174,7 @@ export function focusActiveTab(options?: FocusOptions): void {
/**
* The element sits in a transactional form of an open dialog: the form keeps its draft
* and its focus when the editor turns read-only, nothing moves it. (The citations
* sheet's tiles still edit inline until the reference dialog: they are not drafts.)
* and its focus when the editor turns read-only, nothing moves it.
*/
function inOpenDialog(element: HTMLElement): boolean {
return element.closest('dialog[open] [data-draft-form]') !== null
+43 -5
View File
@@ -68,11 +68,35 @@ function sanitizeFinding(raw: unknown, forms: boolean): EditorView['finding'] {
return { key, citations: sheet }
}
/**
* The reference dialog of a view: over the References tab, or over the citations sheet
* (the only other place that opens it). A form, so only read back where forms are kept;
* whether the reference still exists is the dialog's own gone rule.
*/
function sanitizeReference(
raw: unknown,
finding: EditorView['finding'],
tab: unknown,
): EditorView['reference'] {
if (!isRecord(raw)) return null
const sheet = !!finding && 'key' in finding && finding.citations
if (raw.create === true) return tab === 'references' ? { create: true } : null
const id = raw.edit
if (typeof id !== 'string' || id === '') return null
return tab === 'references' || sheet ? { edit: id } : null
}
/** The finding the References tab is filtered by: a finding node, on that tab only. */
function sanitizeFilter(raw: unknown, tab: unknown): ElementKey | null {
const key = tab === 'references' ? sanitizeKey(raw) : null
return key && isFindingNode(key) ? key : null
}
/**
* A view read back from a history entry, or null when it is no view. The finding layer
* must name a well-formed key and sit on the Constats tab; whether the element still
* exists is the dialog's own gone rule. `forms` false drops the creation form (a reload
* never reopens a form). The reference layer and the filter stay null until they exist.
* exists is the dialog's own gone rule. `forms` false drops the forms (a creation, the
* reference dialog): a reload never reopens a form.
*/
export function sanitizeView(raw: unknown, forms = true): EditorView | null {
if (!isRecord(raw)) return null
@@ -80,12 +104,15 @@ export function sanitizeView(raw: unknown, forms = true): EditorView | null {
const known = ANNOTATION_SECTIONS.includes(raw.section as AnnotationSection)
const finding =
raw.tab === 'findings' ? sanitizeFinding(raw.finding, forms) : null
const reference = forms
? sanitizeReference(raw.reference, finding, raw.tab)
: null
return {
tab: raw.tab as EditorTabId,
section: known ? (raw.section as AnnotationSection) : 'drawing',
finding,
reference: null,
referenceFilter: null,
reference,
referenceFilter: sanitizeFilter(raw.referenceFilter, raw.tab),
}
}
@@ -147,19 +174,30 @@ function isRemoval(top: EditorView, view: EditorView): boolean {
/** What a changed view asks of the history. */
export type HistoryWrite = 'none' | 'push' | 'replace' | 'back'
/** True when `view` shows the finding `key` (its dialog, with or without the sheet). */
export function showsFinding(view: EditorView, key: ElementKey): boolean {
const { finding } = view
const shown = finding && 'key' in finding ? finding.key : null
return shown !== null && JSON.stringify(shown) === JSON.stringify(key)
}
/**
* A user move to `view`. A layer taken away, or a section left for its drawing ("Retour
* au dessin"), goes back when the entry holds the view the move lands on (the entry that
* opened it), else it replaces; a layer, tab or section added pushes, unless the move
* asked for a replace.
* asked for a replace. `backTo` (« Revenir au constat ») goes back when the entry below
* shows that finding.
*/
export function planWrite(
top: HistoryEntry,
view: EditorView,
replace: boolean,
backTo: ElementKey | null = null,
): HistoryWrite {
if (sameView(top.view, view)) return 'none'
if (replace) return 'replace'
// « Revenir au constat »: the entry below already shows that finding, a Back is the move.
if (backTo && top.below && showsFinding(top.below, backTo)) return 'back'
if (isRemoval(top.view, view)) {
return top.below && sameView(top.below, view) ? 'back' : 'replace'
}
@@ -120,12 +120,13 @@ function useReconcile(
writer: Writer,
) {
useEffect(() => {
const { scrollY, replace } = nav.trace
const { scrollY, replace, backTo } = nav.trace
nav.trace.scrollY = null
nav.trace.replace = false
nav.trace.backTo = null
const top = book.entry
if (!top || book.pendingBack) return
const plan = planWrite(top, view, replace)
const plan = planWrite(top, view, replace, backTo)
if (plan === 'none') return
book.scrolls.set(top.id, scrollY ?? window.scrollY)
if (plan === 'back') writer.back()
+55 -10
View File
@@ -29,9 +29,9 @@ export interface FocusRequest {
/**
* What the browser history records of the editor (R2F-1): where the user is, never what
* they typed. A layer (`finding`, `reference`) is a dialog over a place; `citations` is
* the side sheet over the finding dialog; `referenceFilter` narrows the references
* library to the citers of an element. `reference` and `referenceFilter` stay null until
* the reference dialog and the filter exist.
* the side sheet over the finding dialog; `reference` is the reference dialog above
* either; `referenceFilter` (only on the References tab) narrows the library to the
* references a finding cites. The search text is a personal search: never part of a view.
*/
export interface EditorView {
tab: EditorTabId
@@ -64,7 +64,11 @@ export type NavigationAction =
| { type: 'close_finding' }
| { type: 'open_citations'; citedBy: ElementKey }
| { type: 'close_citations' }
| { type: 'show_all_references' }
| { type: 'open_reference'; id: string }
| { type: 'create_reference' }
| { type: 'close_reference' }
| { type: 'show_all_references'; filter: ElementKey }
| { type: 'clear_reference_filter' }
| { type: 'go_to'; target: EditorTarget }
| { type: 'restore_view'; view: EditorView }
| { type: 'focus_consumed'; serial: number }
@@ -115,6 +119,9 @@ function shown(state: NavigationState): NavigationState {
return { ...state, visitedTabs, visitedSections }
}
/** What a move to another tab leaves behind: the reference dialog and the filter. */
const LEFT_REFERENCES = { reference: null, referenceFilter: null } as const
const DEFAULT_VIEW = {
section: 'drawing',
finding: null,
@@ -207,7 +214,7 @@ function closeCitations(state: NavigationState): NavigationState {
/** The finding dialog of `key`, in view mode, on the Constats tab. */
function openFinding(state: NavigationState, key: ElementKey): NavigationState {
const finding = { key, citations: false }
return shown({ ...state, tab: 'findings', finding })
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
}
/** The creation form of a zone, a category or a node, on the Constats tab. */
@@ -215,40 +222,70 @@ function createFinding(
state: NavigationState,
create: { kind: string; parent: ElementKey | null },
): NavigationState {
return shown({ ...state, tab: 'findings', finding: { create } })
const finding = { create }
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
}
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
const serial = state.serial + 1
// The filter survives only a move to the tab itself that names no reference.
const keep = target.tab === 'references' && target.key === null
const moved = {
...state,
tab: target.tab,
section: target.section ?? state.section,
finding: null,
reference: null,
referenceFilter: keep ? state.referenceFilter : null,
focus: { target, serial },
serial,
}
return shown(moved)
}
/** « Tout afficher dans l'onglet Références »: the layers close, the library starts afresh. */
function showAllReferences(state: NavigationState): NavigationState {
/**
* « Tout afficher dans l'onglet Références »: the layers close, the library starts afresh
* and lists what `filter` (the finding the sheet belongs to) cites.
*/
function showAllReferences(
state: NavigationState,
filter: ElementKey,
): NavigationState {
const moved = {
...state,
tab: 'references' as const,
finding: null,
reference: null,
referenceFilter: filter,
libraryReset: state.libraryReset + 1,
}
return shown(moved)
}
/** A tab other than References has no filter: the filter belongs to that tab's view. */
function selectTab(state: NavigationState, tab: EditorTabId): NavigationState {
const filter = tab === 'references' ? state.referenceFilter : null
const left = { finding: null, reference: null, referenceFilter: filter }
return shown({ ...state, ...left, tab })
}
/** The reference dialog of `id`, above the place (and the sheet) the view shows. */
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. */
function createReference(state: NavigationState): NavigationState {
return shown({ ...state, tab: 'references', reference: { create: true } })
}
export function navigationReducer(
state: NavigationState,
action: NavigationAction,
): NavigationState {
switch (action.type) {
case 'select_tab':
return shown({ ...state, tab: action.tab, finding: null })
return selectTab(state, action.tab)
case 'open_section':
return shown({ ...state, section: action.section })
case 'back_to_drawing':
@@ -263,8 +300,16 @@ export function navigationReducer(
return openCitations(state, action.citedBy)
case 'close_citations':
return closeCitations(state)
case 'open_reference':
return openReference(state, action.id)
case 'create_reference':
return createReference(state)
case 'close_reference':
return { ...state, reference: null }
case 'show_all_references':
return showAllReferences(state)
return showAllReferences(state, action.filter)
case 'clear_reference_filter':
return { ...state, referenceFilter: null }
case 'go_to':
return goTo(state, action.target)
case 'restore_view':
+17 -6
View File
@@ -7,9 +7,12 @@ export interface ReferenceView {
sort: ReferenceSort
}
/** Stored order, no search: the only view where ↑ / ↓ mean something (A1). */
export const isSheetView = (view: ReferenceView) =>
view.sort === 'sheet' && view.query.trim() === ''
/**
* Stored order, no search, no finding filter: the only view where ↑ / ↓ mean something
* (A1). `filtered` is true while the library lists one finding's citations (R2F-6).
*/
export const isSheetView = (view: ReferenceView, filtered = false) =>
!filtered && view.sort === 'sheet' && view.query.trim() === ''
/**
* The tile in edit, kept in the shown set at `index` whatever the search or the sort
@@ -20,18 +23,26 @@ export interface Pin {
index: number
}
/** The positions to show: the search, then the sort, then the pinned tile put back. */
/**
* The positions to show: the finding filter (`cited`, the ids that finding cites; null for
* none), the search, then the sort, then the pinned tile put back. A pin is for the
* unfiltered library only: a tile outside the filter never shows.
*/
export function shownPositions(
references: readonly Reference[],
view: ReferenceView,
context: SortContext,
pin: Pin | null,
cited: ReadonlySet<string> | null = null,
): number[] {
const matching = references.flatMap((reference, position) =>
referenceMatches(reference, view.query) ? [position] : [],
referenceMatches(reference, view.query) &&
(cited === null || cited.has(reference.id))
? [position]
: [],
)
const sorted = sortReferenceIds(references, matching, view.sort, context)
if (pin === null) return sorted
if (pin === null || cited !== null) return sorted
const rest = sorted.filter((position) => position !== pin.position)
rest.splice(Math.min(pin.index, rest.length), 0, pin.position)
return rest
+24
View File
@@ -3,6 +3,7 @@ import type { EditorTarget, EditorView, FocusRequest } from './navigation'
import { unmeasuredViews } from './issues'
import type { TabTier } from './useViewport'
import type { Guards } from './useEditorNavigation'
import type { AddedReference } from './useReferenceMoves'
export const EDITOR_TABS = [
'general',
@@ -54,6 +55,27 @@ export interface FindingLayer {
announce: (text: string) => void
}
/**
* What the References tab and the reference dialog need of the navigation (R2F-5, R2F-6):
* the layer and the filter the view holds, and the moves on them.
*/
export interface ReferenceLayer {
view: EditorView['reference']
/** The finding whose citations the library lists; null for the whole bibliography. */
filter: ElementKey | null
guards: Guards
open: (id: string, opener?: HTMLElement | null) => void
start: (opener?: HTMLElement | null) => void
close: (forced?: boolean) => boolean
replace: (id: string | null, text?: string) => void
created: (id: string) => void
added: AddedReference | null
opener: () => HTMLElement | null
clearFilter: (text?: string) => void
backToFinding: (key: ElementKey) => void
announce: (text: string) => void
}
/** Props of every place (tab body, Annotations section). */
export interface EditorPlaceProps {
/** Not editable now: a mode that cannot save, or a recovery offer not answered yet. */
@@ -64,6 +86,8 @@ export interface EditorPlaceProps {
focus?: FocusRequest
/** The finding dialog and the citations sheet over it (only Constats has them). */
layer?: FindingLayer
/** The reference dialog and the filter (only the References tab and the sheet use them). */
references?: ReferenceLayer
/** Bumped by « Tout afficher »: the references library resets its search once per bump. */
libraryReset?: number
/** Reads the sheet's overview again (after a submission: the round freezes the draft). */
+30 -13
View File
@@ -33,6 +33,7 @@ import {
type NavigationState,
} from './navigation'
import { MORE_BUTTON_ID, tabDomId, type EditorTabId } from './tabs'
import { useReferenceMoves, type ReferenceMoves } from './useReferenceMoves'
type MoveKind = 'go_to' | 'show_all' | 'tab_selected' | 'section' | 'back'
@@ -52,7 +53,7 @@ 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 = ['citations', 'finding', 'reference'] as const
const LAYERS = ['finding', '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. */
@@ -72,6 +73,8 @@ export interface Guards {
export interface MoveTrace {
scrollY: number | null
replace: boolean
/** « Revenir au constat »: a Back when the entry below shows this finding. */
backTo: ElementKey | null
}
/** Options of a tab choice. */
@@ -107,8 +110,13 @@ export interface EditorNavigation {
closeCitations: () => boolean
/** « X références », where the focus returns once the sheet is closed. */
citationsTrigger: () => HTMLElement | null
/** « Tout afficher dans l'onglet Références »: layers closed, tab shown, library reset. */
showAllReferences: () => void
/**
* « Tout afficher dans l'onglet Références »: layers closed, tab shown, library reset
* and filtered by the finding the sheet belongs to.
*/
showAllReferences: (filter: ElementKey) => void
/** The reference dialog and the References tab's filter. */
references: ReferenceMoves
guards: Guards
trace: MoveTrace
/** A Back or Forward landed on `view` (the history adapter's way in): no move, no request. */
@@ -197,11 +205,16 @@ function useGuards(): Guards {
}
function useMoveTrace() {
const trace = useRef<MoveTrace>({ scrollY: null, replace: false }).current
const trace = useRef<MoveTrace>({
scrollY: null,
replace: false,
backTo: null,
}).current
const mark = useCallback(
(replace = false) => {
trace.scrollY = window.scrollY
trace.replace = replace
trace.backTo = null
},
[trace],
)
@@ -227,6 +240,7 @@ function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
announce(text)
trace.scrollY = window.scrollY
trace.replace = false
trace.backTo = null
dispatch(action)
setMove({ kind })
},
@@ -255,7 +269,7 @@ function useSectionMoves(go: Go, openers: Openers) {
}
/** What the layers' moves need of the hook. */
interface LayerContext {
export interface LayerContext {
dispatch: Dispatch<NavigationAction>
announce: (text: string) => void
guards: Guards
@@ -315,7 +329,7 @@ function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) {
/** The citations sheet over the finding dialog: opened from a finding node only. */
function useSheetLayer(ctx: LayerContext, openers: Openers) {
const { dispatch, guards, mark } = ctx
const { dispatch, mark } = ctx
const openCitations = useCallback(
(citedBy: ElementKey, opener?: Opener) => {
if (!isFindingNode(citedBy)) return
@@ -327,11 +341,10 @@ function useSheetLayer(ctx: LayerContext, openers: Openers) {
[openers, dispatch, mark],
)
const closeCitations = useCallback(() => {
if (!guards.ask('citations', false).allowed) return false
mark()
dispatch({ type: 'close_citations' })
return true
}, [guards, dispatch, mark])
}, [dispatch, mark])
return { openCitations, closeCitations }
}
@@ -346,11 +359,14 @@ function useLeavingMoves(go: Go, guards: Guards) {
},
[go, guards, moveText],
)
const showAllReferences = useCallback(() => {
if (!guards.askAll(false).allowed) return
const text = t('editor.tab.references')
go({ type: 'show_all_references' }, 'show_all', text)
}, [go, guards, t])
const showAllReferences = useCallback(
(filter: ElementKey) => {
if (!guards.askAll(false).allowed) return
const text = t('editor.tab.references')
go({ type: 'show_all_references', filter }, 'show_all', text)
},
[go, guards, t],
)
return { navigate, showAllReferences }
}
@@ -497,6 +513,7 @@ export function useEditorNavigation(
...useFindingLayer(ctx),
...useSheetLayer(ctx, openers),
...useLeavingMoves(base.go, guards),
references: useReferenceMoves(ctx, base.trace),
citationsTrigger: useCallback(() => triggerOf(openers), [openers]),
guards,
trace: base.trace,
+147
View File
@@ -0,0 +1,147 @@
import { useCallback, useRef, useState, type RefObject } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { LayerContext, MoveTrace } from './useEditorNavigation'
/** The reference a creation just made: the library shows a notice for it, once per serial. */
export interface AddedReference {
id: string
serial: number
}
type Opener = HTMLElement | null | undefined
/** 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
/** A user close; false when the form refused it (a dirty draft asks first). */
close: (forced?: boolean) => boolean
/**
* The dialog becomes another view of itself, by replace (no Back entry): `null` closes
* it. With `text`, a close the user did not ask for (the reference vanished): forced,
* said once the dialogs are closed.
*/
replace: (id: string | null, text?: string) => void
/** A creation succeeded: its entry becomes the reference's own, then the dialog closes. */
created: (id: string) => void
added: AddedReference | null
/** The element that opened the dialog, while it is still on the page. */
opener: () => HTMLElement | null
/** « × » of the filter chip, or a vanished finding (`text` says so): a replace. */
clearFilter: (text?: string) => void
/** « Revenir au constat »: a Back when the entry below shows it, else its dialog. */
backToFinding: (key: ElementKey) => void
}
/** The moves that add the dialog: an edit of a reference, a creation. */
function useOpening({ dispatch, mark }: LayerContext, held: RefObject<Opener>) {
const open = useCallback(
(id: string, opener?: Opener) => {
held.current = opener
mark()
dispatch({ type: 'open_reference', id })
},
[dispatch, mark, held],
)
const start = useCallback(
(opener?: Opener) => {
held.current = opener
mark()
dispatch({ type: 'create_reference' })
},
[dispatch, mark, held],
)
return { open, start }
}
/** The moves that take it away: a user close, and the replace that is no Back step. */
function useClosing({ dispatch, announce, guards, mark }: LayerContext) {
const close = useCallback(
(forced = false) => {
if (!guards.ask('reference', forced).allowed) return false
mark()
dispatch({ type: 'close_reference' })
return true
},
[guards, dispatch, mark],
)
const replace = useCallback(
(id: string | null, text?: string) => {
const note = text ? guards.ask('reference', true).note : undefined
if (text) announce(note ? `${note}. ${text}` : text)
mark(true)
dispatch(
id ? { type: 'open_reference', id } : { type: 'close_reference' },
)
},
[guards, announce, dispatch, mark],
)
return { close, replace }
}
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */
function useCreated(
{ dispatch, mark }: LayerContext,
replace: ReferenceMoves['replace'],
) {
const [added, setAdded] = useState<AddedReference | null>(null)
const created = useCallback(
(id: string) => {
replace(id)
setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
// After the commit that wrote the replace: the entry is the reference's own before
// the close goes back over it, so a Forward never reopens a creation.
queueMicrotask(() => {
mark()
dispatch({ type: 'close_reference' })
})
},
[replace, mark, dispatch],
)
return { created, added }
}
/** The filter's two moves: remove it by replace, return to the finding it names. */
function useFilter(
{ dispatch, announce, mark }: LayerContext,
trace: MoveTrace,
) {
const clearFilter = useCallback(
(text?: string) => {
if (text) announce(text)
mark(true)
dispatch({ type: 'clear_reference_filter' })
},
[announce, dispatch, mark],
)
const backToFinding = useCallback(
(key: ElementKey) => {
mark()
trace.backTo = key
dispatch({ type: 'open_finding', key })
},
[dispatch, mark, trace],
)
return { clearFilter, backToFinding }
}
export function useReferenceMoves(
ctx: LayerContext,
trace: MoveTrace,
): ReferenceMoves {
const held = useRef<Opener>(null)
const opener = useCallback((): HTMLElement | null => {
const element = held.current
return element?.isConnected && !element.closest('[hidden]') ? element : null
}, [held])
const closing = useClosing(ctx)
return {
...useOpening(ctx, held),
...closing,
...useCreated(ctx, closing.replace),
...useFilter(ctx, trace),
opener,
}
}
@@ -1,620 +0,0 @@
/**
* C1: a read-only flip never drops a draft silently, writes nothing, and keeps the tile.
* I1: a user leave with several refused fields focuses the first one, with its own error.
*/
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 { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import {
findingDialog,
inFindingDialog,
openFinding,
} from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
/** Every watcher made by `watchNotes`: stopped after each test, even a failing one. */
const watchers: { stop: () => void }[] = []
afterEach(() => {
watchers.splice(0).forEach((watch) => watch.stop())
cleanup()
resetStore()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string, url = '') =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: url || null, doi: null },
}) as const
/** Three references (ref-b has a URL) and Node A citing ref-a and ref-b. */
function sheetText(): string {
let text = baseText()
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
text = insert(text, ref('ref-b', 'Denoix', 'https://exemple.org/Épaule'))
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: {},
requires_vet_referral: false,
reference_ids: ['ref-a', 'ref-b'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
const NOTE = 'Saisie non appliquée'
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
const doc = () => JSON.parse(store.getState().documentText)
const history = () => ({
undo: store.getState().undo.length,
redo: store.getState().redo.length,
})
const cross = (width: number) =>
act(() => {
setWidth(width)
window.dispatchEvent(new Event('resize'))
})
const flush = () => act(async () => undefined)
/** The prototype object that owns a property, so a wrapper can be put back exactly. */
function ownerOf(target: object, property: string): object {
let owner: object | null = target
while (owner && !Object.hasOwn(owner, property)) {
owner = Object.getPrototypeOf(owner)
}
return owner!
}
/**
* Counts the live region's updates that carry the drop note. It wraps the two DOM setters
* React uses for a text change (`textContent`, `nodeValue`) instead of using a
* MutationObserver: happy-dom keeps an observer's callback in a WeakRef, so a garbage
* collection under load silently ends the observation (seen as a missed announcement).
*/
function watchNotes() {
const seen: string[] = []
const restore: (() => void)[] = []
const wrap = (target: object, property: string) => {
const owner = ownerOf(target, property)
const original = Object.getOwnPropertyDescriptor(owner, property)!
Object.defineProperty(owner, property, {
...original,
set(this: Node, value: string) {
original.set!.call(this, value)
const region = live()
if (region.contains(this) && region.textContent?.includes(NOTE)) {
seen.push(region.textContent)
}
},
})
restore.push(() => Object.defineProperty(owner, property, original))
}
wrap(live(), 'textContent')
wrap(document.createTextNode(''), 'nodeValue')
const watch = { seen, stop: () => restore.forEach((undo) => undo()) }
watchers.push(watch)
return watch
}
async function mount(width = 1280) {
serverHas(sheetText(), 3)
const user = userEvent.setup()
mountDraft({ width, strict: true })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
return user
}
const tabPanel = () => screen.getByRole('tabpanel', { name: 'Références' })
const header = (id: string, host = 'tab') =>
document.querySelector<HTMLElement>(
`button[id^="${host}-reference-"][id$="-${id}-header"]`,
)!
const tile = (id: string, host = 'tab') => header(id, host).closest('li')!
const field = (id: string, name: string, host = 'tab') =>
document.querySelector<HTMLInputElement>(
`#${host}-reference-${id === 'ref-a' ? 0 : id === 'ref-b' ? 1 : 2}-${id}-${name}`,
)!
/** « Références », the tile open and in edit; the focus on its Citation field. */
async function editTile(user: User, id: string, label: RegExp) {
await user.click(screen.getByRole('tab', { name: 'Références' }))
await user.click(within(tabPanel()).getByRole('button', { name: label }))
await user.click(within(tile(id)).getByRole('button', { name: 'Modifier' }))
}
/** Types a schemeless URL (refused) in the focused-then-kept URL field of `id`. */
async function typeBadUrl(user: User, id: string) {
const url = field(id, 'url')
await user.clear(url)
await user.type(url, 'exemple.org')
return url
}
describe('a read-only flip with a refused draft (tab tile)', () => {
it('shows the note, says it once, writes nothing, focuses the tile', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
const before = { references: doc().references, ...history() }
const watch = watchNotes()
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Adresse web (URL)`),
).toBeVisible()
expect(within(tile('ref-b')).queryByRole('textbox')).toBeNull()
expect(
within(tile('ref-b')).getByText('https://exemple.org/Épaule'),
).toBeVisible()
await flush()
expect(watch.seen).toHaveLength(1)
expect(live().textContent).toBe(`${NOTE} : Adresse web (URL)`)
expect({ references: doc().references, ...history() }).toEqual(before)
expect(document.activeElement).toBe(header('ref-b'))
watch.stop()
})
it('keeps the note across the flip back; Terminer removes it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
await flush()
const watch = watchNotes()
cross(1280)
await flush()
expect(watch.seen).toHaveLength(0)
watch.stop()
const item = tile('ref-b')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
expect(field('ref-b', 'url')).toHaveValue('https://exemple.org/Épaule')
expect(history()).toEqual({ undo: 0, redo: 0 })
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
expect(within(item).queryByText(new RegExp(NOTE))).toBeNull()
})
it('the read-only toggle ends the edit state, collapses and clears the note', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
await user.click(header('ref-b'))
expect(header('ref-b')).toHaveAttribute('aria-expanded', 'false')
expect(within(tile('ref-b')).queryByText(new RegExp(NOTE))).toBeNull()
cross(1280)
expect(header('ref-b')).toHaveAttribute('aria-expanded', 'false')
expect(within(tile('ref-b')).queryByRole('textbox')).toBeNull()
})
it('names both refused fields, in field order', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.clear(field('ref-b', 'citation'))
await typeBadUrl(user, 'ref-b')
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Citation, Adresse web (URL)`),
).toBeVisible()
expect(doc().references[1].citation).toBe('Denoix')
})
it('keeps the tile in edit shown when the search does not match it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.type(
within(tabPanel()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'rural',
)
expect(header('ref-b')).not.toBeNull()
await typeBadUrl(user, 'ref-b')
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Adresse web (URL)`),
).toBeVisible()
expect(header('ref-c')).not.toBeNull()
})
})
describe('the note ends on the next action', () => {
/** ref-b flipped with a refused URL and back: in edit again, note shown. */
async function flippedBack() {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
cross(1280)
expect(
within(tile('ref-b')).getByText(/Saisie non appliquée/),
).toBeVisible()
return user
}
const noted = () => within(tabPanel()).queryAllByText(/Saisie non appliquée/)
it("ends on another tile's « Modifier » (this tile leaves edit)", async () => {
const user = await flippedBack()
await user.click(
within(tabPanel()).getByRole('button', { name: /^Barone/ }),
)
await user.click(
within(tile('ref-a')).getByRole('button', { name: 'Modifier' }),
)
expect(noted()).toHaveLength(0)
})
it('ends on « Ajouter une référence »', async () => {
const user = await flippedBack()
await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' }),
)
expect(noted()).toHaveLength(0)
})
it('is replaced by a newer drop of the same tile, announced again', async () => {
const user = await flippedBack()
const watch = watchNotes()
await user.clear(field('ref-b', 'citation'))
await typeBadUrl(user, 'ref-b')
cross(800)
await flush()
const items = noted()
expect(items).toHaveLength(1)
expect(items[0]).toHaveTextContent(`${NOTE} : Citation, Adresse web (URL)`)
expect(watch.seen).toHaveLength(1)
watch.stop()
})
})
describe('a read-only flip without a refused draft', () => {
it('adds only the typed change when a valid draft has the focus', async () => {
const user = await mount()
await editTile(user, 'ref-a', /^Barone/)
const citation = field('ref-a', 'citation')
await user.clear(citation)
await user.type(citation, 'Neuf')
const watch = watchNotes()
cross(800)
expect(history()).toEqual({ undo: 1, redo: 0 })
expect(doc().references[0].citation).toBe('Neuf')
expect(within(tile('ref-a')).queryByText(new RegExp(NOTE))).toBeNull()
expect(document.activeElement).toBe(header('ref-a'))
cross(1280)
await flush()
expect(history()).toEqual({ undo: 1, redo: 0 })
expect(watch.seen).toHaveLength(0)
watch.stop()
})
it('writes nothing, says nothing and shows no note when nothing is pending', async () => {
const user = await mount()
await editTile(user, 'ref-a', /^Barone/)
const watch = watchNotes()
cross(800)
cross(1280)
await flush()
expect(history()).toEqual({ undo: 0, redo: 0 })
expect(watch.seen).toHaveLength(0)
expect(screen.queryByText(new RegExp(NOTE))).toBeNull()
watch.stop()
})
})
describe('an undo that removes a tile holding a refused draft (V1)', () => {
const added = (name: string) =>
document.querySelector<HTMLInputElement>(`#tab-reference-3-ref-d-${name}`)!
/** ref-d inserted by one history entry, then its tile in edit. */
async function editInserted() {
const user = await mount()
act(() => {
store
.getState()
.commit({ op: 'insert', element: ref('ref-d', 'Nouvelle') })
})
expect(history()).toEqual({ undo: 1, redo: 0 })
await editTile(user, 'ref-d', /^Nouvelle/)
return user
}
/** From a valid place: « Défaire » pressed from a refused field only refocuses it. */
async function undoInsertion(user: User) {
await user.tab()
expect(document.activeElement).not.toHaveAttribute('aria-invalid', 'true')
const watch = watchNotes()
await user.click(screen.getByRole('button', { name: /Défaire/ }))
await flush()
expect(header('ref-d')).toBeNull()
expect(doc().references.map((r: { id: string }) => r.id)).toEqual([
'ref-a',
'ref-b',
'ref-c',
])
expect(history()).toEqual({ undo: 0, redo: 1 })
return watch
}
it('says the dropped Citation once', async () => {
const user = await editInserted()
await user.clear(added('citation'))
const watch = await undoInsertion(user)
expect(watch.seen).toEqual([`${NOTE} : Citation`])
watch.stop()
})
it('names both refused fields, once', async () => {
const user = await editInserted()
await user.clear(added('citation'))
await user.click(added('url'))
await user.type(added('url'), 'exemple.org')
const watch = await undoInsertion(user)
expect(watch.seen).toEqual([`${NOTE} : Citation, Adresse web (URL)`])
watch.stop()
})
})
/** The citations panel of Node A, its Denoix tile in edit. */
async function openPanel(user: User) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Fermer les références' }),
),
)
const panel = screen.getByTestId('editor-citations-panel')
await user.click(within(panel).getByRole('button', { name: /^Denoix/ }))
await user.click(within(panel).getByRole('button', { name: 'Modifier' }))
return panel
}
/** The sheet, then the finding dialog under it, closed with their ✕. */
async function closeLayers(user: User) {
await user.click(
screen.getByRole('button', { name: 'Fermer les références' }),
)
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
await user.click(
within(findingDialog()!).getByRole('button', { name: 'Fermer' }),
)
await waitFor(() => expect(document.querySelector('dialog[open]')).toBeNull())
}
describe('a read-only flip in the citations panel', () => {
it('shows the note in the panel tile, says it once, focuses the tile header', async () => {
const user = await mount()
await openPanel(user)
await typeBadUrlIn(user)
const watch = watchNotes()
cross(800)
const item = tile('ref-b', 'panel')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
await flush()
// the page is inert under the two dialogs: the announcement waits for them
expect(watch.seen).toHaveLength(0)
expect(document.activeElement).toBe(header('ref-b', 'panel'))
expect(history()).toEqual({ undo: 0, redo: 0 })
await closeLayers(user)
await waitFor(() => expect(watch.seen).toHaveLength(1))
watch.stop()
})
it('a forced close names every refused field and says it once', async () => {
const user = await mount()
await openPanel(user)
await user.clear(field('ref-b', 'citation', 'panel'))
await typeBadUrlIn(user)
const watch = watchNotes()
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
// The forced close announces in a later commit than the panel's exit: wait for
// the text itself, then let any second announcement land before counting.
await waitFor(() =>
expect(live().textContent).toContain(
`${NOTE} : Citation, Adresse web (URL)`,
),
)
await flush()
expect(watch.seen).toHaveLength(1)
watch.stop()
})
})
describe('an undo that takes a tile holding a refused draft out of the panel (V1)', () => {
it('says the dropped Citation once, the panel stays', async () => {
const user = await mount()
act(() => {
store.getState().commit({
op: 'update',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
element: {
kind: 'finding_node',
value: {
...doc().finding_zones[0].categories[0].children[0],
reference_ids: ['ref-a', 'ref-b', 'ref-c'],
},
},
})
})
expect(history()).toEqual({ undo: 1, redo: 0 })
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await openFinding(user, /Node A/)
await user.click(
inFindingDialog().getByRole('button', { name: '3 références' }),
)
const panel = await screen.findByTestId('editor-citations-panel')
await user.click(within(panel).getByRole('button', { name: /^Code rural/ }))
await user.click(within(panel).getByRole('button', { name: 'Modifier' }))
await user.clear(field('ref-c', 'citation', 'panel'))
await user.tab()
const watch = watchNotes()
await user.click(screen.getByRole('button', { name: /Défaire/ }))
await flush()
expect(header('ref-c', 'panel')).toBeNull()
expect(screen.getByTestId('editor-citations-panel')).toBe(panel)
expect(history()).toEqual({ undo: 0, redo: 1 })
// said once the sheet and the finding dialog under it are closed
expect(watch.seen).toEqual([])
await closeLayers(user)
await waitFor(() => expect(watch.seen).toEqual([`${NOTE} : Citation`]))
watch.stop()
})
})
async function typeBadUrlIn(user: User) {
const url = field('ref-b', 'url', 'panel')
await user.clear(url)
await user.type(url, 'exemple.org')
}
const REQUIRED = 'Ce champ est obligatoire.'
/** Citation cleared then a schemeless URL, both refused, in the tile `id` of `host`. */
async function twoRefused(user: User, id: string, host = 'tab') {
await user.clear(field(id, 'citation', host))
await user.tab()
const url = field(id, 'url', host)
await user.clear(url)
await user.type(url, 'exemple.org')
}
/** I1: the field focused by a refused leave shows its own refusal; no draft is lost. */
function expectCitationRefused(id: string, host = 'tab') {
const citation = field(id, 'citation', host)
expect(document.activeElement).toBe(citation)
expect(citation).toHaveAttribute('aria-invalid', 'true')
expect(citation).toHaveAccessibleDescription(REQUIRED)
expect(citation).toHaveValue('')
}
describe('a user leave with several refused fields (I1)', () => {
it('keyboard « Terminer » focuses Citation with its own error', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await twoRefused(user, 'ref-b')
const done = within(tile('ref-b')).getByRole('button', { name: 'Terminer' })
for (let step = 0; step < 6 && document.activeElement !== done; step++) {
await user.tab()
}
expect(document.activeElement).toBe(done)
await user.keyboard('{Enter}')
expect(done).toBeInTheDocument()
expectCitationRefused('ref-b')
expect(field('ref-b', 'url')).toHaveValue('exemple.org')
expect(history()).toEqual({ undo: 0, redo: 0 })
})
it("another tile's « Modifier » focuses Citation with its own error", async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await twoRefused(user, 'ref-b')
await user.click(
within(tabPanel()).getByRole('button', { name: /^Barone/ }),
)
await user.click(
within(tile('ref-a')).getByRole('button', { name: 'Modifier' }),
)
expect(field('ref-a', 'citation')).toBeNull()
expectCitationRefused('ref-b')
expect(field('ref-b', 'url')).toHaveValue('exemple.org')
})
it('the panel ✕ is cancelled, Citation focused with its own error', async () => {
const user = await mount()
const panel = await openPanel(user)
await twoRefused(user, 'ref-b', 'panel')
await user.click(
within(panel).getByRole('button', { name: 'Fermer les références' }),
)
expect(screen.getByTestId('editor-citations-panel')).toBe(panel)
expectCitationRefused('ref-b', 'panel')
expect(field('ref-b', 'url', 'panel')).toHaveValue('exemple.org')
expect(history()).toEqual({ undo: 0, redo: 0 })
})
it('a mouse « Terminer » with a valid URL focused keeps edit on Citation', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.clear(field('ref-b', 'citation'))
await user.tab()
const url = field('ref-b', 'url')
await user.clear(url)
await user.type(url, 'https://exemple.org/neuf')
const done = within(tile('ref-b')).getByRole('button', { name: 'Terminer' })
await user.click(done)
expect(done).toBeInTheDocument()
expectCitationRefused('ref-b')
expect(doc().references[1].url).toBe('https://exemple.org/neuf')
expect(history()).toEqual({ undo: 1, redo: 0 })
})
})