fix(editor): final review round, history, dialogs, Plus and limits
I1 scroll restored at once on a Back into layers; I2 Aller a opens the target dialog in one push; M1-M9, criteria 8 and 17 (left-draft notice), entry caps, no exhaustive-deps disables, locals within 5.
This commit is contained in:
1 parent
ce171427c0
commit
6bf9290da7
25 files changed
+1002
-202
No files matched your search
@@ -491,9 +491,20 @@ for (const reduced of [false, true]) {
|
|||||||
// The sheet closes and the family opens in the dialog (view mode); closed, the
|
// The sheet closes and the family opens in the dialog (view mode); closed, the
|
||||||
// row holds the focus.
|
// row holds the focus.
|
||||||
await expect(place(page, 'citations')).toHaveCount(0)
|
await expect(place(page, 'citations')).toHaveCount(0)
|
||||||
|
const family = findingDialog(page).getByRole('heading', {
|
||||||
|
name: 'Dysfonction A',
|
||||||
|
})
|
||||||
|
await expect(family).toBeVisible()
|
||||||
|
// Back returns to the place « Aller à » left: Constat A with its sheet open.
|
||||||
|
await page.goBack()
|
||||||
|
await expect(page.locator('dialog[open]')).toHaveCount(2)
|
||||||
|
await expect(place(page, 'citations')).toBeVisible()
|
||||||
await expect(
|
await expect(
|
||||||
findingDialog(page).getByRole('heading', { name: 'Dysfonction A' }),
|
findingDialog(page).getByRole('heading', { name: 'Constat A' }),
|
||||||
).toBeVisible()
|
).toBeVisible()
|
||||||
|
await page.goForward()
|
||||||
|
await expect(place(page, 'citations')).toHaveCount(0)
|
||||||
|
await expect(family).toBeVisible()
|
||||||
await closeFinding(page, dict)
|
await closeFinding(page, dict)
|
||||||
await expect(
|
await expect(
|
||||||
page.getByRole('treeitem', { name: /Dysfonction A/ }),
|
page.getByRole('treeitem', { name: /Dysfonction A/ }),
|
||||||
|
|||||||
@@ -80,6 +80,31 @@ async function entryHolds(page: Page, test: string) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A Back restores the page offset within this many pixels. */
|
||||||
|
const SCROLL_SLACK = 4
|
||||||
|
|
||||||
|
const scrollY = (page: Page) => page.evaluate(() => window.scrollY)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pads the page so it can scroll whatever the viewport, then moves it to `y` (a page
|
||||||
|
* behind a modal still scrolls by script). Answers the offset reached.
|
||||||
|
*/
|
||||||
|
async function scrollTreeTo(page: Page, y: number): Promise<number> {
|
||||||
|
await page.evaluate((top) => {
|
||||||
|
document.body.style.paddingBottom = '3000px'
|
||||||
|
window.scrollTo(0, top)
|
||||||
|
}, y)
|
||||||
|
const reached = await scrollY(page)
|
||||||
|
expect(reached).toBeGreaterThan(0)
|
||||||
|
return reached
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectScrollNear(page: Page, y: number) {
|
||||||
|
await expect
|
||||||
|
.poll(async () => Math.abs((await scrollY(page)) - y))
|
||||||
|
.toBeLessThanOrEqual(SCROLL_SLACK)
|
||||||
|
}
|
||||||
|
|
||||||
/** Whether the sheet is the dialog on top at the right edge of the viewport. */
|
/** Whether the sheet is the dialog on top at the right edge of the viewport. */
|
||||||
const sheetOnTop = (page: Page) =>
|
const sheetOnTop = (page: Page) =>
|
||||||
page.evaluate(() => {
|
page.evaluate(() => {
|
||||||
@@ -127,6 +152,9 @@ test.describe('the owner journey through the history', () => {
|
|||||||
await expect(place(page, 'citations')).toBeVisible()
|
await expect(place(page, 'citations')).toBeVisible()
|
||||||
await expect(sheetHeaders(page)).toHaveCount(2)
|
await expect(sheetHeaders(page)).toHaveCount(2)
|
||||||
await entryHolds(page, 'view.finding && view.finding.citations')
|
await entryHolds(page, 'view.finding && view.finding.citations')
|
||||||
|
// The tree behind the dialogs sits at an offset of its own (the page is padded so it
|
||||||
|
// can scroll whatever the viewport): Back must return to it.
|
||||||
|
const left = await scrollTreeTo(page, 400)
|
||||||
// 5. « Tout afficher dans l'onglet Références »; 6. the tab filtered on A's two references.
|
// 5. « Tout afficher dans l'onglet Références »; 6. the tab filtered on A's two references.
|
||||||
await panel(page)
|
await panel(page)
|
||||||
.getByRole('button', { name: dict['editor.references.panel_show_all'] })
|
.getByRole('button', { name: dict['editor.references.panel_show_all'] })
|
||||||
@@ -141,6 +169,7 @@ test.describe('the owner journey through the history', () => {
|
|||||||
await expect(
|
await expect(
|
||||||
libraryRoot(page).getByText('2 références', { exact: true }),
|
libraryRoot(page).getByText('2 références', { exact: true }),
|
||||||
).toBeVisible()
|
).toBeVisible()
|
||||||
|
expect(Math.abs((await scrollY(page)) - left)).toBeGreaterThan(SCROLL_SLACK)
|
||||||
// 7. browser Back; 8. finding A with its sheet on top, as left.
|
// 7. browser Back; 8. finding A with its sheet on top, as left.
|
||||||
await page.goBack()
|
await page.goBack()
|
||||||
await expect(dialogs(page)).toHaveCount(2)
|
await expect(dialogs(page)).toHaveCount(2)
|
||||||
@@ -148,6 +177,13 @@ test.describe('the owner journey through the history', () => {
|
|||||||
await expect(findingDialog(page)).toContainText('Constat A')
|
await expect(findingDialog(page)).toContainText('Constat A')
|
||||||
expect(await sheetOnTop(page)).toBe(true)
|
expect(await sheetOnTop(page)).toBe(true)
|
||||||
await expect(sheetHeaders(page)).toHaveCount(2)
|
await expect(sheetHeaders(page)).toHaveCount(2)
|
||||||
|
await expectScrollNear(page, left)
|
||||||
|
// Closed by Escape (sheet, then dialog): the tree stays where it was left.
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await expect(dialogs(page)).toHaveCount(1)
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await expectNoDialog(page)
|
||||||
|
await expectScrollNear(page, left)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({
|
test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({
|
||||||
|
|||||||
@@ -7,8 +7,13 @@ import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest'
|
|||||||
import { saveFailureMessage } from '@/editor/messages'
|
import { saveFailureMessage } from '@/editor/messages'
|
||||||
import type { EditorMode } from '@/editor/mode'
|
import type { EditorMode } from '@/editor/mode'
|
||||||
import { useEditorStore } from '@/editor/state/editorStore'
|
import { useEditorStore } from '@/editor/state/editorStore'
|
||||||
import { ownedEntry, withoutForms } from '@/editor/history/entry'
|
import {
|
||||||
|
ownedEntry,
|
||||||
|
withoutForms,
|
||||||
|
type HistoryOwner,
|
||||||
|
} from '@/editor/history/entry'
|
||||||
import useEditorHistory from '@/editor/history/useEditorHistory'
|
import useEditorHistory from '@/editor/history/useEditorHistory'
|
||||||
|
import { useLeftDraft } from '@/editor/leftDraft'
|
||||||
import { citationsOfView, defaultView } from '@/editor/navigation'
|
import { citationsOfView, defaultView } from '@/editor/navigation'
|
||||||
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
|
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
|
||||||
import { initialTab } from '@/editor/tabs'
|
import { initialTab } from '@/editor/tabs'
|
||||||
@@ -119,44 +124,72 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** The sheet and the account the history entries of this editor belong to. */
|
||||||
* The draft page once the version is ready: header, notices, tab row, the citations
|
function useOwner(sheetId: string): HistoryOwner {
|
||||||
* panel and the shown place. Owns the navigation state, so the first tab is known at
|
|
||||||
* mount (`initialTab`) and later edits never move the user off their tab.
|
|
||||||
*/
|
|
||||||
export default function EditorWorkspace(props: Props) {
|
|
||||||
const { sheet, mode, readOnly, tier, reloadSheet } = props
|
|
||||||
const previewState = useEditorStore((s) => s.previewState)
|
|
||||||
const tab = previewState ? initialTab(previewState, tier) : 'annotations'
|
|
||||||
const userId = useAuthStore((s) => s.user?.id ?? '')
|
const userId = useAuthStore((s) => s.user?.id ?? '')
|
||||||
const owner = useMemo(
|
return useMemo(() => ({ sheetId, userId }), [sheetId, userId])
|
||||||
() => ({ sheetId: sheet.sheet_id, userId }),
|
}
|
||||||
[sheet.sheet_id, userId],
|
|
||||||
)
|
/** A reload or a reopened entry shows the view the history kept, never a layer. */
|
||||||
// A reload or a reopened entry shows the view the history kept, never a layer.
|
function useRestoredView(owner: HistoryOwner) {
|
||||||
const { state } = useLocation()
|
const { state } = useLocation()
|
||||||
const [view] = useState(() => {
|
const [view] = useState(() => {
|
||||||
const entry = ownedEntry(state, owner)
|
const entry = ownedEntry(state, owner)
|
||||||
return entry && withoutForms(entry.view)
|
return entry && withoutForms(entry.view)
|
||||||
})
|
})
|
||||||
const nav = useEditorNavigation(tab, view)
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The navigation of this sheet for this account: the first tab known at mount
|
||||||
|
* (`initialTab`), the view a kept entry holds, the browser history in step with it, and
|
||||||
|
* whether the last editor left a dirty dialog behind.
|
||||||
|
*/
|
||||||
|
function useWorkspaceNavigation(sheetId: string, tier: TabTier) {
|
||||||
|
const previewState = useEditorStore((s) => s.previewState)
|
||||||
|
const tab = previewState ? initialTab(previewState, tier) : 'annotations'
|
||||||
|
const owner = useOwner(sheetId)
|
||||||
|
const nav = useEditorNavigation(tab, useRestoredView(owner))
|
||||||
useEditorHistory(nav, owner, defaultView(tab))
|
useEditorHistory(nav, owner, defaultView(tab))
|
||||||
|
return { nav, left: useLeftDraft(nav, owner) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The last editor of this sheet was left with a dirty dialog: said once. */
|
||||||
|
function LeftDraftNotice({ shown }: { shown: boolean }) {
|
||||||
|
const t = useT()
|
||||||
|
if (!shown) return null
|
||||||
|
return <Notice tone="info">{t('editor.leave.draft_dropped')}</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* mount and later edits never move the user off their tab.
|
||||||
|
*/
|
||||||
|
export default function EditorWorkspace(props: Props) {
|
||||||
|
const { sheet, mode, readOnly } = props
|
||||||
|
const { nav, left } = useWorkspaceNavigation(sheet.sheet_id, props.tier)
|
||||||
return (
|
return (
|
||||||
<EditingState readOnly={readOnly} mode={mode}>
|
<EditingState readOnly={readOnly} mode={mode}>
|
||||||
<div className="space-y-4" data-editor-workspace>
|
<div className="space-y-4" data-editor-workspace>
|
||||||
<DraftHeader sheet={sheet} mode={mode} />
|
<DraftHeader sheet={sheet} mode={mode} />
|
||||||
<ModeNotice mode={mode} sheet={sheet} />
|
<ModeNotice mode={mode} sheet={sheet} />
|
||||||
|
<LeftDraftNotice shown={left} />
|
||||||
<SaveFailureNotice />
|
<SaveFailureNotice />
|
||||||
<RecoveryNotice />
|
<RecoveryNotice />
|
||||||
<CopyIssueNotice />
|
<CopyIssueNotice />
|
||||||
<EditorTabs
|
<EditorTabs
|
||||||
active={nav.state.tab}
|
active={nav.state.tab}
|
||||||
tier={tier}
|
tier={props.tier}
|
||||||
onSelect={nav.selectTab}
|
onSelect={nav.selectTab}
|
||||||
/>
|
/>
|
||||||
<FocusConsumedContext value={nav.consumed}>
|
<FocusConsumedContext value={nav.consumed}>
|
||||||
<AnnounceContext value={nav.announce}>
|
<AnnounceContext value={nav.announce}>
|
||||||
<Places nav={nav} readOnly={readOnly} reloadSheet={reloadSheet} />
|
<Places
|
||||||
|
nav={nav}
|
||||||
|
readOnly={readOnly}
|
||||||
|
reloadSheet={props.reloadSheet}
|
||||||
|
/>
|
||||||
</AnnounceContext>
|
</AnnounceContext>
|
||||||
</FocusConsumedContext>
|
</FocusConsumedContext>
|
||||||
<p aria-live="polite" className="sr-only">
|
<p aria-live="polite" className="sr-only">
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import type {
|
import type {
|
||||||
EditCommand,
|
EditCommand,
|
||||||
FindingCategoryKind,
|
FindingCategoryKind,
|
||||||
@@ -44,15 +43,17 @@ export interface FindingCreateFormProps {
|
|||||||
onClose: (forced: boolean) => void
|
onClose: (forced: boolean) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What the form holds before « Créer »; the zone of a category is part of it. */
|
||||||
interface Draft {
|
interface Draft {
|
||||||
fr: string
|
fr: string
|
||||||
en: string
|
en: string
|
||||||
kind: string
|
kind: string
|
||||||
|
zone: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const EMPTY: Draft = { fr: '', en: '', kind: '' }
|
const EMPTY: Draft = { fr: '', en: '', kind: '', zone: '' }
|
||||||
const sameDraft = (a: Draft, b: Draft) =>
|
const sameDraft = (a: Draft, b: Draft) =>
|
||||||
a.fr === b.fr && a.en === b.en && a.kind === b.kind
|
a.fr === b.fr && a.en === b.en && a.kind === b.kind && a.zone === b.zone
|
||||||
|
|
||||||
/** What the core requires before an insert: both names, a zone and a kind for a category. */
|
/** 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) {
|
function isComplete(draft: Draft, pending: PendingFinding, parent: unknown) {
|
||||||
@@ -76,14 +77,23 @@ function insertNew(
|
|||||||
return added ? createdId : null
|
return added ? createdId : null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** With exactly one zone it is preselected: the form starts on it, nothing typed yet. */
|
||||||
|
const preselected = (zones: readonly FindingItem[]) =>
|
||||||
|
zones.length === 1 ? zones[0].zoneId : ''
|
||||||
|
|
||||||
/** The form's state and its one `insert` (« Créer »), refused on a missing field. */
|
/** The form's state and its one `insert` (« Créer »), refused on a missing field. */
|
||||||
function useCreateForm(props: FindingCreateFormProps) {
|
function useCreateForm(props: FindingCreateFormProps) {
|
||||||
const edit = useEditCommand()
|
const edit = useEditCommand()
|
||||||
const zones = useZoneChoice()
|
const zones = useZones()
|
||||||
const form = useFormDraft(EMPTY, props.guards, sameDraft)
|
const form = useFormDraft(
|
||||||
|
{ ...EMPTY, zone: preselected(zones) },
|
||||||
|
props.guards,
|
||||||
|
sameDraft,
|
||||||
|
)
|
||||||
|
const chosen = zones.find((zone) => zone.zoneId === form.draft.zone) ?? null
|
||||||
const create = () => {
|
const create = () => {
|
||||||
const { pending } = props
|
const { pending } = props
|
||||||
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
|
const parent = pending.kind === 'category' ? chosen : pending.parent
|
||||||
if (!isComplete(form.draft, pending, parent)) {
|
if (!isComplete(form.draft, pending, parent)) {
|
||||||
edit.reject('form', 'editor.findings.required')
|
edit.reject('form', 'editor.findings.required')
|
||||||
return
|
return
|
||||||
@@ -91,7 +101,7 @@ function useCreateForm(props: FindingCreateFormProps) {
|
|||||||
const id = insertNew(edit, pending, parent, form.draft)
|
const id = insertNew(edit, pending, parent, form.draft)
|
||||||
if (id !== null) props.onCreated(id, parent)
|
if (id !== null) props.onCreated(id, parent)
|
||||||
}
|
}
|
||||||
return { ...form, zones, create, error: edit.fieldError('form') }
|
return { ...form, zones, chosen, create, error: edit.fieldError('form') }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The kind choice of a category and its two names, as draft fields. */
|
/** The kind choice of a category and its two names, as draft fields. */
|
||||||
@@ -108,7 +118,14 @@ function CreateFields(props: {
|
|||||||
}))
|
}))
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-3 md:grid-cols-2">
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
{category && <ZoneSelect zones={form.zones} readOnly={readOnly} />}
|
{category && (
|
||||||
|
<ZoneSelect
|
||||||
|
zones={form.zones}
|
||||||
|
value={form.draft.zone}
|
||||||
|
readOnly={readOnly}
|
||||||
|
onCommit={(zone) => form.set({ zone })}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{category && (
|
{category && (
|
||||||
<SelectField
|
<SelectField
|
||||||
id="finding-new-kind"
|
id="finding-new-kind"
|
||||||
@@ -153,7 +170,7 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{props.readOnly && <ReadOnlyNotice />}
|
{props.readOnly && <ReadOnlyNotice />}
|
||||||
{category && form.zones.chosen && <ZoneTitle zone={form.zones.chosen} />}
|
{category && form.chosen && <ZoneTitle zone={form.chosen} />}
|
||||||
<CreateFields form={form} category={category} readOnly={props.readOnly} />
|
<CreateFields form={form} category={category} readOnly={props.readOnly} />
|
||||||
{form.error && (
|
{form.error && (
|
||||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||||
@@ -172,30 +189,17 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ZoneChoice {
|
/** The zones a new category can go in. */
|
||||||
zones: readonly FindingItem[]
|
function useZones(): readonly FindingItem[] {
|
||||||
zoneId: string
|
|
||||||
setZoneId: (id: string) => void
|
|
||||||
chosen: FindingItem | null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The zones to choose from; with exactly one, it is preselected, otherwise nothing is. */
|
|
||||||
function useZoneChoice(): ZoneChoice {
|
|
||||||
const doc = useSheetDocument()
|
const doc = useSheetDocument()
|
||||||
const zones = doc ? buildItems(doc).filter((i) => i.kind === 'zone') : []
|
return doc ? buildItems(doc).filter((i) => i.kind === 'zone') : []
|
||||||
const [zoneId, setZoneId] = useState(
|
|
||||||
zones.length === 1 ? zones[0].zoneId : '',
|
|
||||||
)
|
|
||||||
const chosen = zones.find((zone) => zone.zoneId === zoneId) ?? null
|
|
||||||
return { zones, zoneId, setZoneId, chosen }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function ZoneSelect({
|
function ZoneSelect(props: {
|
||||||
zones,
|
zones: readonly FindingItem[]
|
||||||
readOnly,
|
value: string
|
||||||
}: {
|
|
||||||
zones: ZoneChoice
|
|
||||||
readOnly: boolean
|
readOnly: boolean
|
||||||
|
onCommit: (zoneId: string) => void
|
||||||
}) {
|
}) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
const locale = useLocaleStore((s) => s.locale)
|
const locale = useLocaleStore((s) => s.locale)
|
||||||
@@ -203,16 +207,16 @@ function ZoneSelect({
|
|||||||
<SelectField
|
<SelectField
|
||||||
id="finding-new-zone"
|
id="finding-new-zone"
|
||||||
label={t('editor.findings.zone')}
|
label={t('editor.findings.zone')}
|
||||||
value={zones.zoneId}
|
value={props.value}
|
||||||
readOnly={readOnly}
|
readOnly={props.readOnly}
|
||||||
options={[
|
options={[
|
||||||
{ value: '', label: t('editor.field.choose') },
|
{ value: '', label: t('editor.field.choose') },
|
||||||
...zones.zones.map((zone) => ({
|
...props.zones.map((zone) => ({
|
||||||
value: zone.zoneId,
|
value: zone.zoneId,
|
||||||
label: zone.name[locale],
|
label: zone.name[locale],
|
||||||
})),
|
})),
|
||||||
]}
|
]}
|
||||||
onCommit={zones.setZoneId}
|
onCommit={props.onCommit}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect, useRef } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||||
import Dialog from '@/components/ui/Dialog'
|
import Dialog from '@/components/ui/Dialog'
|
||||||
import { visibleElement } from '@/editor/focusRequest'
|
import { visibleElement } from '@/editor/focusRequest'
|
||||||
@@ -60,12 +60,28 @@ function useReturnTarget(layer: ReferenceLayer) {
|
|||||||
}, [opener])
|
}, [opener])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The reference a creation just handed its entry over to (`layer.created`): the dialog
|
||||||
|
* still shows the creation while it closes, never « Modifier la référence ». Forgotten
|
||||||
|
* once the layer is closed.
|
||||||
|
*/
|
||||||
|
function useHandOver(layer: ReferenceLayer) {
|
||||||
|
const [handed, setHanded] = useState<string | null>(null)
|
||||||
|
if (handed !== null && !layer.view) setHanded(null)
|
||||||
|
return { handed, handOver: setHanded }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A creation, or the reference a creation was just handed over to. */
|
||||||
|
function isCreation(view: View, handed: string | null): boolean {
|
||||||
|
return !!view && ('create' in view || view.edit === handed)
|
||||||
|
}
|
||||||
|
|
||||||
/** What the layer shows: a creation, or the reference it edits (null once it is gone). */
|
/** What the layer shows: a creation, or the reference it edits (null once it is gone). */
|
||||||
function useShownReference(layer: ReferenceLayer) {
|
function useShownReference(layer: ReferenceLayer, handed: string | null) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
const doc = useSheetDocument()
|
const doc = useSheetDocument()
|
||||||
const creating = !!layer.view && 'create' in layer.view
|
const creating = isCreation(layer.view, handed)
|
||||||
const edited = editedIn(layer.view, doc?.references)
|
const edited = creating ? null : editedIn(layer.view, doc?.references)
|
||||||
const title = creating
|
const title = creating
|
||||||
? 'editor.reference.new'
|
? 'editor.reference.new'
|
||||||
: 'editor.references.edit_title'
|
: 'editor.references.edit_title'
|
||||||
@@ -73,10 +89,15 @@ function useShownReference(layer: ReferenceLayer) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
|
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
|
||||||
function useOnSaved(layer: ReferenceLayer, creating: boolean) {
|
function useOnSaved(
|
||||||
|
layer: ReferenceLayer,
|
||||||
|
creating: boolean,
|
||||||
|
handOver: (id: string) => void,
|
||||||
|
) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
return (id: string, citation: string) => {
|
return (id: string, citation: string) => {
|
||||||
if (!creating) return void layer.close(true)
|
if (!creating) return void layer.close(true)
|
||||||
|
handOver(id)
|
||||||
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
||||||
layer.created(id)
|
layer.created(id)
|
||||||
}
|
}
|
||||||
@@ -92,9 +113,10 @@ export default function ReferenceDialog({
|
|||||||
layer,
|
layer,
|
||||||
readOnly,
|
readOnly,
|
||||||
}: ReferenceDialogProps) {
|
}: ReferenceDialogProps) {
|
||||||
const shown = useShownReference(layer)
|
const creation = useHandOver(layer)
|
||||||
|
const shown = useShownReference(layer, creation.handed)
|
||||||
const returnFocus = useReturnTarget(layer)
|
const returnFocus = useReturnTarget(layer)
|
||||||
const onSaved = useOnSaved(layer, shown.creating)
|
const onSaved = useOnSaved(layer, shown.creating, creation.handOver)
|
||||||
useGoneRule(layer)
|
useGoneRule(layer)
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState, type RefObject } from 'react'
|
import { useEffect, useRef, useState, type RefObject } from 'react'
|
||||||
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
||||||
import {
|
import {
|
||||||
focusRow,
|
focusRow,
|
||||||
@@ -31,10 +31,11 @@ function useFilterFinding(layer: ReferenceLayer) {
|
|||||||
const doc = useSheetDocument()
|
const doc = useSheetDocument()
|
||||||
const finding = doc ? citingFinding(doc, layer.filter) : null
|
const finding = doc ? citingFinding(doc, layer.filter) : null
|
||||||
const gone = doc !== null && layer.filter !== null && finding === null
|
const gone = doc !== null && layer.filter !== null && finding === null
|
||||||
|
// The vanished finding is the trigger; the move and its wording are the latest ones.
|
||||||
|
const clear = useRef<() => void>(() => undefined)
|
||||||
|
clear.current = () => layer.clearFilter(t('editor.references.filter_gone'))
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (gone) layer.clearFilter(t('editor.references.filter_gone'))
|
if (gone) clear.current()
|
||||||
// The wording and the move are stable per render; the vanished finding is the trigger.
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [gone])
|
}, [gone])
|
||||||
return { finding, cited: finding ? new Set(citedIds(finding)) : null }
|
return { finding, cited: finding ? new Set(citedIds(finding)) : null }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import AddBar from '@/components/editor/findings/AddBar'
|
|||||||
import FindingDialog from '@/components/editor/findings/FindingDialog'
|
import FindingDialog from '@/components/editor/findings/FindingDialog'
|
||||||
import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm'
|
import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm'
|
||||||
import FindingTree from '@/components/editor/findings/FindingTree'
|
import FindingTree from '@/components/editor/findings/FindingTree'
|
||||||
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
|
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
|
||||||
import {
|
import {
|
||||||
buildItems,
|
buildItems,
|
||||||
createdItemId,
|
createdItemId,
|
||||||
@@ -62,13 +62,14 @@ function useFindingDeletion(
|
|||||||
setAsk({ target, fallback: fallbackAfterRemoval(items, item) })
|
setAsk({ target, fallback: fallbackAfterRemoval(items, item) })
|
||||||
}
|
}
|
||||||
// The element is gone: its dialog closes in the same move (replace, no Back step) and
|
// 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.
|
// the focus lands on the nearest row once every dialog is closed, unless a newer
|
||||||
|
// landing supersedes it.
|
||||||
const closeDelete = () => {
|
const closeDelete = () => {
|
||||||
setAsk(null)
|
setAsk(null)
|
||||||
if (!ask || currentItems().some((item) => item.id === selectedId)) return
|
if (!ask || currentItems().some((item) => item.id === selectedId)) return
|
||||||
actions.select(ask.fallback)
|
actions.select(ask.fallback)
|
||||||
actions.closeLayer()
|
actions.closeLayer()
|
||||||
afterModalsClosed(() => actions.focusItem(ask.fallback))
|
landAfterModalsClosed(() => actions.focusItem(ask.fallback))
|
||||||
}
|
}
|
||||||
return { deleting: ask?.target ?? null, askDelete, closeDelete }
|
return { deleting: ask?.target ?? null, askDelete, closeDelete }
|
||||||
}
|
}
|
||||||
@@ -81,17 +82,18 @@ function useSelectionOfLayer(
|
|||||||
) {
|
) {
|
||||||
const { view } = layer
|
const { view } = layer
|
||||||
const wanted = view && 'key' in view ? JSON.stringify(view.key) : null
|
const wanted = view && 'key' in view ? JSON.stringify(view.key) : null
|
||||||
|
// `show` only sets state: the layer's key and the tree are what the effect follows.
|
||||||
|
const reveal = useRef(show)
|
||||||
|
reveal.current = show
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const found = wanted && itemForKey(items, JSON.parse(wanted))
|
const found = wanted && itemForKey(items, JSON.parse(wanted))
|
||||||
if (found) show(found)
|
if (found) reveal.current(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])
|
}, [wanted, items])
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The element the dialog shows vanished (a reload after a conflict): the layer closes by
|
* The element the dialog shows, or the parent of a creation, vanished (a reload after a
|
||||||
* replace and says so; a creation whose parent vanished closes silently.
|
* conflict): the layer closes by replace and says so, with the dropped entry if any.
|
||||||
*/
|
*/
|
||||||
function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
@@ -100,8 +102,7 @@ function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!view) handled.current = null
|
if (!view) handled.current = null
|
||||||
if (!loaded || !view) return
|
if (!loaded || !view) return
|
||||||
const named = 'key' in view
|
const key = 'key' in view ? view.key : view.create.parent
|
||||||
const key = named ? view.key : view.create.parent
|
|
||||||
const stamp = JSON.stringify(view)
|
const stamp = JSON.stringify(view)
|
||||||
const present = (i: FindingItem) => key !== null && sameKey(i.key, key)
|
const present = (i: FindingItem) => key !== null && sameKey(i.key, key)
|
||||||
if (key === null || currentItems().some(present)) return
|
if (key === null || currentItems().some(present)) return
|
||||||
@@ -109,9 +110,7 @@ function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
|||||||
handled.current = stamp
|
handled.current = stamp
|
||||||
// After this commit's effects: a tile in edit re-registers its guard in them, and the
|
// 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.
|
// forced close below must still be able to ask it.
|
||||||
queueMicrotask(() =>
|
queueMicrotask(() => layer.replace(null, t('editor.findings.gone')))
|
||||||
layer.replace(null, named ? t('editor.findings.gone') : undefined),
|
|
||||||
)
|
|
||||||
}, [loaded, view, layer, t])
|
}, [loaded, view, layer, t])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,6 +260,11 @@ function useFindingsData() {
|
|||||||
return { doc, items }
|
return { doc, items }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The element the layer's dialog shows, read from the tree; null for none or a creation. */
|
||||||
|
function shownOf(view: FindingLayer['view'], items: readonly FindingItem[]) {
|
||||||
|
return view && 'key' in view ? itemForKey(items, view.key) : null
|
||||||
|
}
|
||||||
|
|
||||||
/** Everything the tab shows and does, so the component only lays it out. */
|
/** Everything the tab shows and does, so the component only lays it out. */
|
||||||
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
|
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
|
||||||
const data = useFindingsData()
|
const data = useFindingsData()
|
||||||
@@ -269,11 +273,14 @@ function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
|
|||||||
const ctx = { layer, items: data.items, sel, land: landing.land }
|
const ctx = { layer, items: data.items, sel, land: landing.land }
|
||||||
useLayerFollow(focus, ctx)
|
useLayerFollow(focus, ctx)
|
||||||
useGoneRule(layer, data.doc !== null)
|
useGoneRule(layer, data.doc !== null)
|
||||||
const actions = useFindingActions(ctx)
|
return {
|
||||||
const returnFocus = useReturnTarget(layer.view)
|
...data,
|
||||||
const { view } = layer
|
sel,
|
||||||
const shown = view && 'key' in view ? itemForKey(data.items, view.key) : null
|
landing,
|
||||||
return { ...data, sel, landing, actions, returnFocus, shown }
|
actions: useFindingActions(ctx),
|
||||||
|
returnFocus: useReturnTarget(layer.view),
|
||||||
|
shown: shownOf(layer.view, data.items),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
|
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
|
||||||
|
|||||||
@@ -110,9 +110,29 @@ function useBackRequest(open: boolean, close: () => void) {
|
|||||||
}, [open, close])
|
}, [open, close])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keyboard focus that leaves the trigger and the list closes « Plus »: the open overlay
|
||||||
|
* would cover the control the focus reached (WCAG 2.4.11). A focus that goes nowhere in
|
||||||
|
* the page (the browser's own interface) leaves it open.
|
||||||
|
*/
|
||||||
|
function useFocusLeave(open: boolean, close: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
const onOut = (event: FocusEvent) => {
|
||||||
|
const from = event.target instanceof Element ? event.target : null
|
||||||
|
const to = event.relatedTarget
|
||||||
|
if (!from?.closest(MENU_PARTS) || !(to instanceof Element)) return
|
||||||
|
if (!to.closest(MENU_PARTS)) close()
|
||||||
|
}
|
||||||
|
document.addEventListener('focusout', onOut, true)
|
||||||
|
return () => document.removeEventListener('focusout', onOut, true)
|
||||||
|
}, [open, close])
|
||||||
|
}
|
||||||
|
|
||||||
/** Every way « Plus » closes besides a selection and a tab change. */
|
/** Every way « Plus » closes besides a selection and a tab change. */
|
||||||
export function useMoreDismiss(open: boolean, close: () => void) {
|
export function useMoreDismiss(open: boolean, close: () => void) {
|
||||||
useMoreEscape(open, close)
|
useMoreEscape(open, close)
|
||||||
useOutsidePress(open, close)
|
useOutsidePress(open, close)
|
||||||
useBackRequest(open, close)
|
useBackRequest(open, close)
|
||||||
|
useFocusLeave(open, close)
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import { useIsPresent } from 'motion/react'
|
import { useIsPresent } from 'motion/react'
|
||||||
import {
|
import {
|
||||||
|
useCallback,
|
||||||
useLayoutEffect,
|
useLayoutEffect,
|
||||||
useRef,
|
useRef,
|
||||||
type KeyboardEvent,
|
type KeyboardEvent,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
|
type RefObject,
|
||||||
type SyntheticEvent,
|
type SyntheticEvent,
|
||||||
} from 'react'
|
} from 'react'
|
||||||
import { flushAfterModals } from './afterModalsClosed'
|
import { flushAfterModals } from './afterModalsClosed'
|
||||||
@@ -89,34 +91,27 @@ function restoreFocus(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** What the dialog's handlers read at the time they run, never a stale render's. */
|
||||||
* Native modal `<dialog>` shown while mounted (D13): `showModal()` makes the
|
type Latest = () => Pick<ModalDialogProps, 'returnFocus' | 'onClose'>
|
||||||
* rest of the page inert and keeps focus in the top layer. The dialog never
|
|
||||||
* closes itself: Escape and close requests call `onClose`, and it leaves the
|
|
||||||
* screen when the consumer unmounts it. Focus starts on the first control and
|
|
||||||
* then returns to the opener. Tab past the last control reaches the browser's
|
|
||||||
* own interface, never the page, as the platform intends.
|
|
||||||
*/
|
|
||||||
export default function ModalDialog({
|
|
||||||
onClose,
|
|
||||||
returnFocus,
|
|
||||||
layer,
|
|
||||||
labelledBy,
|
|
||||||
label,
|
|
||||||
describedBy,
|
|
||||||
className = '',
|
|
||||||
children,
|
|
||||||
}: ModalDialogProps) {
|
|
||||||
const ref = useRef<HTMLDialogElement>(null)
|
|
||||||
const latest = useRef({ returnFocus, onClose })
|
|
||||||
latest.current = { returnFocus, onClose }
|
|
||||||
const isPresent = useIsPresent()
|
|
||||||
const present = useRef(true)
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
/** A stable reader of the props the last render passed. */
|
||||||
|
function useLatest(props: ReturnType<Latest>): Latest {
|
||||||
|
const box = useRef(props)
|
||||||
|
box.current = props
|
||||||
|
return useCallback(() => box.current, [])
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows the dialog on mount and closes it on unmount, focus in then back to the opener.
|
||||||
|
* Answers whether the dialog is closing itself: 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).
|
||||||
|
*/
|
||||||
|
function useShowModal(
|
||||||
|
ref: RefObject<HTMLDialogElement | null>,
|
||||||
|
latest: Latest,
|
||||||
|
) {
|
||||||
|
const closingSelf = useRef(false)
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
const dialog = ref.current
|
const dialog = ref.current
|
||||||
if (!dialog) return
|
if (!dialog) return
|
||||||
@@ -137,7 +132,7 @@ export default function ModalDialog({
|
|||||||
// After the commit: the render that closes the dialog may remove the opener
|
// After the commit: the render that closes the dialog may remove the opener
|
||||||
// too. A dialog still on screen was only remounted (React StrictMode).
|
// too. A dialog still on screen was only remounted (React StrictMode).
|
||||||
queueMicrotask(() => {
|
queueMicrotask(() => {
|
||||||
const resolve = latest.current.returnFocus
|
const resolve = latest().returnFocus
|
||||||
if (!dialog.isConnected && resolve !== null) {
|
if (!dialog.isConnected && resolve !== null) {
|
||||||
restoreFocus(resolve?.() ?? null, opener, ancestors)
|
restoreFocus(resolve?.() ?? null, opener, ancestors)
|
||||||
}
|
}
|
||||||
@@ -146,8 +141,20 @@ export default function ModalDialog({
|
|||||||
queueMicrotask(flushAfterModals)
|
queueMicrotask(flushAfterModals)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [])
|
// Shown once per mount: the ref and the latest props are read when it runs.
|
||||||
|
}, [ref, latest])
|
||||||
|
return closingSelf
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Escape, the platform's cancel and a close the platform made anyway: each asks. */
|
||||||
|
function useCloseRequests(
|
||||||
|
ref: RefObject<HTMLDialogElement | null>,
|
||||||
|
latest: Latest,
|
||||||
|
isPresent: boolean,
|
||||||
|
closingSelf: RefObject<boolean>,
|
||||||
|
) {
|
||||||
|
const present = useRef(true)
|
||||||
|
present.current = isPresent
|
||||||
const onKeyDown = (event: KeyboardEvent<HTMLDialogElement>) => {
|
const onKeyDown = (event: KeyboardEvent<HTMLDialogElement>) => {
|
||||||
if (event.key !== 'Escape' || event.nativeEvent.isComposing) return
|
if (event.key !== 'Escape' || event.nativeEvent.isComposing) return
|
||||||
// A cancelled keydown is no close request: Chromium would otherwise close the
|
// A cancelled keydown is no close request: Chromium would otherwise close the
|
||||||
@@ -156,21 +163,47 @@ export default function ModalDialog({
|
|||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
// A held key repeats: only the first press asks.
|
// A held key repeats: only the first press asks.
|
||||||
if (event.repeat) return
|
if (event.repeat) return
|
||||||
onClose()
|
latest().onClose()
|
||||||
}
|
}
|
||||||
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
|
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
onClose()
|
latest().onClose()
|
||||||
}
|
}
|
||||||
// Closed by the platform anyway: keep the consumer's state in step. The check
|
// Closed by the platform anyway: keep the consumer's state in step. The check
|
||||||
// ignores the `close` event queued by a cleanup the dialog has since reopened from.
|
// ignores the `close` event queued by a cleanup the dialog has since reopened from.
|
||||||
// A refused close shows the dialog again, never during an exit or once it is gone.
|
// A refused close shows the dialog again, never during an exit or once it is gone.
|
||||||
const onClosed = () => {
|
const onClose = () => {
|
||||||
const dialog = ref.current
|
const dialog = ref.current
|
||||||
if (!dialog || dialog.open || closingSelf.current) return
|
if (!dialog || dialog.open || closingSelf.current) return
|
||||||
const refused = latest.current.onClose() === 'kept'
|
const refused = latest().onClose() === 'kept'
|
||||||
if (refused && present.current && dialog.isConnected) dialog.showModal()
|
if (refused && present.current && dialog.isConnected) dialog.showModal()
|
||||||
}
|
}
|
||||||
|
return { onKeyDown, onCancel, onClose }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Native modal `<dialog>` shown while mounted (D13): `showModal()` makes the
|
||||||
|
* rest of the page inert and keeps focus in the top layer. The dialog never
|
||||||
|
* closes itself: Escape and close requests call `onClose`, and it leaves the
|
||||||
|
* screen when the consumer unmounts it. Focus starts on the first control and
|
||||||
|
* then returns to the opener. Tab past the last control reaches the browser's
|
||||||
|
* own interface, never the page, as the platform intends.
|
||||||
|
*/
|
||||||
|
export default function ModalDialog({
|
||||||
|
onClose,
|
||||||
|
returnFocus,
|
||||||
|
layer,
|
||||||
|
labelledBy,
|
||||||
|
label,
|
||||||
|
describedBy,
|
||||||
|
className = '',
|
||||||
|
children,
|
||||||
|
}: ModalDialogProps) {
|
||||||
|
const ref = useRef<HTMLDialogElement>(null)
|
||||||
|
const latest = useLatest({ returnFocus, onClose })
|
||||||
|
const isPresent = useIsPresent()
|
||||||
|
const closingSelf = useShowModal(ref, latest)
|
||||||
|
const requests = useCloseRequests(ref, latest, isPresent, closingSelf)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<dialog
|
<dialog
|
||||||
@@ -181,9 +214,9 @@ export default function ModalDialog({
|
|||||||
aria-labelledby={labelledBy}
|
aria-labelledby={labelledBy}
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
onKeyDown={onKeyDown}
|
onKeyDown={requests.onKeyDown}
|
||||||
onCancel={onCancel}
|
onCancel={requests.onCancel}
|
||||||
onClose={onClosed}
|
onClose={requests.onClose}
|
||||||
className={`${SURFACE} ${className}`}
|
className={`${SURFACE} ${className}`}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -29,11 +29,35 @@ export function flushAfterModals(): void {
|
|||||||
ready.forEach((fn) => fn())
|
ready.forEach((fn) => fn())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The focus landing still waiting, as its cancel. The page has one focus, so one landing:
|
||||||
|
* a newer one supersedes it (a stale move never takes the focus once the dialogs close).
|
||||||
|
*/
|
||||||
|
let pendingLanding: () => void = () => undefined
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `afterModalsClosed` for a focus landing: a dialog closed in the same commit restores
|
* `afterModalsClosed` for a focus landing: a dialog closed in the same commit restores
|
||||||
* its own focus in a microtask queued before this call, so the landing waits one more
|
* its own focus in a microtask queued before this call, so the landing waits one more
|
||||||
* microtask and is never undone by it.
|
* microtask and is never undone by it. It cancels the landing still waiting, and answers
|
||||||
|
* its own cancel.
|
||||||
*/
|
*/
|
||||||
export function landAfterModalsClosed(fn: () => void): () => void {
|
export function landAfterModalsClosed(fn: () => void): () => void {
|
||||||
return afterModalsClosed(() => queueMicrotask(fn))
|
pendingLanding()
|
||||||
|
let live = true
|
||||||
|
const unwait = afterModalsClosed(() =>
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (live) fn()
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const cancel = () => {
|
||||||
|
live = false
|
||||||
|
unwait()
|
||||||
|
}
|
||||||
|
pendingLanding = cancel
|
||||||
|
return cancel
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drops the landing still waiting: a Back onto a dialog, an editor that goes. */
|
||||||
|
export function cancelLanding(): void {
|
||||||
|
pendingLanding()
|
||||||
}
|
}
|
||||||
@@ -92,7 +92,10 @@ function rowOf(key: ElementKey): HTMLElement | null {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
|
/**
|
||||||
|
* Scrolls to and focuses the visible row tagged with `key`; false unless the row now
|
||||||
|
* holds the focus.
|
||||||
|
*/
|
||||||
export function focusRow(key: ElementKey): boolean {
|
export function focusRow(key: ElementKey): boolean {
|
||||||
const row = rowOf(key)
|
const row = rowOf(key)
|
||||||
if (!row) return false
|
if (!row) return false
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||||
|
import { MAX_FINDING_PATH } from '../findings/tree'
|
||||||
import {
|
import {
|
||||||
ANNOTATION_SECTIONS,
|
ANNOTATION_SECTIONS,
|
||||||
isFindingNode,
|
isFindingNode,
|
||||||
@@ -34,16 +35,23 @@ export const ENTRY_KEY = 'editorEntry'
|
|||||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||||
typeof value === 'object' && value !== null
|
typeof value === 'object' && value !== null
|
||||||
|
|
||||||
|
/** Longest id or key read back: a longer one is no id this editor wrote. */
|
||||||
|
const MAX_ID_LENGTH = 128
|
||||||
|
|
||||||
|
const isId = (value: unknown): value is string =>
|
||||||
|
typeof value === 'string' && value.length <= MAX_ID_LENGTH
|
||||||
|
|
||||||
|
/** A finding path no deeper than the tree allows, each id within the cap. */
|
||||||
|
const isPath = (path: unknown): path is string[] =>
|
||||||
|
Array.isArray(path) && path.length <= MAX_FINDING_PATH && path.every(isId)
|
||||||
|
|
||||||
/** A finding or zone key as the tree builds it, or null when `raw` is no such key. */
|
/** A finding or zone key as the tree builds it, or null when `raw` is no such key. */
|
||||||
function sanitizeKey(raw: unknown): ElementKey | null {
|
function sanitizeKey(raw: unknown): ElementKey | null {
|
||||||
if (!isRecord(raw)) return null
|
if (!isRecord(raw)) return null
|
||||||
if (raw.kind === 'zone' && typeof raw.id === 'string') {
|
if (raw.kind === 'zone' && isId(raw.id)) return { kind: 'zone', id: raw.id }
|
||||||
return { kind: 'zone', id: raw.id }
|
|
||||||
}
|
|
||||||
const { zone_id: zoneId, path } = raw
|
const { zone_id: zoneId, path } = raw
|
||||||
const ids = Array.isArray(path) && path.every((id) => typeof id === 'string')
|
if (raw.kind !== 'finding' || !isId(zoneId) || !isPath(path)) return null
|
||||||
if (raw.kind !== 'finding' || typeof zoneId !== 'string' || !ids) return null
|
return { kind: 'finding', zone_id: zoneId, path }
|
||||||
return { kind: 'finding', zone_id: zoneId, path: path as string[] }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const CREATION_KINDS = ['zone', 'category', 'node']
|
const CREATION_KINDS = ['zone', 'category', 'node']
|
||||||
@@ -82,7 +90,7 @@ function sanitizeReference(
|
|||||||
const sheet = !!finding && 'key' in finding && finding.citations
|
const sheet = !!finding && 'key' in finding && finding.citations
|
||||||
if (raw.create === true) return tab === 'references' ? { create: true } : null
|
if (raw.create === true) return tab === 'references' ? { create: true } : null
|
||||||
const id = raw.edit
|
const id = raw.edit
|
||||||
if (typeof id !== 'string' || id === '') return null
|
if (!isId(id) || id === '') return null
|
||||||
return tab === 'references' || sheet ? { edit: id } : null
|
return tab === 'references' || sheet ? { edit: id } : null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,16 +129,22 @@ export function withoutForms(view: EditorView): EditorView {
|
|||||||
return sanitizeView(view, false) ?? view
|
return sanitizeView(view, false) ?? view
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The entry's id and owner, each a string within the cap, or null. */
|
||||||
|
function idsOf(raw: Record<string, unknown>) {
|
||||||
|
const { id, sheetId, userId } = raw
|
||||||
|
const valid = isId(id) && isId(sheetId) && isId(userId)
|
||||||
|
return valid ? { id, sheetId, userId } : null
|
||||||
|
}
|
||||||
|
|
||||||
/** The entry `state` (a `location.state`) carries, or null when it carries none. */
|
/** The entry `state` (a `location.state`) carries, or null when it carries none. */
|
||||||
export function readEntry(state: unknown): HistoryEntry | null {
|
export function readEntry(state: unknown): HistoryEntry | null {
|
||||||
const raw = isRecord(state) ? state[ENTRY_KEY] : null
|
const raw = isRecord(state) ? state[ENTRY_KEY] : null
|
||||||
if (!isRecord(raw)) return null
|
if (!isRecord(raw)) return null
|
||||||
const view = sanitizeView(raw.view)
|
const view = sanitizeView(raw.view)
|
||||||
const { id, sheetId, userId } = raw
|
const ids = idsOf(raw)
|
||||||
if (!view || typeof id !== 'string') return null
|
if (!view || !ids) return null
|
||||||
if (typeof sheetId !== 'string' || typeof userId !== 'string') return null
|
|
||||||
const below = raw.below === null ? null : sanitizeView(raw.below)
|
const below = raw.below === null ? null : sanitizeView(raw.below)
|
||||||
return { id, view, below, sheetId, userId }
|
return { ...ids, view, below }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An entry restores only for the sheet and the account that wrote it. */
|
/** An entry restores only for the sheet and the account that wrote it. */
|
||||||
@@ -164,7 +178,7 @@ function isStepOver(view: EditorView): boolean {
|
|||||||
|
|
||||||
/** True when the move took a layer away, or left a section for its drawing. */
|
/** True when the move took a layer away, or left a section for its drawing. */
|
||||||
function isRemoval(top: EditorView, view: EditorView): boolean {
|
function isRemoval(top: EditorView, view: EditorView): boolean {
|
||||||
// Another tab is a move of its own (« Tout afficher », « Aller à »): it pushes.
|
// Another tab is a move of its own (« Tout afficher »): it pushes.
|
||||||
if (view.tab !== top.tab) return false
|
if (view.tab !== top.tab) return false
|
||||||
if (layerCount(view) < layerCount(top)) return true
|
if (layerCount(view) < layerCount(top)) return true
|
||||||
const backToDrawing = view.tab === top.tab && isStepOver(top)
|
const backToDrawing = view.tab === top.tab && isStepOver(top)
|
||||||
@@ -186,18 +200,21 @@ export function showsFinding(view: EditorView, key: ElementKey): boolean {
|
|||||||
* au dessin"), goes back when the entry holds the view the move lands on (the entry that
|
* au dessin"), goes back when the entry holds the view the move lands on (the entry that
|
||||||
* opened it), else it replaces; a layer, tab or section added pushes, unless the move
|
* opened it), else it replaces; a layer, tab or section added pushes, unless the move
|
||||||
* asked for a replace. `backTo` (« Revenir au constat ») goes back when the entry below
|
* asked for a replace. `backTo` (« Revenir au constat ») goes back when the entry below
|
||||||
* shows that finding.
|
* shows that finding. `own` (« Aller à ») is a move of its own: it pushes, even when it
|
||||||
|
* leaves fewer layers on the same tab, so the place it left stays one Back away.
|
||||||
*/
|
*/
|
||||||
export function planWrite(
|
export function planWrite(
|
||||||
top: HistoryEntry,
|
top: HistoryEntry,
|
||||||
view: EditorView,
|
view: EditorView,
|
||||||
replace: boolean,
|
replace: boolean,
|
||||||
backTo: ElementKey | null = null,
|
backTo: ElementKey | null = null,
|
||||||
|
own = false,
|
||||||
): HistoryWrite {
|
): HistoryWrite {
|
||||||
if (sameView(top.view, view)) return 'none'
|
if (sameView(top.view, view)) return 'none'
|
||||||
if (replace) return 'replace'
|
if (replace) return 'replace'
|
||||||
// « Revenir au constat »: the entry below already shows that finding, a Back is the move.
|
// « Revenir au constat »: the entry below already shows that finding, a Back is the move.
|
||||||
if (backTo && top.below && showsFinding(top.below, backTo)) return 'back'
|
if (backTo && top.below && showsFinding(top.below, backTo)) return 'back'
|
||||||
|
if (own) return 'push'
|
||||||
if (isRemoval(top.view, view)) {
|
if (isRemoval(top.view, view)) {
|
||||||
return top.below && sameView(top.below, view) ? 'back' : 'replace'
|
return top.below && sameView(top.below, view) ? 'back' : 'replace'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { useLocation, useNavigate, useNavigationType } from 'react-router-dom'
|
import {
|
||||||
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
|
useLocation,
|
||||||
|
useNavigate,
|
||||||
|
useNavigationType,
|
||||||
|
type Location,
|
||||||
|
} from 'react-router-dom'
|
||||||
|
import {
|
||||||
|
cancelLanding,
|
||||||
|
landAfterModalsClosed,
|
||||||
|
} from '@/components/ui/afterModalsClosed'
|
||||||
import { focusActiveTab } from '../focusRequest'
|
import { focusActiveTab } from '../focusRequest'
|
||||||
import { sameView, type EditorView } from '../navigation'
|
import { sameView, type EditorView } from '../navigation'
|
||||||
import {
|
import {
|
||||||
@@ -8,15 +16,18 @@ import {
|
|||||||
shownPlace,
|
shownPlace,
|
||||||
useMoveText,
|
useMoveText,
|
||||||
type EditorNavigation,
|
type EditorNavigation,
|
||||||
|
type MoveTrace,
|
||||||
} from '../useEditorNavigation'
|
} from '../useEditorNavigation'
|
||||||
import {
|
import {
|
||||||
createWriteBudget,
|
createWriteBudget,
|
||||||
entryState,
|
entryState,
|
||||||
|
layerCount,
|
||||||
ownedEntry,
|
ownedEntry,
|
||||||
planWrite,
|
planWrite,
|
||||||
withoutForms,
|
withoutForms,
|
||||||
type HistoryEntry,
|
type HistoryEntry,
|
||||||
type HistoryOwner,
|
type HistoryOwner,
|
||||||
|
type HistoryWrite,
|
||||||
} from './entry'
|
} from './entry'
|
||||||
|
|
||||||
/** Well under WebKit's 100 history writes per 10 s: past it a view stays in memory. */
|
/** Well under WebKit's 100 history writes per 10 s: past it a view stays in memory. */
|
||||||
@@ -29,28 +40,55 @@ const BACK_TIMEOUT_MS = 1_000
|
|||||||
interface Book {
|
interface Book {
|
||||||
/** The entry on top of the history as the adapter knows it (null before the mount). */
|
/** The entry on top of the history as the adapter knows it (null before the mount). */
|
||||||
entry: HistoryEntry | null
|
entry: HistoryEntry | null
|
||||||
|
/** The entry the browser holds on top: not `entry` once a push stayed in memory. */
|
||||||
|
sent: HistoryEntry | null
|
||||||
|
/** The pathname the editor mounted on: a location elsewhere is not this editor's. */
|
||||||
|
path: string | null
|
||||||
/** The router location last read: each location object is read once (see `usePop`). */
|
/** The router location last read: each location object is read once (see `usePop`). */
|
||||||
seen: object | null
|
seen: object | null
|
||||||
pendingBack: boolean
|
pendingBack: boolean
|
||||||
backTimer: ReturnType<typeof setTimeout> | undefined
|
backTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
/** Scroll position of the entries left, by entry id. */
|
/** Scroll position of the entries left, by entry id. */
|
||||||
scrolls: Map<string, number>
|
scrolls: Map<string, number>
|
||||||
|
/** Entry ids: a prefix drawn once per mount, so a reload never reuses one, a counter. */
|
||||||
|
prefix: string
|
||||||
counter: number
|
counter: number
|
||||||
takeWrite: (now: number) => boolean
|
takeWrite: (now: number) => boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A random prefix: entries left by an earlier mount of this tab keep their own ids. */
|
||||||
|
function mountPrefix(): string {
|
||||||
|
const words = crypto.getRandomValues(new Uint32Array(2))
|
||||||
|
return Array.from(words, (word) => word.toString(36)).join('')
|
||||||
|
}
|
||||||
|
|
||||||
function newBook(): Book {
|
function newBook(): Book {
|
||||||
return {
|
return {
|
||||||
entry: null,
|
entry: null,
|
||||||
|
sent: null,
|
||||||
|
path: null,
|
||||||
seen: null,
|
seen: null,
|
||||||
pendingBack: false,
|
pendingBack: false,
|
||||||
backTimer: undefined,
|
backTimer: undefined,
|
||||||
scrolls: new Map(),
|
scrolls: new Map(),
|
||||||
|
prefix: mountPrefix(),
|
||||||
counter: 0,
|
counter: 0,
|
||||||
takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS),
|
takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** An entry read from the browser's history: it is the top, as the browser holds it. */
|
||||||
|
function adopt(book: Book, entry: HistoryEntry): void {
|
||||||
|
book.entry = entry
|
||||||
|
book.sent = entry
|
||||||
|
}
|
||||||
|
|
||||||
|
const placeOf = ({ pathname, search, hash }: Location) => ({
|
||||||
|
pathname,
|
||||||
|
search,
|
||||||
|
hash,
|
||||||
|
})
|
||||||
|
|
||||||
/** A Back or Forward that changed the view: what the landing scrolls to, focuses and says. */
|
/** A Back or Forward that changed the view: what the landing scrolls to, focuses and says. */
|
||||||
interface Landing {
|
interface Landing {
|
||||||
entry: HistoryEntry
|
entry: HistoryEntry
|
||||||
@@ -61,7 +99,8 @@ interface Landing {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The writes, through the router so its own location follows. `push` over the write
|
* The writes, through the router so its own location follows. `push` over the write
|
||||||
* budget keeps the entry in memory only; `replace` swallows a refused write.
|
* budget keeps the entry in memory only; `replace` swallows a refused write. Nothing is
|
||||||
|
* written over a location that is not the editor's (it is leaving).
|
||||||
*/
|
*/
|
||||||
function useWriter(book: Book, owner: HistoryOwner) {
|
function useWriter(book: Book, owner: HistoryOwner) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
@@ -71,31 +110,38 @@ function useWriter(book: Book, owner: HistoryOwner) {
|
|||||||
return useMemo(() => {
|
return useMemo(() => {
|
||||||
const send = (entry: HistoryEntry, replace: boolean) => {
|
const send = (entry: HistoryEntry, replace: boolean) => {
|
||||||
const { navigate, location } = latest.current
|
const { navigate, location } = latest.current
|
||||||
const { pathname, search, hash } = location
|
if (location.pathname !== book.path) return
|
||||||
const to = { pathname, search, hash }
|
|
||||||
try {
|
try {
|
||||||
navigate(to, { replace, state: entryState(entry) })
|
navigate(placeOf(location), { replace, state: entryState(entry) })
|
||||||
|
book.sent = entry
|
||||||
} catch {
|
} catch {
|
||||||
// The view stays in memory; the next move writes again.
|
// The view stays in memory; the next move writes again.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const fresh = (view: EditorView, below: EditorView | null) => {
|
const fresh = (view: EditorView, below: EditorView | null) => {
|
||||||
book.counter += 1
|
book.counter += 1
|
||||||
return { id: `e${book.counter}`, view, below, ...owner }
|
return { id: `${book.prefix}-${book.counter}`, view, below, ...owner }
|
||||||
}
|
}
|
||||||
const write = (entry: HistoryEntry, replace: boolean) => {
|
const write = (entry: HistoryEntry, replace: boolean) => {
|
||||||
book.entry = entry
|
book.entry = entry
|
||||||
// shortcut: past the write budget a push is kept in memory only, so a later Back
|
// shortcut: past the write budget a push is kept in memory only (`settle` closes it
|
||||||
// lands on the real previous entry. Fine at one push per user move; upgrade path:
|
// without a Back), so a browser Back lands on the real previous entry. Fine at one
|
||||||
// coalesce the skipped views into one replace once the window slides.
|
// push per user move; upgrade path: coalesce the skipped views into one replace once
|
||||||
|
// the window slides.
|
||||||
if (replace || book.takeWrite(Date.now())) send(entry, replace)
|
if (replace || book.takeWrite(Date.now())) send(entry, replace)
|
||||||
}
|
}
|
||||||
|
const replace = (view: EditorView) => {
|
||||||
|
const kept = book.entry ?? fresh(view, null)
|
||||||
|
write({ ...kept, view }, true)
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
push: (view: EditorView) =>
|
push: (view: EditorView) =>
|
||||||
write(fresh(view, book.entry?.view ?? null), false),
|
write(fresh(view, book.entry?.view ?? null), false),
|
||||||
replace: (view: EditorView) => {
|
replace,
|
||||||
const kept = book.entry ?? fresh(view, null)
|
/** A close over a push kept in memory: the browser's top is the place, no Back. */
|
||||||
write({ ...kept, view }, true)
|
settle: (view: EditorView) => {
|
||||||
|
book.entry = book.sent
|
||||||
|
if (!book.sent || !sameView(book.sent.view, view)) replace(view)
|
||||||
},
|
},
|
||||||
first: (view: EditorView) => write(fresh(view, null), true),
|
first: (view: EditorView) => write(fresh(view, null), true),
|
||||||
back: () => {
|
back: () => {
|
||||||
@@ -112,6 +158,31 @@ function useWriter(book: Book, owner: HistoryOwner) {
|
|||||||
|
|
||||||
type Writer = ReturnType<typeof useWriter>
|
type Writer = ReturnType<typeof useWriter>
|
||||||
|
|
||||||
|
/** What the last move left for the adapter, read once: the trace is reset. */
|
||||||
|
function takeTrace(trace: MoveTrace): MoveTrace {
|
||||||
|
const taken = { ...trace }
|
||||||
|
Object.assign(trace, {
|
||||||
|
scrollY: null,
|
||||||
|
replace: false,
|
||||||
|
backTo: null,
|
||||||
|
own: false,
|
||||||
|
})
|
||||||
|
return taken
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Carries a planned write out; a Back over a push kept in memory settles instead. */
|
||||||
|
function follow(
|
||||||
|
plan: HistoryWrite,
|
||||||
|
view: EditorView,
|
||||||
|
book: Book,
|
||||||
|
writer: Writer,
|
||||||
|
) {
|
||||||
|
if (plan === 'push') writer.push(view)
|
||||||
|
else if (plan === 'replace') writer.replace(view)
|
||||||
|
else if (book.entry !== book.sent) writer.settle(view)
|
||||||
|
else writer.back()
|
||||||
|
}
|
||||||
|
|
||||||
/** User moves: the view changed, the history follows (R2F-1). */
|
/** User moves: the view changed, the history follows (R2F-1). */
|
||||||
function useReconcile(
|
function useReconcile(
|
||||||
nav: EditorNavigation,
|
nav: EditorNavigation,
|
||||||
@@ -120,18 +191,13 @@ function useReconcile(
|
|||||||
writer: Writer,
|
writer: Writer,
|
||||||
) {
|
) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const { scrollY, replace, backTo } = nav.trace
|
const move = takeTrace(nav.trace)
|
||||||
nav.trace.scrollY = null
|
|
||||||
nav.trace.replace = false
|
|
||||||
nav.trace.backTo = null
|
|
||||||
const top = book.entry
|
const top = book.entry
|
||||||
if (!top || book.pendingBack) return
|
if (!top || book.pendingBack) return
|
||||||
const plan = planWrite(top, view, replace, backTo)
|
const plan = planWrite(top, view, move.replace, move.backTo, move.own)
|
||||||
if (plan === 'none') return
|
if (plan === 'none') return
|
||||||
book.scrolls.set(top.id, scrollY ?? window.scrollY)
|
book.scrolls.set(top.id, move.scrollY ?? window.scrollY)
|
||||||
if (plan === 'back') writer.back()
|
follow(plan, view, book, writer)
|
||||||
else if (plan === 'push') writer.push(view)
|
|
||||||
else writer.replace(view)
|
|
||||||
}, [view, nav.trace, book, writer])
|
}, [view, nav.trace, book, writer])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,7 +249,7 @@ function landOnForeign(ctx: PopContext): Landing | null {
|
|||||||
*/
|
*/
|
||||||
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
|
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
|
||||||
const { book, writer, view } = ctx
|
const { book, writer, view } = ctx
|
||||||
if (landed) book.entry = landed
|
if (landed) adopt(book, landed)
|
||||||
writer.push(view)
|
writer.push(view)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -205,7 +271,7 @@ function landOn(ctx: PopContext, state: unknown): Landing | null {
|
|||||||
const entry = ownedEntry(state, ctx.owner)
|
const entry = ownedEntry(state, ctx.owner)
|
||||||
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
|
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
|
||||||
if (!entry) return landOnForeign(ctx)
|
if (!entry) return landOnForeign(ctx)
|
||||||
book.entry = entry
|
adopt(book, entry)
|
||||||
if (sameView(entry.view, view)) return null
|
if (sameView(entry.view, view)) return null
|
||||||
nav.restoreView(entry.view)
|
nav.restoreView(entry.view)
|
||||||
return {
|
return {
|
||||||
@@ -216,14 +282,15 @@ function landOn(ctx: PopContext, state: unknown): Landing | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The first location of the editor: an entry of this sheet and account is kept (a
|
* The first location of the editor: its pathname is the editor's from now on. An entry of
|
||||||
* reload never reopens a form, so a form layer is replaced by the view without it),
|
* this sheet and account is kept (a reload never reopens a form, so a form layer is
|
||||||
* any other is replaced by the current view.
|
* replaced by the view without it), any other is replaced by the current view.
|
||||||
*/
|
*/
|
||||||
function mount(ctx: PopContext, state: unknown): void {
|
function mount(ctx: PopContext, location: Location): void {
|
||||||
const entry = ownedEntry(state, ctx.owner)
|
ctx.book.path = location.pathname
|
||||||
|
const entry = ownedEntry(location.state, ctx.owner)
|
||||||
if (!entry) return ctx.writer.first(ctx.view)
|
if (!entry) return ctx.writer.first(ctx.view)
|
||||||
ctx.book.entry = entry
|
adopt(ctx.book, entry)
|
||||||
const kept = withoutForms(entry.view)
|
const kept = withoutForms(entry.view)
|
||||||
if (!sameView(kept, entry.view)) ctx.writer.replace(kept)
|
if (!sameView(kept, entry.view)) ctx.writer.replace(kept)
|
||||||
}
|
}
|
||||||
@@ -236,29 +303,42 @@ function landFocus({ entry, tabChanged, layerChanged }: Landing): void {
|
|||||||
else focusActiveTab({ preventScroll: true })
|
else focusActiveTab({ preventScroll: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Scroll, focus and announcement once a Back or Forward has restored a view. */
|
interface Speech {
|
||||||
|
nav: EditorNavigation
|
||||||
|
moveText: ReturnType<typeof useMoveText>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Focus and announcement of a landing, once the dialogs it closed are gone. */
|
||||||
|
function land(landing: Landing, { nav, moveText }: Speech): void {
|
||||||
|
landFocus(landing)
|
||||||
|
if (landing.layerChanged && !landing.tabChanged) return
|
||||||
|
const { view } = landing.entry
|
||||||
|
const section = view.tab === 'annotations' ? view.section : null
|
||||||
|
nav.announce(moveText({ place: 'tab', tab: view.tab, section, key: null }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scroll, focus and announcement once a Back or Forward has restored a view. The effect
|
||||||
|
* follows the landing only (the rest is read from a ref): a later render, a dialog closed
|
||||||
|
* by ✕ or a locale switch, never cancels what it waits for.
|
||||||
|
*/
|
||||||
function useLanding(
|
function useLanding(
|
||||||
nav: EditorNavigation,
|
nav: EditorNavigation,
|
||||||
book: Book,
|
book: Book,
|
||||||
landing: Landing | null,
|
landing: Landing | null,
|
||||||
) {
|
) {
|
||||||
const moveText = useMoveText()
|
const moveText = useMoveText()
|
||||||
const landed = useRef<Landing | null>(null)
|
const latest = useRef<Speech>({ nav, moveText })
|
||||||
|
latest.current = { nav, moveText }
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// A new wording (locale switch) re-creates `moveText`: the landing stays one.
|
if (!landing) return
|
||||||
if (!landing || landed.current === landing) return
|
// The page behind a dialog scrolls too: the offset is applied at once.
|
||||||
landed.current = landing
|
window.scrollTo(0, book.scrolls.get(landing.entry.id) ?? 0)
|
||||||
const { id, view } = landing.entry
|
// A dialog landed on keeps its own focus (then its return target): no older landing
|
||||||
return landAfterModalsClosed(() => {
|
// takes the focus once it is closed.
|
||||||
window.scrollTo(0, book.scrolls.get(id) ?? 0)
|
if (layerCount(landing.entry.view) > 0) return cancelLanding()
|
||||||
landFocus(landing)
|
return landAfterModalsClosed(() => land(landing, latest.current))
|
||||||
if (landing.layerChanged && !landing.tabChanged) return
|
}, [landing, book])
|
||||||
const section = view.tab === 'annotations' ? view.section : null
|
|
||||||
nav.announce(
|
|
||||||
moveText({ place: 'tab', tab: view.tab, section, key: null }),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}, [landing, book, nav, moveText])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The view the reducer holds, as one object that changes only when the view does. */
|
/** The view the reducer holds, as one object that changes only when the view does. */
|
||||||
@@ -284,6 +364,11 @@ function useManualScroll(): void {
|
|||||||
}, [])
|
}, [])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A Back still awaited when the editor goes: its timer goes with it. */
|
||||||
|
function useBackTimerCleanup(book: Book): void {
|
||||||
|
useEffect(() => () => clearTimeout(book.backTimer), [book])
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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
|
* The router makes a new location object per navigation, so a Back onto a key this
|
||||||
@@ -294,15 +379,19 @@ function usePop(ctx: PopContext): Landing | null {
|
|||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
const navType = useNavigationType()
|
const navType = useNavigationType()
|
||||||
const [landing, setLanding] = useState<Landing | null>(null)
|
const [landing, setLanding] = useState<Landing | null>(null)
|
||||||
const { book } = ctx
|
// Read once per location: the context is the one the render of that location holds.
|
||||||
|
const latest = useRef(ctx)
|
||||||
|
latest.current = ctx
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (book.seen === location) return
|
const now = latest.current
|
||||||
book.seen = location
|
if (now.book.seen === location) return
|
||||||
if (book.entry === null) mount(ctx, location.state)
|
now.book.seen = location
|
||||||
else if (navType === 'POP') setLanding(landOn(ctx, location.state))
|
if (now.book.entry === null) mount(now, location)
|
||||||
// Read once per location: the context is the one this render holds.
|
// Another page (another sheet's editor, the list): the editor is leaving, it is the
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// new page's location, and a dirty dialog goes like on any leave.
|
||||||
}, [location])
|
else if (location.pathname !== now.book.path) return
|
||||||
|
else if (navType === 'POP') setLanding(landOn(now, location.state))
|
||||||
|
}, [location, navType])
|
||||||
return landing
|
return landing
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,4 +418,5 @@ export default function useEditorHistory(
|
|||||||
useReconcile(nav, view, book, writer)
|
useReconcile(nav, view, book, writer)
|
||||||
useLanding(nav, book, landing)
|
useLanding(nav, book, landing)
|
||||||
useManualScroll()
|
useManualScroll()
|
||||||
|
useBackTimerCleanup(book)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import type { HistoryOwner } from './history/entry'
|
||||||
|
import type { NavigationState } from './navigation'
|
||||||
|
import type { EditorNavigation, LayerName } from './useEditorNavigation'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A dirty dialog lost when the editor goes (a Back of several entries, BDR-078: a Back
|
||||||
|
* cannot be refused, and a draft is never stored). One flag in this tab's sessionStorage
|
||||||
|
* says so to the next mount of the same sheet for the same account (criterion 17).
|
||||||
|
*/
|
||||||
|
const PREFIX = 'faunosteo:editor:left-draft:'
|
||||||
|
|
||||||
|
export const leftDraftKey = ({ sheetId, userId }: HistoryOwner) =>
|
||||||
|
`${PREFIX}${sheetId}:${userId}`
|
||||||
|
|
||||||
|
/** The top layer first: the dialog the user was typing in when they left. */
|
||||||
|
const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
|
||||||
|
|
||||||
|
function storage(): Storage | null {
|
||||||
|
try {
|
||||||
|
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The element the layer showed: a key, a reference, a creation's parent. Never text. */
|
||||||
|
function elementOf(state: NavigationState, layer: LayerName): unknown {
|
||||||
|
if (layer === 'reference') {
|
||||||
|
const { reference } = state
|
||||||
|
return reference && 'edit' in reference
|
||||||
|
? { kind: 'reference', id: reference.edit }
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
const { finding } = state
|
||||||
|
if (!finding) return null
|
||||||
|
return 'key' in finding ? finding.key : finding.create.parent
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called as the editor goes: a layer whose form holds changes leaves the flag. */
|
||||||
|
function flagIfDirty(owner: HistoryOwner, nav: EditorNavigation): void {
|
||||||
|
if (!owner.sheetId || !owner.userId) return
|
||||||
|
// A forced ask has no side effect: a dirty form answers with its note.
|
||||||
|
const layer = LAYERS_TOP_DOWN.find((l) => nav.guards.ask(l, true).note)
|
||||||
|
if (!layer) return
|
||||||
|
const flag = { kind: layer, key: elementOf(nav.state, layer) }
|
||||||
|
try {
|
||||||
|
storage()?.setItem(leftDraftKey(owner), JSON.stringify(flag))
|
||||||
|
} catch {
|
||||||
|
// A full or blocked storage: the leave goes unsaid, as before.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the flag is there; read once per mount. */
|
||||||
|
function readFlag(owner: HistoryOwner): boolean {
|
||||||
|
try {
|
||||||
|
return storage()?.getItem(leftDraftKey(owner)) != null
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearFlag(owner: HistoryOwner): void {
|
||||||
|
try {
|
||||||
|
storage()?.removeItem(leftDraftKey(owner))
|
||||||
|
} catch {
|
||||||
|
// Nothing to clear.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the last editor of this sheet and account left with a dirty dialog: shown once,
|
||||||
|
* then cleared. The editor's own cleanup runs before its dialogs' (a deleted tree is
|
||||||
|
* cleaned up from its root), so their guards still answer when it flags.
|
||||||
|
*/
|
||||||
|
export function useLeftDraft(
|
||||||
|
nav: EditorNavigation,
|
||||||
|
owner: HistoryOwner,
|
||||||
|
): boolean {
|
||||||
|
const latest = useRef(nav)
|
||||||
|
latest.current = nav
|
||||||
|
const [left] = useState(() => readFlag(owner))
|
||||||
|
useEffect(() => {
|
||||||
|
clearFlag(owner)
|
||||||
|
return () => flagIfDirty(owner, latest.current)
|
||||||
|
}, [owner])
|
||||||
|
return left
|
||||||
|
}
|
||||||
@@ -217,6 +217,12 @@ function openFinding(state: NavigationState, key: ElementKey): NavigationState {
|
|||||||
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
|
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The finding dialog closes with the reference dialog opened over its sheet. */
|
||||||
|
function closeFinding(state: NavigationState): NavigationState {
|
||||||
|
const reference = state.finding ? null : state.reference
|
||||||
|
return { ...state, finding: null, reference }
|
||||||
|
}
|
||||||
|
|
||||||
/** The creation form of a zone, a category or a node, on the Constats tab. */
|
/** The creation form of a zone, a category or a node, on the Constats tab. */
|
||||||
function createFinding(
|
function createFinding(
|
||||||
state: NavigationState,
|
state: NavigationState,
|
||||||
@@ -226,6 +232,17 @@ function createFinding(
|
|||||||
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
|
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The dialog a move to `target` opens with it: a zone's or a finding's, in view mode. */
|
||||||
|
function dialogOf(target: EditorTarget): EditorView['finding'] {
|
||||||
|
const { key } = target
|
||||||
|
const element = key?.kind === 'zone' || key?.kind === 'finding'
|
||||||
|
return key && element ? { key, citations: false } : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Aller à »: every layer closes and the target is shown. A zone or a finding opens its
|
||||||
|
* dialog in the same move, so the history writes one entry and keeps the place it left.
|
||||||
|
*/
|
||||||
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
|
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
|
||||||
const serial = state.serial + 1
|
const serial = state.serial + 1
|
||||||
// The filter survives only a move to the tab itself that names no reference.
|
// The filter survives only a move to the tab itself that names no reference.
|
||||||
@@ -234,7 +251,7 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState {
|
|||||||
...state,
|
...state,
|
||||||
tab: target.tab,
|
tab: target.tab,
|
||||||
section: target.section ?? state.section,
|
section: target.section ?? state.section,
|
||||||
finding: null,
|
finding: dialogOf(target),
|
||||||
reference: null,
|
reference: null,
|
||||||
referenceFilter: keep ? state.referenceFilter : null,
|
referenceFilter: keep ? state.referenceFilter : null,
|
||||||
focus: { target, serial },
|
focus: { target, serial },
|
||||||
@@ -295,7 +312,7 @@ 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':
|
||||||
return { ...state, finding: null }
|
return closeFinding(state)
|
||||||
case 'open_citations':
|
case 'open_citations':
|
||||||
return openCitations(state, action.citedBy)
|
return openCitations(state, action.citedBy)
|
||||||
case 'close_citations':
|
case 'close_citations':
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||||
import {
|
import {
|
||||||
afterModalsClosed,
|
afterModalsClosed,
|
||||||
|
cancelLanding,
|
||||||
landAfterModalsClosed,
|
landAfterModalsClosed,
|
||||||
} from '@/components/ui/afterModalsClosed'
|
} from '@/components/ui/afterModalsClosed'
|
||||||
import { useT } from '@/i18n/useT'
|
import { useT } from '@/i18n/useT'
|
||||||
@@ -75,6 +76,11 @@ export interface MoveTrace {
|
|||||||
replace: boolean
|
replace: boolean
|
||||||
/** « Revenir au constat »: a Back when the entry below shows this finding. */
|
/** « Revenir au constat »: a Back when the entry below shows this finding. */
|
||||||
backTo: ElementKey | null
|
backTo: ElementKey | null
|
||||||
|
/**
|
||||||
|
* « Aller à »: a move of its own, it pushes. Set by the move, read and reset by the
|
||||||
|
* adapter only: a place answering the move in the same commit (`mark`) keeps it.
|
||||||
|
*/
|
||||||
|
own: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Options of a tab choice. */
|
/** Options of a tab choice. */
|
||||||
@@ -100,8 +106,9 @@ export interface EditorNavigation {
|
|||||||
closeFinding: (forced?: boolean) => boolean
|
closeFinding: (forced?: boolean) => boolean
|
||||||
/**
|
/**
|
||||||
* The finding layer becomes another view of itself, by replace (no Back entry): the new
|
* 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
|
* element's dialog, or `null` for none (the reference dialog over its sheet goes too).
|
||||||
* (the element vanished): forced, said once the dialogs are closed.
|
* 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
|
replaceFinding: (key: ElementKey | null, text?: string) => void
|
||||||
/** Opens the citations sheet of a finding node; any other key is ignored. */
|
/** Opens the citations sheet of a finding node; any other key is ignored. */
|
||||||
@@ -209,6 +216,7 @@ function useMoveTrace() {
|
|||||||
scrollY: null,
|
scrollY: null,
|
||||||
replace: false,
|
replace: false,
|
||||||
backTo: null,
|
backTo: null,
|
||||||
|
own: false,
|
||||||
}).current
|
}).current
|
||||||
const mark = useCallback(
|
const mark = useCallback(
|
||||||
(replace = false) => {
|
(replace = false) => {
|
||||||
@@ -241,6 +249,7 @@ function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
|
|||||||
trace.scrollY = window.scrollY
|
trace.scrollY = window.scrollY
|
||||||
trace.replace = false
|
trace.replace = false
|
||||||
trace.backTo = null
|
trace.backTo = null
|
||||||
|
trace.own = kind === 'go_to'
|
||||||
dispatch(action)
|
dispatch(action)
|
||||||
setMove({ kind })
|
setMove({ kind })
|
||||||
},
|
},
|
||||||
@@ -428,6 +437,11 @@ function useMoveFocus(
|
|||||||
}, [move, state, outcomes, dispatch, openers])
|
}, [move, state, outcomes, dispatch, openers])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A focus landing still waiting when the editor goes is dropped with it. */
|
||||||
|
function useLandingCleanup() {
|
||||||
|
useEffect(() => cancelLanding, [])
|
||||||
|
}
|
||||||
|
|
||||||
/** The outcomes the places report for each focus request. */
|
/** The outcomes the places report for each focus request. */
|
||||||
function useReceipts(dispatch: Dispatch<NavigationAction>) {
|
function useReceipts(dispatch: Dispatch<NavigationAction>) {
|
||||||
const outcomes = useRef(new Map<number, FocusOutcome>())
|
const outcomes = useRef(new Map<number, FocusOutcome>())
|
||||||
@@ -496,6 +510,7 @@ export function useEditorNavigation(
|
|||||||
const guards = useGuards()
|
const guards = useGuards()
|
||||||
const receipts = useReceipts(base.dispatch)
|
const receipts = useReceipts(base.dispatch)
|
||||||
useMoveFocus(base.move, base.state, receipts.outcomes, base.dispatch, openers)
|
useMoveFocus(base.move, base.state, receipts.outcomes, base.dispatch, openers)
|
||||||
|
useLandingCleanup()
|
||||||
useCitedBy(base.state, openers)
|
useCitedBy(base.state, openers)
|
||||||
const ctx = {
|
const ctx = {
|
||||||
dispatch: base.dispatch,
|
dispatch: base.dispatch,
|
||||||
|
|||||||
@@ -56,10 +56,9 @@ function useOpening({ dispatch, mark }: LayerContext, held: RefObject<Opener>) {
|
|||||||
return { open, start }
|
return { open, start }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The moves that take it away: a user close, and the replace that is no Back step. */
|
/** A user close: the form may refuse it (a dirty draft asks first). */
|
||||||
function useClosing(ctx: LayerContext) {
|
function useClose({ dispatch, guards, mark }: LayerContext) {
|
||||||
const { dispatch, announce, guards, mark } = ctx
|
return useCallback(
|
||||||
const close = useCallback(
|
|
||||||
(forced = false) => {
|
(forced = false) => {
|
||||||
if (!guards.ask('reference', forced).allowed) return false
|
if (!guards.ask('reference', forced).allowed) return false
|
||||||
mark()
|
mark()
|
||||||
@@ -68,7 +67,11 @@ function useClosing(ctx: LayerContext) {
|
|||||||
},
|
},
|
||||||
[guards, dispatch, mark],
|
[guards, dispatch, mark],
|
||||||
)
|
)
|
||||||
const replace = useCallback(
|
}
|
||||||
|
|
||||||
|
/** The replace that is no Back step; with `text`, forced and said with a dropped draft. */
|
||||||
|
function useReplace({ dispatch, announce, guards, mark }: LayerContext) {
|
||||||
|
return useCallback(
|
||||||
(id: string | null, text?: string) => {
|
(id: string | null, text?: string) => {
|
||||||
const note = text ? guards.ask('reference', true).note : undefined
|
const note = text ? guards.ask('reference', true).note : undefined
|
||||||
if (text) announce(note ? `${note}. ${text}` : text)
|
if (text) announce(note ? `${note}. ${text}` : text)
|
||||||
@@ -79,7 +82,11 @@ function useClosing(ctx: LayerContext) {
|
|||||||
},
|
},
|
||||||
[guards, announce, dispatch, mark],
|
[guards, announce, dispatch, mark],
|
||||||
)
|
)
|
||||||
return { close, replace }
|
}
|
||||||
|
|
||||||
|
/** The moves that take it away: a user close, and the replace that is no Back step. */
|
||||||
|
function useClosing(ctx: LayerContext) {
|
||||||
|
return { close: useClose(ctx), replace: useReplace(ctx) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */
|
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */
|
||||||
|
|||||||
@@ -1645,6 +1645,9 @@ export const en: Dict = {
|
|||||||
'editor.findings.discard': 'Discard',
|
'editor.findings.discard': 'Discard',
|
||||||
'editor.findings.draft_dropped': 'Entry discarded',
|
'editor.findings.draft_dropped': 'Entry discarded',
|
||||||
'editor.findings.gone': 'This finding no longer exists',
|
'editor.findings.gone': 'This finding no longer exists',
|
||||||
|
// Provisional EN, pending the owner's wording.
|
||||||
|
'editor.leave.draft_dropped':
|
||||||
|
'An unsaved entry was discarded when you left the editor',
|
||||||
'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.',
|
||||||
'editor.verification.title': 'Draft check',
|
'editor.verification.title': 'Draft check',
|
||||||
|
|||||||
@@ -1676,6 +1676,8 @@ export const fr: Dict = {
|
|||||||
'editor.findings.discard': 'Abandonner',
|
'editor.findings.discard': 'Abandonner',
|
||||||
'editor.findings.draft_dropped': 'Saisie abandonnée',
|
'editor.findings.draft_dropped': 'Saisie abandonnée',
|
||||||
'editor.findings.gone': "Ce constat n'existe plus",
|
'editor.findings.gone': "Ce constat n'existe plus",
|
||||||
|
'editor.leave.draft_dropped':
|
||||||
|
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur",
|
||||||
'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.",
|
||||||
'editor.verification.title': 'Contrôle du brouillon',
|
'editor.verification.title': 'Contrôle du brouillon',
|
||||||
|
|||||||
@@ -452,3 +452,94 @@ describe('read-only flip and the gone rule', () => {
|
|||||||
expect(findingDialog()).toBeNull()
|
expect(findingDialog()).toBeNull()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const liveText = () =>
|
||||||
|
document.querySelector('p.sr-only[aria-live="polite"]')!.textContent
|
||||||
|
|
||||||
|
describe('final review: a creation whose parent vanishes (M-1)', () => {
|
||||||
|
it('says the dropped names with the gone text, never silently', async () => {
|
||||||
|
const user = await mount()
|
||||||
|
act(() => treeRow(/Cat A/).focus())
|
||||||
|
await user.keyboard('{ArrowUp}{ArrowDown}')
|
||||||
|
await user.click(screen.getByRole('button', { name: 'Ajouter un constat' }))
|
||||||
|
await waitFor(() => expect(findingDialog()).not.toBeNull())
|
||||||
|
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
|
||||||
|
act(() => {
|
||||||
|
store.getState().commit({
|
||||||
|
op: 'remove',
|
||||||
|
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await closed()
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(liveText()).toBe("Saisie abandonnée. Ce constat n'existe plus"),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: the zone of a new category is part of the draft (criterion 8)', () => {
|
||||||
|
it('a zone changed alone asks before « Annuler » closes', async () => {
|
||||||
|
serverHas(
|
||||||
|
insert(sheetText(), {
|
||||||
|
kind: 'zone',
|
||||||
|
value: { id: 'zone-b', name: name('Zone B'), categories: [] },
|
||||||
|
}),
|
||||||
|
3,
|
||||||
|
)
|
||||||
|
const user = userEvent.setup()
|
||||||
|
mountDraft({ width: 1280, probe })
|
||||||
|
await screen.findByRole('heading', {
|
||||||
|
level: 1,
|
||||||
|
name: 'Brouillon, version 4',
|
||||||
|
})
|
||||||
|
await user.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||||
|
await user.click(
|
||||||
|
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
|
||||||
|
)
|
||||||
|
await waitFor(() => expect(findingDialog()).not.toBeNull())
|
||||||
|
await user.selectOptions(inDialog().getByLabelText('Zone'), 'zone-b')
|
||||||
|
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
|
||||||
|
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
|
||||||
|
await user.click(
|
||||||
|
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
|
||||||
|
)
|
||||||
|
act(() => inDialog().getByLabelText('Zone').focus())
|
||||||
|
await user.keyboard('{Escape}')
|
||||||
|
expect(findingDialog()).not.toBeNull()
|
||||||
|
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: leaving the editor with a dirty dialog (criterion 17)', () => {
|
||||||
|
const flagKey = `faunosteo:editor:left-draft:${SHEET}:${USER}`
|
||||||
|
const notice =
|
||||||
|
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur"
|
||||||
|
|
||||||
|
it('leaves one flag without the text, then a notice once on the next mount', async () => {
|
||||||
|
const user = await mount()
|
||||||
|
await openFinding(user, /Node A/)
|
||||||
|
await modify(user)
|
||||||
|
await user.type(nameField(), ' bis')
|
||||||
|
cleanup()
|
||||||
|
const flag = sessionStorage.getItem(flagKey)
|
||||||
|
expect(flag).not.toBeNull()
|
||||||
|
expect(flag).not.toContain('bis')
|
||||||
|
expect(JSON.parse(flag!)).toEqual({
|
||||||
|
kind: 'finding',
|
||||||
|
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'fnode-a'] },
|
||||||
|
})
|
||||||
|
await mount()
|
||||||
|
expect(screen.getByText(notice)).toBeVisible()
|
||||||
|
expect(sessionStorage.getItem(flagKey)).toBeNull()
|
||||||
|
cleanup()
|
||||||
|
await mount()
|
||||||
|
expect(screen.queryByText(notice)).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a clean dialog leaves no flag', async () => {
|
||||||
|
const user = await mount()
|
||||||
|
await openFinding(user, /Node A/)
|
||||||
|
cleanup()
|
||||||
|
expect(sessionStorage.getItem(flagKey)).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -331,3 +331,57 @@ describe('the view the reducer holds', () => {
|
|||||||
expect(state.visitedTabs).toEqual(['findings'])
|
expect(state.visitedTabs).toEqual(['findings'])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('final review: « Aller à » is a move of its own (I-2)', () => {
|
||||||
|
it('pushes over the sheet it leaves, even with fewer layers on the same tab', () => {
|
||||||
|
const sheet = view('findings', { finding: { key: node, citations: true } })
|
||||||
|
const other: ElementKey = {
|
||||||
|
kind: 'finding',
|
||||||
|
zone_id: 'z',
|
||||||
|
path: ['f', 'm'],
|
||||||
|
}
|
||||||
|
const target = view('findings', {
|
||||||
|
finding: { key: other, citations: false },
|
||||||
|
})
|
||||||
|
const top = entry({ view: sheet, below: view('findings') })
|
||||||
|
expect(planWrite(top, target, false)).toBe('replace')
|
||||||
|
expect(planWrite(top, target, false, null, true)).toBe('push')
|
||||||
|
// An arrow-key replace still wins.
|
||||||
|
expect(planWrite(top, target, true, null, true)).toBe('replace')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: read-back values are capped', () => {
|
||||||
|
const long = 'x'.repeat(129)
|
||||||
|
const atCap = 'x'.repeat(128)
|
||||||
|
const deep = (length: number): ElementKey => ({
|
||||||
|
kind: 'finding',
|
||||||
|
zone_id: 'z',
|
||||||
|
path: Array.from({ length }, (_, i) => `p${i}`),
|
||||||
|
})
|
||||||
|
const onFindings = (key: ElementKey) =>
|
||||||
|
view('findings', { finding: { key, citations: false } })
|
||||||
|
|
||||||
|
it('drops an entry whose id, sheet or account is over 128 characters', () => {
|
||||||
|
expect(readEntry(stateOf(entry({ id: atCap })))).not.toBeNull()
|
||||||
|
expect(readEntry(stateOf(entry({ id: long })))).toBeNull()
|
||||||
|
expect(readEntry(stateOf(entry({ sheetId: long })))).toBeNull()
|
||||||
|
expect(readEntry(stateOf(entry({ userId: long })))).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops a key with an over-long id or a path deeper than the tree allows', () => {
|
||||||
|
const zone: ElementKey = { kind: 'zone', id: long }
|
||||||
|
expect(
|
||||||
|
readEntry(stateOf(entry({ view: onFindings(zone) })))?.view.finding,
|
||||||
|
).toBeNull()
|
||||||
|
const wideZone: ElementKey = { kind: 'finding', zone_id: long, path: ['a'] }
|
||||||
|
expect(sanitizeView(onFindings(wideZone))?.finding).toBeNull()
|
||||||
|
const wideId: ElementKey = { kind: 'finding', zone_id: 'z', path: [long] }
|
||||||
|
expect(sanitizeView(onFindings(wideId))?.finding).toBeNull()
|
||||||
|
expect(sanitizeView(onFindings(deep(8)))?.finding).not.toBeNull()
|
||||||
|
expect(sanitizeView(onFindings(deep(9)))?.finding).toBeNull()
|
||||||
|
const edit = { ...onFindings(node), reference: { edit: long } }
|
||||||
|
const sheet = { ...edit, finding: { key: node, citations: true } }
|
||||||
|
expect(sanitizeView(sheet)?.reference).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -3,9 +3,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
|||||||
import {
|
import {
|
||||||
act,
|
act,
|
||||||
cleanup,
|
cleanup,
|
||||||
|
fireEvent,
|
||||||
render,
|
render,
|
||||||
renderHook,
|
renderHook,
|
||||||
screen,
|
screen,
|
||||||
|
waitFor,
|
||||||
} from '@testing-library/react'
|
} from '@testing-library/react'
|
||||||
import userEvent from '@testing-library/user-event'
|
import userEvent from '@testing-library/user-event'
|
||||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||||
@@ -21,7 +23,7 @@ import { useBeforeUnload } from '@/app/useLeaveGuard'
|
|||||||
import EditorTabs from '@/components/editor/EditorTabs'
|
import EditorTabs from '@/components/editor/EditorTabs'
|
||||||
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
|
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
|
||||||
import useEditorHistory from '@/editor/history/useEditorHistory'
|
import useEditorHistory from '@/editor/history/useEditorHistory'
|
||||||
import { defaultView } from '@/editor/navigation'
|
import { defaultView, targetOfKey } from '@/editor/navigation'
|
||||||
import { useEditorNavigation } from '@/editor/useEditorNavigation'
|
import { useEditorNavigation } from '@/editor/useEditorNavigation'
|
||||||
import { useLocaleStore } from '@/state/localeStore'
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
|
|
||||||
@@ -33,6 +35,11 @@ const finding: ElementKey = {
|
|||||||
zone_id: 'zone',
|
zone_id: 'zone',
|
||||||
path: ['family', 'node'],
|
path: ['family', 'node'],
|
||||||
}
|
}
|
||||||
|
const other: ElementKey = {
|
||||||
|
kind: 'finding',
|
||||||
|
zone_id: 'zone',
|
||||||
|
path: ['family', 'other'],
|
||||||
|
}
|
||||||
|
|
||||||
let navigate: NavigateFunction
|
let navigate: NavigateFunction
|
||||||
let location: Location
|
let location: Location
|
||||||
@@ -48,6 +55,10 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) {
|
|||||||
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
|
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
|
||||||
<button onClick={() => nav.openFinding(finding)}>open</button>
|
<button onClick={() => nav.openFinding(finding)}>open</button>
|
||||||
<button onClick={() => nav.openCitations(finding)}>cite</button>
|
<button onClick={() => nav.openCitations(finding)}>cite</button>
|
||||||
|
<button onClick={() => nav.closeCitations()}>uncite</button>
|
||||||
|
<button onClick={() => nav.closeFinding()}>close</button>
|
||||||
|
<button onClick={() => nav.showAllReferences(finding)}>show all</button>
|
||||||
|
<button onClick={() => nav.navigate(targetOfKey(other))}>go to</button>
|
||||||
<button onClick={() => nav.guards.register('finding', guard ?? null)}>
|
<button onClick={() => nav.guards.register('finding', guard ?? null)}>
|
||||||
guard
|
guard
|
||||||
</button>
|
</button>
|
||||||
@@ -59,9 +70,12 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const mount = (guard?: () => { allowed: boolean }) =>
|
const mount = (
|
||||||
|
guard?: () => { allowed: boolean },
|
||||||
|
entries: string[] = ['/x'],
|
||||||
|
) =>
|
||||||
render(
|
render(
|
||||||
<MemoryRouter initialEntries={['/x']}>
|
<MemoryRouter initialEntries={entries} initialIndex={entries.length - 1}>
|
||||||
<Page guard={guard} />
|
<Page guard={guard} />
|
||||||
</MemoryRouter>,
|
</MemoryRouter>,
|
||||||
)
|
)
|
||||||
@@ -204,3 +218,144 @@ describe('useBeforeUnload', () => {
|
|||||||
expect(second.defaultPrevented).toBe(false)
|
expect(second.defaultPrevented).toBe(false)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const click = (name: string) =>
|
||||||
|
userEvent.click(screen.getByRole('button', { name }))
|
||||||
|
const findingLayer = () => JSON.parse(screen.getByTestId('layer').textContent!)
|
||||||
|
/** A layer dialog on screen: what a Back that reopens the layers shows. */
|
||||||
|
function openLayerDialog() {
|
||||||
|
const dialog = document.createElement('dialog')
|
||||||
|
dialog.setAttribute('open', '')
|
||||||
|
dialog.setAttribute('data-layer', '')
|
||||||
|
document.body.append(dialog)
|
||||||
|
return dialog
|
||||||
|
}
|
||||||
|
async function settleDialogs(dialog: HTMLElement) {
|
||||||
|
dialog.remove()
|
||||||
|
await act(async () => {
|
||||||
|
flushAfterModals()
|
||||||
|
await Promise.resolve()
|
||||||
|
await Promise.resolve()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const setScrollY = (y: number) =>
|
||||||
|
Object.defineProperty(window, 'scrollY', {
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
value: y,
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: a Back into the layers (I-1)', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
setScrollY(0)
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restores the page scroll, however the dialogs are closed afterwards', async () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
|
||||||
|
mount()
|
||||||
|
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||||
|
setScrollY(500)
|
||||||
|
await click('open')
|
||||||
|
await click('cite')
|
||||||
|
await click('show all')
|
||||||
|
setScrollY(0)
|
||||||
|
scrollTo.mockClear()
|
||||||
|
const dialog = openLayerDialog()
|
||||||
|
act(() => navigate(-1))
|
||||||
|
expect(findingLayer()).toMatchObject({ citations: true })
|
||||||
|
// Closed by ✕ / Escape: each close dispatches and renders again.
|
||||||
|
await click('uncite')
|
||||||
|
await click('close')
|
||||||
|
await settleDialogs(dialog)
|
||||||
|
expect(scrollTo).toHaveBeenCalledWith(0, 500)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: « Aller à » from the sheet (I-2)', () => {
|
||||||
|
it('keeps the entry of the finding with its sheet: Back from the target returns to it', async () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
mount()
|
||||||
|
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||||
|
await click('open')
|
||||||
|
await click('cite')
|
||||||
|
await click('go to')
|
||||||
|
expect(findingLayer()).toEqual({ key: other, citations: false })
|
||||||
|
expect(entry().below?.finding).toEqual({ key: finding, citations: true })
|
||||||
|
act(() => navigate(-1))
|
||||||
|
expect(findingLayer()).toEqual({ key: finding, citations: true })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: a location that is not the editor’s (M-3)', () => {
|
||||||
|
it('writes nothing and asks no layer on a Back to another page', async () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
const guard = vi.fn(() => ({ allowed: false }))
|
||||||
|
mount(guard, ['/y', '/x'])
|
||||||
|
await click('guard')
|
||||||
|
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||||
|
await click('open')
|
||||||
|
act(() => navigate(-3))
|
||||||
|
expect(location.pathname).toBe('/y')
|
||||||
|
expect(location.state).toBeNull()
|
||||||
|
expect(guard).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: entry ids (M-4)', () => {
|
||||||
|
it('two mounts never share an entry id', async () => {
|
||||||
|
mount()
|
||||||
|
await waitFor(() => expect(entry()).toBeTruthy())
|
||||||
|
const first = entry().id
|
||||||
|
cleanup()
|
||||||
|
mount()
|
||||||
|
await waitFor(() => expect(entry()).toBeTruthy())
|
||||||
|
expect(entry().id).not.toBe(first)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: past the write budget (M-5)', () => {
|
||||||
|
it('a close over a push kept in memory never goes back a real entry', async () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
mount()
|
||||||
|
const tabOf = (name: string) => screen.getByRole('tab', { name })
|
||||||
|
fireEvent.click(tabOf('Constats'))
|
||||||
|
for (let i = 0; i < 19; i += 1) {
|
||||||
|
fireEvent.click(tabOf('Général'))
|
||||||
|
fireEvent.click(tabOf('Constats'))
|
||||||
|
}
|
||||||
|
// The 40th write of the window: sent. The 41st (the sheet) stays in memory.
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'open' }))
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'cite' }))
|
||||||
|
const top = location.key
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'uncite' }))
|
||||||
|
expect(findingLayer()).toEqual({ key: finding, citations: false })
|
||||||
|
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent(
|
||||||
|
'Constats',
|
||||||
|
)
|
||||||
|
expect(location.key).toBe(top)
|
||||||
|
expect(entry().view.finding).toEqual({ key: finding, citations: false })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('final review: queued landings (M-6)', () => {
|
||||||
|
it('a Back during the exit cancels the stale « Tout afficher » landing', async () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
mount()
|
||||||
|
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||||
|
await click('open')
|
||||||
|
await click('cite')
|
||||||
|
const exiting = openLayerDialog()
|
||||||
|
await click('show all')
|
||||||
|
act(() => navigate(-1))
|
||||||
|
expect(findingLayer()).toMatchObject({ citations: true })
|
||||||
|
const focused: Element[] = []
|
||||||
|
const record = (event: FocusEvent) => focused.push(event.target as Element)
|
||||||
|
document.addEventListener('focusin', record)
|
||||||
|
await settleDialogs(exiting)
|
||||||
|
document.removeEventListener('focusin', record)
|
||||||
|
const references = screen.getByRole('tab', { name: 'Références' })
|
||||||
|
expect(focused).not.toContain(references)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -231,3 +231,18 @@ describe('the platform back request', () => {
|
|||||||
expect(more()).toHaveAttribute('aria-expanded', 'false')
|
expect(more()).toHaveAttribute('aria-expanded', 'false')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('final review: keyboard focus leaving « Plus » (M-8)', () => {
|
||||||
|
it('closes when the focus moves out of the trigger and the list', async () => {
|
||||||
|
const { user } = mount()
|
||||||
|
await user.click(more())
|
||||||
|
const item = screen.getByRole('button', { name: 'Constats' })
|
||||||
|
act(() => item.focus())
|
||||||
|
expect(more()).toHaveAttribute('aria-expanded', 'true')
|
||||||
|
act(() => more().focus())
|
||||||
|
expect(more()).toHaveAttribute('aria-expanded', 'true')
|
||||||
|
act(() => screen.getByRole('button', { name: 'outside' }).focus())
|
||||||
|
expect(more()).toHaveAttribute('aria-expanded', 'false')
|
||||||
|
await gone()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -104,11 +104,11 @@ describe('navigationReducer', () => {
|
|||||||
expect(state.focus?.target).toEqual(targetOfKey(key))
|
expect(state.focus?.target).toEqual(targetOfKey(key))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('go_to a tab closes the finding layers', () => {
|
it('go_to a place that is no finding closes the finding layers', () => {
|
||||||
const state = run(
|
const state = run(
|
||||||
initialNavigation('general'),
|
initialNavigation('general'),
|
||||||
{ type: 'open_citations', citedBy: node },
|
{ type: 'open_citations', citedBy: node },
|
||||||
{ type: 'go_to', target: targetOfKey(finding) },
|
{ type: 'go_to', target: targetOfKey(view) },
|
||||||
)
|
)
|
||||||
expect(state.finding).toBeNull()
|
expect(state.finding).toBeNull()
|
||||||
})
|
})
|
||||||
@@ -306,3 +306,28 @@ describe('navigationReducer', () => {
|
|||||||
expect(state.visitedSections).toEqual(['drawing', 'categories'])
|
expect(state.visitedSections).toEqual(['drawing', 'categories'])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('final review', () => {
|
||||||
|
it('a go_to a finding or a zone opens its dialog in the same move (I-2)', () => {
|
||||||
|
const state = run(
|
||||||
|
initialNavigation('general'),
|
||||||
|
{ type: 'open_citations', citedBy: node },
|
||||||
|
{ type: 'go_to', target: targetOfKey(finding) },
|
||||||
|
)
|
||||||
|
expect(state.finding).toEqual({ key: finding, citations: false })
|
||||||
|
const zone: ElementKey = { kind: 'zone', id: 'z1' }
|
||||||
|
const onZone = run(state, { type: 'go_to', target: targetOfKey(zone) })
|
||||||
|
expect(onZone.finding).toEqual({ key: zone, citations: false })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('close_finding takes the reference dialog over the sheet with it (M-2)', () => {
|
||||||
|
const state = run(
|
||||||
|
initialNavigation('findings'),
|
||||||
|
{ type: 'open_citations', citedBy: node },
|
||||||
|
{ type: 'open_reference', id: 'r1' },
|
||||||
|
{ type: 'close_finding' },
|
||||||
|
)
|
||||||
|
expect(state.finding).toBeNull()
|
||||||
|
expect(state.reference).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -532,3 +532,30 @@ describe('the finding filter', () => {
|
|||||||
expect(chip()).toBeVisible()
|
expect(chip()).toBeVisible()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('final review: the creation dialog fades out as a creation (M-9)', () => {
|
||||||
|
it('never shows the edit title while it closes', async () => {
|
||||||
|
const user = await mount()
|
||||||
|
await user.click(
|
||||||
|
screen.getByRole('button', { name: 'Ajouter une référence' }),
|
||||||
|
)
|
||||||
|
await waitFor(() => expect(refDialog()).toBeDefined())
|
||||||
|
await user.selectOptions(field('Type'), 'book')
|
||||||
|
await user.type(field('Citation'), 'Nouvelle source')
|
||||||
|
const titles = new Set<string>()
|
||||||
|
const seen = new MutationObserver(() => {
|
||||||
|
document
|
||||||
|
.querySelectorAll('dialog h2')
|
||||||
|
.forEach((h) => titles.add(h.textContent ?? ''))
|
||||||
|
})
|
||||||
|
seen.observe(document.body, {
|
||||||
|
subtree: true,
|
||||||
|
childList: true,
|
||||||
|
characterData: true,
|
||||||
|
})
|
||||||
|
await save(user)
|
||||||
|
await closed()
|
||||||
|
seen.disconnect()
|
||||||
|
expect(titles).not.toContain('Modifier la référence')
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user