feat(editor): browser history for tabs, sections and Aller a

EditorView held by the navigation reducer (restore_view), a history
adapter hook mounted in EditorWorkspace (push, replace, back, mount
rule, ownership, write budget, scroll map, refused POP), a guard stack
by layer, an announcer queue joined after open dialogs.
This commit is contained in:
bchanot committed 2026-11-13 17:57:52 +01:00
1 parent 69e225ca7a
commit 792394d3b2
11 files changed
+1268 -40

No files matched your search

@@ -0,0 +1,154 @@
/** R2F-1: the history entry, its ownership, the write plan and the write budget. */
import { describe, expect, it } from 'vitest'
import {
createWriteBudget,
ENTRY_KEY,
layerCount,
ownedEntry,
planWrite,
readEntry,
sanitizeView,
type HistoryEntry,
} from '@/editor/history/entry'
import {
defaultView,
initialNavigation,
navigationReducer,
sameView,
viewOf,
type EditorView,
} from '@/editor/navigation'
const view = (tab: EditorView['tab'], patch: Partial<EditorView> = {}) => ({
...defaultView(tab),
...patch,
})
const entry = (patch: Partial<HistoryEntry> = {}): HistoryEntry => ({
id: 'e1',
view: view('general'),
below: null,
sheetId: 'S',
userId: 'U',
...patch,
})
const stateOf = (value: unknown) => ({ [ENTRY_KEY]: value })
describe('sanitizeView', () => {
it('keeps a tab and a section, and holds no layer yet', () => {
const raw = { tab: 'annotations', section: 'views', finding: { key: {} } }
expect(sanitizeView(raw)).toEqual(view('annotations', { section: 'views' }))
})
it('drops what is no view: an unknown tab, a non-object', () => {
expect(sanitizeView({ tab: 'nowhere', section: 'views' })).toBeNull()
expect(sanitizeView('general')).toBeNull()
expect(sanitizeView(null)).toBeNull()
})
it('falls back to the drawing on an unknown section', () => {
expect(sanitizeView({ tab: 'annotations', section: 'x' })?.section).toBe(
'drawing',
)
})
})
describe('readEntry and ownership', () => {
it('reads a well-formed entry and nothing else', () => {
expect(readEntry(stateOf(entry()))).toEqual(entry())
expect(readEntry(null)).toBeNull()
expect(readEntry({})).toBeNull()
expect(readEntry(stateOf({ ...entry(), id: 3 }))).toBeNull()
expect(readEntry(stateOf({ ...entry(), view: 'x' }))).toBeNull()
})
it('restores only for the sheet and the account that wrote it', () => {
const mine = { sheetId: 'S', userId: 'U' }
expect(ownedEntry(stateOf(entry()), mine)).not.toBeNull()
expect(ownedEntry(stateOf(entry()), { ...mine, sheetId: 'T' })).toBeNull()
expect(ownedEntry(stateOf(entry()), { ...mine, userId: 'V' })).toBeNull()
})
it('keeps only navigation: nothing typed survives the read', () => {
const raw = { ...entry(), draft: 'typed text', term: 'search' }
expect(JSON.stringify(readEntry(stateOf(raw)))).not.toContain('typed')
})
})
describe('planWrite', () => {
const top = entry({ view: view('general'), below: null })
it('does nothing for the same view', () => {
expect(planWrite(top, view('general'), false)).toBe('none')
// a section only counts on Annotations
const other = view('general', { section: 'views' })
expect(planWrite(top, other, false)).toBe('none')
})
it('pushes an added tab or section, replaces on a replace hint', () => {
expect(planWrite(top, view('findings'), false)).toBe('push')
expect(planWrite(top, view('findings'), true)).toBe('replace')
const onAnnotations = entry({ view: view('annotations') })
const views = view('annotations', { section: 'views' })
expect(planWrite(onAnnotations, views, false)).toBe('push')
})
it('goes back for a layer removed when the entry holds the view below', () => {
const layer = view('findings', { reference: { create: true } })
const opened = entry({ view: layer, below: view('findings') })
expect(layerCount(layer)).toBe(1)
expect(planWrite(opened, view('findings'), false)).toBe('back')
})
it('replaces a layer removed when the entry below is another view', () => {
const layer = view('findings', { reference: { create: true } })
const opened = entry({ view: layer, below: view('general') })
expect(planWrite(opened, view('findings'), false)).toBe('replace')
expect(planWrite(entry({ view: layer }), view('findings'), false)).toBe(
'replace',
)
})
})
describe('createWriteBudget', () => {
it('lets the limit through per window, then refuses until the window slides', () => {
const take = createWriteBudget(3, 1000)
expect([0, 100, 200].map(take)).toEqual([true, true, true])
expect(take(300)).toBe(false)
expect(take(999)).toBe(false)
expect(take(1000)).toBe(true)
})
})
describe('the view the reducer holds', () => {
it('restore_view lands on a view without a move or a focus request', () => {
const state = initialNavigation('general')
const next = navigationReducer(state, {
type: 'restore_view',
view: view('annotations', { section: 'regions' }),
})
expect(viewOf(next)).toEqual(view('annotations', { section: 'regions' }))
expect(next.focus).toBeUndefined()
expect(next.visitedSections).toContain('regions')
})
it('keeps the remembered section when the view is on another tab', () => {
const base = navigationReducer(initialNavigation('annotations'), {
type: 'open_section',
section: 'views',
})
const next = navigationReducer(base, {
type: 'restore_view',
view: view('general'),
})
expect(next.section).toBe('views')
expect(
sameView(viewOf(next), view('general', { section: 'drawing' })),
).toBe(true)
})
it('opens the state on a view read at mount', () => {
const state = initialNavigation('annotations', view('findings'))
expect(state.tab).toBe('findings')
expect(state.visitedTabs).toEqual(['findings'])
})
})
@@ -0,0 +1,144 @@
/** R2F-1/2: guard stack, announcer queue, a Back refused while the citations panel is open. */
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.openCitations(finding)}>cite</button>
<button onClick={() => nav.registerCanLeave(guard ?? null)}>guard</button>
<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 while the citations panel is open', () => {
it('keeps the page where it is, asks the dirty layer, and pushes the view again', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
const guard = vi.fn(() => ({ allowed: false }))
mount(guard)
await user.click(screen.getByRole('button', { name: 'guard' }))
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('button', { name: 'cite' }))
const before = entry().id
act(() => navigate(-1))
expect(guard).toHaveBeenCalledWith(false)
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent(
'Constats',
)
expect(entry().id).not.toBe(before)
expect(entry().view.tab).toBe('findings')
expect(entry().below?.tab).toBe('general')
})
})
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('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)
})
})
+193
View File
@@ -0,0 +1,193 @@
/** R2F-1: the browser history follows tab, section and « Aller à » moves (MemoryRouter). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Location, NavigateFunction } from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import { defaultView } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { emptyText } from '../helpers/editorFixtures'
import { resetStore, serverHas, SHEET, USER } from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
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(),
}))
let navigate: NavigateFunction
let location: Location
const probe = (n: NavigateFunction, l: Location) => {
navigate = n
location = l
}
const written = () =>
(location.state as Record<string, HistoryEntry> | null)?.[ENTRY_KEY]
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const tab = (name: string) => screen.getByRole('tab', { name })
const selected = () =>
screen.getByRole('tab', { selected: true }).textContent ?? ''
const back = (delta = -1) => act(() => navigate(delta))
const path = `/app/admin/sheets/${SHEET}/draft`
const foreign = (patch: Partial<HistoryEntry>) => ({
[ENTRY_KEY]: {
id: 'old',
view: defaultView('findings'),
below: null,
sheetId: SHEET,
userId: USER,
...patch,
},
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
serverHas(emptyText(), 3, false)
})
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
describe('mount', () => {
it('writes the default view as the first entry', async () => {
mountDraft({ probe })
await ready()
await waitFor(() => expect(written()).toBeTruthy())
const tabs: Record<string, string> = {
Général: 'general',
Annotations: 'annotations',
}
expect(written()?.view.tab).toBe(tabs[selected()])
expect(written()).toMatchObject({
sheetId: SHEET,
userId: USER,
below: null,
})
})
it('restores the view of an entry of this sheet and account', async () => {
const entries = [{ pathname: path, state: foreign({}) }]
mountDraft({ probe, entries })
await ready()
expect(selected()).toBe('Constats')
expect(written()?.id).toBe('old')
})
it('replaces an entry of another sheet or account by the default view', async () => {
const entries = [{ pathname: path, state: foreign({ sheetId: 'other' }) }]
mountDraft({ probe, entries })
await ready()
await waitFor(() => expect(written()?.sheetId).toBe(SHEET))
expect(selected()).not.toBe('Constats')
expect(written()?.id).not.toBe('old')
})
})
describe('tab and section moves', () => {
it('a tab click pushes, Back and Forward restore it, the tab button holds the focus', async () => {
const user = userEvent.setup()
mountDraft({ probe })
await ready()
await waitFor(() => expect(written()).toBeTruthy())
const first = selected()
await user.click(tab('Constats'))
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
expect(written()?.below?.tab).not.toBe('findings')
back()
await waitFor(() => expect(selected()).toBe(first))
await waitFor(() => expect(document.activeElement).toBe(tab(first)))
back(1)
await waitFor(() => expect(selected()).toBe('Constats'))
await waitFor(() => expect(document.activeElement).toBe(tab('Constats')))
})
it('arrow keys along the row replace the entry instead of adding one', async () => {
const user = userEvent.setup()
mountDraft({ probe, entries: ['/app/admin', path] })
await ready()
await user.click(tab('Constats'))
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
tab('Constats').focus()
fireEvent.keyDown(tab('Constats'), { key: 'ArrowRight' })
await waitFor(() => expect(selected()).toBe('Références'))
expect(written()?.view.tab).toBe('references')
// one Back leaves the replaced entry for the one below it, not for « Constats »
back()
await waitFor(() => expect(selected()).not.toBe('Références'))
expect(selected()).not.toBe('Constats')
})
it('an Annotations section pushes, « Retour au dessin » too, Back returns to the section', async () => {
const user = userEvent.setup()
mountDraft({ probe })
await ready()
await user.click(tab('Annotations'))
await user.click(screen.getByRole('button', { name: 'Vues' }))
await waitFor(() => expect(written()?.view.section).toBe('views'))
await user.click(screen.getByRole('button', { name: 'Retour au dessin' }))
await waitFor(() => expect(written()?.view.section).toBe('drawing'))
back()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Retour au dessin' }),
).toBeVisible(),
)
expect(written()?.view.section).toBe('views')
})
it('a move that changes nothing writes nothing', async () => {
const user = userEvent.setup()
mountDraft({ probe })
await ready()
await waitFor(() => expect(written()).toBeTruthy())
const before = location.key
await user.click(screen.getByRole('tab', { selected: true }))
expect(location.key).toBe(before)
})
})
describe('a Back that must not unmount what is on screen', () => {
it('keeps the view and pushes it again while a dialog is open', async () => {
const user = userEvent.setup()
mountDraft({ probe })
await ready()
await user.click(tab('Constats'))
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
document.body.append(dialog)
back()
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
expect(selected()).toBe('Constats')
// the re-pushed entry sits above the one landed on
expect(written()?.below?.tab).not.toBe('findings')
dialog.remove()
})
})
describe('StrictMode', () => {
it('writes the first entry once', async () => {
mountDraft({ probe, strict: true })
await ready()
await waitFor(() => expect(written()).toBeTruthy())
const id = written()?.id
expect(id).toBeTruthy()
await new Promise((resolve) => setTimeout(resolve, 20))
expect(written()?.id).toBe(id)
})
})