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
+467
-252
No files matched your search
@@ -362,27 +362,36 @@ test.describe('citations sheet, editing', () => {
|
|||||||
await expect(page.locator('dialog[open]')).toHaveCount(1)
|
await expect(page.locator('dialog[open]')).toHaveCount(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('keyboard: Tab stays in the sheet, Escape closes only it, the trigger holds the focus', async ({
|
test('keyboard: Enter opens the sheet, Tab reaches each control in order, Escape from one closes only the sheet', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
test.setTimeout(150_000)
|
test.setTimeout(150_000)
|
||||||
await open(page)
|
await open(page)
|
||||||
await openCitations(page, dict, 'Constat A')
|
await openFinding(page, dict, 'Constat A')
|
||||||
const controls = await panel(page)
|
await trigger(page).focus()
|
||||||
.locator('button, [href], input, select, textarea')
|
await page.keyboard.press('Enter')
|
||||||
.count()
|
await expect(place(page, 'citations')).toBeVisible()
|
||||||
for (let step = 0; step < controls + 2; step++) {
|
await expect(page.locator('dialog[open]')).toHaveCount(2)
|
||||||
await page.keyboard.press('Tab')
|
// The tab order of the sheet, in the document's order, each control tagged.
|
||||||
const where = await page.evaluate(() => {
|
const count = await panel(page).evaluate((root) => {
|
||||||
const active = document.activeElement
|
const sheet = root.closest('dialog')!
|
||||||
if (!active || active === document.body) return 'outside'
|
const tabbable = [
|
||||||
return active.closest('[data-place="citations"]') ? 'sheet' : 'page'
|
...sheet.querySelectorAll<HTMLElement>(
|
||||||
|
'button:not([disabled]), [href], input:not([disabled]), select, textarea',
|
||||||
|
),
|
||||||
|
]
|
||||||
|
tabbable.forEach((el, index) => el.setAttribute('data-kb', String(index)))
|
||||||
|
return tabbable.length
|
||||||
})
|
})
|
||||||
// Past the last control the focus leaves for the browser's own interface
|
expect(count).toBeGreaterThanOrEqual(5)
|
||||||
// (body): it never reaches the dialog under the sheet or the page.
|
const at = () =>
|
||||||
expect(where, `Tab ${step + 1}`).not.toBe('page')
|
page.evaluate(() => document.activeElement?.getAttribute('data-kb'))
|
||||||
|
// On open the first control (✕) holds the focus; Tab then walks the rest.
|
||||||
|
expect(await at()).toBe('0')
|
||||||
|
for (let index = 1; index < count; index++) {
|
||||||
|
await page.keyboard.press('Tab')
|
||||||
|
expect(await at(), `Tab to control ${index}`).toBe(String(index))
|
||||||
}
|
}
|
||||||
await sheet(page).evaluate((node) => (node as HTMLElement).focus())
|
|
||||||
await page.keyboard.press('Escape')
|
await page.keyboard.press('Escape')
|
||||||
await expect(panel(page)).toHaveCount(0)
|
await expect(panel(page)).toHaveCount(0)
|
||||||
await expect(findingDialog(page)).toBeVisible()
|
await expect(findingDialog(page)).toBeVisible()
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
import { useEffect, useRef } from 'react'
|
||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
|
import type { DiscardTarget } from '@/components/editor/findings/useDirtyGuard'
|
||||||
import { useT } from '@/i18n/useT'
|
import { useT } from '@/i18n/useT'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,3 +40,37 @@ export default function DiscardConfirm({
|
|||||||
</div>
|
</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'
|
} from '@faunosteo/core-wasm/types'
|
||||||
import DraftField from '@/components/editor/fields/DraftField'
|
import DraftField from '@/components/editor/fields/DraftField'
|
||||||
import SelectField from '@/components/editor/fields/SelectField'
|
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 ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||||
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
|
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||||
import Button from '@/components/ui/Button'
|
|
||||||
import {
|
import {
|
||||||
buildItems,
|
buildItems,
|
||||||
type FindingItem,
|
type FindingItem,
|
||||||
@@ -45,32 +44,35 @@ export interface FindingCreateFormProps {
|
|||||||
onClose: (forced: boolean) => void
|
onClose: (forced: boolean) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
interface Draft {
|
||||||
* Collects what the core requires (names FR/EN, the kind of a category), then one
|
fr: string
|
||||||
* `insert`: no element exists with default labels. The fields are a local draft: nothing
|
en: string
|
||||||
* is written before « Créer », a close or a move never creates (R2F-3).
|
kind: string
|
||||||
*/
|
}
|
||||||
export default function FindingCreateForm(props: FindingCreateFormProps) {
|
|
||||||
const { pending, readOnly, guards, onCreated, onClose } = props
|
const EMPTY: Draft = { fr: '', en: '', kind: '' }
|
||||||
const t = useT()
|
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 edit = useEditCommand()
|
||||||
const zones = useZoneChoice()
|
const zones = useZoneChoice()
|
||||||
const [fr, setFr] = useState('')
|
const form = useFormDraft(EMPTY, guards, sameDraft)
|
||||||
const [en, setEn] = useState('')
|
|
||||||
const [kind, setKind] = useState('')
|
|
||||||
const guard = useDirtyGuard(guards, fr !== '' || en !== '' || kind !== '')
|
|
||||||
const create = () => {
|
const create = () => {
|
||||||
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
|
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
|
||||||
const missingParent = pending.kind === 'category' && !parent
|
if (!isComplete(form.draft, pending, parent)) {
|
||||||
const incomplete =
|
|
||||||
isBlank(fr) ||
|
|
||||||
isBlank(en) ||
|
|
||||||
missingParent ||
|
|
||||||
(pending.kind === 'category' && !kind)
|
|
||||||
if (incomplete) {
|
|
||||||
edit.reject('form', 'editor.findings.required')
|
edit.reject('form', 'editor.findings.required')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const { fr, en, kind } = form.draft
|
||||||
let createdId = ''
|
let createdId = ''
|
||||||
const added = edit.runNew('form', PREFIX[pending.kind], (id) => {
|
const added = edit.runNew('form', PREFIX[pending.kind], (id) => {
|
||||||
createdId = id
|
createdId = id
|
||||||
@@ -79,6 +81,58 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
|||||||
})
|
})
|
||||||
if (added) onCreated(createdId, parent)
|
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'
|
const category = pending.kind === 'category'
|
||||||
return (
|
return (
|
||||||
<form
|
<form
|
||||||
@@ -87,68 +141,25 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
|||||||
noValidate
|
noValidate
|
||||||
onSubmit={(event) => {
|
onSubmit={(event) => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
create()
|
form.create()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{readOnly && <ReadOnlyNotice />}
|
{readOnly && <ReadOnlyNotice />}
|
||||||
{category && zones.chosen && <ZoneTitle zone={zones.chosen} />}
|
{category && form.zones.chosen && <ZoneTitle zone={form.zones.chosen} />}
|
||||||
<div className="grid gap-3 md:grid-cols-2">
|
<CreateFields form={form} category={category} readOnly={readOnly} />
|
||||||
{category && <ZoneSelect zones={zones} readOnly={readOnly} />}
|
{form.error && (
|
||||||
{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') && (
|
|
||||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||||
{edit.fieldError('form')}
|
{form.error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{guard.confirming ? (
|
<FormActions
|
||||||
<DiscardConfirm
|
confirming={guard.confirming}
|
||||||
|
readOnly={readOnly}
|
||||||
|
submitLabel={t('editor.findings.create')}
|
||||||
|
onCancel={() => onClose(readOnly)}
|
||||||
onKeepTyping={guard.keepTyping}
|
onKeepTyping={guard.keepTyping}
|
||||||
onDiscard={() => onClose(true)}
|
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>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { useRef, useState } from 'react'
|
import { useState } from 'react'
|
||||||
import DraftField from '@/components/editor/fields/DraftField'
|
import DraftField from '@/components/editor/fields/DraftField'
|
||||||
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
|
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||||
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
|
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||||
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||||
import Button from '@/components/ui/Button'
|
|
||||||
import { patchElement, type FindingItem } from '@/editor/findings/tree'
|
import { patchElement, type FindingItem } from '@/editor/findings/tree'
|
||||||
import { isBlank, optionalText } from '@/editor/sheetDocument'
|
import { isBlank, optionalText } from '@/editor/sheetDocument'
|
||||||
import { useEditCommand } from '@/editor/useEditCommand'
|
import { useEditCommand } from '@/editor/useEditCommand'
|
||||||
@@ -98,54 +97,24 @@ function VetCheckbox({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
type Locale2 = 'fr' | 'en'
|
||||||
* The element edited in the finding dialog (R2F-3): a local draft, one `update` on
|
const LOCALES: readonly Locale2[] = ['fr', 'en']
|
||||||
* « 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 »
|
interface FieldsProps {
|
||||||
* is left.
|
draft: Draft
|
||||||
*/
|
set: (change: Partial<Draft>) => void
|
||||||
export default function FindingEditForm(props: FindingEditFormProps) {
|
readOnly: boolean
|
||||||
const { item, readOnly, guards, onDone, onDiscardClose } = props
|
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 t = useT()
|
||||||
const edit = useEditCommand()
|
const text = (l: Locale2) => (l === 'fr' ? 'descriptionFr' : 'descriptionEn')
|
||||||
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 (
|
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">
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
{(['fr', 'en'] as const).map((l) => (
|
{LOCALES.map((l) => (
|
||||||
<DraftField
|
<DraftField
|
||||||
key={l}
|
key={l}
|
||||||
id={`finding-edit-name-${l}`}
|
id={`finding-edit-name-${l}`}
|
||||||
@@ -153,57 +122,100 @@ export default function FindingEditForm(props: FindingEditFormProps) {
|
|||||||
value={draft[l]}
|
value={draft[l]}
|
||||||
onChange={(value) => set({ [l]: value })}
|
onChange={(value) => set({ [l]: value })}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
error={fieldError(l)}
|
error={blank.includes(l) ? t('editor.field.required') : undefined}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
{described &&
|
{described &&
|
||||||
(['fr', 'en'] as const).map((l) => (
|
LOCALES.map((l) => (
|
||||||
<DraftField
|
<DraftField
|
||||||
key={`d-${l}`}
|
key={`d-${l}`}
|
||||||
id={`finding-edit-description-${l}`}
|
id={`finding-edit-description-${l}`}
|
||||||
label={t(`editor.findings.description_${l}`)}
|
label={t(`editor.findings.description_${l}`)}
|
||||||
value={l === 'fr' ? draft.descriptionFr : draft.descriptionEn}
|
value={draft[text(l)]}
|
||||||
onChange={(value) =>
|
onChange={(value) => set({ [text(l)]: value })}
|
||||||
set(
|
|
||||||
l === 'fr'
|
|
||||||
? { descriptionFr: value }
|
|
||||||
: { descriptionEn: value },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
multiline
|
multiline
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</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
|
||||||
|
* 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, onDone, onDiscardClose } = props
|
||||||
|
const t = useT()
|
||||||
|
const form = useEditForm(props)
|
||||||
|
const { guard } = form
|
||||||
|
const discard =
|
||||||
|
guard.confirming === 'dialog' ? onDiscardClose : () => onDone(false)
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
data-draft-form
|
||||||
|
className="space-y-3"
|
||||||
|
noValidate
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
form.save()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{readOnly && <ReadOnlyNotice />}
|
||||||
|
<EditFields
|
||||||
|
draft={form.draft}
|
||||||
|
set={form.set}
|
||||||
|
readOnly={readOnly}
|
||||||
|
described={item.kind !== 'zone'}
|
||||||
|
blank={form.blank}
|
||||||
|
/>
|
||||||
{item.element.kind === 'finding_node' && (
|
{item.element.kind === 'finding_node' && (
|
||||||
<VetCheckbox
|
<VetCheckbox
|
||||||
checked={draft.vet}
|
checked={form.draft.vet}
|
||||||
readOnly={readOnly}
|
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)]">
|
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||||
{edit.fieldError('save')}
|
{form.error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{guard.confirming ? (
|
<FormActions
|
||||||
<DiscardConfirm
|
confirming={guard.confirming}
|
||||||
|
readOnly={readOnly}
|
||||||
|
submitLabel={t('editor.findings.save')}
|
||||||
|
onCancel={form.cancel}
|
||||||
onKeepTyping={guard.keepTyping}
|
onKeepTyping={guard.keepTyping}
|
||||||
onDiscard={() =>
|
onDiscard={discard}
|
||||||
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>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useBeforeUnload } from '@/app/useLeaveGuard'
|
import { useBeforeUnload } from '@/app/useLeaveGuard'
|
||||||
import type { Guards } from '@/editor/useEditorNavigation'
|
import type { Guards } from '@/editor/useEditorNavigation'
|
||||||
|
import { useT } from '@/i18n/useT'
|
||||||
|
|
||||||
/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */
|
/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */
|
||||||
export type DiscardTarget = 'form' | '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 finding layer's guard while a form holds changes (R2F-3): a user close that reaches
|
||||||
* the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
|
* the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
|
||||||
* modifications ? » (`confirming`). A forced close, or a form with nothing typed, goes
|
* modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and
|
||||||
* ahead. `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
|
* says the draft was dropped (BDR-115); a form with nothing typed says nothing.
|
||||||
|
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
|
||||||
*/
|
*/
|
||||||
export function useDirtyGuard(guards: Guards, dirty: boolean) {
|
export function useDirtyGuard(guards: Guards, dirty: boolean) {
|
||||||
|
const t = useT()
|
||||||
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
|
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
|
||||||
const latest = useRef(dirty)
|
const latest = useRef({ dirty, dropped: t('editor.findings.draft_dropped') })
|
||||||
latest.current = dirty
|
latest.current = { dirty, dropped: t('editor.findings.draft_dropped') }
|
||||||
useBeforeUnload(dirty)
|
useBeforeUnload(dirty)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
guards.register('finding', (forced) => {
|
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')
|
setConfirming('dialog')
|
||||||
return { allowed: false }
|
return { allowed: false }
|
||||||
})
|
})
|
||||||
@@ -30,3 +35,20 @@ export function useDirtyGuard(guards: Guards, dirty: boolean) {
|
|||||||
keepTyping: () => setConfirming(null),
|
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> = {
|
const ADD_BUTTON: Record<string, string> = {
|
||||||
zone: 'finding-add-zone',
|
zone: 'finding-add-zone',
|
||||||
category: 'finding-add-category',
|
category: 'finding-add-category',
|
||||||
@@ -158,35 +142,35 @@ function pendingOf(
|
|||||||
return { kind: kind as FindingKind, parent: found?.item ?? null }
|
return { kind: kind as FindingKind, parent: found?.item ?? null }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
|
interface TreeSelection {
|
||||||
export default function FindingsTab({
|
selectedId: string | null
|
||||||
readOnly,
|
selected: FindingItem | undefined
|
||||||
focus,
|
expanded: ReadonlySet<string>
|
||||||
layer = NO_LAYER,
|
select: (id: string | null) => void
|
||||||
}: EditorPlaceProps) {
|
toggle: (id: string, open: boolean) => void
|
||||||
const t = useT()
|
reveal: (found: { item: FindingItem; ancestors: string[] }) => void
|
||||||
const doc = useSheetDocument()
|
}
|
||||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
|
||||||
|
/** 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 [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
|
||||||
const [seeded, setSeeded] = useState(false)
|
const [seeded, setSeeded] = useState(false)
|
||||||
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
|
if (loaded && !seeded) {
|
||||||
const clearFocusId = useCallback(() => setFocusId(null), [])
|
|
||||||
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
|
|
||||||
if (doc && !seeded) {
|
|
||||||
setSeeded(true)
|
setSeeded(true)
|
||||||
setExpanded(
|
setExpanded(
|
||||||
new Set(items.filter((i) => i.kind === 'zone').map((i) => i.id)),
|
new Set(items.filter((i) => i.kind === 'zone').map((i) => i.id)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
const selected = items.find((item) => item.id === selectedId)
|
const reveal: TreeSelection['reveal'] = (found) => {
|
||||||
const reveal = (found: { item: FindingItem; ancestors: string[] }) => {
|
|
||||||
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
|
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
|
||||||
setSelectedId(found.item.id)
|
select(found.item.id)
|
||||||
}
|
}
|
||||||
const toggle = (id: string, open: boolean) => {
|
const toggle = (id: string, open: boolean) => {
|
||||||
if (!open && selectedId && isUnder(items, selectedId, id)) {
|
if (!open && selectedId && isUnder(items, selectedId, id)) select(id)
|
||||||
setSelectedId(id)
|
|
||||||
}
|
|
||||||
setExpanded((prev) => {
|
setExpanded((prev) => {
|
||||||
const next = new Set(prev)
|
const next = new Set(prev)
|
||||||
if (open) next.add(id)
|
if (open) next.add(id)
|
||||||
@@ -194,36 +178,97 @@ export default function FindingsTab({
|
|||||||
return next
|
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) => {
|
useFocusRequest(focus, (target) => {
|
||||||
const found = target.key && itemForKey(items, target.key)
|
const found = target.key && itemForKey(items, target.key)
|
||||||
if (!found) return 'none'
|
if (!found) return 'none'
|
||||||
reveal(found)
|
sel.reveal(found)
|
||||||
// « Aller à » shows the element as its row selected and its dialog open in view
|
// The row takes the focus again when the dialog is closed.
|
||||||
// mode; the row takes the focus again when the dialog is closed.
|
|
||||||
layer.open(found.item.key)
|
layer.open(found.item.key)
|
||||||
setFocusId({ id: found.item.id })
|
land(found.item.id)
|
||||||
return 'found'
|
return 'found'
|
||||||
})
|
})
|
||||||
useSelectionOfLayer(layer, items, reveal)
|
useSelectionOfLayer(layer, items, sel.reveal)
|
||||||
useGoneRule(layer, doc !== null)
|
}
|
||||||
|
|
||||||
|
/** 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 = (
|
const created = (
|
||||||
id: string,
|
id: string,
|
||||||
parent: FindingItem | null,
|
parent: FindingItem | null,
|
||||||
kind: FindingKind,
|
kind: FindingKind,
|
||||||
) => {
|
) => {
|
||||||
if (parent) toggle(parent.id, true)
|
if (parent) sel.toggle(parent.id, true)
|
||||||
setSelectedId(createdItemId(kind, parent, id))
|
sel.select(createdItemId(kind, parent, id))
|
||||||
layer.replace(createdKey(kind, parent, id))
|
layer.replace(createdKey(kind, parent, id))
|
||||||
}
|
}
|
||||||
const { deleting, askDelete, closeDelete } = useFindingDeletion(
|
const activate = (item: FindingItem) => {
|
||||||
items,
|
sel.select(item.id)
|
||||||
selectedId,
|
layer.open(item.key)
|
||||||
{
|
}
|
||||||
select: setSelectedId,
|
return { ...deletion, created, activate }
|
||||||
focusItem: (id) => setFocusId(id ? { id } : null),
|
}
|
||||||
closeLayer: () => layer.replace(null),
|
|
||||||
},
|
/** 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 { view } = layer
|
||||||
const shown = view && 'key' in view ? itemForKey(items, view.key) : null
|
const shown = view && 'key' in view ? itemForKey(items, view.key) : null
|
||||||
return (
|
return (
|
||||||
@@ -233,39 +278,36 @@ export default function FindingsTab({
|
|||||||
className="min-h-24 space-y-3"
|
className="min-h-24 space-y-3"
|
||||||
>
|
>
|
||||||
<AddBar
|
<AddBar
|
||||||
selected={selected}
|
selected={sel.selected}
|
||||||
hasZone={items.some((item) => item.kind === 'zone')}
|
hasZone={items.some((item) => item.kind === 'zone')}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)}
|
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)]">
|
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||||
{t('editor.findings.empty')}
|
{t('editor.findings.empty')}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<FindingTree
|
<FindingTree
|
||||||
visible={visibleItems(items, expanded)}
|
visible={visibleItems(items, sel.expanded)}
|
||||||
selectedId={selected?.id ?? null}
|
selectedId={sel.selected?.id ?? null}
|
||||||
expanded={expanded}
|
expanded={sel.expanded}
|
||||||
onSelect={setSelectedId}
|
onSelect={sel.select}
|
||||||
onActivate={(item) => {
|
onActivate={actions.activate}
|
||||||
setSelectedId(item.id)
|
onToggle={sel.toggle}
|
||||||
layer.open(item.key)
|
focusId={landing.focusId}
|
||||||
}}
|
onFocused={landing.clear}
|
||||||
onToggle={toggle}
|
|
||||||
focusId={focusId}
|
|
||||||
onFocused={clearFocusId}
|
|
||||||
/>
|
/>
|
||||||
<FindingDialog
|
<FindingDialog
|
||||||
layer={layer}
|
layer={layer}
|
||||||
item={shown?.item ?? null}
|
item={shown?.item ?? null}
|
||||||
pending={pendingOf(view, items)}
|
pending={pendingOf(view, items)}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
returnFocus={useReturnTarget(view)}
|
returnFocus={tab.returnFocus}
|
||||||
onDelete={askDelete}
|
onDelete={actions.askDelete}
|
||||||
onCreated={created}
|
onCreated={actions.created}
|
||||||
/>
|
/>
|
||||||
<DeleteDialog target={deleting} onClose={closeDelete} />
|
<DeleteDialog target={actions.deleting} onClose={actions.closeDelete} />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -211,7 +211,19 @@ export function refocusIfHidden(
|
|||||||
if (!gone && document.activeElement === held) return
|
if (!gone && document.activeElement === held) return
|
||||||
const homeShown = home?.isConnected && !home.closest('[hidden]')
|
const homeShown = home?.isConnected && !home.closest('[hidden]')
|
||||||
if (homeShown) home.focus()
|
if (homeShown) home.focus()
|
||||||
if (!homeShown || document.activeElement !== home) focusActiveTab()
|
if (homeShown && document.activeElement === home) return
|
||||||
|
// Under a modal dialog the tab row is inert: the focus stays in the top dialog.
|
||||||
|
if (!focusTopDialog()) focusActiveTab()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first control of the top open dialog takes the focus; false when none is open. */
|
||||||
|
function focusTopDialog(): boolean {
|
||||||
|
const top = [...document.querySelectorAll<HTMLElement>('dialog[open]')].at(-1)
|
||||||
|
const control = top?.querySelector<HTMLElement>(
|
||||||
|
'button:not([disabled]), input:not([disabled]), select, textarea, a[href]',
|
||||||
|
)
|
||||||
|
control?.focus()
|
||||||
|
return control !== undefined && document.activeElement === control
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -258,7 +258,6 @@ export function navigationReducer(
|
|||||||
case 'create_finding':
|
case 'create_finding':
|
||||||
return createFinding(state, { kind: action.kind, parent: action.parent })
|
return createFinding(state, { kind: action.kind, parent: action.parent })
|
||||||
case 'close_finding':
|
case 'close_finding':
|
||||||
console.trace('CLOSE_FINDING')
|
|
||||||
return { ...state, finding: null }
|
return { ...state, finding: null }
|
||||||
case 'open_citations':
|
case 'open_citations':
|
||||||
return openCitations(state, action.citedBy)
|
return openCitations(state, action.citedBy)
|
||||||
@@ -269,7 +268,6 @@ export function navigationReducer(
|
|||||||
case 'go_to':
|
case 'go_to':
|
||||||
return goTo(state, action.target)
|
return goTo(state, action.target)
|
||||||
case 'restore_view':
|
case 'restore_view':
|
||||||
console.trace('RESTORE', JSON.stringify(action.view.finding))
|
|
||||||
return restoreView(state, action.view)
|
return restoreView(state, action.view)
|
||||||
case 'focus_consumed':
|
case 'focus_consumed':
|
||||||
return state.focus?.serial === action.serial
|
return state.focus?.serial === action.serial
|
||||||
|
|||||||
@@ -168,7 +168,7 @@ function useLiveRegion() {
|
|||||||
waiting.current()
|
waiting.current()
|
||||||
waiting.current = afterModalsClosed(() => {
|
waiting.current = afterModalsClosed(() => {
|
||||||
const joined = queued.current.splice(0).join('. ')
|
const joined = queued.current.splice(0).join('. ')
|
||||||
setLive((previous) => (previous === joined ? `${joined} ` : joined))
|
setLive((previous) => (previous === joined ? `${joined} ` : joined))
|
||||||
})
|
})
|
||||||
}, [])
|
}, [])
|
||||||
return { live, announce }
|
return { live, announce }
|
||||||
@@ -267,7 +267,12 @@ interface LayerContext {
|
|||||||
* own confirmation and the close is cancelled. `replaceFinding` is the move that is no
|
* 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.
|
* Back step: the creation turned into its element, a deletion, an element that vanished.
|
||||||
*/
|
*/
|
||||||
function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) {
|
function useFindingLayer(ctx: LayerContext) {
|
||||||
|
return { ...useFindingOpening(ctx), ...useFindingClosing(ctx) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The moves that add the layer: a dialog for an element, a creation form. */
|
||||||
|
function useFindingOpening({ dispatch, mark }: LayerContext) {
|
||||||
const openFinding = useCallback(
|
const openFinding = useCallback(
|
||||||
(key: ElementKey) => {
|
(key: ElementKey) => {
|
||||||
mark()
|
mark()
|
||||||
@@ -282,9 +287,13 @@ function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) {
|
|||||||
},
|
},
|
||||||
[dispatch, mark],
|
[dispatch, mark],
|
||||||
)
|
)
|
||||||
|
return { openFinding, startFinding }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The moves that take it away: a user close, and the replace that is no Back step. */
|
||||||
|
function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) {
|
||||||
const closeFinding = useCallback(
|
const closeFinding = useCallback(
|
||||||
(forced = false) => {
|
(forced = false) => {
|
||||||
console.trace('closeFinding', forced)
|
|
||||||
if (!guards.askAll(forced).allowed) return false
|
if (!guards.askAll(forced).allowed) return false
|
||||||
mark()
|
mark()
|
||||||
dispatch({ type: 'close_finding' })
|
dispatch({ type: 'close_finding' })
|
||||||
@@ -301,7 +310,7 @@ function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) {
|
|||||||
},
|
},
|
||||||
[guards, announce, dispatch, mark],
|
[guards, announce, dispatch, mark],
|
||||||
)
|
)
|
||||||
return { openFinding, startFinding, closeFinding, replaceFinding }
|
return { closeFinding, replaceFinding }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The citations sheet over the finding dialog: opened from a finding node only. */
|
/** The citations sheet over the finding dialog: opened from a finding node only. */
|
||||||
|
|||||||
@@ -1640,6 +1640,7 @@ export const en: Dict = {
|
|||||||
'editor.findings.discard_ask': 'Discard your changes?',
|
'editor.findings.discard_ask': 'Discard your changes?',
|
||||||
'editor.findings.keep_typing': 'Keep editing',
|
'editor.findings.keep_typing': 'Keep editing',
|
||||||
'editor.findings.discard': 'Discard',
|
'editor.findings.discard': 'Discard',
|
||||||
|
'editor.findings.draft_dropped': 'Entry discarded',
|
||||||
'editor.findings.gone': 'This finding no longer exists',
|
'editor.findings.gone': 'This finding no longer exists',
|
||||||
'editor.findings.flip_narrow': 'Widen the window to continue: your entry is kept.',
|
'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.findings.flip_blocked': 'Editing is no longer possible: your entry is kept, you can only discard it.',
|
||||||
|
|||||||
@@ -1671,6 +1671,7 @@ export const fr: Dict = {
|
|||||||
'editor.findings.discard_ask': 'Abandonner les modifications ?',
|
'editor.findings.discard_ask': 'Abandonner les modifications ?',
|
||||||
'editor.findings.keep_typing': 'Continuer la saisie',
|
'editor.findings.keep_typing': 'Continuer la saisie',
|
||||||
'editor.findings.discard': 'Abandonner',
|
'editor.findings.discard': 'Abandonner',
|
||||||
|
'editor.findings.draft_dropped': 'Saisie abandonnée',
|
||||||
'editor.findings.gone': "Ce constat n'existe plus",
|
'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_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.findings.flip_blocked': "La modification n'est plus possible : votre saisie est conservée, vous pouvez seulement l'abandonner.",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { vi } from 'vitest'
|
import { vi } from 'vitest'
|
||||||
|
import type { FindingLayer } from '@/editor/tabs'
|
||||||
import CitationsSheet from '@/components/editor/references/CitationsSheet'
|
import CitationsSheet from '@/components/editor/references/CitationsSheet'
|
||||||
import FindingsTab from '@/components/editor/tabs/FindingsTab'
|
import FindingsTab from '@/components/editor/tabs/FindingsTab'
|
||||||
import { findingLayerOf } from '@/editor/findingLayer'
|
import { findingLayerOf } from '@/editor/findingLayer'
|
||||||
@@ -36,3 +37,19 @@ export default function FindingsHost({
|
|||||||
</ReadOnlyContext>
|
</ReadOnlyContext>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A layer that never opens: for a test that mounts Constats only to read its focus. */
|
||||||
|
export const testLayer: FindingLayer = {
|
||||||
|
view: null,
|
||||||
|
guards: {
|
||||||
|
register: () => undefined,
|
||||||
|
ask: () => ({ allowed: true }),
|
||||||
|
askAll: () => ({ allowed: true }),
|
||||||
|
},
|
||||||
|
open: () => undefined,
|
||||||
|
start: () => undefined,
|
||||||
|
close: () => true,
|
||||||
|
replace: () => undefined,
|
||||||
|
openCitations: () => undefined,
|
||||||
|
announce: () => undefined,
|
||||||
|
}
|
||||||
@@ -330,6 +330,45 @@ describe('read-only flip and the gone rule', () => {
|
|||||||
expect(field).toHaveFocus()
|
expect(field).toHaveFocus()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('a flip to read-only while « Modifier » holds the focus keeps it in the dialog (the tab row is inert)', async () => {
|
||||||
|
const user = await mount()
|
||||||
|
await openFinding(user, /Cat A/)
|
||||||
|
const button = inDialog().getByRole('button', { name: 'Modifier' })
|
||||||
|
button.focus()
|
||||||
|
expect(button).toHaveFocus()
|
||||||
|
act(() => {
|
||||||
|
setWidth(900)
|
||||||
|
window.dispatchEvent(new Event('resize'))
|
||||||
|
})
|
||||||
|
// The edit-only actions left the page: the focus moved to the dialog's first control.
|
||||||
|
expect(button.isConnected).toBe(false)
|
||||||
|
expect(findingDialog()!.contains(document.activeElement)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a forced close of a dirty form says the dropped draft once, with the gone text', async () => {
|
||||||
|
const user = await mount()
|
||||||
|
await openFinding(user, /Node A/)
|
||||||
|
await modify(user)
|
||||||
|
await user.type(nameField(), ' bis')
|
||||||
|
act(() => {
|
||||||
|
store.getState().commit({
|
||||||
|
op: 'remove',
|
||||||
|
key: {
|
||||||
|
kind: 'finding',
|
||||||
|
zone_id: 'zone-a',
|
||||||
|
path: ['fcat-a', 'fnode-a'],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await closed()
|
||||||
|
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(live().textContent).toBe(
|
||||||
|
"Saisie abandonnée. Ce constat n'existe plus",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
it('an element that vanishes closes its dialog by replace and says so', async () => {
|
it('an element that vanishes closes its dialog by replace and says so', async () => {
|
||||||
const user = await mount()
|
const user = await mount()
|
||||||
await openFinding(user, /Node A/)
|
await openFinding(user, /Node A/)
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import type {
|
|||||||
AnatomicalSheetDocument,
|
AnatomicalSheetDocument,
|
||||||
ElementKey,
|
ElementKey,
|
||||||
} from '@faunosteo/core-wasm/types'
|
} from '@faunosteo/core-wasm/types'
|
||||||
|
import { findingLayerOf } from '@/editor/findingLayer'
|
||||||
|
import { testLayer } from '../helpers/findingsHost'
|
||||||
import FindingsTab from '@/components/editor/tabs/FindingsTab'
|
import FindingsTab from '@/components/editor/tabs/FindingsTab'
|
||||||
import RegionsSection from '@/components/editor/annotations/sections/RegionsSection'
|
import RegionsSection from '@/components/editor/annotations/sections/RegionsSection'
|
||||||
import EditorTabBody from '@/components/editor/EditorTabBody'
|
import EditorTabBody from '@/components/editor/EditorTabBody'
|
||||||
@@ -115,7 +117,7 @@ describe('focus requests', () => {
|
|||||||
zone_id: 'zone-a',
|
zone_id: 'zone-a',
|
||||||
path: ['fcat-a', 'node-a'],
|
path: ['fcat-a', 'node-a'],
|
||||||
}
|
}
|
||||||
render(<FindingsTab {...base} focus={request(key)} />)
|
render(<FindingsTab {...base} layer={testLayer} focus={request(key)} />)
|
||||||
const item = await screen.findByRole('treeitem', { name: /Nœud A/ })
|
const item = await screen.findByRole('treeitem', { name: /Nœud A/ })
|
||||||
expect(item.getAttribute('aria-selected')).toBe('true')
|
expect(item.getAttribute('aria-selected')).toBe('true')
|
||||||
await waitFor(() => expect(document.activeElement).toBe(item))
|
await waitFor(() => expect(document.activeElement).toBe(item))
|
||||||
@@ -210,7 +212,7 @@ describe('focus requests', () => {
|
|||||||
const gone: ElementKey = { kind: 'zone', id: 'zone-gone' }
|
const gone: ElementKey = { kind: 'zone', id: 'zone-gone' }
|
||||||
render(
|
render(
|
||||||
<FocusConsumedContext value={consumed}>
|
<FocusConsumedContext value={consumed}>
|
||||||
<FindingsTab {...base} focus={request(gone, 4)} />
|
<FindingsTab {...base} layer={testLayer} focus={request(gone, 4)} />
|
||||||
</FocusConsumedContext>,
|
</FocusConsumedContext>,
|
||||||
)
|
)
|
||||||
await waitFor(() => expect(consumed).toHaveBeenCalledWith(4, 'none'))
|
await waitFor(() => expect(consumed).toHaveBeenCalledWith(4, 'none'))
|
||||||
@@ -268,7 +270,7 @@ function Probe({ go, tier }: { go: EditorTarget; tier: 'wide' | 'small' }) {
|
|||||||
visited={state.visitedTabs}
|
visited={state.visitedTabs}
|
||||||
{...base}
|
{...base}
|
||||||
navigate={nav.navigate}
|
navigate={nav.navigate}
|
||||||
openCitations={nav.openCitations}
|
layer={findingLayerOf(nav)}
|
||||||
focus={state.focus}
|
focus={state.focus}
|
||||||
annotations={{
|
annotations={{
|
||||||
section: state.section,
|
section: state.section,
|
||||||
@@ -388,6 +390,9 @@ describe('a request that finds nothing', () => {
|
|||||||
const key: ElementKey = { kind: 'zone', id: 'zone-a' }
|
const key: ElementKey = { kind: 'zone', id: 'zone-a' }
|
||||||
render(<Probe go={targetOfKey(key)} tier="wide" />)
|
render(<Probe go={targetOfKey(key)} tier="wide" />)
|
||||||
await user.click(screen.getByText('go'))
|
await user.click(screen.getByText('go'))
|
||||||
|
// « Aller à » opens the element's dialog; closed, its row holds the focus.
|
||||||
|
const dialog = await screen.findByRole('dialog')
|
||||||
|
await user.click(within(dialog).getByRole('button', { name: 'Fermer' }))
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(document.activeElement).toBe(
|
expect(document.activeElement).toBe(
|
||||||
screen.getByRole('treeitem', { name: /Zone A/ }),
|
screen.getByRole('treeitem', { name: /Zone A/ }),
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import {
|
|||||||
store,
|
store,
|
||||||
versionAnswer,
|
versionAnswer,
|
||||||
} from '../helpers/editorHarness'
|
} from '../helpers/editorHarness'
|
||||||
|
import { testLayer } from '../helpers/findingsHost'
|
||||||
import { openFinding } from '../helpers/findingDialog'
|
import { openFinding } from '../helpers/findingDialog'
|
||||||
import { mountDraft, setWidth } from '../helpers/editorRoute'
|
import { mountDraft, setWidth } from '../helpers/editorRoute'
|
||||||
|
|
||||||
@@ -513,6 +514,7 @@ describe('a request reaches only its owner', () => {
|
|||||||
readOnly={false}
|
readOnly={false}
|
||||||
navigate={vi.fn()}
|
navigate={vi.fn()}
|
||||||
reloadSheet={vi.fn()}
|
reloadSheet={vi.fn()}
|
||||||
|
layer={testLayer}
|
||||||
focus={{
|
focus={{
|
||||||
target: targetOfKey({
|
target: targetOfKey({
|
||||||
kind: 'finding',
|
kind: 'finding',
|
||||||
|
|||||||
Reference in new issue
Block a user