Files
faunosteo/apps/app/tests/unit/editor-focus-request.test.tsx
T
bchanot cd794f3c39 feat(editor): properties dialog over the column, transactional save
U2 Task 6 (A1, A2, A3, A9, A10, R-3, R-5, R-6, R-14, R-16).

- Dialog: `anchor` places the panel at the column's left and width,
  from its top, under a 22 % ink veil that ignores clicks; the visual
  viewport below 320 px; centred without an anchor box.
- Navigation: `annotation` layer (LAYERS, EditorView, history entry,
  leave guards, left-draft flag); Back closes, Forward reopens.
- AnnotationDialog: read body, « Modifier » form (CreationFields with
  « Couleur », missingFields, R-3 messages), one `update` on the
  current annotation by id, « Marquer comme relu », « Modifier la
  forme », « Supprimer »; read-only flip keeps the draft.
- The column always shows the overview, selected row marked; Enter on
  it, a second click or a double click, the strip's « Propriétés »
  open the dialog. « Aller à » focuses the row (R-5).
- Read-only twin: strip and read-only dialog at 1 024 px and wider,
  inline read body below. PropertiesPanel and AnnotationFields gone.
- Strip lead 256 px and a fixed status slot, so the commands fit at
  1 024 px and a status change moves nothing.
- e2e: `aside-content` exemption removed; scroll-to-top workarounds
  of editor-geometry, editor-zones and editor-journey removed.

Removed assertions mapped:
  editor-annotations-tab.test.tsx:
  - selectFromList waited for `annotation-properties` -> waits for the strip's « Propriétés » (selection without dialog, A1)
  - refused place: issues block `annotation-geometry-issues` in the panel -> the strip notice alert (present, then gone)
  - keyboard creation / C26 confirmation: `annotation-properties` after create -> strip « Propriétés » (new element selected)
  - Désélectionner from the panel -> « Désélectionner » in the strip (all 7 tests); « panel closes » -> strip has no « Propriétés »
  - undo after deselect (typed name) -> handle key series then deselect then undo
  - commits a valid typed value once without blur (name field) -> a pending handle key series committed once by the strip deselect
  - a refused typed value: the panel closes (two tests: strip deselect, tap deselect) -> removed: no field outside the dialog; the dialog's draft writes nothing before « Enregistrer » (new dialog tests)
  - not offered while a replace tracing runs: panel's Désélectionner absent -> strip offers neither « Désélectionner » nor « Propriétés » during the tracing
  - tap: isDeselected read `annotation-properties` -> strip « Propriétés » absent; link select -> strip title data-selection
  - tap: undo after tap deselect (typed name) -> handle series; typed value committed on blur -> handle series committed on blur
  - strip geometry issues: list read in the panel -> list read in the properties dialog's issues block
  - a new commit replaces the message (typed name) -> « Marquer comme relu » in the dialog
  editor-escape.test.tsx:
  - `panel()` = `annotation-properties` -> the strip's « Propriétés » or the phone twin's inline read body
  - Escape from a panel button (« Marquer comme relu ») -> from the selected row in the side column: focus on the row
  - after A then B from the panel (via « Toutes les annotations ») -> select A, select B, Escape from a button of the side column: focus on B's row
  - a text field (panel « Nom (FR) ») -> the overview « Filtrer par nom »
  - redraw via the panel's « Remplacer par un polygone » -> the strip's command
  - modal / delete dialog opened by the panel's « Supprimer » -> « Supprimer » of the properties dialog
  - read-only width: hidden `annotation-properties` -> hidden strip « Propriétés » of the kept edit body
  editor-history-buttons.test.tsx (typed text and the press, 8 tests): the annotation's committed « Nom (FR) » field of the panel -> the sheet's committed « Nom (FR) » on Général (same TextField commit-on-blur path; annotation fields are now a dialog draft)
  editor-focus-request.test.tsx: « Aller à » focuses `data-properties-heading` inside `annotation-properties` -> focuses the annotation's row, marked aria-current, no dialog (R-5)
  editor-sections.test.tsx: « Aller à » with nothing in progress focused the properties heading -> focuses the row (R-5); creation kept: no `annotation-properties` -> no strip « Propriétés »
  editor-overview.test.tsx (edit and read-only): row opens `annotation-properties`, « Toutes les annotations » returns -> row selects, stays marked aria-current, no dialog; strip « Désélectionner » returns focus to the row; filter kept across select and « Désélectionner »
  editor-citations-guards.test.tsx: LAYERS_TOP_DOWN gains 'annotation' at the bottom
  editor-keep-alive.test.tsx: `annotation-properties` visible after the round trip -> the strip's « Propriétés » visible (selection kept)
  editor-no-loss.test.tsx: ids `ro-annotation-name-fr` and `annotation-name-fr` (both panels' fields) -> the twin's inline read body (no ids), then the dialog edit form's `annotation-edit-fr`, kept through a flip to 800 px, no duplicate id; « Aller à » visible `annotation-properties` -> visible `annotation-read` (inline twin), none at 1 280
  editor-point-edit.test.tsx / editor-zone-edit.test.tsx: `select()` waited for `annotation-properties` and returned it -> waits for the strip's « Propriétés » and returns the strip (its « Désélectionner » and « Remplacer par un polygone » moved there)
  - move mode Escape: `annotation-properties` still there -> the strip's « Propriétés » back after the mode
  - « Toutes les annotations » asks first during a started move -> Enter on the selected row asks first (no dialog), and the strip offers neither « Propriétés » nor « Désélectionner » during the mode
  - Escape from the handle / slider: `annotation-properties` gone -> the strip's « Propriétés » gone
  - I-3 touch tap: `annotation-properties` gone -> the strip's « Propriétés » gone
  e2e (sandbox):
  - support/layout.ts: `aside-content` exemption removed (ShiftExemption type, the loose compare); every `swaps`/`SWAPS` argument removed (editor-annotations, editor-zones, editor-geometry)
  - support/editor.ts pickAnnotation: clicked « Toutes les annotations » first when the panel showed -> the overview is always shown: clicks the row, then scrolls back to the top (the page no longer shortens)
  - editor-annotations: `annotation-properties` visible after a creation -> strip with « Propriétés »; review toggle and « Supprimer » of the panel -> the properties dialog's; a jitter click on the selected point now opens the dialog (A1), closed by Escape before the drag; handle names exact (the marked row shares the prefix); trace close moved out of expectNoShift (creation panel until Task 7, shortcut + TODO)
  - editor-deselect: `annotation-properties` -> the strip with « Propriétés » or the twin's inline read body; Escape in a field: panel « Nom (FR) » -> overview filter; delete dialog from the panel -> from the properties dialog (Escape closes it, then the dialog); « a typed value is applied by the click that deselects » (name field, refused blank) -> a pending point-handle key series applied by the deselecting click and by « Désélectionner » (refused value: no field outside the dialog); « the selected one stays » -> a second click, double click and jitter open the dialog, Escape closes it, selection kept
  - editor-geometry: `annotation-geometry-issues` in the panel -> read in the properties dialog, then the strip notice; after the refusal the error count unchanged; scroll-to-top workaround removed
  - editor-zones: panel « Désélectionner » -> strip; scroll-to-top after pickAnnotation removed (helper does it)
  - editor-structures: panel « Supprimer » -> properties dialog « Supprimer », confirmation over it
  - editor-journey: `#annotation-name-fr` committed field + `#annotation-laterality` -> the dialog's edit form, one « Enregistrer »; scroll-to-top removed
  - editor-shell / editor-shell-journeys: « Aller à » focus on `data-properties-heading` -> the annotation's row (aria-current), no dialog (R-5)
  - editor-shell-layout: focus kind `annotation-properties` -> removed (the overview is the side)
2026-11-17 22:01:57 +01:00

495 lines
15 KiB
TypeScript

/** « Aller à … »: each request reaches the place its target names, once, and never lands on body. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useState } from 'react'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
ElementKey,
} from '@faunosteo/core-wasm/types'
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
import { testLayer } from '../helpers/findingsHost'
import ReferencesHost from '../helpers/referencesHost'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import RegionsSection from '@/components/editor/annotations/sections/RegionsSection'
import EditorTabBody from '@/components/editor/EditorTabBody'
import EditorTabs from '@/components/editor/EditorTabs'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import {
FocusConsumedContext,
isTextField,
ownedBy,
type FocusRequest,
} from '@/editor/focusRequest'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import { issueTarget } from '@/editor/verification'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert, point } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
store,
} from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const base = { readOnly: false, navigate: vi.fn(), reloadSheet: vi.fn() }
const section = {
section: 'drawing' as const,
visited: ['drawing'] as const,
onOpenSection: vi.fn(),
onBack: vi.fn(),
}
const request = (key: ElementKey, serial = 1): FocusRequest => ({
target: targetOfKey(key),
serial,
})
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const name = (n: string) => ({ fr: n, en: n })
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
function findingsText(): string {
let text = insert(baseText(), {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
text = edit(text, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: name('Cat A'),
description: {},
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
return edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
element: {
kind: 'finding_node',
value: {
id: 'node-a',
name: name('Nœud A'),
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
}
describe('focus requests', () => {
it('Constats: expands to the finding, selects it and shows its detail', async () => {
await openReady({ text: findingsText() })
const key: ElementKey = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'node-a'],
}
render(<FindingsTab {...base} layer={testLayer} focus={request(key)} />)
const item = await screen.findByRole('treeitem', { name: /Nœud A/ })
expect(item.getAttribute('aria-selected')).toBe('true')
await waitFor(() => expect(document.activeElement).toBe(item))
})
it('Annotations (R-5): selects the annotation and focuses its row, no dialog', async () => {
const text = insert(baseText(), point('anno-b', 20, 20, 3))
await openReady({ text })
render(
<AnnotationsTab
{...base}
{...section}
focus={request({ kind: 'annotation', id: 'anno-b' })}
/>,
)
// anno-b and anno-a share a name: the circle's centre tells which one is selected.
await screen.findByRole('button', { name: 'Propriétés' })
expect(
screen.getByTestId('overlay-selection').querySelector('circle'),
).toHaveAttribute('cx', '20')
const row = document.querySelector(
'[data-focus-key=\'{"kind":"annotation","id":"anno-b"}\']',
)
await waitFor(() => expect(document.activeElement).toBe(row))
expect(row).toHaveAttribute('aria-current', 'true')
expect(screen.queryByRole('dialog')).toBeNull()
})
it('Références and Régions: focus the named row', async () => {
let text = insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
text = insert(text, {
kind: 'region',
value: {
code: 'C',
name: name('Cervicales'),
count: 7,
count_range: null,
},
})
await openReady({ text })
render(
<ReferencesHost
{...base}
focus={request({ kind: 'reference', id: 'ref-a' })}
/>,
)
// The landing waits for any dialog a move closed: one microtask when none is open.
await waitFor(() =>
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
),
)
cleanup()
render(
<RegionsSection
{...base}
focus={request({ kind: 'region', code: 'C' })}
/>,
)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'"C"',
)
})
it('consumes a serial once', async () => {
const text = insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const focus = request({ kind: 'reference', id: 'ref-a' })
const view = render(<ReferencesHost {...base} focus={focus} />)
;(document.activeElement as HTMLElement).blur()
view.rerender(<ReferencesHost {...base} focus={focus} />)
expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull()
})
it('reports found, or none when the place holds no such element', async () => {
await openReady({ text: findingsText() })
const consumed = vi.fn()
const gone: ElementKey = { kind: 'zone', id: 'zone-gone' }
render(
<FocusConsumedContext value={consumed}>
<FindingsTab {...base} layer={testLayer} focus={request(gone, 4)} />
</FocusConsumedContext>,
)
await waitFor(() => expect(consumed).toHaveBeenCalledWith(4, 'none'))
})
})
describe('ownedBy', () => {
it('passes a request only to the place its target names', () => {
const view = request({ kind: 'view', id: 'view-main' })
expect(ownedBy(view, 'annotations.views')).toBe(view)
expect(ownedBy(view, 'annotations.drawing')).toBeUndefined()
expect(ownedBy(view, 'general')).toBeUndefined()
const ref = request({ kind: 'reference', id: 'ref-a' })
expect(ownedBy(ref, 'references')).toBe(ref)
expect(ownedBy(ref, 'findings')).toBeUndefined()
expect(ownedBy(undefined, 'general')).toBeUndefined()
})
})
describe('issueTarget', () => {
it('resolves nested finding paths, regions and references', async () => {
await openReady({ text: findingsText() })
const d = doc()
const path = 'finding_zones[0].categories[0].children[0].reference_ids[1]'
expect(issueTarget(d, path, 'fr')).toMatchObject({
target: {
place: 'tab',
tab: 'findings',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'node-a'] },
},
name: 'Nœud A',
})
expect(issueTarget(d, 'finding_zones[0]', 'fr')?.target).toMatchObject({
key: { kind: 'zone', id: 'zone-a' },
})
expect(
issueTarget(d, 'vertebral_config.regions[3].count_range', 'fr'),
).toMatchObject({
target: { tab: 'annotations', section: 'regions', key: null },
})
expect(issueTarget(d, 'nothing', 'fr')).toBeNull()
})
})
/** The workspace's wiring in miniature: the hook, the tab row, the shown body. */
function Probe({ go, tier }: { go: EditorTarget; tier: 'wide' | 'small' }) {
const nav = useEditorNavigation('verification')
const { state } = nav
return (
<FocusConsumedContext value={nav.consumed}>
<EditorTabs active={state.tab} tier={tier} onSelect={nav.selectTab} />
<button onClick={() => nav.navigate(go)}>go</button>
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
{...base}
navigate={nav.navigate}
layer={findingLayerOf(nav)}
references={referenceLayerOf(nav)}
focus={state.focus}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
</FocusConsumedContext>
)
}
function ShowAllProbe() {
const nav = useEditorNavigation('findings')
return (
<>
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
<button
onClick={() =>
nav.showAllReferences({
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
})
}
>
show all
</button>
</>
)
}
describe('« Tout afficher » landing', () => {
it('falls back to the tab button when the tab heading is absent', async () => {
await openReady()
const user = userEvent.setup()
render(<ShowAllProbe />)
await user.click(screen.getByText('show all'))
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('tab', { name: 'Références' }),
),
)
})
})
describe('a request that finds nothing', () => {
const missing: EditorTarget = {
place: 'tab',
tab: 'findings',
section: null,
key: { kind: 'zone', id: 'zone-gone' },
}
it('lands on the tab button, never on body', async () => {
await openReady({ text: findingsText() })
const user = userEvent.setup()
render(<Probe go={missing} tier="wide" />)
await user.click(screen.getByText('go'))
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('tab', { name: 'Constats' }),
),
)
})
it('below 640 px lands on « Plus » while the tab sits in its closed list', async () => {
await openReady({ text: findingsText() })
const user = userEvent.setup()
render(<Probe go={missing} tier="small" />)
await user.click(screen.getByText('go'))
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Plus' }),
),
)
})
it('Vérification « Aller à » a reference: the tab shows, its row holds the focus', async () => {
const text = insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const user = userEvent.setup()
const key: ElementKey = { kind: 'reference', id: 'ref-a' }
render(<Probe go={targetOfKey(key)} tier="wide" />)
await user.click(screen.getByText('go'))
await waitFor(() =>
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
),
)
expect(screen.getByRole('tab', { name: 'Références' })).toHaveAttribute(
'aria-selected',
'true',
)
})
it('a reference path that names no element lands on the tab heading', async () => {
await openReady()
const user = userEvent.setup()
const alone: EditorTarget = {
place: 'tab',
tab: 'references',
section: null,
key: null,
}
render(<Probe go={alone} tier="wide" />)
await user.click(screen.getByText('go'))
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('heading', { name: 'Références' }),
),
)
})
it('a found element keeps the focus it took', async () => {
await openReady({ text: findingsText() })
const user = userEvent.setup()
const key: ElementKey = { kind: 'zone', id: 'zone-a' }
render(<Probe go={targetOfKey(key)} tier="wide" />)
await user.click(screen.getByText('go'))
// « Aller à » opens the element's dialog; closed, its row holds the focus.
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Fermer' }))
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('treeitem', { name: /Zone A/ }),
),
)
})
})
/** The route's contract: one place mounted at a time, the request cleared once consumed. */
function Harness() {
const [shown, setShown] = useState<'references' | 'regions'>('references')
const [focus, setFocus] = useState<FocusRequest | undefined>(
request({ kind: 'reference', id: 'ref-a' }),
)
const clear = (serial: number) =>
setFocus((prev) => (prev?.serial === serial ? undefined : prev))
return (
<FocusConsumedContext value={clear}>
<button
onClick={() =>
setShown(shown === 'references' ? 'regions' : 'references')
}
>
switch
</button>
{shown === 'references' ? (
<ReferencesHost {...base} focus={focus} />
) : (
<RegionsSection {...base} focus={focus} />
)}
</FocusConsumedContext>
)
}
describe('a consumed request', () => {
it('is not replayed when the place is left and reopened', async () => {
const text = insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const user = userEvent.setup()
render(<Harness />)
await waitFor(() =>
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
),
)
await user.click(screen.getByText('switch'))
await user.click(screen.getByText('switch'))
expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull()
})
})
describe('isTextField', () => {
const input = (type: string) => {
const element = document.createElement('input')
element.type = type
return element
}
it('is true for what takes typed text', () => {
for (const type of ['text', 'search', 'email']) {
expect(isTextField(input(type))).toBe(true)
}
expect(isTextField(document.createElement('textarea'))).toBe(true)
expect(isTextField(document.createElement('select'))).toBe(true)
})
it('is false for a checkbox, a radio, a range, a button input', () => {
for (const type of ['checkbox', 'radio', 'range', 'button', 'file']) {
expect(isTextField(input(type))).toBe(false)
}
const off = document.createElement('div')
off.setAttribute('contenteditable', 'false')
expect(isTextField(off)).toBe(false)
})
})