fix(editor): Task 2 review round 1, trace calls, form hooks, keyboard proof
This commit is contained in:
1 parent
c893dec60b
commit
b703333b20
15 files changed
+476
-261
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { DiscardTarget } from '@/components/editor/findings/useDirtyGuard'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/**
|
||||
@@ -39,3 +40,37 @@ export default function DiscardConfirm({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface ActionsProps {
|
||||
confirming: DiscardTarget | null
|
||||
readOnly: boolean
|
||||
/** « Créer » or « Enregistrer ». */
|
||||
submitLabel: string
|
||||
onCancel: () => void
|
||||
onKeepTyping: () => void
|
||||
onDiscard: () => void
|
||||
}
|
||||
|
||||
/** A form's footer: cancel and submit, or the discard confirmation once a close asked. */
|
||||
export function FormActions(props: ActionsProps) {
|
||||
const t = useT()
|
||||
if (props.confirming) {
|
||||
return (
|
||||
<DiscardConfirm
|
||||
onKeepTyping={props.onKeepTyping}
|
||||
onDiscard={props.onDiscard}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const cancel = props.readOnly ? 'discard' : 'cancel'
|
||||
return (
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={props.onCancel}>
|
||||
{t(`editor.findings.${cancel}`)}
|
||||
</Button>
|
||||
<Button type="submit" disabled={props.readOnly}>
|
||||
{props.submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,10 +6,9 @@ import type {
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
|
||||
import { FormActions } 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 { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||
import {
|
||||
buildItems,
|
||||
type FindingItem,
|
||||
@@ -45,32 +44,35 @@ export interface FindingCreateFormProps {
|
||||
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. 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(props: FindingCreateFormProps) {
|
||||
const { pending, readOnly, guards, onCreated, onClose } = props
|
||||
const t = useT()
|
||||
interface Draft {
|
||||
fr: string
|
||||
en: string
|
||||
kind: string
|
||||
}
|
||||
|
||||
const EMPTY: Draft = { fr: '', en: '', kind: '' }
|
||||
const sameDraft = (a: Draft, b: Draft) =>
|
||||
a.fr === b.fr && a.en === b.en && a.kind === b.kind
|
||||
|
||||
/** What the core requires before an insert: both names, a zone and a kind for a category. */
|
||||
function isComplete(draft: Draft, pending: PendingFinding, parent: unknown) {
|
||||
if (isBlank(draft.fr) || isBlank(draft.en)) return false
|
||||
return pending.kind !== 'category' || (parent !== null && draft.kind !== '')
|
||||
}
|
||||
|
||||
/** The form's state and its one `insert` (« Créer »), refused on a missing field. */
|
||||
function useCreateForm(props: FindingCreateFormProps) {
|
||||
const { pending, guards, onCreated } = props
|
||||
const edit = useEditCommand()
|
||||
const zones = useZoneChoice()
|
||||
const [fr, setFr] = useState('')
|
||||
const [en, setEn] = useState('')
|
||||
const [kind, setKind] = useState('')
|
||||
const guard = useDirtyGuard(guards, fr !== '' || en !== '' || kind !== '')
|
||||
const form = useFormDraft(EMPTY, guards, sameDraft)
|
||||
const create = () => {
|
||||
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
|
||||
const missingParent = pending.kind === 'category' && !parent
|
||||
const incomplete =
|
||||
isBlank(fr) ||
|
||||
isBlank(en) ||
|
||||
missingParent ||
|
||||
(pending.kind === 'category' && !kind)
|
||||
if (incomplete) {
|
||||
if (!isComplete(form.draft, pending, parent)) {
|
||||
edit.reject('form', 'editor.findings.required')
|
||||
return
|
||||
}
|
||||
const { fr, en, kind } = form.draft
|
||||
let createdId = ''
|
||||
const added = edit.runNew('form', PREFIX[pending.kind], (id) => {
|
||||
createdId = id
|
||||
@@ -79,6 +81,58 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
||||
})
|
||||
if (added) onCreated(createdId, parent)
|
||||
}
|
||||
return { ...form, zones, create, error: edit.fieldError('form') }
|
||||
}
|
||||
|
||||
/** The kind choice of a category and its two names, as draft fields. */
|
||||
function CreateFields(props: {
|
||||
form: ReturnType<typeof useCreateForm>
|
||||
category: boolean
|
||||
readOnly: boolean
|
||||
}) {
|
||||
const { form, category, readOnly } = props
|
||||
const t = useT()
|
||||
const kinds = CATEGORY_KINDS.map((k) => ({
|
||||
value: k,
|
||||
label: t(`editor.findings.kind.${k}`),
|
||||
}))
|
||||
return (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{category && <ZoneSelect zones={form.zones} readOnly={readOnly} />}
|
||||
{category && (
|
||||
<SelectField
|
||||
id="finding-new-kind"
|
||||
label={t('editor.findings.kind')}
|
||||
value={form.draft.kind}
|
||||
readOnly={readOnly}
|
||||
options={[{ value: '', label: t('editor.field.choose') }, ...kinds]}
|
||||
onCommit={(kind) => form.set({ kind })}
|
||||
/>
|
||||
)}
|
||||
{(['fr', 'en'] as const).map((l) => (
|
||||
<DraftField
|
||||
key={l}
|
||||
id={`finding-new-name-${l}`}
|
||||
label={t(`editor.general.name_${l}`)}
|
||||
value={form.draft[l]}
|
||||
onChange={(value) => form.set({ [l]: value })}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects what the core requires (names FR/EN, the kind of a category), then one
|
||||
* `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(props: FindingCreateFormProps) {
|
||||
const { pending, readOnly, onClose } = props
|
||||
const t = useT()
|
||||
const form = useCreateForm(props)
|
||||
const { guard } = form
|
||||
const category = pending.kind === 'category'
|
||||
return (
|
||||
<form
|
||||
@@ -87,68 +141,25 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
||||
noValidate
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
create()
|
||||
form.create()
|
||||
}}
|
||||
>
|
||||
{readOnly && <ReadOnlyNotice />}
|
||||
{category && zones.chosen && <ZoneTitle zone={zones.chosen} />}
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{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) => ({
|
||||
value: k,
|
||||
label: t(`editor.findings.kind.${k}`),
|
||||
})),
|
||||
]}
|
||||
onCommit={setKind}
|
||||
/>
|
||||
)}
|
||||
<DraftField
|
||||
id="finding-new-name-fr"
|
||||
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') && (
|
||||
{category && form.zones.chosen && <ZoneTitle zone={form.zones.chosen} />}
|
||||
<CreateFields form={form} category={category} readOnly={readOnly} />
|
||||
{form.error && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{edit.fieldError('form')}
|
||||
{form.error}
|
||||
</p>
|
||||
)}
|
||||
{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>
|
||||
)}
|
||||
<FormActions
|
||||
confirming={guard.confirming}
|
||||
readOnly={readOnly}
|
||||
submitLabel={t('editor.findings.create')}
|
||||
onCancel={() => onClose(readOnly)}
|
||||
onKeepTyping={guard.keepTyping}
|
||||
onDiscard={() => onClose(true)}
|
||||
/>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { 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 { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||
import { useFormDraft } 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'
|
||||
@@ -98,6 +97,74 @@ function VetCheckbox({
|
||||
)
|
||||
}
|
||||
|
||||
type Locale2 = 'fr' | 'en'
|
||||
const LOCALES: readonly Locale2[] = ['fr', 'en']
|
||||
|
||||
interface FieldsProps {
|
||||
draft: Draft
|
||||
set: (change: Partial<Draft>) => void
|
||||
readOnly: boolean
|
||||
described: boolean
|
||||
blank: readonly string[]
|
||||
}
|
||||
|
||||
/** The names, then the descriptions of a family or a node, as draft fields. */
|
||||
function EditFields({ draft, set, readOnly, described, blank }: FieldsProps) {
|
||||
const t = useT()
|
||||
const text = (l: Locale2) => (l === 'fr' ? 'descriptionFr' : 'descriptionEn')
|
||||
return (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{LOCALES.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={blank.includes(l) ? t('editor.field.required') : undefined}
|
||||
/>
|
||||
))}
|
||||
{described &&
|
||||
LOCALES.map((l) => (
|
||||
<DraftField
|
||||
key={`d-${l}`}
|
||||
id={`finding-edit-description-${l}`}
|
||||
label={t(`editor.findings.description_${l}`)}
|
||||
value={draft[text(l)]}
|
||||
onChange={(value) => set({ [text(l)]: value })}
|
||||
readOnly={readOnly}
|
||||
multiline
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The form's state: draft, blank names, and the one save (none when nothing changed). */
|
||||
function useEditForm(props: FindingEditFormProps) {
|
||||
const { item, readOnly, guards, onDone } = props
|
||||
const edit = useEditCommand()
|
||||
const form = useFormDraft(draftOf(item), guards, sameDraft)
|
||||
const [blank, setBlank] = useState<readonly string[]>([])
|
||||
const save = () => {
|
||||
const missing = LOCALES.filter((l) => isBlank(form.draft[l]))
|
||||
setBlank(missing)
|
||||
if (missing.length > 0) {
|
||||
document.getElementById(`finding-edit-name-${missing[0]}`)?.focus()
|
||||
} else if (!form.dirty) {
|
||||
onDone(false)
|
||||
} else {
|
||||
const element = patchOf(item, form.draft)
|
||||
const command = { op: 'update', key: item.key, element } as const
|
||||
if (edit.run('save', command)) onDone(true)
|
||||
}
|
||||
}
|
||||
const cancel = () =>
|
||||
form.dirty && !readOnly ? form.guard.askToLeave() : onDone(false)
|
||||
return { ...form, blank, save, cancel, error: edit.fieldError('save') }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -105,34 +172,12 @@ function VetCheckbox({
|
||||
* is left.
|
||||
*/
|
||||
export default function FindingEditForm(props: FindingEditFormProps) {
|
||||
const { item, readOnly, guards, onDone, onDiscardClose } = props
|
||||
const { item, readOnly, 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
|
||||
const form = useEditForm(props)
|
||||
const { guard } = form
|
||||
const discard =
|
||||
guard.confirming === 'dialog' ? onDiscardClose : () => onDone(false)
|
||||
return (
|
||||
<form
|
||||
data-draft-form
|
||||
@@ -140,70 +185,37 @@ export default function FindingEditForm(props: FindingEditFormProps) {
|
||||
noValidate
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
save()
|
||||
form.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>
|
||||
<EditFields
|
||||
draft={form.draft}
|
||||
set={form.set}
|
||||
readOnly={readOnly}
|
||||
described={item.kind !== 'zone'}
|
||||
blank={form.blank}
|
||||
/>
|
||||
{item.element.kind === 'finding_node' && (
|
||||
<VetCheckbox
|
||||
checked={draft.vet}
|
||||
checked={form.draft.vet}
|
||||
readOnly={readOnly}
|
||||
onChange={(vet) => set({ vet })}
|
||||
onChange={(vet) => form.set({ vet })}
|
||||
/>
|
||||
)}
|
||||
{edit.fieldError('save') && (
|
||||
{form.error && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{edit.fieldError('save')}
|
||||
{form.error}
|
||||
</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>
|
||||
)}
|
||||
<FormActions
|
||||
confirming={guard.confirming}
|
||||
readOnly={readOnly}
|
||||
submitLabel={t('editor.findings.save')}
|
||||
onCancel={form.cancel}
|
||||
onKeepTyping={guard.keepTyping}
|
||||
onDiscard={discard}
|
||||
/>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useBeforeUnload } from '@/app/useLeaveGuard'
|
||||
import type { Guards } from '@/editor/useEditorNavigation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */
|
||||
export type DiscardTarget = 'form' | 'dialog'
|
||||
@@ -8,17 +9,21 @@ 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.
|
||||
* modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and
|
||||
* says the draft was dropped (BDR-115); a form with nothing typed says nothing.
|
||||
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
|
||||
*/
|
||||
export function useDirtyGuard(guards: Guards, dirty: boolean) {
|
||||
const t = useT()
|
||||
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
|
||||
const latest = useRef(dirty)
|
||||
latest.current = dirty
|
||||
const latest = useRef({ dirty, dropped: t('editor.findings.draft_dropped') })
|
||||
latest.current = { dirty, dropped: t('editor.findings.draft_dropped') }
|
||||
useBeforeUnload(dirty)
|
||||
useEffect(() => {
|
||||
guards.register('finding', (forced) => {
|
||||
if (forced || !latest.current) return { allowed: true }
|
||||
const { dirty: held, dropped } = latest.current
|
||||
if (!held) return { allowed: true }
|
||||
if (forced) return { allowed: true, note: dropped }
|
||||
setConfirming('dialog')
|
||||
return { allowed: false }
|
||||
})
|
||||
@@ -30,3 +35,20 @@ export function useDirtyGuard(guards: Guards, dirty: boolean) {
|
||||
keepTyping: () => setConfirming(null),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A form's local draft: `set` merges a change, `dirty` is true once it differs from the
|
||||
* first value (`same` compares two drafts), and the layer's guard follows `dirty`.
|
||||
*/
|
||||
export function useFormDraft<T extends object>(
|
||||
initial: T,
|
||||
guards: Guards,
|
||||
same: (a: T, b: T) => boolean,
|
||||
) {
|
||||
const first = useRef(initial).current
|
||||
const [draft, setDraft] = useState(first)
|
||||
const dirty = !same(draft, first)
|
||||
const guard = useDirtyGuard(guards, dirty)
|
||||
const set = (change: Partial<T>) => setDraft({ ...draft, ...change })
|
||||
return { draft, set, dirty, guard }
|
||||
}
|
||||
@@ -36,22 +36,6 @@ 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',
|
||||
@@ -158,35 +142,35 @@ function pendingOf(
|
||||
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,
|
||||
layer = NO_LAYER,
|
||||
}: EditorPlaceProps) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
interface TreeSelection {
|
||||
selectedId: string | null
|
||||
selected: FindingItem | undefined
|
||||
expanded: ReadonlySet<string>
|
||||
select: (id: string | null) => void
|
||||
toggle: (id: string, open: boolean) => void
|
||||
reveal: (found: { item: FindingItem; ancestors: string[] }) => void
|
||||
}
|
||||
|
||||
/** Selection and expansion of the tree: the zones start open, a closed branch takes the selection. */
|
||||
function useTreeSelection(
|
||||
items: readonly FindingItem[],
|
||||
loaded: boolean,
|
||||
): TreeSelection {
|
||||
const [selectedId, select] = useState<string | null>(null)
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
|
||||
const [seeded, setSeeded] = useState(false)
|
||||
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
|
||||
const clearFocusId = useCallback(() => setFocusId(null), [])
|
||||
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
|
||||
if (doc && !seeded) {
|
||||
if (loaded && !seeded) {
|
||||
setSeeded(true)
|
||||
setExpanded(
|
||||
new Set(items.filter((i) => i.kind === 'zone').map((i) => i.id)),
|
||||
)
|
||||
}
|
||||
const selected = items.find((item) => item.id === selectedId)
|
||||
const reveal = (found: { item: FindingItem; ancestors: string[] }) => {
|
||||
const reveal: TreeSelection['reveal'] = (found) => {
|
||||
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
|
||||
setSelectedId(found.item.id)
|
||||
select(found.item.id)
|
||||
}
|
||||
const toggle = (id: string, open: boolean) => {
|
||||
if (!open && selectedId && isUnder(items, selectedId, id)) {
|
||||
setSelectedId(id)
|
||||
}
|
||||
if (!open && selectedId && isUnder(items, selectedId, id)) select(id)
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (open) next.add(id)
|
||||
@@ -194,36 +178,97 @@ export default function FindingsTab({
|
||||
return next
|
||||
})
|
||||
}
|
||||
const selected = items.find((item) => item.id === selectedId)
|
||||
return { selectedId, selected, expanded, select, toggle, reveal }
|
||||
}
|
||||
|
||||
/** The row the focus lands on after a move: set, applied once the dialogs are gone, cleared. */
|
||||
function useFocusLanding() {
|
||||
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
|
||||
const clear = useCallback(() => setFocusId(null), [])
|
||||
const land = useCallback(
|
||||
(id: string | null) => setFocusId(id ? { id } : null),
|
||||
[],
|
||||
)
|
||||
return { focusId, clear, land }
|
||||
}
|
||||
|
||||
interface TabContext {
|
||||
layer: FindingLayer
|
||||
items: readonly FindingItem[]
|
||||
sel: TreeSelection
|
||||
land: (id: string | null) => void
|
||||
}
|
||||
|
||||
/** « Aller à » and the layer's own element: both select the row, the first opens the dialog. */
|
||||
function useLayerFollow(focus: EditorPlaceProps['focus'], ctx: TabContext) {
|
||||
const { layer, items, sel, land } = ctx
|
||||
useFocusRequest(focus, (target) => {
|
||||
const found = target.key && itemForKey(items, target.key)
|
||||
if (!found) return 'none'
|
||||
reveal(found)
|
||||
// « Aller à » shows the element as its row selected and its dialog open in view
|
||||
// mode; the row takes the focus again when the dialog is closed.
|
||||
sel.reveal(found)
|
||||
// The row takes the focus again when the dialog is closed.
|
||||
layer.open(found.item.key)
|
||||
setFocusId({ id: found.item.id })
|
||||
land(found.item.id)
|
||||
return 'found'
|
||||
})
|
||||
useSelectionOfLayer(layer, items, reveal)
|
||||
useGoneRule(layer, doc !== null)
|
||||
useSelectionOfLayer(layer, items, sel.reveal)
|
||||
}
|
||||
|
||||
/** What the tab does with the layer: a creation turns into its element, a row opens its dialog, a deletion. */
|
||||
function useFindingActions(ctx: TabContext) {
|
||||
const { layer, items, sel, land } = ctx
|
||||
const deletion = useFindingDeletion(items, sel.selectedId, {
|
||||
select: sel.select,
|
||||
focusItem: land,
|
||||
closeLayer: () => layer.replace(null),
|
||||
})
|
||||
const created = (
|
||||
id: string,
|
||||
parent: FindingItem | null,
|
||||
kind: FindingKind,
|
||||
) => {
|
||||
if (parent) toggle(parent.id, true)
|
||||
setSelectedId(createdItemId(kind, parent, id))
|
||||
if (parent) sel.toggle(parent.id, true)
|
||||
sel.select(createdItemId(kind, parent, id))
|
||||
layer.replace(createdKey(kind, parent, id))
|
||||
}
|
||||
const { deleting, askDelete, closeDelete } = useFindingDeletion(
|
||||
items,
|
||||
selectedId,
|
||||
{
|
||||
select: setSelectedId,
|
||||
focusItem: (id) => setFocusId(id ? { id } : null),
|
||||
closeLayer: () => layer.replace(null),
|
||||
},
|
||||
)
|
||||
const activate = (item: FindingItem) => {
|
||||
sel.select(item.id)
|
||||
layer.open(item.key)
|
||||
}
|
||||
return { ...deletion, created, activate }
|
||||
}
|
||||
|
||||
/** Everything the tab shows and does, so the component only lays it out. */
|
||||
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
|
||||
const doc = useSheetDocument()
|
||||
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
|
||||
const sel = useTreeSelection(items, doc !== null)
|
||||
const landing = useFocusLanding()
|
||||
const ctx = { layer, items, sel, land: landing.land }
|
||||
useLayerFollow(focus, ctx)
|
||||
useGoneRule(layer, doc !== null)
|
||||
const actions = useFindingActions(ctx)
|
||||
const returnFocus = useReturnTarget(layer.view)
|
||||
return { doc, items, sel, landing, actions, returnFocus }
|
||||
}
|
||||
|
||||
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
|
||||
export default function FindingsTab(props: EditorPlaceProps) {
|
||||
const { layer } = props
|
||||
if (!layer)
|
||||
throw new Error('Constats needs the finding layer of the workspace')
|
||||
return <FindingsBody {...props} layer={layer} />
|
||||
}
|
||||
|
||||
function FindingsBody({
|
||||
readOnly,
|
||||
focus,
|
||||
layer,
|
||||
}: EditorPlaceProps & { layer: FindingLayer }) {
|
||||
const t = useT()
|
||||
const tab = useFindingsTab(focus, layer)
|
||||
const { items, sel, landing, actions } = tab
|
||||
const { view } = layer
|
||||
const shown = view && 'key' in view ? itemForKey(items, view.key) : null
|
||||
return (
|
||||
@@ -233,39 +278,36 @@ export default function FindingsTab({
|
||||
className="min-h-24 space-y-3"
|
||||
>
|
||||
<AddBar
|
||||
selected={selected}
|
||||
selected={sel.selected}
|
||||
hasZone={items.some((item) => item.kind === 'zone')}
|
||||
readOnly={readOnly}
|
||||
onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)}
|
||||
/>
|
||||
{doc && items.length === 0 && (
|
||||
{tab.doc && items.length === 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.findings.empty')}
|
||||
</p>
|
||||
)}
|
||||
<FindingTree
|
||||
visible={visibleItems(items, expanded)}
|
||||
selectedId={selected?.id ?? null}
|
||||
expanded={expanded}
|
||||
onSelect={setSelectedId}
|
||||
onActivate={(item) => {
|
||||
setSelectedId(item.id)
|
||||
layer.open(item.key)
|
||||
}}
|
||||
onToggle={toggle}
|
||||
focusId={focusId}
|
||||
onFocused={clearFocusId}
|
||||
visible={visibleItems(items, sel.expanded)}
|
||||
selectedId={sel.selected?.id ?? null}
|
||||
expanded={sel.expanded}
|
||||
onSelect={sel.select}
|
||||
onActivate={actions.activate}
|
||||
onToggle={sel.toggle}
|
||||
focusId={landing.focusId}
|
||||
onFocused={landing.clear}
|
||||
/>
|
||||
<FindingDialog
|
||||
layer={layer}
|
||||
item={shown?.item ?? null}
|
||||
pending={pendingOf(view, items)}
|
||||
readOnly={readOnly}
|
||||
returnFocus={useReturnTarget(view)}
|
||||
onDelete={askDelete}
|
||||
onCreated={created}
|
||||
returnFocus={tab.returnFocus}
|
||||
onDelete={actions.askDelete}
|
||||
onCreated={actions.created}
|
||||
/>
|
||||
<DeleteDialog target={deleting} onClose={closeDelete} />
|
||||
<DeleteDialog target={actions.deleting} onClose={actions.closeDelete} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user