feat(editor): finding dialog and citations side sheet in the history

Constats opens each element in one modal dialog (view, edit with a
local draft, creation) driven by the editor view layer of the browser
history. The citations panel becomes a modal side sheet stacked over
it; its geometry, exit machinery and page inertness are removed.
Back and Forward restore the layers, a dirty form asks first.
This commit is contained in:
bchanot committed 2026-11-13 18:51:35 +01:00
1 parent 8e4f02620a
commit 18085cecf8
50 files changed
+2642 -1504

No files matched your search

@@ -1,21 +1,16 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useMemo, useState, type ReactNode } from 'react'
import { useLocation } from 'react-router-dom'
import { AnimatePresence } from 'motion/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
import Notice from '@/components/ui/Notice'
import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext'
import {
AnnounceContext,
FocusConsumedContext,
isTextField,
} from '@/editor/focusRequest'
import { EditorModeContext, ReadOnlyContext } from '@/editor/editingContext'
import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest'
import { saveFailureMessage } from '@/editor/messages'
import type { EditorMode } from '@/editor/mode'
import { useEditorStore } from '@/editor/state/editorStore'
import { ownedEntry } from '@/editor/history/entry'
import { ownedEntry, withoutForms } from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import { defaultView } from '@/editor/navigation'
import { citationsOfView, defaultView } from '@/editor/navigation'
import { findingLayerOf } from '@/editor/findingLayer'
import { initialTab } from '@/editor/tabs'
import {
useEditorNavigation,
@@ -31,7 +26,7 @@ import EditorTabBody from './EditorTabBody'
import EditorTabs from './EditorTabs'
import ModeNotice from './ModeNotice'
import RecoveryNotice from './RecoveryNotice'
import CitationsLayer from './references/CitationsLayer'
import CitationsSheet from './references/CitationsSheet'
interface Props {
sheet: OfficialSheetAdmin
@@ -61,18 +56,16 @@ function SaveFailureNotice() {
/** What dialogs and edit-only parts below need of the editor's state. */
function EditingState({
readOnly,
citationsOf,
mode,
children,
}: {
readOnly: boolean
citationsOf: ElementKey | null
mode: EditorMode
children: ReactNode
}) {
return (
<ReadOnlyContext value={readOnly}>
<ReferencesOpenContext value={citationsOf}>
{children}
</ReferencesOpenContext>
<EditorModeContext value={mode}>{children}</EditorModeContext>
</ReadOnlyContext>
)
}
@@ -84,75 +77,42 @@ interface PlacesProps {
}
/**
* Under the tab row: the tab panels and the citations panel of a finding beside them. The
* container starts after the tab row, so the panel and its scrim never cover the header or
* the tabs; from the opening to the end of the exit the tab panels are inert. Its minimum
* height is permanent (never toggled): the panel and the scrim reach the bottom of the
* window and the document never changes size when the panel opens or closes (P16').
* The tab panels, then the citations sheet: the sheet comes after the tab body (which
* holds the finding dialog) so it is shown after it and lies over it.
*/
function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
const { state } = nav
const open = state.citationsOf !== null
return (
<div className="relative min-h-[calc(100dvh-3.5rem)]">
<AnimatePresence onExitComplete={nav.exitComplete}>
{state.citationsOf && !nav.exiting && (
<CitationsLayer
key="citations"
readOnly={readOnly}
citedBy={state.citationsOf}
onClose={nav.closeCitations}
onGone={nav.dropCitations}
onShowAll={nav.showAllReferences}
navigate={nav.navigate}
registerCanLeave={nav.registerCanLeave}
/>
)}
</AnimatePresence>
<div inert={open}>
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
readOnly={readOnly}
navigate={nav.navigate}
openCitations={nav.openCitations}
libraryReset={state.libraryReset}
focus={state.focus}
reloadSheet={reloadSheet}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
</div>
</div>
<>
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
readOnly={readOnly}
navigate={nav.navigate}
layer={findingLayerOf(nav)}
libraryReset={state.libraryReset}
focus={state.focus}
reloadSheet={reloadSheet}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
<CitationsSheet
citedBy={citationsOfView(state)}
readOnly={readOnly}
guards={nav.guards}
onClose={nav.closeCitations}
onShowAll={nav.showAllReferences}
navigate={nav.navigate}
returnFocus={nav.citationsTrigger}
/>
</>
)
}
/**
* A keydown aimed at `body` (nothing focused) never reaches the workspace's own handler:
* while the citations panel is open, Escape there closes it all the same, unless a
* modal dialog is open or the key was already handled.
*/
function useBodyEscape(open: boolean, close: () => void) {
const closeRef = useRef(close)
closeRef.current = close
useEffect(() => {
if (!open) return
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.isComposing || event.target !== document.body) return
if (document.querySelector('dialog[open]')) return
event.preventDefault()
closeRef.current()
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open])
}
/**
* The draft page once the version is ready: header, notices, tab row, the citations
* panel and the shown place. Owns the navigation state, so the first tab is known at
@@ -169,24 +129,15 @@ export default function EditorWorkspace(props: Props) {
)
// A reload or a reopened entry shows the view the history kept, never a layer.
const { state } = useLocation()
const [entry] = useState(() => ownedEntry(state, owner))
const nav = useEditorNavigation(tab, entry?.view)
const [view] = useState(() => {
const entry = ownedEntry(state, owner)
return entry && withoutForms(entry.view)
})
const nav = useEditorNavigation(tab, view)
useEditorHistory(nav, owner, defaultView(tab))
const open = nav.state.citationsOf !== null
useBodyEscape(open, nav.closeCitations)
return (
<EditingState readOnly={readOnly} citationsOf={nav.state.citationsOf}>
<div
className="space-y-4"
data-editor-workspace
onKeyDown={(event) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.nativeEvent.isComposing || !open) return
if (isTextField(event.target)) return
event.preventDefault()
nav.closeCitations()
}}
>
<EditingState readOnly={readOnly} mode={mode}>
<div className="space-y-4" data-editor-workspace>
<DraftHeader sheet={sheet} mode={mode} />
<ModeNotice mode={mode} sheet={sheet} />
<SaveFailureNotice />
@@ -3,7 +3,7 @@ import Input from '@/components/ui/Input'
import Textarea from '@/components/ui/Textarea'
/**
* A controlled field of a creation form: it never commits, the form's own button does
* A controlled field of a form: it never commits, the form's own button does
* (BDR-050). The committed fields of existing elements are `TextField`.
*/
export default function DraftField({
@@ -13,6 +13,7 @@ export default function DraftField({
onChange,
onBlur,
multiline,
readOnly,
hint,
error,
}: {
@@ -23,6 +24,8 @@ export default function DraftField({
/** Optional: a form field that applies its text when it loses the focus. */
onBlur?: () => void
multiline?: boolean
/** Shown but not editable (the editor turned read-only under a form that is kept). */
readOnly?: boolean
hint?: string
error?: string
}) {
@@ -31,6 +34,8 @@ export default function DraftField({
value,
onChange: (e: { target: { value: string } }) => onChange(e.target.value),
onBlur,
readOnly,
'aria-readonly': readOnly || undefined,
'aria-invalid': Boolean(error),
'aria-describedby': fieldDescribedBy(id, hint, error),
}
@@ -22,6 +22,7 @@ export default function AddBar({
return (
<div className="flex flex-wrap gap-2">
<ActionButton
id="finding-add-zone"
readOnly={readOnly}
variant="secondary"
size="sm"
@@ -30,6 +31,7 @@ export default function AddBar({
{t('editor.findings.add_zone')}
</ActionButton>
<ActionButton
id="finding-add-category"
readOnly={readOnly}
variant="secondary"
size="sm"
@@ -39,6 +41,7 @@ export default function AddBar({
{t('editor.findings.add_category')}
</ActionButton>
<ActionButton
id="finding-add-node"
readOnly={readOnly}
variant="secondary"
size="sm"
@@ -0,0 +1,41 @@
import { useEffect, useRef } from 'react'
import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
/**
* The footer of a form with changes that a close request reached: keep typing (focused),
* or discard. It is part of the dialog, never inert.
*/
export default function DiscardConfirm({
onKeepTyping,
onDiscard,
}: {
onKeepTyping: () => void
onDiscard: () => void
}) {
const t = useT()
const keep = useRef<HTMLButtonElement>(null)
useEffect(() => keep.current?.focus(), [])
return (
<div
role="group"
aria-label={t('editor.findings.discard_ask')}
className="space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3"
>
<p className="text-sm font-medium">{t('editor.findings.discard_ask')}</p>
<div className="flex flex-wrap justify-end gap-2">
<Button
ref={keep}
type="button"
variant="secondary"
onClick={onKeepTyping}
>
{t('editor.findings.keep_typing')}
</Button>
<Button type="button" variant="danger" onClick={onDiscard}>
{t('editor.findings.discard')}
</Button>
</div>
</div>
)
}
@@ -1,113 +1,10 @@
import type { EditCommand } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import TextField from '@/components/editor/fields/TextField'
import FindingContent from '@/components/editor/findings/FindingContent'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import type { FindingItem } from '@/editor/findings/tree'
import type { EditCommandApi } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
export interface FindingDetailProps {
item: FindingItem
readOnly: boolean
onDelete: () => void
/** Opens the citations panel of this finding (a family has none). */
onShowReferences?: (opener: HTMLElement) => void
}
/** The selected element: its names, its review state and the actions on it. */
export default function FindingDetail({
item,
readOnly,
onDelete,
onShowReferences,
}: FindingDetailProps) {
const t = useT()
const edit = useEditCommand()
return (
<div className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-medium">
{t(`editor.findings.type.${item.kind}`)}
</p>
{item.status && <StatusBadge status={item.status} />}
</div>
<Names item={item} readOnly={readOnly} edit={edit} />
<FindingContent
item={item}
readOnly={readOnly}
edit={edit}
onShowReferences={onShowReferences}
/>
<div className="flex flex-wrap items-center justify-end gap-1">
<ReviewActions item={item} readOnly={readOnly} edit={edit} />
<MoveButtons
index={item.index}
count={item.siblings}
readOnly={readOnly}
onMove={(position) =>
edit.run('actions', { op: 'move', key: item.key, position })
}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('actions') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('actions')}
</p>
)}
</div>
)
}
function Names({
item,
readOnly,
edit,
}: {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
}) {
const t = useT()
const rename = (locale: Locale) => (value: string) =>
isBlank(value)
? edit.reject(locale, 'editor.field.required')
: edit.run(locale, {
op: 'update',
key: item.key,
element: patchElement(item, {
name: { ...item.name, [locale]: value },
}),
})
return (
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={`${item.id}-${locale}`}
id={`finding-name-${locale}`}
label={t(`editor.general.name_${locale}`)}
value={item.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
trim
error={edit.fieldError(locale)}
/>
))}
</div>
)
}
function statusCommand(
item: FindingItem,
status: 'reviewed' | 'to_confirm',
@@ -155,3 +52,54 @@ function ReviewActions({
</>
)
}
interface ActionsProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
onEdit: () => void
onDelete: () => void
}
/** The view mode's actions (edit tier only): « Modifier », review, order, « Supprimer ». */
export default function FindingActions(props: ActionsProps) {
const { item, readOnly, edit, onEdit, onDelete } = props
const t = useT()
return (
<>
<div className="flex flex-wrap items-center justify-end gap-1">
<ActionButton
id="finding-edit-button"
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={onEdit}
>
{t('editor.findings.edit')}
</ActionButton>
<ReviewActions item={item} readOnly={readOnly} edit={edit} />
<MoveButtons
index={item.index}
count={item.siblings}
readOnly={readOnly}
onMove={(position) =>
edit.run('actions', { op: 'move', key: item.key, position })
}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('actions') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('actions')}
</p>
)}
</>
)
}
@@ -0,0 +1,138 @@
import Icon from '@/components/ui/Icon'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
interface CitationsProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
/** The citations sheet is open over the dialog (the trigger reads « expanded »). */
sheetOpen: boolean
/** Opens the citations sheet; a family has none (it lists its citations here). */
onShowReferences: (opener: HTMLElement) => void
}
const RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** « X références »: the way to the sheet of a finding node's citations. */
function SheetTrigger({
item,
count,
sheetOpen,
onShowReferences,
}: Pick<CitationsProps, 'item' | 'sheetOpen' | 'onShowReferences'> & {
count: number
}) {
const plural = usePlural()
return (
<button
type="button"
data-citations-trigger={JSON.stringify(item.key)}
aria-expanded={sheetOpen}
aria-controls="editor-citations-panel"
onClick={(event) => onShowReferences(event.currentTarget)}
className={`inline-flex min-h-11 items-center gap-1 rounded-full border border-[var(--color-border)] px-3 text-sm ${RING}`}
>
<Icon name="book" size={16} />
{plural('editor.findings.references_open', count)}
</button>
)
}
/** A family's inline list of cited references, each removable (« Retirer »). */
function CitationList({
ids,
readOnly,
remove,
}: {
ids: readonly string[]
readOnly: boolean
remove: (id: string) => void
}) {
const t = useT()
const doc = useSheetDocument()
const citation = (id: string) =>
doc?.references.find((r) => r.id === id)?.citation ?? id
return (
<ul className="space-y-1">
{ids.map((id) => (
<li key={id} className="flex items-center gap-2 text-sm">
<span className="min-w-0 flex-1">{citation(id)}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() => remove(id)}
>
{t('editor.action.remove')}
</ActionButton>
</li>
))}
</ul>
)
}
/**
* « Références citées » of a category or a node. A finding node shows « X références »
* (the sheet), a family its list. « Citer une référence » acts at once, one entry in the
* document's history, in view mode too (it is no part of the transactional form).
*/
export default function FindingCitations(props: CitationsProps) {
const { item, readOnly, edit } = props
const t = useT()
const doc = useSheetDocument()
const { element } = item
if (element.kind === 'zone') return null
const ids = element.value.reference_ids
const patch = (reference_ids: string[]) =>
edit.run('references', {
op: 'update',
key: item.key,
element: patchElement(item, { reference_ids }),
})
const options = [
{ value: '', label: t('editor.field.choose') },
...(doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation })),
]
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length > 0 && element.kind === 'finding_node' && (
<SheetTrigger {...props} count={ids.length} />
)}
</div>
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{element.kind === 'finding_category' && (
<CitationList
ids={ids}
readOnly={readOnly}
remove={(id) => patch(ids.filter((other) => other !== id))}
/>
)}
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) => id !== '' && patch([...ids, id])}
error={edit.fieldError('references')}
/>
)}
</div>
)
}
@@ -1,211 +0,0 @@
import { useContext } from 'react'
import ActionButton from '@/components/editor/fields/ActionButton'
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import Icon from '@/components/ui/Icon'
import { ReferencesOpenContext } from '@/editor/editingContext'
import {
patchElement,
sameKey,
type FindingItem,
type FindingPatch,
} from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { optionalText, useSheetDocument } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
interface ContentProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
/** Opens the citations panel; given for a finding only, a family has no panel. */
onShowReferences?: (opener: HTMLElement) => void
}
/** The content of a category or a node: descriptions, vet referral, cited references. */
export default function FindingContent(props: ContentProps) {
const { element } = props.item
if (element.kind === 'zone') return null
const patch = (field: string, change: FindingPatch) =>
props.edit.run(field, {
op: 'update',
key: props.item.key,
element: patchElement(props.item, change),
})
return (
<div className="space-y-3">
<Descriptions
{...props}
current={element.value.description}
patch={patch}
/>
{element.kind === 'finding_node' && (
<VetFlag
{...props}
value={element.value.requires_vet_referral}
patch={patch}
/>
)}
<Citations
{...props}
ids={element.value.reference_ids}
patch={patch}
onShowReferences={
element.kind === 'finding_node' ? props.onShowReferences : undefined
}
/>
</div>
)
}
type Patch = (field: string, change: FindingPatch) => boolean
function Descriptions({
item,
readOnly,
edit,
current,
patch,
}: ContentProps & {
current: { fr?: string; en?: string }
patch: Patch
}) {
const t = useT()
const commit = (locale: Locale) => (value: string) =>
patch(`description-${locale}`, {
description: optionalText(current, locale, value),
})
return (
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={`${item.id}-${locale}`}
id={`finding-description-${locale}`}
label={t(`editor.findings.description_${locale}`)}
value={current[locale] ?? ''}
onCommit={commit(locale)}
readOnly={readOnly}
multiline
error={edit.fieldError(`description-${locale}`)}
/>
))}
</div>
)
}
function VetFlag({
readOnly,
edit,
value,
patch,
}: ContentProps & { value: boolean; patch: Patch }) {
const t = useT()
const label = t('editor.findings.vet_referral')
if (readOnly) {
const answer = t(value ? 'editor.findings.yes' : 'editor.findings.no')
return <ReadOnlyValue id="finding-vet" label={label} value={answer} />
}
return (
<div>
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={value}
onChange={(e) =>
patch('vet', { requires_vet_referral: e.target.checked })
}
/>
{label}
</label>
{edit.fieldError('vet') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('vet')}
</p>
)}
</div>
)
}
function Citations({
item,
readOnly,
edit,
ids,
patch,
onShowReferences,
}: ContentProps & { ids: readonly string[]; patch: Patch }) {
const t = useT()
const plural = usePlural()
const doc = useSheetDocument()
const citationsOf = useContext(ReferencesOpenContext)
const panelOpen = citationsOf !== null && sameKey(citationsOf, item.key)
const references = doc?.references ?? []
const citation = (id: string) =>
references.find((r) => r.id === id)?.citation ?? id
const options = [
{ value: '', label: t('editor.field.choose') },
...references
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation })),
]
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length > 0 && onShowReferences && (
<button
type="button"
data-citations-trigger={JSON.stringify(item.key)}
aria-expanded={panelOpen}
aria-controls="editor-citations-panel"
onClick={(event) => onShowReferences(event.currentTarget)}
className="inline-flex min-h-11 items-center gap-1 rounded-full border border-[var(--color-border)] px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name="book" size={16} />
{plural('editor.findings.references_open', ids.length)}
</button>
)}
</div>
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
<ul className="space-y-1">
{ids.map((id) => (
<li key={id} className="flex items-center gap-2 text-sm">
<span className="min-w-0 flex-1">{citation(id)}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() =>
patch('references', {
reference_ids: ids.filter((other) => other !== id),
})
}
>
{t('editor.action.remove')}
</ActionButton>
</li>
))}
</ul>
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) =>
id !== '' && patch('references', { reference_ids: [...ids, id] })
}
error={edit.fieldError('references')}
/>
)}
</div>
)
}
@@ -4,9 +4,12 @@ import type {
FindingCategoryKind,
FindingNode,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
import Button from '@/components/ui/Button'
import {
buildItems,
type FindingItem,
@@ -15,6 +18,7 @@ import {
import type { IdPrefix } from '@/editor/ids'
import { isBlank, useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -31,26 +35,30 @@ export interface PendingFinding {
parent: FindingItem | null
}
export interface FindingCreateFormProps {
pending: PendingFinding
readOnly: boolean
guards: Guards
/** `created` is the new element's id, `parent` the element it went under. */
onCreated: (id: string, parent: FindingItem | null) => void
/** A close of the dialog; forced after « Abandonner ». */
onClose: (forced: boolean) => void
}
/**
* Collects what the core requires (names FR/EN, the kind of a category), then one
* `insert`: no element exists with default labels.
* `insert`: no element exists with default labels. The fields are a local draft: nothing
* is written before « Créer », a close or a move never creates (R2F-3).
*/
export default function FindingCreateForm({
pending,
onCreated,
onCancel,
}: {
pending: PendingFinding
onCreated: (id: string, parent: FindingItem | null) => void
onCancel: () => void
}) {
export default function FindingCreateForm(props: FindingCreateFormProps) {
const { pending, readOnly, guards, onCreated, onClose } = props
const t = useT()
const edit = useEditCommand()
const zones = useZoneChoice()
const title = useFormTitle(pending, zones.chosen)
const [fr, setFr] = useState('')
const [en, setEn] = useState('')
const [kind, setKind] = useState('')
const guard = useDirtyGuard(guards, fr !== '' || en !== '' || kind !== '')
const create = () => {
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
const missingParent = pending.kind === 'category' && !parent
@@ -71,16 +79,27 @@ export default function FindingCreateForm({
})
if (added) onCreated(createdId, parent)
}
const category = pending.kind === 'category'
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{title}</p>
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
create()
}}
>
{readOnly && <ReadOnlyNotice />}
{category && zones.chosen && <ZoneTitle zone={zones.chosen} />}
<div className="grid gap-3 md:grid-cols-2">
{pending.kind === 'category' && <ZoneSelect zones={zones} />}
{pending.kind === 'category' && (
{category && <ZoneSelect zones={zones} readOnly={readOnly} />}
{category && (
<SelectField
id="finding-new-kind"
label={t('editor.findings.kind')}
value={kind}
readOnly={readOnly}
options={[
{ value: '', label: t('editor.field.choose') },
...CATEGORY_KINDS.map((k) => ({
@@ -96,12 +115,14 @@ export default function FindingCreateForm({
label={t('editor.general.name_fr')}
value={fr}
onChange={setFr}
readOnly={readOnly}
/>
<DraftField
id="finding-new-name-en"
label={t('editor.general.name_en')}
value={en}
onChange={setEn}
readOnly={readOnly}
/>
</div>
{edit.fieldError('form') && (
@@ -109,15 +130,26 @@ export default function FindingCreateForm({
{edit.fieldError('form')}
</p>
)}
<div className="flex gap-2">
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.findings.create')}
</ActionButton>
<ActionButton readOnly={false} variant="ghost" onClick={onCancel}>
{t('editor.findings.cancel')}
</ActionButton>
</div>
</div>
{guard.confirming ? (
<DiscardConfirm
onKeepTyping={guard.keepTyping}
onDiscard={() => onClose(true)}
/>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={() => onClose(readOnly)}
>
{t(readOnly ? 'editor.findings.discard' : 'editor.findings.cancel')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.findings.create')}
</Button>
</div>
)}
</form>
)
}
@@ -139,7 +171,13 @@ function useZoneChoice(): ZoneChoice {
return { zones, zoneId, setZoneId, chosen }
}
function ZoneSelect({ zones }: { zones: ZoneChoice }) {
function ZoneSelect({
zones,
readOnly,
}: {
zones: ZoneChoice
readOnly: boolean
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return (
@@ -147,6 +185,7 @@ function ZoneSelect({ zones }: { zones: ZoneChoice }) {
id="finding-new-zone"
label={t('editor.findings.zone')}
value={zones.zoneId}
readOnly={readOnly}
options={[
{ value: '', label: t('editor.field.choose') },
...zones.zones.map((zone) => ({
@@ -159,19 +198,17 @@ function ZoneSelect({ zones }: { zones: ZoneChoice }) {
)
}
/** A category lands at zone level: its title names the zone chosen in the form. */
function useFormTitle(
pending: PendingFinding,
zone: FindingItem | null,
): string {
/** A category lands at zone level: the line under the dialog's title names the zone chosen. */
function ZoneTitle({ zone }: { zone: FindingItem }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (pending.kind !== 'category')
return t(`editor.findings.new.${pending.kind}`)
if (!zone) return t('editor.findings.add_category')
return t('editor.findings.new.category_in_zone').replace(
'{zone}',
zone.name[locale],
return (
<p className="text-sm font-medium">
{t('editor.findings.new.category_in_zone').replace(
'{zone}',
zone.name[locale],
)}
</p>
)
}
@@ -0,0 +1,133 @@
import { useEffect, useRef, useState } from 'react'
import FindingCreateForm, {
type PendingFinding,
} from '@/components/editor/findings/FindingCreateForm'
import FindingEditForm from '@/components/editor/findings/FindingEditForm'
import FindingView from '@/components/editor/findings/FindingView'
import Dialog from '@/components/ui/Dialog'
import { usePlaceVisible } from '@/lib/placeVisibility'
import type { FindingItem, FindingKind } from '@/editor/findings/tree'
import type { FindingLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface FindingDialogProps {
layer: FindingLayer
/** The element the dialog shows; null while it creates one or is closed. */
item: FindingItem | null
/** The creation the dialog holds, null for the view of an element. */
pending: PendingFinding | null
readOnly: boolean
/** Where the focus goes once the dialog is closed (the tree row, the add button). */
returnFocus: () => HTMLElement | null
onDelete: (item: FindingItem) => void
onCreated: (id: string, parent: FindingItem | null, kind: FindingKind) => void
}
interface ItemBodyProps {
item: FindingItem
layer: FindingLayer
readOnly: boolean
onDelete: (item: FindingItem) => void
}
const EDIT_BUTTON_ID = 'finding-edit-button'
/** After the form closes its button is gone: « Modifier » takes the focus back. */
function useFocusEditButton(editing: boolean) {
const wanted = useRef(false)
useEffect(() => {
if (editing || !wanted.current) return
wanted.current = false
document.getElementById(EDIT_BUTTON_ID)?.focus()
}, [editing])
return () => {
wanted.current = true
}
}
/** View mode, or the edit form: a local mode of the one dialog, no history entry. */
function ItemBody({ item, layer, readOnly, onDelete }: ItemBodyProps) {
const t = useT()
const [editing, setEditing] = useState(false)
const [saved, setSaved] = useState(false)
const returnToEdit = useFocusEditButton(editing)
const { view } = layer
const sheetOpen = view !== null && 'key' in view && view.citations
return (
<div className="space-y-2">
{editing ? (
<FindingEditForm
item={item}
readOnly={readOnly}
guards={layer.guards}
onDone={(wrote) => {
returnToEdit()
setSaved(wrote)
setEditing(false)
}}
onDiscardClose={() => layer.close(true)}
/>
) : (
<FindingView
item={item}
readOnly={readOnly}
sheetOpen={sheetOpen}
onEdit={() => {
setSaved(false)
setEditing(true)
}}
onDelete={() => onDelete(item)}
onShowReferences={(opener) => layer.openCitations(item.key, opener)}
/>
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{saved ? t('editor.findings.saved') : ''}
</p>
</div>
)
}
/**
* The finding dialog (R2F-3): one `ModalDialog` kept across its modes (view, edit,
* creation). The view layer of the browser history drives it; it opens only while its
* place is shown (no native modal inside a hidden part).
*/
export default function FindingDialog(props: FindingDialogProps) {
const { layer, item, pending, readOnly } = props
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const visible = usePlaceVisible()
const title = pending
? t(`editor.findings.new.${pending.kind}`)
: (item?.name[locale] ?? '')
return (
<Dialog
open={visible && (item !== null || pending !== null)}
layer
size="lg"
title={title}
returnFocus={props.returnFocus}
onClose={() => (layer.close() ? undefined : 'kept')}
>
{pending && (
<FindingCreateForm
pending={pending}
readOnly={readOnly}
guards={layer.guards}
onCreated={(id, parent) => props.onCreated(id, parent, pending.kind)}
onClose={(forced) => layer.close(forced)}
/>
)}
{item && (
<ItemBody
key={item.id}
item={item}
layer={layer}
readOnly={readOnly}
onDelete={props.onDelete}
/>
)}
</Dialog>
)
}
@@ -0,0 +1,209 @@
import { useRef, useState } from 'react'
import DraftField from '@/components/editor/fields/DraftField'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import Button from '@/components/ui/Button'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank, optionalText } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
/** What the form edits, as plain strings: nothing is written before « Enregistrer ». */
interface Draft {
fr: string
en: string
descriptionFr: string
descriptionEn: string
vet: boolean
}
function draftOf(item: FindingItem): Draft {
const { element } = item
const described = element.kind === 'zone' ? {} : element.value.description
return {
fr: item.name.fr,
en: item.name.en,
descriptionFr: described.fr ?? '',
descriptionEn: described.en ?? '',
vet: element.kind === 'finding_node' && element.value.requires_vet_referral,
}
}
/** The draft as it would be saved: names trimmed, a blank description absent. */
function normalized(draft: Draft): Draft {
return {
...draft,
fr: draft.fr.trim(),
en: draft.en.trim(),
descriptionFr: isBlank(draft.descriptionFr) ? '' : draft.descriptionFr,
descriptionEn: isBlank(draft.descriptionEn) ? '' : draft.descriptionEn,
}
}
const sameDraft = (a: Draft, b: Draft) =>
JSON.stringify(normalized(a)) === JSON.stringify(normalized(b))
/** The one `update` the form makes: names, and for a family or a node the texts. */
function patchOf(item: FindingItem, draft: Draft) {
const now = normalized(draft)
const { element } = item
const name = { fr: now.fr, en: now.en }
if (element.kind === 'zone') return patchElement(item, { name })
let description = optionalText(
element.value.description,
'fr',
now.descriptionFr,
)
description = optionalText(description, 'en', now.descriptionEn)
const vet = { requires_vet_referral: now.vet }
return patchElement(item, {
name,
description,
...(element.kind === 'finding_node' ? vet : {}),
})
}
export interface FindingEditFormProps {
item: FindingItem
readOnly: boolean
guards: Guards
/** Back to the view mode; `saved` is true when a command was written. */
onDone: (saved: boolean) => void
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
onDiscardClose: () => void
}
function VetCheckbox({
checked,
readOnly,
onChange,
}: {
checked: boolean
readOnly: boolean
onChange: (value: boolean) => void
}) {
const t = useT()
return (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={checked}
disabled={readOnly}
onChange={(event) => onChange(event.target.checked)}
/>
{t('editor.findings.vet_referral')}
</label>
)
}
/**
* The element edited in the finding dialog (R2F-3): a local draft, one `update` on
* « Enregistrer » (none when nothing changed), nothing on « Annuler » or a close. When the
* editor turns read-only the draft stays, its fields read-only, and only « Abandonner »
* is left.
*/
export default function FindingEditForm(props: FindingEditFormProps) {
const { item, readOnly, guards, onDone, onDiscardClose } = props
const t = useT()
const edit = useEditCommand()
const initial = useRef(draftOf(item)).current
const [draft, setDraft] = useState(initial)
const [blank, setBlank] = useState<readonly string[]>([])
const dirty = !sameDraft(draft, initial)
const guard = useDirtyGuard(guards, dirty)
const set = (change: Partial<Draft>) => setDraft({ ...draft, ...change })
const save = () => {
const missing = (['fr', 'en'] as const).filter((l) => isBlank(draft[l]))
setBlank(missing)
if (missing.length > 0) {
document.getElementById(`finding-edit-name-${missing[0]}`)?.focus()
return
}
if (!dirty) return onDone(false)
const command = {
op: 'update',
key: item.key,
element: patchOf(item, draft),
} as const
if (edit.run('save', command)) onDone(true)
}
const cancel = () => (dirty && !readOnly ? guard.askToLeave() : onDone(false))
const described = item.kind !== 'zone'
const fieldError = (l: 'fr' | 'en') =>
blank.includes(l) ? t('editor.field.required') : undefined
return (
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
save()
}}
>
{readOnly && <ReadOnlyNotice />}
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((l) => (
<DraftField
key={l}
id={`finding-edit-name-${l}`}
label={t(`editor.general.name_${l}`)}
value={draft[l]}
onChange={(value) => set({ [l]: value })}
readOnly={readOnly}
error={fieldError(l)}
/>
))}
{described &&
(['fr', 'en'] as const).map((l) => (
<DraftField
key={`d-${l}`}
id={`finding-edit-description-${l}`}
label={t(`editor.findings.description_${l}`)}
value={l === 'fr' ? draft.descriptionFr : draft.descriptionEn}
onChange={(value) =>
set(
l === 'fr'
? { descriptionFr: value }
: { descriptionEn: value },
)
}
readOnly={readOnly}
multiline
/>
))}
</div>
{item.element.kind === 'finding_node' && (
<VetCheckbox
checked={draft.vet}
readOnly={readOnly}
onChange={(vet) => set({ vet })}
/>
)}
{edit.fieldError('save') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('save')}
</p>
)}
{guard.confirming ? (
<DiscardConfirm
onKeepTyping={guard.keepTyping}
onDiscard={() =>
guard.confirming === 'dialog' ? onDiscardClose() : onDone(false)
}
/>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={cancel}>
{t(readOnly ? 'editor.findings.discard' : 'editor.findings.cancel')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.findings.save')}
</Button>
</div>
)}
</form>
)
}
@@ -1,4 +1,5 @@
import { useEffect, useRef, type KeyboardEvent } from 'react'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import { keyMove, type FindingItem } from '@/editor/findings/tree'
import { useT } from '@/i18n/useT'
@@ -9,6 +10,8 @@ export interface FindingTreeProps {
selectedId: string | null
expanded: ReadonlySet<string>
onSelect: (id: string) => void
/** Click, Enter or Space on a row: the row is selected and its dialog opens. */
onActivate: (item: FindingItem) => void
onToggle: (id: string, open: boolean) => void
/** Moves focus to this item (after a deletion); null leaves focus alone. */
focusId: { id: string } | null
@@ -26,6 +29,7 @@ export default function FindingTree(props: FindingTreeProps) {
const refs = useRef(new Map<string, HTMLElement>())
const focusAfter = useRef<string | null>(null)
const { visible, selectedId, expanded, onSelect, onToggle } = props
const { onActivate } = props
const { focusId, onFocused } = props
useEffect(() => {
if (focusAfter.current) refs.current.get(focusAfter.current)?.focus()
@@ -33,11 +37,17 @@ export default function FindingTree(props: FindingTreeProps) {
})
useEffect(() => {
if (!focusId) return
refs.current.get(focusId.id)?.focus()
// After the dialogs a move closed: the page behind them is inert until then.
afterModalsClosed(() => refs.current.get(focusId.id)?.focus())
onFocused()
}, [focusId, onFocused])
const current = visible.find((item) => item.id === selectedId) ?? visible[0]
const onKeyDown = (event: KeyboardEvent, item: FindingItem) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onActivate(item)
return
}
const move = keyMove(visible, item, expanded, event.key)
if (!move) return
event.preventDefault()
@@ -66,7 +76,7 @@ export default function FindingTree(props: FindingTreeProps) {
else refs.current.delete(item.id)
}}
onKeyDown={onKeyDown}
onSelect={onSelect}
onActivate={onActivate}
onToggle={onToggle}
/>
))}
@@ -81,7 +91,7 @@ interface TreeRowProps {
open: boolean
register: (el: HTMLElement | null) => void
onKeyDown: (event: KeyboardEvent, item: FindingItem) => void
onSelect: (id: string) => void
onActivate: (item: FindingItem) => void
onToggle: (id: string, open: boolean) => void
}
@@ -92,7 +102,7 @@ function TreeRow({
open,
register,
onKeyDown,
onSelect,
onActivate,
onToggle,
}: TreeRowProps) {
const locale = useLocaleStore((s) => s.locale)
@@ -107,10 +117,11 @@ function TreeRow({
aria-expanded={item.hasChildren ? open : undefined}
tabIndex={tabbable ? 0 : -1}
data-testid="finding-item"
data-finding-key={JSON.stringify(item.key)}
onKeyDown={(event) => {
if (event.target === event.currentTarget) onKeyDown(event, item)
}}
onClick={() => onSelect(item.id)}
onClick={() => onActivate(item)}
style={{ paddingLeft: `${(item.level - 1) * 1.25 + 0.5}rem` }}
className={`flex cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-sm ${
selected
@@ -0,0 +1,94 @@
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
import FindingActions from '@/components/editor/findings/FindingActions'
import FindingCitations from '@/components/editor/findings/FindingCitations'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import type { FindingItem } from '@/editor/findings/tree'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
export interface FindingViewProps {
item: FindingItem
readOnly: boolean
sheetOpen: boolean
onEdit: () => void
onDelete: () => void
onShowReferences: (opener: HTMLElement) => void
}
/** The texts of a category or a node, read: descriptions, then the vet referral of a node. */
function Texts({ item }: { item: FindingItem }) {
const t = useT()
const { element } = item
if (element.kind === 'zone') return null
return (
<>
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<ReadOnlyValue
key={locale}
id={`finding-description-${locale}`}
label={t(`editor.findings.description_${locale}`)}
value={element.value.description[locale] ?? ''}
multiline
/>
))}
</div>
{element.kind === 'finding_node' && (
<ReadOnlyValue
id="finding-vet"
label={t('editor.findings.vet_referral')}
value={t(
element.value.requires_vet_referral
? 'editor.findings.yes'
: 'editor.findings.no',
)}
/>
)}
</>
)
}
/**
* The element read in the finding dialog (R2F-3): type and status, names, texts, its
* citations, and the actions of the edit tier. Nothing here edits a field in place.
*/
export default function FindingView(props: FindingViewProps) {
const { item, readOnly, sheetOpen } = props
const t = useT()
const edit = useEditCommand()
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-medium">
{t(`editor.findings.type.${item.kind}`)}
</p>
{item.status && <StatusBadge status={item.status} />}
</div>
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<ReadOnlyValue
key={locale}
id={`finding-name-${locale}`}
label={t(`editor.general.name_${locale}`)}
value={item.name[locale]}
/>
))}
</div>
<Texts item={item} />
<FindingCitations
item={item}
readOnly={readOnly}
edit={edit}
sheetOpen={sheetOpen}
onShowReferences={props.onShowReferences}
/>
<FindingActions
item={item}
readOnly={readOnly}
edit={edit}
onEdit={props.onEdit}
onDelete={props.onDelete}
/>
</div>
)
}
@@ -0,0 +1,14 @@
import Notice from '@/components/ui/Notice'
import { useEditorMode } from '@/editor/editingContext'
import { useT } from '@/i18n/useT'
/**
* The editor turned read-only under a form the dialog keeps: why, worded from the mode.
* A narrow window comes back on widening; any other mode leaves only « Abandonner ».
*/
export default function ReadOnlyNotice() {
const t = useT()
const mode = useEditorMode()
const key = mode === 'narrow' ? 'flip_narrow' : 'flip_blocked'
return <Notice tone="info">{t(`editor.findings.${key}`)}</Notice>
}
@@ -0,0 +1,32 @@
import { useEffect, useRef, useState } from 'react'
import { useBeforeUnload } from '@/app/useLeaveGuard'
import type { Guards } from '@/editor/useEditorNavigation'
/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */
export type DiscardTarget = 'form' | 'dialog'
/**
* The finding layer's guard while a form holds changes (R2F-3): a user close that reaches
* the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
* modifications ? » (`confirming`). A forced close, or a form with nothing typed, goes
* ahead. `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
*/
export function useDirtyGuard(guards: Guards, dirty: boolean) {
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
const latest = useRef(dirty)
latest.current = dirty
useBeforeUnload(dirty)
useEffect(() => {
guards.register('finding', (forced) => {
if (forced || !latest.current) return { allowed: true }
setConfirming('dialog')
return { allowed: false }
})
return () => guards.register('finding', null)
}, [guards])
return {
confirming,
askToLeave: () => setConfirming('form'),
keepTyping: () => setConfirming(null),
}
}
@@ -1,122 +0,0 @@
import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'
import { motion, useIsPresent, useReducedMotion } from 'motion/react'
import { PANEL_ENTER_S, PANEL_EXIT_S } from '@/editor/useCitationsExit'
import KeptPlace from '../KeptPlace'
import CitationsPanel from './CitationsPanel'
type Props = Parameters<typeof CitationsPanel>[0]
/** The top bar (`h-14`): the panel sticks right under it. */
const TOP_BAR_REM = 3.5
/**
* The panel's visible height: from its top (under the top bar once the page has scrolled)
* to the nearer of the container's bottom and the viewport's bottom. Kept right on scroll,
* resize and visual-viewport changes (mobile URL bar, keyboard); only the panel's own
* height is written, so the document never changes size.
*/
function useFitToViewport(panel: RefObject<HTMLElement | null>) {
useLayoutEffect(() => {
const element = panel.current
const container = element?.parentElement
if (!element || !container) return
const bar =
TOP_BAR_REM *
parseFloat(getComputedStyle(document.documentElement).fontSize)
const fit = () => {
const box = container.getBoundingClientRect()
const viewport = window.visualViewport?.height ?? window.innerHeight
const visible = Math.min(box.bottom, viewport) - Math.max(box.top, bar)
element.style.height = `${Math.max(visible, 0)}px`
}
fit()
const watched: EventTarget[] = [window]
if (window.visualViewport) watched.push(window.visualViewport)
for (const target of watched) {
target.addEventListener('scroll', fit, { passive: true })
target.addEventListener('resize', fit)
}
const observer =
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(fit)
// Content above the container reflowing moves its top without resizing it.
observer?.observe(container)
observer?.observe(document.documentElement)
return () => {
for (const target of watched) {
target.removeEventListener('scroll', fit)
target.removeEventListener('resize', fit)
}
observer?.disconnect()
}
}, [panel])
}
/**
* The citations panel and its scrim over the places (board 25). The panel slides in from
* the right (translateX only), the scrim fades on the same timings; under reduced motion
* both change at once, the callbacks still fire (P29). While it exits, the panel is inert
* (the page behind stays inert until the workspace lifts it, P9).
*
* Geometry (P16, P16'): the wrapper fills the Places container, clips the slide on the x
* axis only (`clip`, never `hidden`) and is 34 rem at most; the panel inside sticks under
* the top bar, is exactly as tall as what is visible (`useFitToViewport`) and scrolls its
* own list, so the page's size never changes.
*/
export default function CitationsLayer(props: Props) {
const reduced = useReducedMotion()
const present = useIsPresent()
const layer = useRef<HTMLDivElement>(null)
const focused = useRef(false)
useFitToViewport(layer)
// A reopen during a slow exit reuses this instance: it focuses its heading again.
useEffect(() => {
if (!present) focused.current = false
}, [present])
const slide = { x: reduced ? 0 : '100%' }
const enter = {
duration: reduced ? 0 : PANEL_ENTER_S,
ease: 'easeOut',
} as const
const leave = {
duration: reduced ? 0 : PANEL_EXIT_S,
ease: 'easeIn',
} as const
// The heading takes the focus once the panel is in place (P9, P29).
const entered = () => {
if (!present || focused.current) return
focused.current = true
layer.current
?.querySelector<HTMLElement>('[data-place-heading]')
?.focus({ preventScroll: true })
}
return (
<>
<motion.div
aria-hidden="true"
data-testid="references-scrim"
onClick={props.onClose}
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: enter }}
exit={{ opacity: 0, transition: leave }}
/>
<KeptPlace
name="citations"
visible
inert={!present}
className="absolute inset-y-0 right-0 z-20 w-[min(34rem,100%)] overflow-x-clip"
>
<motion.div
ref={layer}
className="sticky top-14"
initial={slide}
animate={{ x: 0, transition: enter }}
exit={{ ...slide, transition: leave }}
onAnimationComplete={entered}
>
<CitationsPanel {...props} />
</motion.div>
</KeptPlace>
</>
)
}
@@ -1,14 +1,7 @@
import {
useCallback,
useLayoutEffect,
useRef,
type KeyboardEvent,
type RefObject,
} from 'react'
import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'
import type { LocalizedText, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { isTextField } from '@/editor/focusRequest'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import { usePlural } from '@/editor/plural'
import type { CitationEntry } from '@/editor/references/panel'
@@ -18,7 +11,7 @@ import ReferenceTile from './ReferenceTile'
import { useCitationsPanel, type PanelHooks } from './useCitationsPanel'
interface Props extends PanelHooks {
/** ✕, Escape and the scrim: a close the tile in edit may refuse. */
/** ✕ (Escape and the scrim close the sheet itself): a close the tile in edit may refuse. */
onClose: () => void
/** « Tout afficher dans l'onglet Références ». */
onShowAll: () => void
@@ -231,20 +224,10 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
)
}
/** Escape closes the panel, unless a field of it is being typed in (A5, P27). */
function closeOnEscape(onClose: () => void) {
return (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.nativeEvent.isComposing || isTextField(event.target)) return
event.stopPropagation()
onClose()
}
}
/**
* The citations of one finding (board 25): the references it cites as tiles, « Tout
* afficher » for the whole library. No search, add, delete or order (P7). Not a dialog:
* the workspace makes the page behind it inert. Opens from a finding's trigger only.
* The citations of one finding: the references it cites as tiles, « Tout afficher » for
* the whole library. No search, add, delete or order (P7). The content of the side sheet
* (CitationsSheet), which is the modal; opens from a finding's trigger only.
*/
export default function CitationsPanel(props: Props) {
const { onClose, onShowAll } = props
@@ -256,7 +239,6 @@ export default function CitationsPanel(props: Props) {
id="editor-citations-panel"
data-testid="editor-citations-panel"
aria-labelledby="editor-citations-title"
onKeyDown={closeOnEscape(onClose)}
className="flex h-full flex-col gap-3 border-l border-[var(--color-border)] bg-[var(--color-surface)] p-4 shadow-xl"
>
<PanelHeader onClose={onClose} headingRef={panel.heading} />
@@ -0,0 +1,86 @@
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). */
const ENTER_S = 0.18
const EXIT_S = 0.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. */
onClose: () => boolean
/** « Tout afficher dans l'onglet Références ». */
onShowAll: () => void
/** « Aller à » a citing finding or a reference. */
navigate: (target: EditorTarget) => void
/** « X références » of the dialog under the sheet, where the focus returns. */
returnFocus: () => HTMLElement | null
}
/**
* 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.
*/
function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
const { citedBy, onClose } = props
const reduced = useReducedMotion()
const slide = reduced ? { x: 0 } : { x: '100%' }
const enter = { duration: reduced ? 0 : ENTER_S, ease: 'easeOut' } as const
const leave = { duration: reduced ? 0 : EXIT_S, ease: 'easeIn' } as const
const close = () => (onClose() ? undefined : 'kept')
return (
<ModalDialog
layer
onClose={close}
returnFocus={props.returnFocus}
ignoreEscape={isTextField}
labelledBy="editor-citations-title"
className="open:block"
>
<motion.div
aria-hidden="true"
data-testid="references-scrim"
onClick={close}
className="absolute inset-0 bg-[rgba(31,27,22,0.25)]"
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: enter }}
exit={{ opacity: 0, transition: leave }}
/>
<motion.div
data-place="citations"
className="absolute inset-y-0 right-0 w-[min(34rem,100vw)]"
initial={slide}
animate={{ x: 0, transition: enter }}
exit={{ ...slide, transition: leave }}
>
<CitationsPanel
readOnly={props.readOnly}
citedBy={citedBy}
guards={props.guards}
onClose={onClose}
onShowAll={props.onShowAll}
navigate={props.navigate}
/>
</motion.div>
</ModalDialog>
)
}
export default function CitationsSheet(props: CitationsSheetProps) {
const { citedBy } = props
return (
<AnimatePresence>
{citedBy && <SheetSurface key="citations" {...props} citedBy={citedBy} />}
</AnimatePresence>
)
}
@@ -6,16 +6,15 @@ 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 { CanLeave } from '@/editor/useEditorNavigation'
import type { Guards, LeaveAnswer } from '@/editor/useEditorNavigation'
import { useDroppedText } from './useReferenceEdit'
import { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
readOnly: boolean
citedBy: ElementKey
/** The finding vanished: a close nobody can refuse. */
onGone: () => void
registerCanLeave: (guard: CanLeave | null) => void
/** 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. */
@@ -29,32 +28,26 @@ function useCitedFinding(citedBy: ElementKey) {
}
/**
* The panel closes once its finding is gone: a forced close. It runs after the leave
* check registered itself (effects of one component run in order), so a tile in edit is
* still asked. A read-only flip does not close it: the panel stays, as the crossing
* specs expect, and its tiles stop being editable.
* 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 useCloseWhenGone(gone: boolean, onGone: () => void) {
useEffect(() => {
if (gone) onGone()
}, [gone, onGone])
}
/** P22'': a user close asks the tile in edit first; a forced one drops a refused draft. */
function useLeaveCheck(
tiles: ReturnType<typeof useTileState>,
register: PanelHooks['registerCanLeave'],
) {
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(() => {
register((forced) => {
const refused = tiles.leave()
if (refused.length === 0) return { allowed: true }
if (!forced) return { allowed: false }
return { allowed: true, note: droppedText(refused) }
})
return () => register(null)
})
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. */
@@ -108,7 +101,7 @@ function useFocusRescue() {
/**
* What the panel shows of the finding: its cited ids and its path. Once the finding is
* gone (the panel is leaving) the last known answer stays, so the panel does not empty
* gone (the sheet is leaving) the last known answer stays, so the sheet does not empty
* while it slides out and a tile in edit can still be asked to apply its draft.
*/
function useShownFinding(
@@ -142,8 +135,7 @@ export function useCitationsPanel(hooks: PanelHooks) {
const edit = useEditCommand()
const tiles = useTileState(doc ? keys : null)
const focus = useFocusRescue()
useLeaveCheck(tiles, hooks.registerCanLeave)
useCloseWhenGone(doc !== null && item === null, hooks.onGone)
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.
@@ -2,6 +2,7 @@ import { useEffect, useState, type RefObject } from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import {
focusRow,
focusRowLater,
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
@@ -59,7 +60,7 @@ function useReferenceFocus(
if (target.key === null || at < 0) return 'none'
tiles.reveal(keys[at])
if (referenceMatches(all[at], shown.view.query)) {
return focusRow(target.key) ? 'found' : 'none'
return focusRowLater(target.key) ? 'found' : 'none'
}
shown.update({ query: '' })
later(target.key)
@@ -1,27 +1,28 @@
import { useCallback, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly'
import AddBar from '@/components/editor/findings/AddBar'
import FindingCreateForm, {
type PendingFinding,
} from '@/components/editor/findings/FindingCreateForm'
import FindingDetail from '@/components/editor/findings/FindingDetail'
import FindingDialog from '@/components/editor/findings/FindingDialog'
import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm'
import FindingTree from '@/components/editor/findings/FindingTree'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import {
buildItems,
createdItemId,
createdKey,
fallbackAfterRemoval,
isUnder,
itemForKey,
sameKey,
visibleItems,
type FindingItem,
type FindingKind,
} from '@/editor/findings/tree'
import { useFocusRequest } from '@/editor/focusRequest'
import { useFocusRequest, visibleElement } from '@/editor/focusRequest'
import { useEditorStore } from '@/editor/state/editorStore'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorPlaceProps } from '@/editor/tabs'
import type { EditorPlaceProps, FindingLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -35,12 +36,37 @@ function currentItems(): FindingItem[] {
}
}
/** A place mounted without the navigation (a test harness): no layer ever opens. */
const NO_LAYER: FindingLayer = {
view: null,
guards: {
register: () => undefined,
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
},
open: () => undefined,
start: () => undefined,
close: () => true,
replace: () => undefined,
openCitations: () => undefined,
announce: () => undefined,
}
const ADD_BUTTON: Record<string, string> = {
zone: 'finding-add-zone',
category: 'finding-add-category',
node: 'finding-add-node',
}
/** The deletion flow: the target, the item to select after it, and the focus left behind. */
function useFindingDeletion(
items: readonly FindingItem[],
selectedId: string | null,
select: (id: string | null) => void,
focusItem: (id: string | null) => void,
actions: {
select: (id: string | null) => void
focusItem: (id: string | null) => void
closeLayer: () => void
},
) {
const locale = useLocaleStore((s) => s.locale)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
@@ -49,29 +75,100 @@ function useFindingDeletion(
setFallback(fallbackAfterRemoval(items, item))
setDeleting({ key: item.key, label: item.name[locale] })
}
// The element is gone: its dialog closes in the same move (replace, no Back step) and
// the focus lands on the nearest row once every dialog is closed.
const closeDelete = () => {
setDeleting(null)
const gone = !currentItems().some((item) => item.id === selectedId)
if (gone) {
select(fallback)
focusItem(fallback)
}
if (currentItems().some((item) => item.id === selectedId)) return
actions.select(fallback)
actions.closeLayer()
afterModalsClosed(() => actions.focusItem(fallback))
}
return { deleting, askDelete, closeDelete }
}
/** Constats: the tree zones → categories → nodes, edited one command at a time. */
/** The layer's element follows the view: a Back or a reload selects and shows its row. */
function useSelectionOfLayer(
layer: FindingLayer,
items: readonly FindingItem[],
show: (found: { item: FindingItem; ancestors: string[] }) => void,
) {
const { view } = layer
const wanted = view && 'key' in view ? JSON.stringify(view.key) : null
useEffect(() => {
const found = wanted && itemForKey(items, JSON.parse(wanted))
if (found) show(found)
// `show` only sets state; the layer's key and the tree are what it follows.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [wanted, items])
}
/**
* The element the dialog shows vanished (a reload after a conflict): the layer closes by
* replace and says so; a creation whose parent vanished closes silently.
*/
function useGoneRule(layer: FindingLayer, loaded: boolean) {
const t = useT()
const { view } = layer
const handled = useRef<string | null>(null)
useEffect(() => {
if (!view) handled.current = null
if (!loaded || !view) return
const named = 'key' in view
const key = named ? view.key : view.create.parent
const stamp = JSON.stringify(view)
const present = (i: FindingItem) => key !== null && sameKey(i.key, key)
if (key === null || currentItems().some(present)) return
if (handled.current === stamp) return
handled.current = stamp
// After this commit's effects: a tile in edit re-registers its guard in them, and the
// forced close below must still be able to ask it.
queueMicrotask(() =>
layer.replace(null, named ? t('editor.findings.gone') : undefined),
)
}, [loaded, view, layer, t])
}
/** Where a closed dialog returns the focus: its tree row, or the button that started it. */
function useReturnTarget(view: FindingLayer['view']) {
const last = useRef(view)
if (view) last.current = view
return useCallback((): HTMLElement | null => {
const shown = last.current
if (!shown) return null
if ('create' in shown) {
return document.getElementById(ADD_BUTTON[shown.create.kind])
}
const wanted = JSON.stringify(shown.key)
return visibleElement('[data-finding-key]', (el) => {
return el.dataset.findingKey === wanted
})
}, [])
}
/** The creation the view holds, with its parent read from the tree; null when none. */
function pendingOf(
view: FindingLayer['view'],
items: readonly FindingItem[],
): PendingFinding | null {
if (!view || !('create' in view)) return null
const { kind, parent } = view.create
const found = parent ? itemForKey(items, parent) : null
if (parent && !found) return null
return { kind: kind as FindingKind, parent: found?.item ?? null }
}
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
export default function FindingsTab({
readOnly,
focus,
openCitations,
layer = NO_LAYER,
}: EditorPlaceProps) {
const t = useT()
const doc = useSheetDocument()
const [selectedId, setSelectedId] = useState<string | null>(null)
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
const [seeded, setSeeded] = useState(false)
const [pending, setPending] = useState<PendingFinding | null>(null)
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
const clearFocusId = useCallback(() => setFocusId(null), [])
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
@@ -82,6 +179,10 @@ export default function FindingsTab({
)
}
const selected = items.find((item) => item.id === selectedId)
const reveal = (found: { item: FindingItem; ancestors: string[] }) => {
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
setSelectedId(found.item.id)
}
const toggle = (id: string, open: boolean) => {
if (!open && selectedId && isUnder(items, selectedId, id)) {
setSelectedId(id)
@@ -96,23 +197,32 @@ export default function FindingsTab({
useFocusRequest(focus, (target) => {
const found = target.key && itemForKey(items, target.key)
if (!found) return 'none'
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
setSelectedId(found.item.id)
reveal(found)
setFocusId({ id: found.item.id })
return 'found'
})
const created = (id: string, parent: FindingItem | null) => {
if (!pending) return
useSelectionOfLayer(layer, items, reveal)
useGoneRule(layer, doc !== null)
const created = (
id: string,
parent: FindingItem | null,
kind: FindingKind,
) => {
if (parent) toggle(parent.id, true)
setSelectedId(createdItemId(pending.kind, parent, id))
setPending(null)
setSelectedId(createdItemId(kind, parent, id))
layer.replace(createdKey(kind, parent, id))
}
const { deleting, askDelete, closeDelete } = useFindingDeletion(
items,
selectedId,
setSelectedId,
(id) => setFocusId(id ? { id } : null),
{
select: setSelectedId,
focusItem: (id) => setFocusId(id ? { id } : null),
closeLayer: () => layer.replace(null),
},
)
const { view } = layer
const shown = view && 'key' in view ? itemForKey(items, view.key) : null
return (
<section
data-testid="editor-tab-findings"
@@ -123,18 +233,8 @@ export default function FindingsTab({
selected={selected}
hasZone={items.some((item) => item.kind === 'zone')}
readOnly={readOnly}
onStart={setPending}
onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)}
/>
{pending && (
<EditOnly readOnly={readOnly}>
<FindingCreateForm
key={`${pending.kind}-${pending.parent?.id ?? ''}`}
pending={pending}
onCreated={created}
onCancel={() => setPending(null)}
/>
</EditOnly>
)}
{doc && items.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.empty')}
@@ -145,21 +245,23 @@ export default function FindingsTab({
selectedId={selected?.id ?? null}
expanded={expanded}
onSelect={setSelectedId}
onActivate={(item) => {
setSelectedId(item.id)
layer.open(item.key)
}}
onToggle={toggle}
focusId={focusId}
onFocused={clearFocusId}
/>
{selected && (
<FindingDetail
key={selected.id}
item={selected}
readOnly={readOnly}
onDelete={() => askDelete(selected)}
onShowReferences={
openCitations && ((opener) => openCitations(selected.key, opener))
}
/>
)}
<FindingDialog
layer={layer}
item={shown?.item ?? null}
pending={pendingOf(view, items)}
readOnly={readOnly}
returnFocus={useReturnTarget(view)}
onDelete={askDelete}
onCreated={created}
/>
<DeleteDialog target={deleting} onClose={closeDelete} />
</section>
)
+4
View File
@@ -9,6 +9,8 @@ export interface DialogProps {
onClose: () => unknown
/** Where the focus goes after the close (ModalDialog): a target, or null when a move owns it. */
returnFocus?: ModalDialogProps['returnFocus']
/** A view layer of the editor (ModalDialog): a Back may close it. */
layer?: boolean
title: string
/** The dialog's message, announced with its name (aria-describedby). */
description?: ReactNode
@@ -32,6 +34,7 @@ export default function Dialog({ open, ...surface }: DialogProps) {
function DialogSurface({
onClose,
returnFocus,
layer,
title,
description,
children,
@@ -46,6 +49,7 @@ function DialogSurface({
<ModalDialog
onClose={onClose}
returnFocus={returnFocus}
layer={layer}
labelledBy={titleId}
describedBy={description ? descriptionId : undefined}
className="open:flex items-center justify-center p-3 sm:p-4"
+36 -7
View File
@@ -20,6 +20,16 @@ export interface ModalDialogProps {
* move that closed it.
*/
returnFocus?: (() => HTMLElement | null) | null
/**
* Escape typed where this answers true is swallowed: no close request. For a part that
* still edits inline (the citations sheet's tiles) and keeps Escape for the field.
*/
ignoreEscape?: (target: EventTarget) => boolean
/**
* A view layer of the editor (R2F-1): its state is in the browser history, so a Back
* may close it. Any other modal open refuses a Back.
*/
layer?: boolean
/** Id of the visible title; `label` names a dialog that shows none. */
labelledBy?: string
label?: string
@@ -62,8 +72,9 @@ function ancestorsOf(element: HTMLElement | null): HTMLElement[] {
}
/**
* The resolved target when it takes focus, else the opener when it still does, else the
* first control of its nearest container still on the page.
* The resolved target when it takes focus; else, if the focus is nowhere (`body`), the
* opener when it still does, else the first control of its nearest container still on
* the page. A focus another closing dialog already placed is left alone.
*/
function restoreFocus(
target: HTMLElement | null,
@@ -71,6 +82,8 @@ function restoreFocus(
ancestors: HTMLElement[],
): void {
if (target && tryFocus(target, true)) return
const active = document.activeElement
if (active && active !== document.body) return
if (!opener || tryFocus(opener)) return
for (const container of ancestors) {
if (!container.isConnected) continue
@@ -92,6 +105,8 @@ function restoreFocus(
export default function ModalDialog({
onClose,
returnFocus,
ignoreEscape,
layer,
labelledBy,
label,
describedBy,
@@ -101,8 +116,12 @@ export default function ModalDialog({
const ref = useRef<HTMLDialogElement>(null)
const latest = useRef({ returnFocus, onClose })
latest.current = { returnFocus, onClose }
const isPresent = useIsPresent()
const present = useRef(true)
present.current = useIsPresent()
present.current = isPresent
// The `close` event of the cleanup's own `close()` is no request (a DOM that fires it
// at once, as the test DOM does, would otherwise reach the consumer).
const closingSelf = useRef(false)
useLayoutEffect(() => {
const dialog = ref.current
@@ -116,7 +135,11 @@ export default function ModalDialog({
// panel when the content is long, the close button otherwise.
dialog.querySelector<HTMLElement>(FOCUSABLE)?.focus()
return () => {
if (dialog.open) dialog.close()
if (dialog.open) {
closingSelf.current = true
dialog.close()
closingSelf.current = false
}
// After the commit: the render that closes the dialog may remove the opener
// too. A dialog still on screen was only remounted (React StrictMode).
queueMicrotask(() => {
@@ -124,7 +147,9 @@ export default function ModalDialog({
if (!dialog.isConnected && resolve !== null) {
restoreFocus(resolve?.() ?? null, opener, ancestors)
}
flushAfterModals()
// After the restores of every dialog closed in this commit: a landing that
// waited for them must not be undone by a later one.
queueMicrotask(flushAfterModals)
})
}
}, [])
@@ -136,7 +161,8 @@ export default function ModalDialog({
event.preventDefault()
event.stopPropagation()
// A held key repeats: only the first press asks.
if (!event.repeat) onClose()
if (event.repeat || ignoreEscape?.(event.target)) return
onClose()
}
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault()
@@ -147,7 +173,7 @@ export default function ModalDialog({
// A refused close shows the dialog again, never during an exit or once it is gone.
const onClosed = () => {
const dialog = ref.current
if (!dialog || dialog.open) return
if (!dialog || dialog.open || closingSelf.current) return
const refused = latest.current.onClose() === 'kept'
if (refused && present.current && dialog.isConnected) dialog.showModal()
}
@@ -155,6 +181,9 @@ export default function ModalDialog({
return (
<dialog
ref={ref}
// A dialog playing its exit answers nothing: a second click or key is lost.
inert={!isPresent}
data-layer={layer ? '' : undefined}
aria-labelledby={labelledBy}
aria-label={label}
aria-describedby={describedBy}
+1 -3
View File
@@ -7,7 +7,6 @@ import {
isTextField,
visibleElement,
} from '@/editor/focusRequest'
import { ReferencesOpenContext } from '@/editor/editingContext'
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
@@ -102,8 +101,7 @@ export function useSelectionEscape(
) {
const asideRef = useRef<HTMLElement>(null)
const deselect = useDeselect(id, clear)
const citationsOf = useContext(ReferencesOpenContext)
useEscapeDeselect(active && citationsOf === null, (event) =>
useEscapeDeselect(active, (event) =>
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
)
return { asideRef, byDrawing: deselect.byDrawing }
+11 -12
View File
@@ -1,31 +1,30 @@
import { createContext, useContext, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { EditorMode } from './mode'
import { usePlaceVisible } from '@/lib/placeVisibility'
/** The editor cannot be edited now (route rule: mode, recovery, store not in step). */
export const ReadOnlyContext = createContext(false)
/**
* The finding whose citations panel is open, null when none. Set from the opening to the
* end of the exit animation: a place beside the panel is not where a modal may open, and
* only that finding's trigger reads « expanded ».
*/
export const ReferencesOpenContext = createContext<ElementKey | null>(null)
/** Why the editor is read-only, or `edit`: a kept form words its notice from it. */
export const EditorModeContext = createContext<EditorMode>('edit')
export function useEditorMode(): EditorMode {
return useContext(EditorModeContext)
}
export function useEditorReadOnly(): boolean {
return useContext(ReadOnlyContext)
}
/**
* Whether a decision dialog of a kept part may open: only while editing, in a shown
* place, with the citations panel closed, so no native modal ever sits inside a hidden
* subtree and focus is never lost to `body`.
* Whether a decision dialog of a kept part may open: only while editing and in a shown
* place, so no native modal ever sits inside a hidden subtree and focus is never lost
* to `body`.
*/
export function useDecisionsOpen(): boolean {
const readOnly = useContext(ReadOnlyContext)
const citationsOf = useContext(ReferencesOpenContext)
const visible = usePlaceVisible()
return !readOnly && visible && citationsOf === null
return !readOnly && visible
}
/**
+16
View File
@@ -0,0 +1,16 @@
import type { FindingLayer } from './tabs'
import type { EditorNavigation } from './useEditorNavigation'
/** What Constats needs of the navigation for its dialog and the sheet over it. */
export function findingLayerOf(nav: EditorNavigation): FindingLayer {
return {
view: nav.state.finding,
guards: nav.guards,
open: nav.openFinding,
start: nav.startFinding,
close: nav.closeFinding,
replace: nav.replaceFinding,
openCitations: nav.openCitations,
announce: nav.announce,
}
}
+11
View File
@@ -246,6 +246,17 @@ export function createdItemId(
return itemId(parent.zoneId, path)
}
/** The key of a just-inserted element, appended under `parent` (null = a zone). */
export function createdKey(
kind: FindingKind,
parent: FindingItem | null,
id: string,
): ElementKey {
if (kind === 'zone' || !parent) return { kind: 'zone', id }
const path = kind === 'category' ? [id] : [...parent.path, id]
return { kind: 'finding', zone_id: parent.zoneId, path }
}
/** The item a focus request names (a zone or a finding), with its ancestors' ids. */
export function itemForKey(
items: readonly FindingItem[],
+40 -12
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useEffect, useRef } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import type {
AnnotationSection,
EditorTarget,
@@ -82,21 +83,34 @@ export function visibleElement(
)
}
/** The visible row tagged with `key`. */
function rowOf(key: ElementKey): HTMLElement | null {
const wanted = JSON.stringify(key)
return visibleElement(
'[data-focus-key]',
(candidate) => candidate.dataset.focusKey === wanted,
)
}
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
export function focusRow(key: ElementKey): boolean {
const wanted = JSON.stringify(key)
const row = [
...document.querySelectorAll<HTMLElement>('[data-focus-key]'),
].find(
(candidate) =>
candidate.dataset.focusKey === wanted && !candidate.closest('[hidden]'),
)
const row = rowOf(key)
if (!row) return false
row.scrollIntoView?.({ block: 'center' })
row.focus()
return document.activeElement === row
}
/**
* The row is there: its focus waits for the dialogs a move closed (the page behind them
* is inert until then). False when no visible row carries `key`.
*/
export function focusRowLater(key: ElementKey): boolean {
if (!rowOf(key)) return false
afterModalsClosed(() => void focusRow(key))
return true
}
/** Row-based places (Général, Vues, Catégories, Régions): focus the named row. */
export function useRowFocus(focus: FocusRequest | undefined): void {
useFocusRequest(focus, (target) =>
@@ -132,13 +146,17 @@ export function isTextField(target: EventTarget | null): boolean {
/**
* Commits the text being typed before a place is left: blurs the focused field, so its
* `TextField` commits on blur. Safari and iPadOS do not move the focus to a tapped button,
* so the blur is forced rather than assumed. Answers whether a field was blurred.
* so the blur is forced rather than assumed. A field of a transactional form
* (`data-draft-form`) is a local draft nothing commits: it keeps its focus. Answers
* whether a field was blurred.
*/
export function commitFocusedField(): boolean {
const active = document.activeElement
const isField = isTextField(active)
if (isField) (active as HTMLElement).blur()
return isField
if (!isTextField(active)) return false
const field = active as HTMLElement
if (field.closest('[data-draft-form]')) return false
field.blur()
return true
}
/** The tab shown, or « Plus » while the shown tab sits in the closed list. */
@@ -154,6 +172,15 @@ export function focusActiveTab(options?: FocusOptions): void {
activeTabButton()?.focus(options)
}
/**
* 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.)
*/
function inOpenDialog(element: HTMLElement): boolean {
return element.closest('dialog[open] [data-draft-form]') !== null
}
/** The element holding the focus, when it is something other than `body`. */
export function heldElement(): HTMLElement | null {
const active = document.activeElement
@@ -178,7 +205,7 @@ export function refocusIfHidden(
held: HTMLElement | null,
home: HTMLElement | null = null,
): void {
if (!held) return
if (!held || inOpenDialog(held)) return
const gone = !held.isConnected || held.closest('[hidden]')
if (!gone && document.activeElement !== held) held.focus()
if (!gone && document.activeElement === held) return
@@ -193,6 +220,7 @@ export function refocusIfHidden(
*/
export function releaseEditFocus(): void {
const held = heldElement()
if (held && inOpenDialog(held)) return
commitFocusedField()
refocusIfHidden(held)
}
+60 -8
View File
@@ -1,5 +1,7 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
ANNOTATION_SECTIONS,
isFindingNode,
sameView,
type AnnotationSection,
type EditorView,
@@ -32,24 +34,66 @@ export const ENTRY_KEY = 'editorEntry'
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
/** A finding or zone key as the tree builds it, or null when `raw` is no such key. */
function sanitizeKey(raw: unknown): ElementKey | null {
if (!isRecord(raw)) return null
if (raw.kind === 'zone' && typeof raw.id === 'string') {
return { kind: 'zone', id: raw.id }
}
const { zone_id: zoneId, path } = raw
const ids = Array.isArray(path) && path.every((id) => typeof id === 'string')
if (raw.kind !== 'finding' || typeof zoneId !== 'string' || !ids) return null
return { kind: 'finding', zone_id: zoneId, path: path as string[] }
}
const CREATION_KINDS = ['zone', 'category', 'node']
/** A finding creation, a form: only read back where forms are kept. */
function sanitizeCreation(raw: unknown): EditorView['finding'] {
if (!isRecord(raw) || !isRecord(raw.create)) return null
const { kind, parent } = raw.create
if (typeof kind !== 'string' || !CREATION_KINDS.includes(kind)) return null
const key = parent === null ? null : sanitizeKey(parent)
if (parent !== null && key === null) return null
return { create: { kind, parent: key } }
}
/** The finding layer of a view: its dialog, with its citations sheet over it. */
function sanitizeFinding(raw: unknown, forms: boolean): EditorView['finding'] {
if (!isRecord(raw)) return null
if ('create' in raw) return forms ? sanitizeCreation(raw) : null
const key = sanitizeKey(raw.key)
if (!key) return null
const sheet = raw.citations === true && isFindingNode(key)
return { key, citations: sheet }
}
/**
* A view read back from a history entry, or null when it is no view. Vanished keys drop
* their layer: no layer is ever written yet, so the three layer fields come back null.
* shortcut: later layers validate their key against the loaded sheet here.
* 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.
*/
export function sanitizeView(raw: unknown): EditorView | null {
export function sanitizeView(raw: unknown, forms = true): EditorView | null {
if (!isRecord(raw)) return null
if (!EDITOR_TABS.includes(raw.tab as EditorTabId)) return null
const known = ANNOTATION_SECTIONS.includes(raw.section as AnnotationSection)
const finding =
raw.tab === 'findings' ? sanitizeFinding(raw.finding, forms) : null
return {
tab: raw.tab as EditorTabId,
section: known ? (raw.section as AnnotationSection) : 'drawing',
finding: null,
finding,
reference: null,
referenceFilter: null,
}
}
/** The view a reload shows for an entry: its reading layers, never a form. */
export function withoutForms(view: EditorView): EditorView {
return sanitizeView(view, false) ?? view
}
/** The entry `state` (a `location.state`) carries, or null when it carries none. */
export function readEntry(state: unknown): HistoryEntry | null {
const raw = isRecord(state) ? state[ENTRY_KEY] : null
@@ -76,9 +120,14 @@ export function ownedEntry(
export const entryState = (entry: HistoryEntry) => ({ [ENTRY_KEY]: entry })
/** Layers over the place: a finding dialog or a reference dialog each count one. */
/**
* Layers over the place: the finding dialog and the citations sheet over it, the
* reference dialog, each count one.
*/
export function layerCount(view: EditorView): number {
return (view.finding ? 1 : 0) + (view.reference ? 1 : 0)
const { finding } = view
const sheet = finding && 'key' in finding && finding.citations
return (finding ? 1 : 0) + (sheet ? 1 : 0) + (view.reference ? 1 : 0)
}
/** An Annotations section other than the drawing is a step over it, like a layer. */
@@ -88,6 +137,8 @@ function isStepOver(view: EditorView): boolean {
/** True when the move took a layer away, or left a section for its drawing. */
function isRemoval(top: EditorView, view: EditorView): boolean {
// Another tab is a move of its own (« Tout afficher », « Aller à »): it pushes.
if (view.tab !== top.tab) return false
if (layerCount(view) < layerCount(top)) return true
const backToDrawing = view.tab === top.tab && isStepOver(top)
return backToDrawing && !isStepOver(view) && layerCount(view) === 0
@@ -108,10 +159,11 @@ export function planWrite(
replace: boolean,
): HistoryWrite {
if (sameView(top.view, view)) return 'none'
if (replace) return 'replace'
if (isRemoval(top.view, view)) {
return top.below && sameView(top.below, view) ? 'back' : 'replace'
}
return replace ? 'replace' : 'push'
return 'push'
}
/** Sliding-window budget of history writes: past it a view stays in memory. */
+71 -31
View File
@@ -14,6 +14,7 @@ import {
entryState,
ownedEntry,
planWrite,
withoutForms,
type HistoryEntry,
type HistoryOwner,
} from './entry'
@@ -28,8 +29,8 @@ const BACK_TIMEOUT_MS = 1_000
interface Book {
/** The entry on top of the history as the adapter knows it (null before the mount). */
entry: HistoryEntry | null
/** The router key last looked at, so each location is read once. */
handled: string | null
/** The router location last read: each location object is read once (see `usePop`). */
seen: object | null
pendingBack: boolean
backTimer: ReturnType<typeof setTimeout> | undefined
/** Scroll position of the entries left, by entry id. */
@@ -41,7 +42,7 @@ interface Book {
function newBook(): Book {
return {
entry: null,
handled: null,
seen: null,
pendingBack: false,
backTimer: undefined,
scrolls: new Map(),
@@ -54,6 +55,8 @@ function newBook(): Book {
interface Landing {
entry: HistoryEntry
tabChanged: boolean
/** A dialog opened or closed: its own focus (first control, return target) stands. */
layerChanged: boolean
}
/**
@@ -131,14 +134,29 @@ function useReconcile(
}, [view, nav.trace, book, writer])
}
/** The page shows something the history does not carry: a POP must not unmount it. */
function popRefused(nav: EditorNavigation): boolean {
/** The layers (dialogs) two views show: a POP between them opens or closes a dialog. */
function sameLayers(a: EditorView, b: EditorView): boolean {
return (
document.querySelector('dialog[open]') !== null ||
nav.state.citationsOf !== null
JSON.stringify([a.finding, a.reference]) ===
JSON.stringify([b.finding, b.reference])
)
}
/**
* A POP the page must not follow: a modal that is no layer is open (its place-scoped
* state is not in the history), or a dirty layer would be removed. Either way the layers
* are asked, so a dirty form shows its own confirmation.
*/
function popRefused(ctx: PopContext, entry: HistoryEntry | null): boolean {
const { nav, view, defaultView } = ctx
if (document.querySelector('dialog[open]:not([data-layer])')) {
nav.guards.askAll(false)
return true
}
if (sameLayers(entry?.view ?? defaultView, view)) return false
return !nav.guards.askAll(false).allowed
}
interface PopContext {
nav: EditorNavigation
book: Book
@@ -153,47 +171,65 @@ function landOnForeign(ctx: PopContext): Landing | null {
const { nav, writer, defaultView, book } = ctx
writer.first(defaultView)
nav.restoreView(defaultView)
return book.entry && { entry: book.entry, tabChanged: true }
return (
book.entry && { entry: book.entry, tabChanged: true, layerChanged: false }
)
}
/**
* Something the history does not carry is on screen: the view stays, the pre-POP view is
* pushed again above the entry landed on. A dirty form shows its own confirmation.
* pushed again above the entry landed on.
*/
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
const { nav, book, writer, view } = ctx
nav.guards.askAll(false)
const { book, writer, view } = ctx
if (landed) book.entry = landed
writer.push(view)
return null
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, owner, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
/** A `back()` this adapter asked for is expected: reads and clears the flag. */
function takePendingBack(book: Book): boolean {
const expected = book.pendingBack
book.pendingBack = false
clearTimeout(book.backTimer)
const entry = ownedEntry(state, owner)
if (!expected && popRefused(nav)) return refusePop(ctx, entry)
return expected
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
const expected = takePendingBack(book)
const entry = ownedEntry(state, ctx.owner)
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
if (!entry) return landOnForeign(ctx)
book.entry = entry
if (sameView(entry.view, view)) return null
nav.restoreView(entry.view)
return { entry, tabChanged: entry.view.tab !== view.tab }
return {
entry,
tabChanged: entry.view.tab !== view.tab,
layerChanged: !sameLayers(entry.view, view),
}
}
/** The first location of the editor: an entry of this sheet and account is kept, else replaced. */
/**
* The first location of the editor: an entry of this sheet and account is kept (a
* reload never reopens a form, so a form layer is replaced by the view without it),
* any other is replaced by the current view.
*/
function mount(ctx: PopContext, state: unknown): void {
const entry = ownedEntry(state, ctx.owner)
if (entry) ctx.book.entry = entry
else ctx.writer.first(ctx.view)
if (!entry) return ctx.writer.first(ctx.view)
ctx.book.entry = entry
const kept = withoutForms(entry.view)
if (!sameView(kept, entry.view)) ctx.writer.replace(kept)
}
/** Focus after a Back or Forward: the tab button, or the heading of a section reached. */
function landFocus({ entry, tabChanged }: Landing): void {
function landFocus({ entry, tabChanged, layerChanged }: Landing): void {
if (layerChanged && !tabChanged) return
const heading = tabChanged ? null : headingOf(shownPlace(entry.view))
if (heading) heading.focus({ preventScroll: true })
else focusActiveTab({ preventScroll: true })
@@ -215,6 +251,7 @@ function useLanding(
return afterModalsClosed(() => {
window.scrollTo(0, book.scrolls.get(id) ?? 0)
landFocus(landing)
if (landing.layerChanged && !landing.tabChanged) return
const section = view.tab === 'annotations' ? view.section : null
nav.announce(
moveText({ place: 'tab', tab: view.tab, section, key: null }),
@@ -246,23 +283,25 @@ function useManualScroll(): void {
}, [])
}
/** Each new location is read once: the first is the mount, a POP after it is a landing. */
/**
* Each new location is read once: the first is the mount, a POP after it is a landing.
* The router makes a new location object per navigation, so a Back onto a key this
* adapter already read (the entry it mounted on, or one whose push never rendered) is a
* new object and is read; the second run of an effect (StrictMode) sees the same one.
*/
function usePop(ctx: PopContext): Landing | null {
const location = useLocation()
const navType = useNavigationType()
const [landing, setLanding] = useState<Landing | null>(null)
const { book } = ctx
useEffect(() => {
// The type is part of the stamp: a POP back onto a key this adapter pushed, with the
// transition of a later push never rendered, is still a landing to read.
const stamp = `${location.key}|${navType}`
if (book.handled === stamp) return
book.handled = stamp
if (book.seen === location) return
book.seen = location
if (book.entry === null) mount(ctx, location.state)
else if (navType === 'POP') setLanding(landOn(ctx, location.state))
// Read once per location: the context is the one this render holds.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.key, navType])
}, [location])
return landing
}
@@ -271,7 +310,8 @@ function usePop(ctx: PopContext): Landing | null {
* reducer holds. A move dispatches at once and the history follows from one effect that
* compares the view with the last entry this adapter wrote (a ref, never `useLocation()`,
* which lags a transition). A Back or Forward restores the view of the entry it lands on,
* unless a dialog or the citations panel is open: then the pre-move view is pushed back.
* unless a modal that is no layer is open or a dirty layer would go: then the pre-move
* view is pushed back.
* Foreign entries (another sheet, another account) and entries without a view are replaced
* by the default view.
*/
+46 -16
View File
@@ -28,9 +28,10 @@ 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; `referenceFilter`
* narrows the references library to the citers of an element. Only `tab` and `section`
* are ever set so far: the three others are the room later layers fill.
* 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.
*/
export interface EditorView {
tab: EditorTabId
@@ -44,8 +45,6 @@ export interface EditorView {
}
export interface NavigationState extends EditorView {
/** The finding whose citations panel is open; null while it is closed. */
citationsOf: ElementKey | null
/** Bumped by `show_all_references`: the library resets its search once per bump. */
libraryReset: number
/** Places already shown, so a body mounts on first visit and stays mounted. */
@@ -60,6 +59,9 @@ export type NavigationAction =
| { type: 'select_tab'; tab: EditorTabId }
| { type: 'open_section'; section: AnnotationSection }
| { type: 'back_to_drawing' }
| { type: 'open_finding'; key: ElementKey }
| { type: 'create_finding'; kind: string; parent: ElementKey | null }
| { type: 'close_finding' }
| { type: 'open_citations'; citedBy: ElementKey }
| { type: 'close_citations' }
| { type: 'show_all_references' }
@@ -120,8 +122,8 @@ const DEFAULT_VIEW = {
referenceFilter: null,
} as const
/** The finding whose citations panel the view shows, null when it shows none. */
function citationsOfView(view: EditorView): ElementKey | null {
/** The finding whose citations sheet the view shows, null when it shows none. */
export function citationsOfView(view: EditorView): ElementKey | null {
const { finding } = view
return finding && 'key' in finding && finding.citations ? finding.key : null
}
@@ -139,7 +141,6 @@ export function initialNavigation(
const start = view ?? defaultView(tab)
return shown({
...start,
citationsOf: citationsOfView(start),
libraryReset: 0,
visitedTabs: [],
visitedSections: [],
@@ -178,7 +179,6 @@ function restoreView(
...state,
...view,
section,
citationsOf: citationsOfView(view),
focus: undefined,
})
}
@@ -191,9 +191,31 @@ export function isFindingNode(key: ElementKey): boolean {
return key.kind === 'finding' && key.path.length > 1
}
/** Only a finding node has a citations panel: any other key leaves the state as it is. */
/** Only a finding node has a citations sheet: any other key leaves the state as it is. */
function openCitations(state: NavigationState, citedBy: ElementKey) {
return isFindingNode(citedBy) ? { ...state, citationsOf: citedBy } : state
const finding = { key: citedBy, citations: true }
return isFindingNode(citedBy) ? shown({ ...state, finding }) : state
}
/** Closes the sheet only: the finding dialog under it stays. */
function closeCitations(state: NavigationState): NavigationState {
const { finding } = state
if (!finding || !('key' in finding)) return state
return { ...state, finding: { key: finding.key, citations: false } }
}
/** 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 })
}
/** The creation form of a zone, a category or a node, on the Constats tab. */
function createFinding(
state: NavigationState,
create: { kind: string; parent: ElementKey | null },
): NavigationState {
return shown({ ...state, tab: 'findings', finding: { create } })
}
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
@@ -202,19 +224,19 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState {
...state,
tab: target.tab,
section: target.section ?? state.section,
citationsOf: null,
finding: null,
focus: { target, serial },
serial,
}
return shown(moved)
}
/** « Tout afficher dans l'onglet Références »: the panel closes, the library starts afresh. */
/** « Tout afficher dans l'onglet Références »: the layers close, the library starts afresh. */
function showAllReferences(state: NavigationState): NavigationState {
const moved = {
...state,
tab: 'references' as const,
citationsOf: null,
finding: null,
libraryReset: state.libraryReset + 1,
}
return shown(moved)
@@ -226,20 +248,28 @@ export function navigationReducer(
): NavigationState {
switch (action.type) {
case 'select_tab':
return shown({ ...state, tab: action.tab, citationsOf: null })
return shown({ ...state, tab: action.tab, finding: null })
case 'open_section':
return shown({ ...state, section: action.section })
case 'back_to_drawing':
return shown({ ...state, section: 'drawing' })
case 'open_finding':
return openFinding(state, action.key)
case 'create_finding':
return createFinding(state, { kind: action.kind, parent: action.parent })
case 'close_finding':
console.trace('CLOSE_FINDING')
return { ...state, finding: null }
case 'open_citations':
return openCitations(state, action.citedBy)
case 'close_citations':
return { ...state, citationsOf: null }
return closeCitations(state)
case 'show_all_references':
return showAllReferences(state)
case 'go_to':
return goTo(state, action.target)
case 'restore_view':
console.trace('RESTORE', JSON.stringify(action.view.finding))
return restoreView(state, action.view)
case 'focus_consumed':
return state.focus?.serial === action.serial
+19 -3
View File
@@ -1,7 +1,8 @@
import type { ElementKey, PreviewState } from '@faunosteo/core-wasm/types'
import type { EditorTarget, FocusRequest } from './navigation'
import type { EditorTarget, EditorView, FocusRequest } from './navigation'
import { unmeasuredViews } from './issues'
import type { TabTier } from './useViewport'
import type { Guards } from './useEditorNavigation'
export const EDITOR_TABS = [
'general',
@@ -38,6 +39,21 @@ export function initialTab(state: PreviewState, tier: TabTier): EditorTabId {
return SHOWN[tier].includes(wanted) ? wanted : 'annotations'
}
/**
* What Constats needs of the navigation for its dialog (R2F-3): the layer the view
* holds and the moves on it. A user close answers false when a form refused it.
*/
export interface FindingLayer {
view: EditorView['finding']
guards: Guards
open: (key: ElementKey) => void
start: (kind: string, parent: ElementKey | null) => void
close: (forced?: boolean) => boolean
replace: (key: ElementKey | null, text?: string) => void
openCitations: (citedBy: ElementKey, opener?: HTMLElement | null) => 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. */
@@ -46,8 +62,8 @@ export interface EditorPlaceProps {
navigate: (target: EditorTarget) => void
/** « Aller à … » with an element: the place seeds its own selection from it once. */
focus?: FocusRequest
/** Opens the citations panel of one finding (only Constats offers it). */
openCitations?: (citedBy: ElementKey, opener?: HTMLElement | null) => void
/** The finding dialog and the citations sheet over it (only Constats has them). */
layer?: FindingLayer
/** 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). */
-61
View File
@@ -1,61 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { NavigationAction } from './navigation'
/** Panel motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
export const PANEL_ENTER_S = 0.18
export const PANEL_EXIT_S = 0.14
/** The exit plus a margin: past it, a callback that never came is applied by the timer. */
const FALLBACK_MS = PANEL_EXIT_S * 1000 + 100
export type PendingKind =
| 'go_to'
| 'citations_closed'
| 'show_all'
| 'tab_selected'
/** The one move a close records: applied when the exit is over (P9). */
export interface PendingClose {
action: NavigationAction
kind: PendingKind
text: string
/** Said before `text`: a draft dropped by a forced close. It survives a replacement. */
note?: string
}
/**
* The close of the citations panel as a two-step move (P9, P28): `record` starts the exit
* (the page stays inert, the panel is inert too); `complete` runs once, from the panel's
* `onExitComplete` or from a one-shot timer when that never fires, and hands the pending
* move to `apply`. A second close is a no-op; a tab choice replaces the pending move.
*/
export function useCitationsExit(apply: (move: PendingClose) => void) {
const [exiting, setExiting] = useState(false)
const pending = useRef<PendingClose | null>(null)
const timer = useRef<number | undefined>(undefined)
const complete = useCallback(() => {
const move = pending.current
if (move === null) return
pending.current = null
window.clearTimeout(timer.current)
setExiting(false)
apply(move)
}, [apply])
const record = useCallback(
(move: PendingClose) => {
if (pending.current !== null) {
if (move.kind !== 'tab_selected') return
const note = pending.current.note ?? move.note
pending.current = note ? { ...move, note } : move
return
}
pending.current = move
setExiting(true)
timer.current = window.setTimeout(complete, FALLBACK_MS)
},
[complete],
)
const busy = useCallback(() => pending.current !== null, [])
useEffect(() => () => window.clearTimeout(timer.current), [])
return { exiting, record, complete, busy }
}
+114 -175
View File
@@ -13,13 +13,13 @@ import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import { useT } from '@/i18n/useT'
import {
commitFocusedField,
focusActiveTab,
placeOf,
visibleElement,
type FocusOutcome,
type PlaceName,
} from './focusRequest'
import {
citationsOfView,
initialNavigation,
isFindingNode,
navigationReducer,
@@ -30,27 +30,17 @@ import {
type NavigationState,
} from './navigation'
import { MORE_BUTTON_ID, tabDomId, type EditorTabId } from './tabs'
import {
useCitationsExit,
type PendingClose,
type PendingKind,
} from './useCitationsExit'
type MoveKind = PendingKind | 'section' | 'back'
type MoveKind = 'go_to' | 'show_all' | 'tab_selected' | 'section' | 'back'
/**
* A programmatic move: a new object per move, so the effect after it runs once.
* `afterExit`: it is the pending move of a closed panel, so a focus the user already
* placed elsewhere during the exit is left alone (P28).
*/
/** A programmatic move: a new object per move, so the effect after it runs once. */
interface Move {
kind: MoveKind
afterExit?: boolean
}
/**
* The panel's answer before a close (P22''): `allowed` false cancels a user close. A forced
* close always goes ahead; `note` (a draft dropped) is said with the close.
* A layer's answer before it is left (P22''): `allowed` false cancels a user move. A
* forced one always goes ahead; `note` (a draft dropped) is said with the move.
*/
export interface LeaveAnswer {
allowed: boolean
@@ -93,24 +83,29 @@ export interface EditorNavigation {
/** The polite live region's text; a repeat alternates a trailing no-break space. */
live: string
navigate: (target: EditorTarget) => void
/** False when the open panel refused the tab change (a refused field keeps the page). */
selectTab: (tab: EditorTabId, options?: SelectOptions) => boolean
openSection: (section: AnnotationSection, opener?: Opener) => void
backToDrawing: () => void
/** Opens the citations panel of a finding node; any other key is ignored. */
/** The finding dialog of `key`, in view mode. */
openFinding: (key: ElementKey) => void
/** The creation form of a zone, a category or a node, in the finding dialog. */
startFinding: (kind: string, parent: ElementKey | null) => void
/** A user close of the finding dialog; false when a layer refused it (a dirty form). */
closeFinding: (forced?: boolean) => boolean
/**
* The finding layer becomes another view of itself, by replace (no Back entry): the new
* element's dialog, or `null` for none. With `text`, a close the user did not ask for
* (the element vanished): forced, said once the dialogs are closed.
*/
replaceFinding: (key: ElementKey | null, text?: string) => void
/** Opens the citations sheet of a finding node; any other key is ignored. */
openCitations: (citedBy: ElementKey, opener?: Opener) => void
/** A user close (✕, Escape, scrim): the panel exits, then the focus goes to P6's fallbacks. */
closeCitations: () => void
/** The finding vanished: the same close, never refused (a refused draft is dropped, said). */
dropCitations: () => void
/** « Tout afficher dans l'onglet Références »: panel closed, tab shown, library reset. */
/** A user close of the sheet; false when a tile in edit refused it. */
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
/** The panel is playing its exit: the state still holds it, the page stays inert. */
exiting: boolean
/** The panel's `onExitComplete`: applies the pending move. */
exitComplete: () => void
/** The citations panel hands its `canLeave` over while it is mounted (P22''). */
registerCanLeave: (guard: CanLeave | null) => void
guards: Guards
trace: MoveTrace
/** A Back or Forward landed on `view` (the history adapter's way in): no move, no request. */
@@ -170,7 +165,7 @@ function useLiveRegion() {
waiting.current()
waiting.current = afterModalsClosed(() => {
const joined = queued.current.splice(0).join('. ')
setLive((previous) => (previous === joined ? `${joined} ` : joined))
setLive((previous) => (previous === joined ? `${joined} ` : joined))
})
}, [])
return { live, announce }
@@ -211,7 +206,7 @@ function useMoveTrace() {
}
interface Openers {
/** The trigger that opened the citations panel, and the finding it belongs to. */
/** The trigger that opened the citations sheet, and the finding it belongs to. */
citations: RefObject<HTMLElement | null>
citedBy: RefObject<ElementKey | null>
section: RefObject<HTMLElement | null>
@@ -219,22 +214,10 @@ interface Openers {
type Go = (action: NavigationAction, kind: MoveKind, text: string) => void
/**
* The one way to move: commit the typed text, announce, dispatch, record the move.
* `finish` is the same without the commit, for the move a closed panel recorded.
*/
/** The one way to move: commit the typed text, announce, dispatch, record the move. */
function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
const { live, announce } = useLiveRegion()
const [move, setMove] = useState<Move | null>(null)
const finish = useCallback(
(move: PendingClose) => {
announce(move.note ? `${move.note}. ${move.text}` : move.text)
trace.scrollY = window.scrollY
dispatch(move.action)
setMove({ kind: move.kind, afterExit: true })
},
[announce, dispatch, trace],
)
const go: Go = useCallback(
(action, kind, text) => {
commitFocusedField()
@@ -246,18 +229,12 @@ function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
},
[announce, dispatch, trace],
)
return { move, go, finish, live, announce }
return { move, go, live, announce }
}
/** Tab and section moves: « Aller à », a section entry, « Retour au dessin ». */
function useSectionMoves(go: Go, openers: Openers) {
const t = useT()
const moveText = useMoveText()
const navigate = useCallback(
(target: EditorTarget) =>
go({ type: 'go_to', target }, 'go_to', moveText(target)),
[go, moveText],
)
const openSection = useCallback(
(section: AnnotationSection, opener?: Opener) => {
openers.section.current = opener ?? null
@@ -271,101 +248,98 @@ function useSectionMoves(go: Go, openers: Openers) {
const text = `${t('editor.tab.annotations')} · ${t('editor.place.drawing')}`
go({ type: 'back_to_drawing' }, 'back', text)
}, [go, t])
return { navigate, openSection, backToDrawing }
return { openSection, backToDrawing }
}
/** What the panel's moves need of the hook: its state, the exit and the leave check. */
interface PanelContext {
open: boolean
go: Go
openers: Openers
/** What the layers' moves need of the hook. */
interface LayerContext {
dispatch: Dispatch<NavigationAction>
announce: (text: string) => void
exit: ReturnType<typeof useCitationsExit>
guards: Guards
mark: (replace?: boolean) => void
}
/**
* Records a close of the panel. A user close asks the panel first (P22''): a refused
* draft cancels it (false). While an exit is playing, a close is a no-op (a tab choice
* replaces the pending move) and asks nothing: the draft was settled by the first close.
* The finding dialog (R2F-3). A user close asks every layer first: a dirty form shows its
* own confirmation and the close is cancelled. `replaceFinding` is the move that is no
* Back step: the creation turned into its element, a deletion, an element that vanished.
*/
function useRequestClose(ctx: PanelContext) {
const { open, exit, guards, mark } = ctx
const { busy, record } = exit
return useCallback(
(move: PendingClose, forced: boolean): boolean => {
if (!open) return true
function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) {
const openFinding = useCallback(
(key: ElementKey) => {
mark()
if (busy()) {
record(move)
return true
}
commitFocusedField()
const { allowed, note } = guards.ask('citations', forced)
if (!allowed) return false
record(note ? { ...move, note } : move)
dispatch({ type: 'open_finding', key })
},
[dispatch, mark],
)
const startFinding = useCallback(
(kind: string, parent: ElementKey | null) => {
mark()
dispatch({ type: 'create_finding', kind, parent })
},
[dispatch, mark],
)
const closeFinding = useCallback(
(forced = false) => {
console.trace('closeFinding', forced)
if (!guards.askAll(forced).allowed) return false
mark()
dispatch({ type: 'close_finding' })
return true
},
[open, busy, record, guards, mark],
[guards, dispatch, mark],
)
const replaceFinding = useCallback(
(key: ElementKey | null, text?: string) => {
const note = text ? guards.askAll(true).note : undefined
if (text) announce(note ? `${note}. ${text}` : text)
mark(true)
dispatch(key ? { type: 'open_finding', key } : { type: 'close_finding' })
},
[guards, announce, dispatch, mark],
)
return { openFinding, startFinding, closeFinding, replaceFinding }
}
/** Opens the panel of a finding node: no move is recorded, the panel focuses itself. */
function useOpenCitations(ctx: PanelContext) {
const t = useT()
const { openers, dispatch, announce } = ctx
return useCallback(
/** 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 openCitations = useCallback(
(citedBy: ElementKey, opener?: Opener) => {
if (!isFindingNode(citedBy)) return
commitFocusedField()
openers.citations.current = opener ?? null
openers.citedBy.current = citedBy
announce(t('editor.references.panel_title'))
mark()
dispatch({ type: 'open_citations', citedBy })
},
[openers, dispatch, announce, t],
[openers, dispatch, mark],
)
const closeCitations = useCallback(() => {
if (!guards.ask('citations', false).allowed) return false
mark()
dispatch({ type: 'close_citations' })
return true
}, [guards, dispatch, mark])
return { openCitations, closeCitations }
}
/** The panel's closes: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
function useCloseMoves(ctx: PanelContext) {
/** « Aller à » and « Tout afficher » leave every layer: a layer in edit may refuse. */
function useLeavingMoves(go: Go, guards: Guards) {
const t = useT()
const moveText = useMoveText()
const { open, go } = ctx
const request = useRequestClose(ctx)
const closing = useCallback(
(forced: boolean) => {
const text = t('editor.live.references_closed')
request(
{ action: { type: 'close_citations' }, kind: 'citations_closed', text },
forced,
)
},
[request, t],
)
// With no panel open there is nothing to exit: the tab shows at once.
const showAllReferences = useCallback(() => {
const action = { type: 'show_all_references' } as const
const text = t('editor.tab.references')
if (!open) return go(action, 'show_all', text)
request({ action, kind: 'show_all', text }, false)
}, [open, go, request, t])
const navigate = useCallback(
(target: EditorTarget) => {
const action = { type: 'go_to', target } as const
request({ action, kind: 'go_to', text: moveText(target) }, false)
if (!guards.askAll(false).allowed) return
go({ type: 'go_to', target }, 'go_to', moveText(target))
},
[request, moveText],
[go, guards, moveText],
)
return {
closeCitations: useCallback(() => closing(false), [closing]),
dropCitations: useCallback(() => closing(true), [closing]),
showAllReferences,
navigate,
request,
}
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])
return { navigate, showAllReferences }
}
/** « Retour au dessin »: the entry that opened the section, else the canvas box. */
@@ -386,27 +360,6 @@ function triggerOf(openers: Openers): HTMLElement | null {
})
}
/** Focuses `element` and says whether it really holds the focus now. */
function focusHeld(element: HTMLElement | null): boolean {
element?.focus()
return element !== null && document.activeElement === element
}
/** Panel closed (P6): the trigger when it is shown, else the active tab's button. */
function focusAfterClose(openers: Openers) {
if (!focusHeld(triggerOf(openers))) focusActiveTab()
}
/** Nothing the user chose holds the focus: `body`, or what the closing panel still has. */
function focusIsFree(): boolean {
const active = document.activeElement
return (
active === null ||
active === document.body ||
active.closest('[data-place="citations"]') !== null
)
}
/** Where the focus lands after a programmatic move; never `body`. */
function landingOf(move: Move, state: NavigationState): HTMLElement | null {
if (move.kind === 'show_all') {
@@ -419,7 +372,8 @@ function landingOf(move: Move, state: NavigationState): HTMLElement | null {
/**
* After each move: a request an element answered is done; else (no owner answered, or
* the move had no request) the focus goes to the heading or the tab button.
* the move had no request) the focus goes to the heading or the tab button. Once the
* dialogs a move closed are gone: the page behind them was inert.
*/
function useMoveFocus(
move: Move | null,
@@ -439,10 +393,10 @@ function useMoveFocus(
if (outcome === 'found' || outcome === 'kept') return
dispatch({ type: 'focus_consumed', serial })
}
if (move.afterExit && !focusIsFree()) return
if (move.kind === 'citations_closed') focusAfterClose(openers)
else if (move.kind === 'back') backTarget(openers.section.current)?.focus()
else landingOf(move, state)?.focus()
afterModalsClosed(() => {
if (move.kind === 'back') backTarget(openers.section.current)?.focus()
else landingOf(move, state)?.focus()
})
}, [move, state, outcomes, dispatch, openers])
}
@@ -459,32 +413,30 @@ function useReceipts(dispatch: Dispatch<NavigationAction>) {
return { outcomes, consumed }
}
/** A tab choice; with the citations panel open it closes and the new tab takes the focus. */
/** A tab choice: the typed text is committed, the history asked for a push or a replace. */
function useTabSelect(
request: ReturnType<typeof useCloseMoves>['request'],
dispatch: Dispatch<NavigationAction>,
open: boolean,
mark: (replace?: boolean) => void,
) {
const t = useT()
return useCallback(
(tab: EditorTabId, options?: SelectOptions): boolean => {
const action = { type: 'select_tab', tab } as const
if (open) {
const text = t(`editor.tab.${tab}`)
const allowed = request({ action, kind: 'tab_selected', text }, false)
if (allowed) mark(options?.replace)
return allowed
}
commitFocusedField()
mark(options?.replace)
dispatch(action)
dispatch({ type: 'select_tab', tab })
return true
},
[request, dispatch, open, t, mark],
[dispatch, mark],
)
}
/** The sheet's finding is the one « X références » belongs to, even after a Back. */
function useCitedBy(state: NavigationState, openers: Openers) {
const citedBy = citationsOfView(state)
useEffect(() => {
if (citedBy) openers.citedBy.current = citedBy
}, [citedBy, openers])
}
/** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */
export function useEditorNavigation(
initialTab: EditorTabId,
@@ -494,41 +446,28 @@ export function useEditorNavigation(
initialNavigation(initialTab, initialView),
)
const { trace, mark } = useMoveTrace()
const { move, go, finish, live, announce } = useGo(dispatch, trace)
const { move, go, live, announce } = useGo(dispatch, trace)
const openers = useRef<Openers>({
citations: { current: null },
citedBy: { current: null },
section: { current: null },
}).current
const guards = useGuards()
const exit = useCitationsExit(finish)
const registerCanLeave = useCallback(
(guard: CanLeave | null) => guards.register('citations', guard),
[guards],
)
const open = state.citationsOf !== null
const receipts = useReceipts(dispatch)
useMoveFocus(move, state, receipts.outcomes, dispatch, openers)
const sections = useSectionMoves(go, openers)
const ctx = { open, go, openers, dispatch, announce, exit, guards, mark }
const openCitations = useOpenCitations(ctx)
const panel = useCloseMoves(ctx)
useCitedBy(state, openers)
const ctx = { dispatch, announce, guards, mark }
return {
state,
live,
announce,
consumed: receipts.consumed,
selectTab: useTabSelect(panel.request, dispatch, open, mark),
openSection: sections.openSection,
backToDrawing: sections.backToDrawing,
navigate: open ? panel.navigate : sections.navigate,
openCitations,
closeCitations: panel.closeCitations,
dropCitations: panel.dropCitations,
showAllReferences: panel.showAllReferences,
exiting: exit.exiting,
exitComplete: exit.complete,
registerCanLeave,
selectTab: useTabSelect(dispatch, mark),
...useSectionMoves(go, openers),
...useFindingLayer(ctx),
...useSheetLayer(ctx, openers),
...useLeavingMoves(go, guards),
citationsTrigger: useCallback(() => triggerOf(openers), [openers]),
guards,
trace,
restoreView: useCallback(
+9 -1
View File
@@ -1207,7 +1207,6 @@ export const en: Dict = {
'editor.section.back': 'Back to the drawing',
'editor.live.creation_kept': "A creation is in progress: finish or abandon it to reach this annotation.",
'editor.live.tracing_kept': "A tracing is in progress: finish or cancel it to reach this annotation.",
'editor.live.references_closed': 'References closed',
'editor.overview.label': 'Sheet overview',
'editor.overview.views': 'Views',
'editor.overview.view_main': 'Main view',
@@ -1635,6 +1634,15 @@ export const en: Dict = {
'editor.findings.references': 'Cited references',
'editor.findings.references_none': 'No reference cited.',
'editor.findings.reference_add': 'Cite a reference',
'editor.findings.edit': 'Edit',
'editor.findings.save': 'Save',
'editor.findings.saved': 'Changes saved',
'editor.findings.discard_ask': 'Discard your changes?',
'editor.findings.keep_typing': 'Keep editing',
'editor.findings.discard': 'Discard',
'editor.findings.gone': 'This finding no longer exists',
'editor.findings.flip_narrow': 'Widen the window to continue: your entry is kept.',
'editor.findings.flip_blocked': 'Editing is no longer possible: your entry is kept, you can only discard it.',
'editor.verification.title': 'Draft check',
'editor.verification.errors_one': '{count} blocking error',
'editor.verification.errors_other': '{count} blocking errors',
+9 -1
View File
@@ -1238,7 +1238,6 @@ export const fr: Dict = {
'editor.section.back': 'Retour au dessin',
'editor.live.creation_kept': "Une création est en cours : terminez-la ou abandonnez-la pour atteindre cette annotation.",
'editor.live.tracing_kept': "Un tracé est en cours : terminez-le ou annulez-le pour atteindre cette annotation.",
'editor.live.references_closed': 'Références fermées',
'editor.overview.label': 'Aperçu de la fiche',
'editor.overview.views': 'Vues',
'editor.overview.view_main': 'Vue principale',
@@ -1666,6 +1665,15 @@ export const fr: Dict = {
'editor.findings.references': 'Références citées',
'editor.findings.references_none': 'Aucune référence citée.',
'editor.findings.reference_add': 'Citer une référence',
'editor.findings.edit': 'Modifier',
'editor.findings.save': 'Enregistrer',
'editor.findings.saved': 'Modifications enregistrées',
'editor.findings.discard_ask': 'Abandonner les modifications ?',
'editor.findings.keep_typing': 'Continuer la saisie',
'editor.findings.discard': 'Abandonner',
'editor.findings.gone': "Ce constat n'existe plus",
'editor.findings.flip_narrow': 'Élargissez la fenêtre pour poursuivre : votre saisie est conservée.',
'editor.findings.flip_blocked': "La modification n'est plus possible : votre saisie est conservée, vous pouvez seulement l'abandonner.",
'editor.verification.title': 'Contrôle du brouillon',
'editor.verification.errors_one': '{count} erreur bloquante',
'editor.verification.errors_other': '{count} erreurs bloquantes',
+35
View File
@@ -0,0 +1,35 @@
import { act, screen, waitFor, within } from '@testing-library/react'
import type userEvent from '@testing-library/user-event'
type User = ReturnType<typeof userEvent.setup>
export const treeRow = (name: RegExp) => screen.getByRole('treeitem', { name })
/** The open finding dialog: the layer dialog that is not the citations sheet. */
export const findingDialog = () =>
[...document.querySelectorAll<HTMLElement>('dialog[open][data-layer]')].find(
(dialog) => !dialog.querySelector('[data-testid="editor-citations-panel"]'),
) ?? null
/** Expands a tree row from the keyboard: a click would open its dialog (R2F-3). */
export async function expandRow(user: User, name: RegExp) {
act(() => treeRow(name).focus())
await user.keyboard('{ArrowRight}')
}
/**
* Activates the row of `name` (a click): its dialog opens. The family is expanded first
* when the row is hidden under it.
*/
export async function openFinding(
user: User,
name: RegExp,
family: RegExp = /Cat A/,
) {
if (!screen.queryByRole('treeitem', { name })) await expandRow(user, family)
await user.click(treeRow(name))
await waitFor(() => expect(findingDialog()).not.toBeNull())
}
/** The dialog's content, queried like a place. */
export const inFindingDialog = () => within(findingDialog()!)
+38
View File
@@ -0,0 +1,38 @@
import { vi } from 'vitest'
import CitationsSheet from '@/components/editor/references/CitationsSheet'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import { findingLayerOf } from '@/editor/findingLayer'
import { citationsOfView } from '@/editor/navigation'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import { ReadOnlyContext } from '@/editor/editingContext'
/**
* Constats with the navigation that drives its dialog and the sheet over it (what the
* workspace gives it), without the rest of the editor.
*/
export default function FindingsHost({
readOnly = false,
}: {
readOnly?: boolean
}) {
const nav = useEditorNavigation('findings')
return (
<ReadOnlyContext value={readOnly}>
<FindingsTab
readOnly={readOnly}
navigate={vi.fn()}
reloadSheet={vi.fn()}
layer={findingLayerOf(nav)}
/>
<CitationsSheet
citedBy={citationsOfView(nav.state)}
readOnly={readOnly}
guards={nav.guards}
onClose={nav.closeCitations}
onShowAll={nav.showAllReferences}
navigate={nav.navigate}
returnFocus={nav.citationsTrigger}
/>
</ReadOnlyContext>
)
}
@@ -1,124 +0,0 @@
/** R2.4: the exit coordinator of the citations panel (P9, P28) and the gates it feeds. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
renderHook,
render,
screen,
} from '@testing-library/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
ReadOnlyContext,
ReferencesOpenContext,
useDecisionsOpen,
} from '@/editor/editingContext'
import {
PANEL_EXIT_S,
useCitationsExit,
type PendingClose,
} from '@/editor/useCitationsExit'
beforeEach(() => vi.useFakeTimers())
afterEach(() => {
cleanup()
vi.useRealTimers()
})
const move = (kind: PendingClose['kind']): PendingClose => ({
action: { type: 'close_citations' },
kind,
text: kind,
})
describe('useCitationsExit', () => {
it('applies the pending move once, from the callback', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('citations_closed')))
expect(result.current.exiting).toBe(true)
act(() => result.current.complete())
act(() => result.current.complete())
expect(apply).toHaveBeenCalledTimes(1)
expect(apply).toHaveBeenCalledWith(move('citations_closed'))
expect(result.current.exiting).toBe(false)
})
it('applies it from the one-shot timer when the callback never fires', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('show_all')))
act(() => void vi.advanceTimersByTime(PANEL_EXIT_S * 1000 + 99))
expect(apply).not.toHaveBeenCalled()
act(() => void vi.advanceTimersByTime(2))
expect(apply).toHaveBeenCalledTimes(1)
act(() => result.current.complete())
act(() => void vi.advanceTimersByTime(1000))
expect(apply).toHaveBeenCalledTimes(1)
})
it('a callback that comes first cancels the timer', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('go_to')))
act(() => result.current.complete())
act(() => void vi.advanceTimersByTime(1000))
expect(apply).toHaveBeenCalledTimes(1)
})
it('a second close is a no-op, a tab choice replaces the move', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('citations_closed')))
act(() => result.current.record(move('show_all')))
expect(result.current.busy()).toBe(true)
act(() => result.current.record(move('tab_selected')))
act(() => result.current.complete())
expect(apply).toHaveBeenCalledWith(move('tab_selected'))
})
it('a tab choice keeps the note of a forced close it replaces', () => {
const apply = vi.fn()
const { result } = renderHook(() => useCitationsExit(apply))
const note = 'Saisie non appliquée : Citation'
act(() => result.current.record({ ...move('citations_closed'), note }))
act(() => result.current.record(move('tab_selected')))
act(() => result.current.complete())
expect(apply).toHaveBeenCalledWith({ ...move('tab_selected'), note })
})
it('a timer left running does not fire after the editor is left', () => {
const apply = vi.fn()
const { result, unmount } = renderHook(() => useCitationsExit(apply))
act(() => result.current.record(move('citations_closed')))
unmount()
act(() => void vi.advanceTimersByTime(1000))
expect(apply).not.toHaveBeenCalled()
})
})
describe('useDecisionsOpen while the citations panel is open', () => {
const key: ElementKey = { kind: 'finding', zone_id: 'z', path: ['c', 'n'] }
const Probe = () => <p>{useDecisionsOpen() ? 'open' : 'held'}</p>
const within = (readOnly: boolean, citationsOf: ElementKey | null) =>
render(
<ReadOnlyContext value={readOnly}>
<ReferencesOpenContext value={citationsOf}>
<Probe />
</ReferencesOpenContext>
</ReadOnlyContext>,
)
it('holds every decision dialog back, panel open or still leaving (no modal in an inert page)', () => {
within(false, key)
expect(screen.getByText('held')).toBeInTheDocument()
})
it('lets them open once the panel is gone, and never while read-only', () => {
within(false, null)
expect(screen.getByText('open')).toBeInTheDocument()
cleanup()
within(true, null)
expect(screen.getByText('held')).toBeInTheDocument()
})
})
@@ -1,53 +0,0 @@
/** R2.4 fix: the layer's heading focus survives a reopen during a slow exit; it fits the viewport. */
import type { ComponentProps } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import { AnimatePresence } from 'motion/react'
import CitationsLayer from '@/components/editor/references/CitationsLayer'
import '../helpers/motion'
vi.mock('@/components/editor/references/CitationsPanel', () => ({
default: () => (
<h2 tabIndex={-1} data-place-heading>
Panel
</h2>
),
}))
afterEach(cleanup)
const props: ComponentProps<typeof CitationsLayer> = {
readOnly: false,
citedBy: { kind: 'finding', zone_id: 'z', path: ['c', 'n'] },
onClose: () => undefined,
onGone: () => undefined,
onShowAll: () => undefined,
navigate: () => undefined,
registerCanLeave: () => undefined,
}
const harness = (show: boolean) => (
<AnimatePresence>
{show && <CitationsLayer key="citations" {...props} />}
</AnimatePresence>
)
const heading = () => screen.getByRole('heading', { name: 'Panel' })
describe('CitationsLayer', () => {
it('focuses its heading again when reopened with the same key during the exit', async () => {
const view = render(harness(true))
await waitFor(() => expect(document.activeElement).toBe(heading()))
;(document.activeElement as HTMLElement).blur()
view.rerender(harness(false))
view.rerender(harness(true))
await waitFor(() => expect(document.activeElement).toBe(heading()))
})
it('writes a pixel height on the panel, never on the page', async () => {
render(harness(true))
const panel = heading().closest('[data-place="citations"]')!
.firstElementChild as HTMLElement
expect(panel.style.height).toMatch(/^\d+(\.\d+)?px$/)
expect(document.documentElement.style.height).toBe('')
})
})
+10 -15
View File
@@ -15,6 +15,7 @@ import ModalDialog from '@/components/ui/ModalDialog'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, edit, insert, point } from '../helpers/editorFixtures'
import { resetStore, serverHas, store } from '../helpers/editorHarness'
import { openFinding } from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
@@ -142,9 +143,7 @@ const citations = () => screen.queryByTestId('editor-citations-panel')
/** Constats, the node selected, its « 1 référence » trigger pressed. */
async function openCitations(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await openFinding(user, /Node A/)
await user.click(screen.getByRole('button', { name: '1 référence' }))
expect(citations()).not.toBeNull()
}
@@ -277,15 +276,21 @@ describe('Escape with the focus on the page', () => {
expect(panel()).toBeDefined()
})
it('the citations panel open: it closes, the annotation selection is kept', async () => {
it('the citations sheet open: Escape closes it only, the annotation selection is kept', async () => {
const user = await mount(WITH_NODE())
await select(user)
await openCitations(user)
const trigger = screen.getByRole('button', { name: '1 référence' })
expect(trigger).toHaveAttribute('aria-expanded', 'true')
escape(document.body)
await user.keyboard('{Escape}')
await waitFor(() => expect(citations()).toBeNull())
expect(trigger).toHaveAttribute('aria-expanded', 'false')
// the finding dialog under the sheet is still there: a second Escape closes it
expect(document.querySelector('dialog[open]')).not.toBeNull()
await user.keyboard('{Escape}')
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(panel()).toBeDefined()
})
@@ -317,16 +322,6 @@ describe('Escape with the focus on the page', () => {
})
describe('Escape and the other layers', () => {
it('closes the citations panel from the tab row, the selection kept', async () => {
const user = await mount(WITH_NODE())
await select(user)
await openCitations(user)
escape(screen.getByRole('tab', { name: 'Constats' }))
await waitFor(() => expect(citations()).toBeNull())
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(panel()).toBeDefined()
})
it('closes « Plus » first (small tier), the twin selection kept', async () => {
const user = await mount(TWO(), 500)
await select(user)
@@ -0,0 +1,415 @@
/** R2F-3: the finding dialog (view, edit, creation), its history entries and its guards. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Location, NavigateFunction } from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import { defaultView } from '@/editor/navigation'
import {
baseText,
resetStore,
serverHas,
SHEET,
store,
USER,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import {
findingDialog,
inFindingDialog,
openFinding,
treeRow,
} from '../helpers/findingDialog'
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(),
}))
let navigate: NavigateFunction
let location: Location
const probe = (n: NavigateFunction, l: Location) => {
navigate = n
location = l
}
const written = () =>
(location.state as Record<string, HistoryEntry> | null)?.[ENTRY_KEY]
const back = () => act(async () => navigate(-1))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const path = `/app/admin/sheets/${SHEET}/draft`
const name = (n: string) => ({ fr: n, en: n })
/** Zone A > Cat A > Node A (cites nothing). */
function sheetText(): string {
let text = insert(baseText(), {
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: [],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280): Promise<User> {
serverHas(sheetText(), 3)
const user = userEvent.setup()
mountDraft({ width, probe })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
return user
}
const doc = () => JSON.parse(store.getState().documentText)
const entries = () => store.getState().undo.length
const inDialog = () => inFindingDialog()
const modify = (user: User) =>
user.click(inDialog().getByRole('button', { name: 'Modifier' }))
const nameField = () => inDialog().getByLabelText('Nom (FR)')
const closed = () => waitFor(() => expect(findingDialog()).toBeNull())
describe('opening', () => {
it('a click, Enter and Space each select the row and open its dialog; the tree stays', async () => {
const user = await mount()
const before = screen.getAllByRole('treeitem').length
await openFinding(user, /Cat A/)
expect(treeRow(/Cat A/)).toHaveAttribute('aria-selected', 'true')
expect(inDialog().getByRole('heading', { name: 'Cat A' })).toBeVisible()
await user.click(inDialog().getByRole('button', { name: 'Fermer' }))
await closed()
treeRow(/Cat A/).focus()
await user.keyboard('{Enter}')
await waitFor(() => expect(findingDialog()).not.toBeNull())
await user.keyboard('{Escape}')
await closed()
await user.keyboard(' ')
await waitFor(() => expect(findingDialog()).not.toBeNull())
expect(screen.getAllByRole('treeitem')).toHaveLength(before)
})
it('writes one entry on open; Back closes it and the row holds the focus', async () => {
const user = await mount()
const first = written()!.id
await openFinding(user, /Cat A/)
await waitFor(() => expect(written()?.id).not.toBe(first))
expect(written()?.view.finding).toMatchObject({ citations: false })
expect(written()?.below?.finding).toBeNull()
await back()
await closed()
await waitFor(() => expect(document.activeElement).toBe(treeRow(/Cat A/)))
expect(written()?.id).toBe(first)
})
it('the close button asks nothing of a pristine view and pops its entry', async () => {
const user = await mount()
const first = written()!.id
await openFinding(user, /Cat A/)
await waitFor(() => expect(written()?.id).not.toBe(first))
await user.click(inDialog().getByRole('button', { name: 'Fermer' }))
await closed()
await waitFor(() => expect(written()?.id).toBe(first))
expect(document.activeElement).toBe(treeRow(/Cat A/))
})
})
describe('edit mode', () => {
it('a pristine « Enregistrer » is no command and no entry; a changed one is one', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
const before = entries()
await modify(user)
await user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
expect(entries()).toBe(before)
expect(inDialog().getByRole('button', { name: 'Modifier' })).toHaveFocus()
await modify(user)
await user.clear(nameField())
await user.type(nameField(), 'Renommée')
await user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
expect(entries()).toBe(before + 1)
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Renommée')
expect(inDialog().getByRole('status')).toHaveTextContent(
'Modifications enregistrées',
)
})
it('a blank name is refused on its field, nothing is written', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
const before = entries()
await user.clear(nameField())
await user.click(inDialog().getByRole('button', { name: 'Enregistrer' }))
expect(entries()).toBe(before)
expect(nameField()).toHaveFocus()
expect(nameField()).toHaveAccessibleDescription('Ce champ est obligatoire.')
})
it('« Annuler » with changes asks first; « Abandonner » commits nothing', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
const before = entries()
await user.type(nameField(), ' bis')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
expect(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
).toHaveFocus()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(nameField()).toHaveValue('Cat A bis')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(entries()).toBe(before)
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
expect(inDialog().getByRole('button', { name: 'Modifier' })).toBeVisible()
})
it('a dirty close request (Escape, ✕, a native cancel) asks and keeps the dialog', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
await user.type(nameField(), ' bis')
await user.keyboard('{Escape}')
expect(findingDialog()).not.toBeNull()
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
await user.click(inDialog().getByRole('button', { name: 'Fermer' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
fireEvent(findingDialog()!, new Event('cancel', { cancelable: true }))
expect(findingDialog()).not.toBeNull()
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
})
it('a Back with changes asks, keeps the page and the draft, then Abandonner pops once', async () => {
const user = await mount()
const first = written()!.id
await openFinding(user, /Cat A/)
await waitFor(() => expect(written()?.id).not.toBe(first))
await modify(user)
await user.type(nameField(), ' bis')
await back()
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
expect(findingDialog()).not.toBeNull()
fireEvent.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(nameField()).toHaveValue('Cat A bis')
fireEvent(findingDialog()!, new Event('cancel', { cancelable: true }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await closed()
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(entries()).toBe(0)
// The refused Back pushes the view again from an effect: the test router's low-priority
// transition lands up to 5 s later (a test-DOM artifact, a browser applies it at once).
}, 20_000)
})
describe('creation', () => {
it('is a layer of its own, replaced by the element after « Créer » (no extra entry)', async () => {
const user = await mount()
const first = written()!.id
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await waitFor(() => expect(written()?.id).not.toBe(first))
const creation = written()!.id
expect(written()?.view.finding).toEqual({
create: { kind: 'zone', parent: null },
})
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
await user.type(document.getElementById('finding-new-name-en')!, 'Head')
await user.click(
within(findingDialog()!).getByRole('button', { name: 'Créer' }),
)
await waitFor(() => expect(written()?.view.finding).toHaveProperty('key'))
expect(written()?.id).toBe(creation)
expect(doc().finding_zones).toHaveLength(2)
await back()
await closed()
expect(written()?.id).toBe(first)
})
it('a dirty creation asks before it closes and writes nothing', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
await user.keyboard('{Escape}')
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
await closed()
expect(doc().finding_zones).toHaveLength(1)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Ajouter une zone' }),
),
)
})
})
describe('read-only flip and the gone rule', () => {
it('1280 to 900 to 1280 keeps the draft and the focus, « Enregistrer » off meanwhile', async () => {
const user = await mount()
await openFinding(user, /Cat A/)
await modify(user)
await user.type(nameField(), ' bis')
const field = nameField()
act(() => {
setWidth(900)
window.dispatchEvent(new Event('resize'))
})
expect(nameField()).toBe(field)
expect(field).toHaveAttribute('readonly')
expect(field).toHaveFocus()
expect(inDialog().getByText(/Élargissez la fenêtre/)).toBeVisible()
expect(
inDialog().getByRole('button', { name: 'Enregistrer' }),
).toBeDisabled()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
act(() => {
setWidth(1280)
window.dispatchEvent(new Event('resize'))
})
expect(field).not.toHaveAttribute('readonly')
expect(field).toHaveValue('Cat A bis')
expect(field).toHaveFocus()
})
it('an element that vanishes closes its dialog by replace and says so', async () => {
const user = await mount()
await openFinding(user, /Node A/)
const open = written()!
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await closed()
await waitFor(() =>
expect(
document.querySelector('p.sr-only[aria-live="polite"]'),
).toHaveTextContent("Ce constat n'existe plus"),
)
expect(written()?.id).toBe(open.id)
expect(written()?.view.finding).toBeNull()
})
it('a reading dialog restored for a key the sheet lacks is dropped, with its announcement', async () => {
serverHas(sheetText(), 3)
const gone = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'gone'],
}
const view = {
...defaultView('findings'),
finding: { key: gone, citations: false },
}
const state = {
[ENTRY_KEY]: {
id: 'old',
view,
below: null,
sheetId: SHEET,
userId: USER,
},
}
mountDraft({ probe, entries: [{ pathname: path, state }] })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(findingDialog()).toBeNull()
expect(written()?.id).toBe('old')
await waitFor(() =>
expect(
document.querySelector('p.sr-only[aria-live="polite"]'),
).toHaveTextContent("Ce constat n'existe plus"),
)
})
it('a creation form in the entry is never restored by a reload', async () => {
serverHas(sheetText(), 3)
const view = {
...defaultView('findings'),
finding: { create: { kind: 'zone', parent: null } },
}
const state = {
[ENTRY_KEY]: {
id: 'old',
view,
below: null,
sheetId: SHEET,
userId: USER,
},
}
mountDraft({ probe, entries: [{ pathname: path, state }] })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(findingDialog()).toBeNull()
})
})
+246 -102
View File
@@ -1,17 +1,24 @@
/** Lot I: the Constats tree. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
ElementKey,
FindingNode,
} from '@faunosteo/core-wasm/types'
import FindingCreateForm from '@/components/editor/findings/FindingCreateForm'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree'
import { initialNavigation, navigationReducer } from '@/editor/navigation'
import { ReferencesOpenContext } from '@/editor/editingContext'
import {
citationsOfView,
initialNavigation,
navigationReducer,
} from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
@@ -21,6 +28,8 @@ import {
resetStore,
store,
} from '../helpers/editorHarness'
import { findingDialog, inFindingDialog } from '../helpers/findingDialog'
import FindingsHost from '../helpers/findingsHost'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
@@ -32,7 +41,7 @@ vi.mock('@faunosteo/supabase', async (orig) => ({
submitSheetReview: vi.fn(),
}))
const props = { readOnly: false, navigate: vi.fn(), reloadSheet: vi.fn() }
type User = ReturnType<typeof userEvent.setup>
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const name = (n: string) => ({ fr: n, en: n })
@@ -92,6 +101,33 @@ afterEach(() => {
const items = () => screen.getAllByRole('treeitem')
const labels = () => items().map((i) => i.textContent ?? '')
/** The X of the finding dialog: it closes and the row it opened from holds the focus. */
async function closeDialog(user: User) {
const dialog = findingDialog()!
await user.click(within(dialog).getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(findingDialog()).toBeNull())
}
/** Selects a row by activating it (its dialog opens) and closes the dialog again. */
async function pick(user: User, row: HTMLElement) {
await user.click(row)
await waitFor(() => expect(findingDialog()).not.toBeNull())
await closeDialog(user)
}
/** The deletion dialog stacked over the finding dialog: the last dialog of the page. */
async function deleteDialog() {
await waitFor(() =>
expect(document.querySelectorAll('dialog[open]')).toHaveLength(2),
)
return within(document.querySelectorAll('dialog[open]')[1] as HTMLElement)
}
/** The dialog's one « Enregistrer »: names, descriptions and the vet flag in one save. */
async function startEdit(user: User) {
await user.click(inFindingDialog().getByRole('button', { name: 'Modifier' }))
}
describe('findings tree model', () => {
it('flattens in order and hides collapsed branches', async () => {
await openReady({ text: treeText() })
@@ -124,7 +160,7 @@ describe('findings tree model', () => {
children: [],
review_status: 'inherited',
})
render(<FindingsTab {...props} />)
render(<FindingsHost />)
expect(screen.getAllByRole('treeitem').length).toBeGreaterThan(0)
})
@@ -184,7 +220,7 @@ describe('findings tree model', () => {
describe('Constats tab', () => {
it('renders a tree with levels, and zones carry no badge', async () => {
await openReady({ text: treeText() })
render(<FindingsTab {...props} />)
render(<FindingsHost />)
expect(screen.getByRole('tree')).toBeInTheDocument()
const [zoneA] = items()
expect(zoneA).toHaveAttribute('aria-level', '1')
@@ -197,7 +233,7 @@ describe('Constats tab', () => {
it('moves with the arrows, opens and closes branches', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
items()[0].focus()
await user.keyboard('{ArrowDown}')
expect(items()[1]).toHaveFocus()
@@ -217,7 +253,7 @@ describe('Constats tab', () => {
it('creates a zone only with both names', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
@@ -233,16 +269,17 @@ describe('Constats tab', () => {
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(doc().finding_zones).toHaveLength(3)
expect(doc().finding_zones[2].id).toMatch(/^zone-[a-z2-7]{10}$/)
expect(
screen.getByLabelText('Nom (FR)', { selector: '#finding-name-fr' }),
).toHaveValue('Tête')
// the creation turns into the view of the new element, in the same dialog
expect(inFindingDialog().getByText('Zone de constats')).toBeInTheDocument()
expect(document.querySelector('#finding-name-fr')).toHaveTextContent('Tête')
expect(document.querySelector('#finding-new-name-fr')).toBeNull()
})
it('creates a category with a kind and a node under the selection', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[0])
render(<FindingsHost />)
await pick(user, items()[0])
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
@@ -270,6 +307,8 @@ describe('Constats tab', () => {
kind: 'anamnesis',
review_status: 'to_confirm',
})
// the new category is selected behind its dialog: close it, add a node under it
await closeDialog(user)
await user.click(screen.getByRole('button', { name: 'Ajouter un constat' }))
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
@@ -301,7 +340,7 @@ describe('Constats tab', () => {
it('lands in the zone chosen in the form, not the zone of the selected node (C46)', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
items()[0].focus()
await user.keyboard('{ArrowDown}{ArrowRight}{ArrowRight}')
expect(items()[2]).toHaveAttribute('aria-selected', 'true')
@@ -325,7 +364,7 @@ describe('Constats tab', () => {
it('appends the category after the existing ones of the chosen zone', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
@@ -339,10 +378,10 @@ describe('Constats tab', () => {
it('is enabled with nothing selected and preselects nothing among several zones', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
const add = screen.getByRole('button', { name: 'Ajouter une catégorie' })
expect(add).toBeEnabled()
await user.click(items()[2])
await pick(user, items()[2])
await user.click(add)
expect(screen.getByLabelText('Zone')).toHaveValue('')
})
@@ -357,7 +396,7 @@ describe('Constats tab', () => {
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
@@ -369,7 +408,7 @@ describe('Constats tab', () => {
it('is disabled with its hint while no zone exists', async () => {
await openReady()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
expect(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
).toBeDisabled()
@@ -392,11 +431,11 @@ describe('Constats tab', () => {
}
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
const add = screen.getByRole('button', { name: 'Ajouter un constat' })
await user.click(items()[0])
await pick(user, items()[0])
expect(add).toBeDisabled()
await user.click(items()[1])
await pick(user, items()[1])
for (let i = 0; i < 30; i++) {
if (document.activeElement?.getAttribute('aria-level') === '8') break
await user.keyboard('{ArrowRight}')
@@ -407,33 +446,53 @@ describe('Constats tab', () => {
expect(add).toBeDisabled()
})
it('renames, marks reviewed and resets to confirm', async () => {
it('marks reviewed and resets to confirm from the dialog, at once', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(items()[1])
await user.click(screen.getByRole('button', { name: 'Marquer comme relu' }))
await user.click(
inFindingDialog().getByRole('button', { name: 'Marquer comme relu' }),
)
expect(doc().finding_zones[0].categories[0].review_status).toBe('reviewed')
expect(within(items()[1]).getByText('Relu')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: 'Remettre à confirmer' }),
inFindingDialog().getByRole('button', { name: 'Remettre à confirmer' }),
)
expect(doc().finding_zones[0].categories[0].review_status).toBe(
'to_confirm',
)
const fr = screen.getByLabelText('Nom (FR)', {
selector: '#finding-name-fr',
})
})
it('renames in the edit form: nothing is written before « Enregistrer », one update after', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
await startEdit(user)
const fr = inFindingDialog().getByLabelText('Nom (FR)')
await user.clear(fr)
await user.type(fr, 'Renommée')
await user.tab()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Cat A')
const before = store.getState().undo.length
await user.click(
inFindingDialog().getByRole('button', { name: 'Enregistrer' }),
)
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Renommée')
expect(store.getState().undo.length).toBe(before + 1)
expect(inFindingDialog().getByRole('status')).toHaveTextContent(
'Modifications enregistrées',
)
expect(document.querySelector('#finding-name-fr')).toHaveTextContent(
'Renommée',
)
})
it('marks a node with set_status and a zone with mark_reviewed', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(items()[0])
expect(
screen.queryByRole('button', { name: 'Remettre à confirmer' }),
@@ -442,8 +501,11 @@ describe('Constats tab', () => {
const cat = doc().finding_zones[0].categories[0]
expect(cat.review_status).toBe('reviewed')
expect(cat.children[0].children[0].review_status).toBe('reviewed')
await user.click(items()[1])
await closeDialog(user)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
await user.click(
screen.getByRole('button', { name: 'Remettre à confirmer' }),
)
@@ -455,9 +517,10 @@ describe('Constats tab', () => {
it('reorders siblings with the arrows', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(items()[1])
expect(screen.getByRole('button', { name: 'Monter' })).toBeDisabled()
await closeDialog(user)
await user.click(items()[0])
await user.click(screen.getByRole('button', { name: 'Descendre' }))
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-b', 'zone-a'])
@@ -467,14 +530,20 @@ describe('Constats tab', () => {
it('deletes with the descendants listed, then removes them', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(items()[1])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/aussi supprimés/)).toBeInTheDocument()
expect(within(dialog).getAllByRole('listitem')).toHaveLength(2)
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
await user.click(
inFindingDialog().getByRole('button', { name: 'Supprimer' }),
)
const dialog = await deleteDialog()
expect(dialog.getByText(/aussi supprimés/)).toBeInTheDocument()
expect(dialog.getAllByRole('listitem')).toHaveLength(2)
await user.click(dialog.getByRole('button', { name: 'Supprimer' }))
expect(doc().finding_zones[0].categories).toEqual([])
// the deletion closes both dialogs: the finding layer is replaced, no Back step
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
expect(screen.queryByText('Cat A')).toBeNull()
})
@@ -491,22 +560,20 @@ describe('Constats tab', () => {
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
render(<FindingsHost />)
await user.click(items()[0])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(
within(dialog).getByText(/ne peut pas être supprimé/),
).toBeInTheDocument()
expect(
within(dialog).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
await user.click(
inFindingDialog().getByRole('button', { name: 'Supprimer' }),
)
const dialog = await deleteDialog()
expect(dialog.getByText(/ne peut pas être supprimé/)).toBeInTheDocument()
expect(dialog.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(doc().finding_zones).toHaveLength(2)
})
it('is plain text and keyboard-navigable when read-only', async () => {
await openReady({ text: treeText() })
render(<FindingsTab {...props} readOnly />)
render(<FindingsHost readOnly />)
expect(
screen.queryByRole('button', { name: 'Ajouter une zone' }),
).toBeNull()
@@ -515,12 +582,15 @@ describe('Constats tab', () => {
const user = userEvent.setup()
await user.click(items()[1])
expect(screen.queryByRole('textbox')).toBeNull()
expect(
inFindingDialog().queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(document.querySelector('#finding-name-fr')).toHaveTextContent(
'Cat A',
)
})
it('edits descriptions (blank side omitted), the vet flag and the cited references', async () => {
it('edits descriptions (blank side omitted) and the vet flag in one save, cites at once', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
@@ -534,26 +604,74 @@ describe('Constats tab', () => {
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
const node = () => doc().finding_zones[0].categories[0].children[0]
const fr = screen.getByLabelText('Description (FR)')
const save = () =>
user.click(inFindingDialog().getByRole('button', { name: 'Enregistrer' }))
await startEdit(user)
const fr = inFindingDialog().getByLabelText('Description (FR)')
await user.type(fr, 'Texte')
await user.tab()
expect(node().description).toEqual({ fr: 'Texte' })
await user.clear(fr)
await user.tab()
await user.click(
inFindingDialog().getByLabelText('Renvoi vers un vétérinaire'),
)
expect(node().description).toEqual({})
await user.click(screen.getByLabelText('Renvoi vers un vétérinaire'))
const before = store.getState().undo.length
await save()
expect(node().description).toEqual({ fr: 'Texte' })
expect(node().requires_vet_referral).toBe(true)
expect(store.getState().undo.length).toBe(before + 1)
await startEdit(user)
await user.clear(inFindingDialog().getByLabelText('Description (FR)'))
await save()
expect(node().description).toEqual({})
// « Citer une référence » is no part of the form: it acts at once, in view mode
await user.selectOptions(
screen.getByLabelText('Citer une référence'),
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(node().reference_ids).toEqual(['ref-a'])
await user.click(screen.getByRole('button', { name: /Retirer Alpha/ }))
expect(node().reference_ids).toEqual([])
// a finding node lists its citations in the sheet, not inline
expect(
inFindingDialog().queryByRole('button', { name: /Retirer Alpha/ }),
).toBeNull()
expect(
inFindingDialog().getByRole('button', { name: '1 référence' }),
).toBeInTheDocument()
})
it('a family keeps its inline list of citations with « Retirer »', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsHost />)
await user.click(items()[1])
const family = () => doc().finding_zones[0].categories[0]
await user.selectOptions(
inFindingDialog().getByLabelText('Citer une référence'),
'ref-a',
)
expect(family().reference_ids).toEqual(['ref-a'])
await user.click(
inFindingDialog().getByRole('button', { name: /Retirer Alpha/ }),
)
expect(family().reference_ids).toEqual([])
expect(
inFindingDialog().getByText('Aucune référence citée.'),
).toBeInTheDocument()
})
it('the trigger shows exactly for the keys open_citations accepts', async () => {
@@ -574,22 +692,30 @@ describe('Constats tab', () => {
}
await openReady({ text })
const user = userEvent.setup()
const openCitations = vi.fn()
render(<FindingsTab {...props} openCitations={openCitations} />)
await user.click(items()[1])
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}{ArrowRight}')
const all = buildItems(doc())
expect(items()).toHaveLength(all.length)
const truth: [string, boolean][] = []
for (const [index, item] of all.entries()) {
await user.click(items()[index])
const shown = screen.queryByRole('button', { name: /^1 référence$/ })
await waitFor(() => expect(findingDialog()).not.toBeNull())
const shown = inFindingDialog().queryByRole('button', {
name: /^1 référence$/,
})
const start = initialNavigation('findings')
const accepted =
navigationReducer(start, { type: 'open_citations', citedBy: item.key })
.citationsOf !== null
citationsOfView(
navigationReducer(start, {
type: 'open_citations',
citedBy: item.key,
}),
) !== null
expect(shown !== null, item.id).toBe(accepted)
truth.push([item.kind, shown !== null])
await closeDialog(user)
}
expect(truth).toEqual([
['zone', false],
@@ -602,7 +728,7 @@ describe('Constats tab', () => {
expect(all.filter((item) => item.kind === 'node')).toHaveLength(2)
})
it('the trigger reads « expanded » only for the finding the panel shows', async () => {
it('the trigger reads « expanded » while the sheet of its finding is open', async () => {
let text = insert(treeText(), {
kind: 'reference',
value: { id: 'ref-a', type: 'book', citation: 'A', url: null, doi: null },
@@ -620,39 +746,46 @@ describe('Constats tab', () => {
}
await openReady({ text })
const user = userEvent.setup()
const shows = (citationsOf: ElementKey | null) => (
<ReferencesOpenContext value={citationsOf}>
<FindingsTab {...props} openCitations={vi.fn()} />
</ReferencesOpenContext>
)
const { rerender } = render(shows(nodes[1].key))
await user.click(items()[1])
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(items()[2])
const trigger = () => screen.getByRole('button', { name: /^1 référence$/ })
const trigger = () =>
inFindingDialog().getByRole('button', { name: /^1 référence$/ })
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
rerender(shows(nodes[0].key))
expect(trigger()).toHaveAttribute('aria-controls', 'editor-citations-panel')
await user.click(trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
rerender(shows(null))
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
await user.click(
screen.getByRole('button', { name: 'Fermer les références' }),
)
await waitFor(() =>
expect(trigger()).toHaveAttribute('aria-expanded', 'false'),
)
})
it('a category has no vet flag; read-only hides the editing actions', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
const { rerender } = render(<FindingsTab {...props} />)
const { rerender } = render(<FindingsHost />)
await user.click(items()[1])
await startEdit(user)
expect(screen.queryByLabelText('Renvoi vers un vétérinaire')).toBeNull()
rerender(<FindingsTab {...props} readOnly />)
expect(screen.getByLabelText('Description (FR)')).toBeInTheDocument()
rerender(<FindingsHost readOnly />)
expect(screen.queryByLabelText('Citer une référence')).toBeNull()
expect(screen.queryByRole('textbox')).toBeNull()
// the open form is kept, its fields read-only, « Enregistrer » disabled
expect(screen.getByLabelText('Nom (FR)')).toHaveAttribute('readonly')
expect(screen.getByRole('button', { name: 'Enregistrer' })).toBeDisabled()
})
it('collapsing an ancestor of the selection selects the ancestor', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
render(<FindingsHost />)
await pick(user, items()[1])
items()[1].focus()
await user.keyboard('{ArrowRight}{ArrowRight}')
expect(items()[2]).toHaveAttribute('aria-selected', 'true')
await user.click(items()[0].querySelector('span') as HTMLElement)
@@ -663,37 +796,48 @@ describe('Constats tab', () => {
it('after a delete the previous sibling, else the parent, is selected and focused', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[2])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
render(<FindingsHost />)
const remove = async (row: HTMLElement) => {
await user.click(row)
await user.click(
inFindingDialog().getByRole('button', { name: 'Supprimer' }),
)
const dialog = await deleteDialog()
await user.click(dialog.getByRole('button', { name: 'Supprimer' }))
await waitFor(() =>
expect(document.querySelector('dialog[open]')).toBeNull(),
)
}
await remove(items()[2])
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-a'])
await waitFor(() => expect(items()[0]).toHaveFocus())
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()[0]).toHaveFocus()
await user.click(items()[1])
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[0])
const second = (await screen.findAllByRole('dialog')).at(-1) as HTMLElement
await user.click(within(second).getByRole('button', { name: 'Supprimer' }))
await remove(items()[1])
await waitFor(() => expect(items()[0]).toHaveFocus())
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()[0]).toHaveFocus()
})
})
describe('the category form title (N1 review, C46)', () => {
it('names the chosen zone, and falls back to an existing label before the choice', async () => {
describe('the category form zone line (N1 review, C46)', () => {
it('names the chosen zone once it is chosen, nothing before the choice', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(
<FindingCreateForm
pending={{ kind: 'category', parent: null }}
readOnly={false}
guards={{
register: vi.fn(),
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
}}
onCreated={vi.fn()}
onCancel={vi.fn()}
onClose={vi.fn()}
/>,
)
const title = () => document.querySelector('p.font-medium')?.textContent
expect(title()).toBe('Ajouter une catégorie')
const line = () => document.querySelector('p.font-medium')?.textContent
expect(line()).toBeUndefined()
await user.selectOptions(screen.getByLabelText('Zone'), 'zone-a')
expect(title()).toBe('Nouvelle catégorie dans la zone « Zone A »')
expect(line()).toBe('Nouvelle catégorie dans la zone « Zone A »')
})
})
@@ -33,12 +33,58 @@ const entry = (patch: Partial<HistoryEntry> = {}): HistoryEntry => ({
})
const stateOf = (value: unknown) => ({ [ENTRY_KEY]: value })
const node = { kind: 'finding', zone_id: 'z', path: ['f', 'n'] } as const
describe('sanitizeView', () => {
it('keeps a tab and a section, and holds no layer yet', () => {
it('keeps a tab and a section, and drops a malformed layer', () => {
const raw = { tab: 'annotations', section: 'views', finding: { key: {} } }
expect(sanitizeView(raw)).toEqual(view('annotations', { section: 'views' }))
})
it('keeps the reading layers of Constats: the dialog and the sheet over it', () => {
const dialog = {
tab: 'findings',
section: 'drawing',
finding: { key: node },
}
expect(sanitizeView(dialog)?.finding).toEqual({
key: node,
citations: false,
})
const sheet = { ...dialog, finding: { key: node, citations: true } }
expect(sanitizeView(sheet)?.finding).toEqual({ key: node, citations: true })
expect(layerCount(sanitizeView(sheet)!)).toBe(2)
})
it('a sheet needs a finding node, a layer needs the Constats tab', () => {
const family = { kind: 'finding', zone_id: 'z', path: ['f'] }
const raw = { tab: 'findings', section: 'drawing' }
const asked = { ...raw, finding: { key: family, citations: true } }
expect(sanitizeView(asked)?.finding).toEqual({
key: family,
citations: false,
})
const elsewhere = {
tab: 'general',
finding: { key: node, citations: false },
}
expect(sanitizeView(elsewhere)?.finding).toBeNull()
})
it('a creation is a form: read back only where forms are kept', () => {
const raw = {
tab: 'findings',
section: 'drawing',
finding: { create: { kind: 'node', parent: node } },
}
expect(sanitizeView(raw)?.finding).toEqual({
create: { kind: 'node', parent: node },
})
expect(sanitizeView(raw, false)?.finding).toBeNull()
const odd = { ...raw, finding: { create: { kind: 'x', parent: null } } }
expect(sanitizeView(odd)?.finding).toBeNull()
})
it('drops what is no view: an unknown tab, a non-object', () => {
expect(sanitizeView({ tab: 'nowhere', section: 'views' })).toBeNull()
expect(sanitizeView('general')).toBeNull()
@@ -115,6 +161,38 @@ describe('planWrite', () => {
expect(planWrite(inSection, view('general'), false)).toBe('push')
})
it('a finding dialog and its sheet go back one layer at a time', () => {
const dialog = view('findings', {
finding: { key: node, citations: false },
})
const sheet = view('findings', { finding: { key: node, citations: true } })
expect(planWrite(entry({ view: view('findings') }), dialog, false)).toBe(
'push',
)
expect(planWrite(entry({ view: dialog }), sheet, false)).toBe('push')
const onSheet = entry({ view: sheet, below: dialog })
expect(planWrite(onSheet, dialog, false)).toBe('back')
const opened = entry({ view: dialog, below: view('findings') })
expect(planWrite(opened, view('findings'), false)).toBe('back')
})
it('a layer left for another tab is a push, a replace hint overrides a removal', () => {
const sheet = view('findings', { finding: { key: node, citations: true } })
const top = entry({ view: sheet, below: view('findings') })
// « Tout afficher » and « Aller à »: a step forward, Back returns to the sheet
expect(planWrite(top, view('references'), false)).toBe('push')
// a deletion or a vanished element: no Back step to a dead dialog
expect(planWrite(top, view('findings'), true)).toBe('replace')
// a creation turned into its element: same layer, replaced
const create = view('findings', {
finding: { create: { kind: 'node', parent: null } },
})
const created = view('findings', {
finding: { key: node, citations: false },
})
expect(planWrite(entry({ view: create }), created, true)).toBe('replace')
})
it('goes back for a layer removed when the entry holds the view below', () => {
const layer = view('findings', { reference: { create: true } })
const opened = entry({ view: layer, below: view('findings') })
@@ -1,4 +1,4 @@
/** R2F-1/2: guard stack, announcer queue, a Back refused while the citations panel is open. */
/** R2F-1/2: guard stack, announcer queue, a Back over the finding layers. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
act,
@@ -46,8 +46,12 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) {
return (
<>
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
<button onClick={() => nav.openFinding(finding)}>open</button>
<button onClick={() => nav.openCitations(finding)}>cite</button>
<button onClick={() => nav.registerCanLeave(guard ?? null)}>guard</button>
<button onClick={() => nav.guards.register('finding', guard ?? null)}>
guard
</button>
<p data-testid="layer">{JSON.stringify(nav.state.finding)}</p>
<button onClick={() => nav.announce('one')}>say one</button>
<button onClick={() => nav.announce('two')}>say two</button>
<p data-testid="live">{nav.live}</p>
@@ -62,24 +66,63 @@ const mount = (guard?: () => { allowed: boolean }) =>
</MemoryRouter>,
)
describe('a Back while the citations panel is open', () => {
it('keeps the page where it is, asks the dirty layer, and pushes the view again', async () => {
describe('a Back over the finding layers', () => {
async function openSheet(guard?: () => { allowed: boolean }) {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
const guard = vi.fn(() => ({ allowed: false }))
mount(guard)
await user.click(screen.getByRole('button', { name: 'guard' }))
if (guard) await user.click(screen.getByRole('button', { name: 'guard' }))
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('button', { name: 'open' }))
await user.click(screen.getByRole('button', { name: 'cite' }))
const before = entry().id
return user
}
const layer = () => JSON.parse(screen.getByTestId('layer').textContent!)
it('closes the sheet first, then the dialog, one layer per entry', async () => {
await openSheet()
expect(layer()).toMatchObject({ citations: true })
expect(entry().below?.finding).toMatchObject({ citations: false })
act(() => navigate(-1))
expect(guard).toHaveBeenCalledWith(false)
expect(layer()).toMatchObject({ citations: false })
act(() => navigate(-1))
expect(layer()).toBeNull()
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent(
'Constats',
)
})
it('a dirty layer keeps the page where it is: asked, the view pushed again', async () => {
const guard = vi.fn(() => ({ allowed: false }))
await openSheet(guard)
const before = entry().id
act(() => navigate(-1))
expect(guard).toHaveBeenCalledWith(false)
expect(layer()).toMatchObject({ citations: true })
expect(entry().id).not.toBe(before)
expect(entry().view.tab).toBe('findings')
expect(entry().below?.tab).toBe('general')
expect(entry().view.finding).toMatchObject({ citations: true })
expect(entry().below?.finding).toMatchObject({ citations: false })
})
it('a modal that is no layer refuses the Back too', async () => {
await openSheet()
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
document.body.append(dialog)
act(() => navigate(-1))
expect(layer()).toMatchObject({ citations: true })
dialog.remove()
})
it('a layer dialog open does not refuse it', async () => {
await openSheet()
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
dialog.setAttribute('data-layer', '')
document.body.append(dialog)
act(() => navigate(-1))
expect(layer()).toMatchObject({ citations: false })
dialog.remove()
})
})
@@ -88,6 +88,20 @@ describe('mount', () => {
expect(written()?.id).toBe('old')
})
it('a reload never reopens a form: the creation layer is replaced by the view without it', async () => {
const create = {
...defaultView('findings'),
finding: { create: { kind: 'zone', parent: null } },
}
const entries = [{ pathname: path, state: foreign({ view: create }) }]
mountDraft({ probe, entries })
await ready()
expect(selected()).toBe('Constats')
await waitFor(() => expect(written()?.view.finding).toBeNull())
expect(written()?.id).toBe('old')
expect(screen.queryByRole('dialog')).toBeNull()
})
it('replaces an entry of another sheet or account by the default view', async () => {
const entries = [{ pathname: path, state: foreign({ sheetId: 'other' }) }]
mountDraft({ probe, entries })
@@ -35,6 +35,7 @@ import {
store,
versionAnswer,
} from '../helpers/editorHarness'
import { openFinding } from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
@@ -126,9 +127,7 @@ function referenceText(): string {
/** Constats, the node selected, its « 1 référence » trigger pressed. */
async function openCitations(user: Awaited<ReturnType<typeof mount>>) {
await user.click(tab('Constats'))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await openFinding(user, /Node A/)
await user.click(screen.getByRole('button', { name: '1 référence' }))
}
@@ -203,7 +202,9 @@ describe('text typed in a place that is left', () => {
const user = await mount()
await user.click(tab('Références'))
await user.click(
inPlace('references').getByRole('button', { name: 'Ajouter une référence' }),
inPlace('references').getByRole('button', {
name: 'Ajouter une référence',
}),
)
const field = inPlace('references').getByLabelText('Citation', {
selector: '#tab-reference-new-citation',
+50 -16
View File
@@ -1,9 +1,11 @@
import { describe, expect, it } from 'vitest'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
citationsOfView,
initialNavigation,
navigationReducer,
targetOfKey,
viewOf,
type EditorTarget,
type NavigationState,
} from '../../src/editor/navigation'
@@ -74,7 +76,7 @@ describe('navigationReducer', () => {
expect(state.visitedTabs).toEqual(['annotations'])
expect(state.visitedSections).toEqual(['drawing'])
expect(initialNavigation('general').visitedSections).toEqual([])
expect(state.citationsOf).toBeNull()
expect(state.finding).toBeNull()
expect(state.libraryReset).toBe(0)
})
@@ -97,21 +99,21 @@ describe('navigationReducer', () => {
type: 'go_to',
target: targetOfKey(key),
})
expect(state).toMatchObject({ tab: 'references', citationsOf: null })
expect(state).toMatchObject({ tab: 'references', finding: null })
expect(state.visitedTabs).toEqual(['general', 'references'])
expect(state.focus?.target).toEqual(targetOfKey(key))
})
it('go_to a tab closes the citations panel', () => {
it('go_to a tab closes the finding layers', () => {
const state = run(
initialNavigation('general'),
{ type: 'open_citations', citedBy: node },
{ type: 'go_to', target: targetOfKey(finding) },
)
expect(state.citationsOf).toBeNull()
expect(state.finding).toBeNull()
})
it('select_tab closes the panel and keeps the section, no request', () => {
it('select_tab closes the layers and keeps the section, no request', () => {
const state = run(
initialNavigation('annotations'),
{ type: 'open_section', section: 'regions' },
@@ -121,16 +123,16 @@ describe('navigationReducer', () => {
expect(state).toMatchObject({
tab: 'findings',
section: 'regions',
citationsOf: null,
finding: null,
focus: undefined,
})
})
it('open_citations opens for a finding node only', () => {
const base = initialNavigation('findings')
expect(
run(base, { type: 'open_citations', citedBy: node }).citationsOf,
).toBe(node)
const opened = run(base, { type: 'open_citations', citedBy: node })
expect(citationsOfView(opened)).toBe(node)
expect(opened.finding).toEqual({ key: node, citations: true })
for (const refused of [
finding,
view,
@@ -141,7 +143,7 @@ describe('navigationReducer', () => {
}
})
it('show_all_references closes the panel, shows the tab and bumps the reset', () => {
it('show_all_references closes the layers, shows the tab and bumps the reset', () => {
const state = run(
initialNavigation('findings'),
{ type: 'open_citations', citedBy: node },
@@ -149,7 +151,7 @@ describe('navigationReducer', () => {
)
expect(state).toMatchObject({
tab: 'references',
citationsOf: null,
finding: null,
libraryReset: 1,
focus: undefined,
})
@@ -183,13 +185,45 @@ describe('navigationReducer', () => {
{ type: 'open_citations', citedBy: node },
)
expect(opened).toMatchObject({ tab: 'annotations', section: 'views' })
expect(opened.citationsOf).toBe(node)
expect(citationsOfView(opened)).toBe(node)
const closed = run(opened, { type: 'close_citations' })
expect(closed).toMatchObject({
tab: 'annotations',
section: 'views',
citationsOf: null,
expect(closed).toMatchObject({ tab: 'annotations', section: 'views' })
expect(citationsOfView(closed)).toBeNull()
// the sheet closes alone: the finding dialog under it stays
expect(closed.finding).toEqual({ key: node, citations: false })
})
it('open_finding shows the dialog of a key on Constats, close_finding takes both layers', () => {
const opened = run(initialNavigation('general'), {
type: 'open_finding',
key: finding,
})
expect(opened).toMatchObject({ tab: 'findings' })
expect(opened.finding).toEqual({ key: finding, citations: false })
const sheet = run(opened, { type: 'open_citations', citedBy: node })
expect(sheet.finding).toEqual({ key: node, citations: true })
expect(run(sheet, { type: 'close_finding' }).finding).toBeNull()
})
it('create_finding holds the kind and the parent, a creation has no sheet', () => {
const state = run(initialNavigation('findings'), {
type: 'create_finding',
kind: 'node',
parent: finding,
})
expect(state.finding).toEqual({ create: { kind: 'node', parent: finding } })
expect(citationsOfView(state)).toBeNull()
expect(run(state, { type: 'close_citations' })).toBe(state)
})
it('restore_view puts back the layers of the view it is given', () => {
const base = initialNavigation('findings')
const restored = run(base, {
type: 'restore_view',
view: { ...viewOf(base), finding: { key: node, citations: true } },
})
expect(citationsOfView(restored)).toBe(node)
expect(restored.focus).toBeUndefined()
})
it('focus_consumed clears only its serial and serials are not reused', () => {
+22 -7
View File
@@ -171,16 +171,31 @@ describe('typed values come back after a 1 024 px crossing', () => {
await keepsTypedValue(user, 'view-new-fr', 'Nom (FR)', 'Ajouter la vue')
})
it('the findings creation form', async () => {
it('the findings creation form: kept in its dialog, read-only while narrow, focus kept', async () => {
const user = await mount()
await user.click(tab('Constats'))
await user.click(button('Ajouter une zone'))
await keepsTypedValue(
user,
'finding-new-name-fr',
'Nom (FR)',
'Ajouter une zone',
)
const field = byId('finding-new-name-fr')
await user.type(field, 'Saisie')
expect(field).toHaveFocus()
cross(900)
// no edit part leaves the page: the dialog keeps the draft, says why, writes nothing
expect(field).toBeVisible()
expect(field).toHaveAttribute('readonly')
expect(field).toHaveAttribute('aria-readonly', 'true')
expect(field).toHaveValue('Saisie')
expect(field).toHaveFocus()
expect(screen.getByText(/Élargissez la fenêtre/)).toBeInTheDocument()
expect(button('Créer')).toBeDisabled()
expect(store.getState().unsaved).toBe(false)
cross(1280)
expect(byId('finding-new-name-fr')).toBe(field)
expect(field).not.toHaveAttribute('readonly')
expect(field).toHaveValue('Saisie')
expect(field).toHaveFocus()
expect(screen.queryByText(/Élargissez la fenêtre/)).toBeNull()
expect(button('Créer')).toBeEnabled()
expect(store.getState().unsaved).toBe(false)
})
it('the submission note', async () => {
@@ -13,6 +13,11 @@ import {
serverHas,
store,
} from '../helpers/editorHarness'
import {
findingDialog,
inFindingDialog,
openFinding,
} from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
@@ -401,18 +406,13 @@ describe('an undo that removes a tile holding a refused draft (V1)', () => {
/** 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 user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await openFinding(user, /Node A/)
await user.click(
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name: '2 références' },
),
inFindingDialog().getByRole('button', { name: '2 références' }),
)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('heading', { name: 'Références citées' }),
screen.getByRole('button', { name: 'Fermer les références' }),
),
)
const panel = screen.getByTestId('editor-citations-panel')
@@ -421,6 +421,20 @@ async function openPanel(user: User) {
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()
@@ -431,9 +445,12 @@ describe('a read-only flip in the citations panel', () => {
const item = tile('ref-b', 'panel')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
await flush()
expect(watch.seen).toHaveLength(1)
// 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()
})
@@ -491,14 +508,9 @@ describe('an undo that takes a tile holding a refused draft out of the panel (V1
})
expect(history()).toEqual({ undo: 1, redo: 0 })
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await openFinding(user, /Node A/)
await user.click(
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name: '3 références' },
),
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/ }))
@@ -511,7 +523,10 @@ describe('an undo that takes a tile holding a refused draft out of the panel (V1
expect(header('ref-c', 'panel')).toBeNull()
expect(screen.getByTestId('editor-citations-panel')).toBe(panel)
expect(history()).toEqual({ undo: 0, redo: 1 })
expect(watch.seen).toEqual([`${NOTE} : Citation`])
// 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()
})
})
@@ -19,6 +19,11 @@ import {
serverHas,
store,
} from '../helpers/editorHarness'
import {
findingDialog,
inFindingDialog,
openFinding,
} from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
import { setReducedMotion } from '../helpers/motion'
@@ -107,10 +112,7 @@ const hasPanel = () => screen.queryByTestId('editor-citations-panel') !== null
const layer = () => panel().closest('[data-place="citations"]')!
const tiles = () => [...panel().querySelectorAll('ul > li')]
const trigger = (name = '2 références') =>
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name },
)
inFindingDialog().getByRole('button', { name })
const heading = () =>
within(panel()).getByRole('heading', { name: 'Références citées' })
const doc = () => JSON.parse(store.getState().documentText)
@@ -119,6 +121,13 @@ const nodeA = () =>
reference_ids: string[]
review_status: string
}
const removeNodeA = () =>
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'fnode-a'] },
})
})
const closed = () => waitFor(() => expect(hasPanel()).toBe(false))
const focusIs = (element: () => Element) =>
waitFor(() => expect(document.activeElement).toBe(element()))
@@ -133,21 +142,17 @@ async function mount(width = 1280, text = nodeText()) {
type User = ReturnType<typeof userEvent.setup>
/** The finding dialog of `label` (a row activation opens it, R2F-3). */
async function select(user: User, label: RegExp) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
const family = screen.getByRole('treeitem', { name: /Cat A/ })
if (!screen.queryByRole('treeitem', { name: /Node A/ })) {
await user.click(family)
await user.keyboard('{ArrowRight}')
}
await user.click(screen.getByRole('treeitem', { name: label }))
await openFinding(user, label)
}
/** The panel of Node A, open and in place: its heading holds the focus. */
/** The sheet of Node A, open over its dialog: its first control (✕) holds the focus. */
async function openFromFinding(user: User, name = '2 références') {
await select(user, /Node A/)
await user.click(trigger(name))
await focusIs(heading)
await focusIs(closeButton)
}
const link = () =>
@@ -169,7 +174,7 @@ describe('opening', () => {
await user.click(trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
expect(document.activeElement).not.toBe(heading())
await focusIs(heading)
await focusIs(closeButton)
expect(panel()).toHaveAttribute('aria-labelledby', 'editor-citations-title')
})
@@ -261,7 +266,7 @@ describe('opening', () => {
})
describe('motion', () => {
const slid = () => (layer().firstElementChild as HTMLElement).style.transform
const slid = () => (layer() as HTMLElement).style.transform
it('slides in from the right and fades the scrim, the page behind inert', async () => {
const user = await mount()
@@ -270,8 +275,8 @@ describe('motion', () => {
expect(slid()).toMatch(/translateX\(/)
expect(screen.getByTestId('references-scrim')).toBeInTheDocument()
expect(panel().closest('header')).toBeNull()
await focusIs(heading)
expect(slid()).not.toMatch(/translateX\([1-9]/)
await focusIs(closeButton)
await waitFor(() => expect(slid()).not.toMatch(/translateX\([1-9]/))
})
it('reduced motion: no slide, the same lifecycle', async () => {
@@ -280,7 +285,7 @@ describe('motion', () => {
await select(user, /Node A/)
await user.click(trigger())
expect(slid()).not.toMatch(/translateX\(/)
await focusIs(heading)
await focusIs(closeButton)
await user.click(closeButton())
await closed()
await focusIs(() => trigger())
@@ -302,23 +307,26 @@ describe.each(MODES)('closing, %s', (_label, reduced) => {
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(heading)
await focusIs(closeButton)
await user.keyboard('{Escape}')
await closed()
await focusIs(() => trigger())
await user.click(trigger())
await focusIs(heading)
await focusIs(closeButton)
fireEvent.click(screen.getByTestId('references-scrim'))
await closed()
await focusIs(() => trigger())
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('Escape with nothing focused closes it too', async () => {
it('the platform close request closes it with nothing focused (no key reaches the page)', async () => {
const user = await mount()
await openFromFinding(user)
;(document.activeElement as HTMLElement).blur()
await user.keyboard('{Escape}')
fireEvent(
panel().closest('dialog')!,
new Event('cancel', { cancelable: true }),
)
await closed()
await focusIs(() => trigger())
})
@@ -343,18 +351,6 @@ describe.each(MODES)('closing, %s', (_label, reduced) => {
expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(3)
})
it('selecting a tab closes it, the new tab button holds the focus', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
await focusIs(() => screen.getByRole('tab', { name: 'Vérification' }))
})
it('« Aller à » a citer from a panel tile closes it and lands on that finding', async () => {
const user = await mount()
await openFromFinding(user)
@@ -365,100 +361,62 @@ describe.each(MODES)('closing, %s', (_label, reduced) => {
await focusIs(() => screen.getByRole('treeitem', { name: /Cat A/ }))
})
it('the finding vanishing closes it, the active tab button holds the focus', async () => {
it('the finding vanishing closes both layers and says so once the dialogs are gone', async () => {
const user = await mount()
await openFromFinding(user)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
removeNodeA()
await closed()
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
await waitFor(() => expect(findingDialog()).toBeNull())
await waitFor(() =>
expect(live()).toHaveTextContent("Ce constat n'existe plus"),
)
expect(document.activeElement).not.toBe(document.body)
})
it('below 640 px the active tab sits under « Plus »: it holds the focus', async () => {
it('below 640 px the sheet opens from « Plus » > Constats and closes on its own', async () => {
const user = await mount(375)
await user.click(screen.getByRole('button', { name: 'Plus' }))
await user.click(screen.getByRole('button', { name: 'Constats' }))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await openFinding(user, /Node A/)
await user.click(trigger())
await focusIs(heading)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await focusIs(closeButton)
await user.click(closeButton())
await closed()
await focusIs(() => screen.getByRole('button', { name: 'Plus' }))
await focusIs(() => trigger())
})
})
describe('the exit', () => {
it('keeps the page and the panel inert until it is over, then lifts it', async () => {
it('a sheet playing its exit is inert, its trigger reads « expanded » until it is gone', async () => {
const user = await mount()
const page = () =>
screen.getAllByRole('tabpanel', { hidden: true })[0].parentElement
await openFromFinding(user)
expect(page()).toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
await user.click(closeButton())
expect(hasPanel()).toBe(true)
expect(layer()).toHaveAttribute('inert')
expect(page()).toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'true')
expect(panel().closest('dialog')).toHaveAttribute('inert')
await closed()
expect(page()).not.toHaveAttribute('inert')
expect(trigger()).toHaveAttribute('aria-expanded', 'false')
})
it('a second close is a no-op, a tab choice replaces the pending move', async () => {
it('a second close during the exit finds no layer and does nothing', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(closeButton())
fireEvent.keyDown(layer(), { key: 'Escape' })
fireEvent.click(screen.getByTestId('references-scrim'))
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
await focusIs(() => screen.getByRole('tab', { name: 'Vérification' }))
expect(findingDialog()).not.toBeNull()
await focusIs(() => trigger())
})
it('leaves a focus the user placed elsewhere during the exit alone', async () => {
it('Ctrl+Z is ignored while the sheet is open: Défaire is unreachable under a dialog', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
await user.click(closeButton())
const save = screen.getByRole('button', { name: /Enregistrer/ })
act(() => save.focus())
await closed()
await new Promise((resolve) => setTimeout(resolve, 50))
expect(document.activeElement).toBe(save)
})
it('Défaire and Refaire stay usable while it is open', async () => {
const user = await mount()
act(() => void commitMove(40))
await openFromFinding(user)
const undo = screen.getByRole('button', { name: /Défaire/ })
await waitFor(() => expect(undo).toBeEnabled())
await user.click(undo)
const before = store.getState().undo.length
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(store.getState().undo.length).toBe(before)
expect(hasPanel()).toBe(true)
expect(screen.getByRole('button', { name: /Refaire/ })).toBeEnabled()
})
})
@@ -487,7 +445,7 @@ describe('the library and the history around the panel', () => {
)
})
it('an undo that removes the finding closes it: the active tab button holds the focus (P6)', async () => {
it('an undo that removes the finding closes both layers (gone rule)', async () => {
const user = await mount()
act(() => {
store.getState().commit({
@@ -509,10 +467,11 @@ describe('the library and the history around the panel', () => {
})
await select(user, /Node B/)
await user.click(trigger('1 référence'))
await focusIs(heading)
await focusIs(closeButton)
act(() => void store.getState().undoStep())
await closed()
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
await waitFor(() => expect(findingDialog()).toBeNull())
expect(document.activeElement).not.toBe(document.body)
})
})
@@ -593,8 +552,8 @@ describe('« Retirer de ce constat »', () => {
expect(hasPanel()).toBe(true)
await user.click(closeButton())
await closed()
// the trigger is gone with its count: the active tab button takes the focus (P6)
await focusIs(() => screen.getByRole('tab', { name: 'Constats' }))
// the trigger is gone with its count: the focus stays inside the finding dialog
expect(findingDialog()!.contains(document.activeElement)).toBe(true)
})
it('a dangling id is a « Référence introuvable » row with Retirer, counted like the rest', async () => {
@@ -647,15 +606,10 @@ describe("a tile in edit when the panel closes (P22'')", () => {
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('a refused draft cancels a tab switch and « Tout afficher »', async () => {
it('a refused draft cancels « Tout afficher »', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
await user.click(
within(panel()).getByRole('button', {
name: "Tout afficher dans l'onglet Références",
@@ -668,20 +622,12 @@ describe("a tile in edit when the panel closes (P22'')", () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
removeNodeA()
await closed()
expect(
screen.getByText(/Saisie non appliquée : Citation/),
).toBeInTheDocument()
await waitFor(() => expect(findingDialog()).toBeNull())
await waitFor(() =>
expect(live()).toHaveTextContent(/Saisie non appliquée : Citation/),
)
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
@@ -695,14 +641,16 @@ describe("a tile in edit when the panel closes (P22'')", () => {
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
it('Ctrl+Z reverts a reference edit while the panel is open', async () => {
it('a committed tile edit is one entry, reverted by Défaire once the sheet is closed', async () => {
const user = await mount()
const field = await edit(user)
await user.clear(field)
await user.type(field, 'Neuf')
fireEvent.blur(field)
expect(doc().references[0].citation).toBe('Neuf')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
await user.click(closeButton())
await closed()
act(() => void store.getState().undoStep())
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
})
@@ -758,16 +706,6 @@ describe('one user edit, one history entry in the panel (C1)', () => {
expect(doc().references[0].url).toBeNull()
})
it('a tab switch with the field still focused adds one entry', async () => {
const user = await mount()
const before = await typeUrl(user)
fireEvent.click(screen.getByRole('tab', { name: 'Vérification' }))
await closed()
expect(entries() - before).toBe(1)
undo()
expect(doc().references[0].url).toBeNull()
})
it('a forced close (finding vanished) adds the edit once, besides the removal', async () => {
const user = await mount()
const before = await typeUrl(user)
@@ -776,15 +714,18 @@ describe('one user edit, one history entry in the panel (C1)', () => {
})
await closed()
expect(entries() - before).toBe(2)
await waitFor(() => expect(findingDialog()).toBeNull())
expect(doc().references[0].url).toBe('https://a.org/')
})
})
describe('the panel review fixes', () => {
it('opening announces the panel title, not the tab name (M4)', async () => {
it('the sheet is a modal dialog named by its title (M4: no announcement needed)', async () => {
const user = await mount()
await openFromFinding(user)
expect(live()?.textContent?.trim()).toBe('Références citées')
const dialog = panel().closest('dialog')!
expect(dialog).toHaveAttribute('aria-labelledby', 'editor-citations-title')
expect(dialog).toHaveAttribute('open')
})
it('every « Aller à » names its citer (M6)', async () => {
@@ -835,20 +776,4 @@ describe('the panel review fixes', () => {
expect(tiles()).toHaveLength(0)
await focusIs(heading)
})
it('an arrow key in the tab row leaves the focus on the refused field (M2)', async () => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
const field = panel().querySelector<HTMLTextAreaElement>(
'#panel-reference-0-ref-a-citation',
)!
await user.clear(field)
const tab = screen.getByRole('tab', { name: 'Constats' })
fireEvent.keyDown(tab, { key: 'ArrowRight' })
expect(hasPanel()).toBe(true)
expect(document.activeElement).toBe(field)
expect(tab).toHaveAttribute('aria-selected', 'true')
})
})