Files
faunosteo/apps/app/tests/unit/editor-history-guards.test.tsx
T
bchanot 18085cecf8 feat(editor): finding dialog and citations side sheet in the history
Constats opens each element in one modal dialog (view, edit with a
local draft, creation) driven by the editor view layer of the browser
history. The citations panel becomes a modal side sheet stacked over
it; its geometry, exit machinery and page inertness are removed.
Back and Forward restore the layers, a dirty form asks first.
2026-11-13 18:51:35 +01:00

203 lines
7.2 KiB
TypeScript

/** R2F-1/2: guard stack, announcer queue, a Back over the finding layers. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
render,
renderHook,
screen,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
MemoryRouter,
useLocation,
useNavigate,
type Location,
type NavigateFunction,
} from 'react-router-dom'
import { flushAfterModals } from '@/components/ui/afterModalsClosed'
import { useBeforeUnload } from '@/app/useLeaveGuard'
import EditorTabs from '@/components/editor/EditorTabs'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import { defaultView } from '@/editor/navigation'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import { useLocaleStore } from '@/state/localeStore'
afterEach(cleanup)
const owner = { sheetId: 'S', userId: 'U' }
const finding: ElementKey = {
kind: 'finding',
zone_id: 'zone',
path: ['family', 'node'],
}
let navigate: NavigateFunction
let location: Location
const entry = () => (location.state as Record<string, HistoryEntry>)[ENTRY_KEY]
function Page({ guard }: { guard?: () => { allowed: boolean } }) {
const nav = useEditorNavigation('general')
navigate = useNavigate()
location = useLocation()
useEditorHistory(nav, owner, defaultView('general'))
return (
<>
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
<button onClick={() => nav.openFinding(finding)}>open</button>
<button onClick={() => nav.openCitations(finding)}>cite</button>
<button onClick={() => nav.guards.register('finding', guard ?? null)}>
guard
</button>
<p data-testid="layer">{JSON.stringify(nav.state.finding)}</p>
<button onClick={() => nav.announce('one')}>say one</button>
<button onClick={() => nav.announce('two')}>say two</button>
<p data-testid="live">{nav.live}</p>
</>
)
}
const mount = (guard?: () => { allowed: boolean }) =>
render(
<MemoryRouter initialEntries={['/x']}>
<Page guard={guard} />
</MemoryRouter>,
)
describe('a Back over the finding layers', () => {
async function openSheet(guard?: () => { allowed: boolean }) {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount(guard)
if (guard) await user.click(screen.getByRole('button', { name: 'guard' }))
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('button', { name: 'open' }))
await user.click(screen.getByRole('button', { name: 'cite' }))
return user
}
const layer = () => JSON.parse(screen.getByTestId('layer').textContent!)
it('closes the sheet first, then the dialog, one layer per entry', async () => {
await openSheet()
expect(layer()).toMatchObject({ citations: true })
expect(entry().below?.finding).toMatchObject({ citations: false })
act(() => navigate(-1))
expect(layer()).toMatchObject({ citations: false })
act(() => navigate(-1))
expect(layer()).toBeNull()
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent(
'Constats',
)
})
it('a dirty layer keeps the page where it is: asked, the view pushed again', async () => {
const guard = vi.fn(() => ({ allowed: false }))
await openSheet(guard)
const before = entry().id
act(() => navigate(-1))
expect(guard).toHaveBeenCalledWith(false)
expect(layer()).toMatchObject({ citations: true })
expect(entry().id).not.toBe(before)
expect(entry().view.finding).toMatchObject({ citations: true })
expect(entry().below?.finding).toMatchObject({ citations: false })
})
it('a modal that is no layer refuses the Back too', async () => {
await openSheet()
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
document.body.append(dialog)
act(() => navigate(-1))
expect(layer()).toMatchObject({ citations: true })
dialog.remove()
})
it('a layer dialog open does not refuse it', async () => {
await openSheet()
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
dialog.setAttribute('data-layer', '')
document.body.append(dialog)
act(() => navigate(-1))
expect(layer()).toMatchObject({ citations: false })
dialog.remove()
})
})
describe('the guard stack', () => {
it('asks each layer on its own, and all of them top down', () => {
const { result } = renderHook(() => useEditorNavigation('general'))
const { guards } = result.current
const order: string[] = []
guards.register('citations', () => {
order.push('citations')
return { allowed: true, note: 'a' }
})
guards.register('finding', () => {
order.push('finding')
return { allowed: false, note: 'b' }
})
expect(guards.ask('reference', false)).toEqual({ allowed: true })
expect(guards.ask('finding', true).allowed).toBe(false)
order.length = 0
expect(guards.askAll(false)).toEqual({ allowed: false, note: 'b. a' })
expect(order).toEqual(['finding', 'citations'])
guards.register('finding', null)
expect(guards.askAll(false).allowed).toBe(true)
})
})
describe('the announcer', () => {
it('says what is announced at once while no dialog is open', async () => {
mount()
await userEvent.click(screen.getByRole('button', { name: 'say one' }))
expect(screen.getByTestId('live')).toHaveTextContent('one')
})
it('joins what is announced under an open dialog into one announcement', async () => {
const user = userEvent.setup()
mount()
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
document.body.append(dialog)
await user.click(screen.getByRole('button', { name: 'say one' }))
await user.click(screen.getByRole('button', { name: 'say two' }))
expect(screen.getByTestId('live')).toHaveTextContent('')
dialog.remove()
act(() => flushAfterModals())
expect(screen.getByTestId('live')).toHaveTextContent('one. two')
})
})
describe('the announcer, a wait that never fires', () => {
it('does not hold later messages back', async () => {
const user = userEvent.setup()
mount()
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
document.body.append(dialog)
await user.click(screen.getByRole('button', { name: 'say one' }))
// the dialog goes without ModalDialog's cleanup: nothing flushes the queue
dialog.remove()
await user.click(screen.getByRole('button', { name: 'say two' }))
expect(screen.getByTestId('live')).toHaveTextContent('one. two')
})
})
describe('useBeforeUnload', () => {
it('asks while dirty and stops when clean', () => {
const { rerender } = renderHook(({ dirty }) => useBeforeUnload(dirty), {
initialProps: { dirty: true },
})
const first = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(first)
expect(first.defaultPrevented).toBe(true)
rerender({ dirty: false })
const second = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(second)
expect(second.defaultPrevented).toBe(false)
})
})