Files
faunosteo/apps/app/tests/unit/editor-focus-request.test.tsx
T
bchanot 0467885527 fix(editor): final review fixes (touch undo guard, focus, save line)
Important 1: a touch press fires pointer leave between up and click; only a
mouse leave (or a pointer cancel) forgets the refused field, so Annuler no
longer undoes an unrelated change. Important 2: the LAN spec reads the
revision before the attach, through shownRevision, which throws instead of NaN
(spec stays not run). Minor 1: refocusIfHidden refocuses a still shown element
the commit blurred (references search on a 1 024 px crossing). Minor 2:
discardChanges keeps lastSave (reload path still drops it). Minor 3: the
overview filter term lives in UiState / the read-only twin, not the card.
Minor 4: categories section drops its inner h3 and the unused
editor.general.categories keys. AC8: badge test.

Assertions rewritten or added (R-24):
- editor-tabs-general « Général no longer holds the categories editor »:
  queryByText of the deleted heading (now vacuous) -> queryByLabelText of the
  category name fields.
- editor-focus-request « Annotations: selects the annotation »: findAllByText
  /anno-b|Sélection/ -> the properties panel holds Centre x = 20 (anno-b) and
  owns the focused heading.
- editor-shell-layout panel walk: added after.at(-1) === 'side'.
- editor-recovery title « Annuler les modifications » -> « Abandonner ».
- new: touch/cancel/mouse press, references search crossing, discard keeps
  lastSave, filter kept, one categories heading, badge 1/2/0, shownRevision.
2026-11-09 12:19:32 +01:00

376 lines
11 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 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 ReferencesPanel from '@/components/editor/references/ReferencesPanel'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import {
FocusConsumedContext,
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 panel = { open: true, onClose: 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} 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: selects the annotation and focuses the properties heading', 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.
const properties = await screen.findByTestId('annotation-properties')
expect(within(properties).getByLabelText('Centre x')).toHaveValue('20')
await waitFor(() =>
expect(document.activeElement).toHaveAttribute('data-properties-heading'),
)
expect(properties).toContainElement(document.activeElement as HTMLElement)
})
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(
<ReferencesPanel
{...base}
{...panel}
focus={request({ kind: 'reference', id: 'ref-a' })}
/>,
)
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(<ReferencesPanel {...base} {...panel} focus={focus} />)
;(document.activeElement as HTMLElement).blur()
view.rerender(<ReferencesPanel {...base} {...panel} 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} 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}
focus={state.focus}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
</FocusConsumedContext>
)
}
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('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'))
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' ? (
<ReferencesPanel {...base} {...panel} 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 />)
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()
})
})