diff --git a/apps/app/e2e/shell/editor-history.spec.ts b/apps/app/e2e/shell/editor-history.spec.ts new file mode 100644 index 00000000..0855fe7f --- /dev/null +++ b/apps/app/e2e/shell/editor-history.spec.ts @@ -0,0 +1,155 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { expect, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + editorActor, + openEditor, + openSection, + place, + pointOf, + seedDraft, + selectTab, + shapeWith, +} from '../support/editor' + +// R2 UX finish, task 1 (R2F-1): the browser's Back and Forward walk the editor's tabs and +// Annotations sections. Chromium's own history (page.goBack) drives them; the top-layer and +// focus rules are the browser's, so they are proved here and not in happy-dom. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const dialog = (page: Page) => page.getByRole('dialog') +const selected = (page: Page) => page.getByRole('tab', { selected: true }) +const tabName = (tab: string) => + new RegExp(`^${dict[`editor.tab.${tab}`]}( |$)`) + +/** + * The history follows a move from an effect, a few milliseconds after the click: wait for + * the entry on top to name the tab before pressing Back (a user cannot be that quick). + */ +async function written(page: Page, tab: string) { + await page.waitForFunction( + (wanted) => history.state?.usr?.editorEntry?.view?.tab === wanted, + tab, + ) +} + +async function sectionWritten(page: Page, section: string) { + await page.waitForFunction( + (wanted) => history.state?.usr?.editorEntry?.view?.section === wanted, + section, + ) +} + +async function open(page: Page) { + const actor = await editorActor('fr') + const linked = pointOf('p1', 'main', { cx: 500, cy: 400, r: 40 }, 'Point lié') + const seed = await seedDraft(actor, { shape: shapeWith(linked) }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(selected(page)).toHaveText(tabName('annotations')) + return seed +} + +test.describe('editor browser history', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('tabs: Back and Forward restore them, the tab button holds the focus', async ({ + page, + }) => { + await open(page) + await selectTab(page, dict, 'findings') + await written(page, 'findings') + await selectTab(page, dict, 'references') + await written(page, 'references') + await page.goBack() + await expect(selected(page)).toHaveText(tabName('findings')) + await expect(page.locator(':focus')).toHaveAttribute( + 'id', + 'editor-tab-findings', + ) + await page.goBack() + await expect(selected(page)).toHaveText(tabName('annotations')) + await expect(page.locator(':focus')).toHaveAttribute( + 'id', + 'editor-tab-annotations', + ) + await page.goForward() + await expect(selected(page)).toHaveText(tabName('findings')) + await page.goForward() + await expect(selected(page)).toHaveText(tabName('references')) + }) + + test('an Annotations section is an entry of its own: Back shows the drawing, Forward the section', async ({ + page, + }) => { + await open(page) + await openSection(page, dict, 'categories') + await sectionWritten(page, 'categories') + await page.goBack() + await expect(place(page, 'annotations.drawing')).toBeVisible() + await expect(place(page, 'annotations.categories')).toBeHidden() + await expect(page.locator(':focus')).not.toHaveJSProperty('tagName', 'BODY') + await page.goForward() + await expect(place(page, 'annotations.categories')).toBeVisible() + }) + + test('arrow keys along the tab row replace the entry: one Back leaves the walk', async ({ + page, + }) => { + await open(page) + await selectTab(page, dict, 'findings') + await written(page, 'findings') + await page.keyboard.press('ArrowRight') + await expect(selected(page)).toHaveText(tabName('references')) + await written(page, 'references') + await page.keyboard.press('ArrowRight') + await expect(selected(page)).toHaveText(tabName('verification')) + await written(page, 'verification') + await page.goBack() + await expect(selected(page)).toHaveText(tabName('annotations')) + }) + + test('a reload reopens the view of the entry', async ({ page }) => { + await open(page) + await selectTab(page, dict, 'findings') + await written(page, 'findings') + await page.reload() + await expect(selected(page)).toHaveText(tabName('findings')) + await page.goBack() + await expect(selected(page)).toHaveText(tabName('annotations')) + }) + + test('a DeleteDialog open when Back is pressed stays open, the view unchanged', async ({ + page, + }) => { + await open(page) + await openSection(page, dict, 'categories') + await sectionWritten(page, 'categories') + await page + .getByRole('listitem') + .filter({ has: page.locator('#category-cat-a-name-fr') }) + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await expect(dialog(page)).toBeVisible() + await page.goBack() + await expect(dialog(page)).toBeVisible() + await expect(place(page, 'annotations.categories')).toBeVisible() + await dialog(page) + .getByRole('button', { name: dict['editor.delete.close'], exact: true }) + .last() + .click() + await expect(dialog(page)).toHaveCount(0) + // The refused Back left the section one entry above the drawing: this one goes. + await page.goBack() + await expect(place(page, 'annotations.drawing')).toBeVisible() + }) +}) diff --git a/apps/app/src/components/editor/EditorTabs.tsx b/apps/app/src/components/editor/EditorTabs.tsx index 84840fd1..cc586f5f 100644 --- a/apps/app/src/components/editor/EditorTabs.tsx +++ b/apps/app/src/components/editor/EditorTabs.tsx @@ -41,7 +41,10 @@ function ErrorCount({ tab }: { tab: EditorTabId }) { } /** Answers false when the change was refused (a field of the open panel refused to apply). */ -type SelectTab = (tab: EditorTabId) => boolean | void +type SelectTab = ( + tab: EditorTabId, + options?: { replace?: boolean }, +) => boolean | void interface TabListProps { shown: readonly EditorTabId[] @@ -59,7 +62,8 @@ function TabList({ shown, active, onSelect }: TabListProps) { if (step === 0 || at < 0) return event.preventDefault() const next = shown[(at + step + shown.length) % shown.length] - if (onSelect(next) === false) return + // An arrow-key walk along the row replaces its history entry instead of adding one. + if (onSelect(next, { replace: true }) === false) return document.getElementById(tabDomId(next))?.focus() } return ( diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx index 3e63363b..ed0f8a8c 100644 --- a/apps/app/src/components/editor/EditorWorkspace.tsx +++ b/apps/app/src/components/editor/EditorWorkspace.tsx @@ -1,4 +1,5 @@ -import { useEffect, useRef, type ReactNode } from 'react' +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { useLocation } from 'react-router-dom' import { AnimatePresence } from 'motion/react' import type { ElementKey } from '@faunosteo/core-wasm/types' import type { OfficialSheetAdmin } from '@faunosteo/supabase' @@ -12,6 +13,9 @@ import { import { saveFailureMessage } from '@/editor/messages' import type { EditorMode } from '@/editor/mode' import { useEditorStore } from '@/editor/state/editorStore' +import { ownedEntry } from '@/editor/history/entry' +import useEditorHistory from '@/editor/history/useEditorHistory' +import { defaultView } from '@/editor/navigation' import { initialTab } from '@/editor/tabs' import { useEditorNavigation, @@ -19,6 +23,7 @@ import { } from '@/editor/useEditorNavigation' import type { TabTier } from '@/editor/useViewport' import { useT } from '@/i18n/useT' +import { useAuthStore } from '@/state/authStore' import ConflictDialog from './ConflictDialog' import CopyIssueNotice from './CopyIssueNotice' import DraftHeader from './DraftHeader' @@ -156,9 +161,17 @@ function useBodyEscape(open: boolean, close: () => void) { export default function EditorWorkspace(props: Props) { const { sheet, mode, readOnly, tier, reloadSheet } = props const previewState = useEditorStore((s) => s.previewState) - const nav = useEditorNavigation( - previewState ? initialTab(previewState, tier) : 'annotations', + const tab = previewState ? initialTab(previewState, tier) : 'annotations' + const userId = useAuthStore((s) => s.user?.id ?? '') + const owner = useMemo( + () => ({ sheetId: sheet.sheet_id, userId }), + [sheet.sheet_id, userId], ) + // A reload or a reopened entry shows the view the history kept, never a layer. + const { state } = useLocation() + const [entry] = useState(() => ownedEntry(state, owner)) + const nav = useEditorNavigation(tab, entry?.view) + useEditorHistory(nav, owner, defaultView(tab)) const open = nav.state.citationsOf !== null useBodyEscape(open, nav.closeCitations) return ( diff --git a/apps/app/src/editor/history/entry.ts b/apps/app/src/editor/history/entry.ts new file mode 100644 index 00000000..062831ff --- /dev/null +++ b/apps/app/src/editor/history/entry.ts @@ -0,0 +1,111 @@ +import { + ANNOTATION_SECTIONS, + sameView, + type AnnotationSection, + type EditorView, +} from '../navigation' +import { EDITOR_TABS, type EditorTabId } from '../tabs' + +/** + * What one browser history entry of the editor holds (R2F-1): the view, the view below + * it (the place a Back returns to), and whose editor wrote it. Navigation only: never + * typed text, a search term or a draft. + */ +export interface HistoryEntry { + /** Keys the scroll map: one per entry written, kept by a replace. */ + id: string + view: EditorView + below: EditorView | null + sheetId: string + userId: string +} + +/** The sheet and the account an entry may be restored for. */ +export interface HistoryOwner { + sheetId: string + userId: string +} + +/** The key of the entry inside the router's `location.state`. */ +export const ENTRY_KEY = 'editorEntry' + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null + +/** + * A view read back from a history entry, or null when it is no view. Vanished keys drop + * their layer: no layer is ever written yet, so the three layer fields come back null. + * shortcut: later layers validate their key against the loaded sheet here. + */ +export function sanitizeView(raw: unknown): EditorView | null { + if (!isRecord(raw)) return null + if (!EDITOR_TABS.includes(raw.tab as EditorTabId)) return null + const known = ANNOTATION_SECTIONS.includes(raw.section as AnnotationSection) + return { + tab: raw.tab as EditorTabId, + section: known ? (raw.section as AnnotationSection) : 'drawing', + finding: null, + reference: null, + referenceFilter: null, + } +} + +/** The entry `state` (a `location.state`) carries, or null when it carries none. */ +export function readEntry(state: unknown): HistoryEntry | null { + const raw = isRecord(state) ? state[ENTRY_KEY] : null + if (!isRecord(raw)) return null + const view = sanitizeView(raw.view) + const { id, sheetId, userId } = raw + if (!view || typeof id !== 'string') return null + if (typeof sheetId !== 'string' || typeof userId !== 'string') return null + const below = raw.below === null ? null : sanitizeView(raw.below) + return { id, view, below, sheetId, userId } +} + +/** An entry restores only for the sheet and the account that wrote it. */ +export function ownedEntry( + state: unknown, + owner: HistoryOwner, +): HistoryEntry | null { + const entry = readEntry(state) + const mine = entry?.sheetId === owner.sheetId && entry.userId === owner.userId + return mine ? entry : null +} + +export const entryState = (entry: HistoryEntry) => ({ [ENTRY_KEY]: entry }) + +/** Layers over the place: a finding dialog or a reference dialog each count one. */ +export function layerCount(view: EditorView): number { + return (view.finding ? 1 : 0) + (view.reference ? 1 : 0) +} + +/** What a changed view asks of the history. */ +export type HistoryWrite = 'none' | 'push' | 'replace' | 'back' + +/** + * A user move to `view`. A layer taken away goes back when the entry holds the view the + * move lands on (the entry that opened the layer), else it replaces; a layer, tab or + * section added pushes, unless the move asked for a replace. + */ +export function planWrite( + top: HistoryEntry, + view: EditorView, + replace: boolean, +): HistoryWrite { + if (sameView(top.view, view)) return 'none' + if (layerCount(view) < layerCount(top.view)) { + return top.below && sameView(top.below, view) ? 'back' : 'replace' + } + return replace ? 'replace' : 'push' +} + +/** Sliding-window budget of history writes: past it a view stays in memory. */ +export function createWriteBudget(limit: number, windowMs: number) { + const stamps: number[] = [] + return (now: number): boolean => { + while (stamps.length > 0 && now - stamps[0] >= windowMs) stamps.shift() + if (stamps.length >= limit) return false + stamps.push(now) + return true + } +} diff --git a/apps/app/src/editor/history/useEditorHistory.ts b/apps/app/src/editor/history/useEditorHistory.ts new file mode 100644 index 00000000..a5dae84e --- /dev/null +++ b/apps/app/src/editor/history/useEditorHistory.ts @@ -0,0 +1,256 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { useLocation, useNavigate, useNavigationType } from 'react-router-dom' +import { afterModalsClosed } from '@/components/ui/afterModalsClosed' +import { focusActiveTab } from '../focusRequest' +import { sameView, type EditorView } from '../navigation' +import { + headingOf, + shownPlace, + useMoveText, + type EditorNavigation, +} from '../useEditorNavigation' +import { + createWriteBudget, + entryState, + ownedEntry, + planWrite, + type HistoryEntry, + type HistoryOwner, +} from './entry' + +/** Well under WebKit's 100 history writes per 10 s: past it a view stays in memory. */ +const WRITE_LIMIT = 40 +const WRITE_WINDOW_MS = 10_000 +/** A `back()` that never lands (nothing to go back to) stops blocking writes after this. */ +const BACK_TIMEOUT_MS = 1_000 + +/** What the adapter keeps between renders; none of it is rendered. */ +interface Book { + /** The entry on top of the history as the adapter knows it (null before the mount). */ + entry: HistoryEntry | null + /** The router key last looked at, so each location is read once. */ + handled: string | null + pendingBack: boolean + backTimer: ReturnType | undefined + /** Scroll position of the entries left, by entry id. */ + scrolls: Map + lastScroll: number + counter: number + takeWrite: (now: number) => boolean +} + +function newBook(): Book { + return { + entry: null, + handled: null, + pendingBack: false, + backTimer: undefined, + scrolls: new Map(), + lastScroll: 0, + counter: 0, + takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS), + } +} + +/** A Back or Forward that changed the view: what the landing scrolls to, focuses and says. */ +interface Landing { + entry: HistoryEntry + tabChanged: boolean +} + +/** + * 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. + */ +function useWriter(book: Book, owner: HistoryOwner) { + const navigate = useNavigate() + const location = useLocation() + const latest = useRef({ navigate, location }) + latest.current = { navigate, location } + return useMemo(() => { + const send = (entry: HistoryEntry, replace: boolean) => { + const { navigate, location } = latest.current + const { pathname, search, hash } = location + const to = { pathname, search, hash } + try { + navigate(to, { replace, state: entryState(entry) }) + } catch { + // The view stays in memory; the next move writes again. + } + } + const fresh = (view: EditorView, below: EditorView | null) => { + book.counter += 1 + return { id: `e${book.counter}`, view, below, ...owner } + } + const write = (entry: HistoryEntry, replace: boolean) => { + book.entry = entry + if (replace || book.takeWrite(Date.now())) send(entry, replace) + } + return { + push: (view: EditorView) => + write(fresh(view, book.entry?.view ?? null), false), + replace: (view: EditorView) => { + const kept = book.entry ?? fresh(view, null) + write({ ...kept, view }, true) + }, + first: (view: EditorView) => write(fresh(view, null), true), + back: () => { + book.pendingBack = true + clearTimeout(book.backTimer) + book.backTimer = setTimeout(() => { + book.pendingBack = false + }, BACK_TIMEOUT_MS) + latest.current.navigate(-1) + }, + } + }, [book, owner]) +} + +type Writer = ReturnType + +/** User moves: the view changed, the history follows (R2F-1). */ +function useReconcile( + nav: EditorNavigation, + view: EditorView, + book: Book, + writer: Writer, +) { + useEffect(() => { + const { scrollY, replace } = nav.trace + nav.trace.scrollY = null + nav.trace.replace = false + const top = book.entry + if (!top || book.pendingBack) return + const plan = planWrite(top, view, replace) + if (plan === 'none') return + book.scrolls.set(top.id, scrollY ?? window.scrollY) + if (plan === 'back') writer.back() + else if (plan === 'push') writer.push(view) + else writer.replace(view) + }, [view, nav.trace, book, writer]) +} + +/** The page shows something the history does not carry: a POP must not unmount it. */ +function popRefused(nav: EditorNavigation): boolean { + return ( + document.querySelector('dialog[open]') !== null || + nav.state.citationsOf !== null + ) +} + +interface PopContext { + nav: EditorNavigation + book: Book + writer: Writer + owner: HistoryOwner + defaultView: EditorView + view: EditorView +} + +/** The entry of a Back or Forward is not this editor's: the default view replaces it. */ +function landOnForeign(ctx: PopContext): Landing | null { + const { nav, writer, defaultView, book } = ctx + writer.first(defaultView) + nav.restoreView(defaultView) + return book.entry && { entry: book.entry, tabChanged: true } +} + +/** What the page does with the entry a Back or Forward landed on. */ +function landOn(ctx: PopContext, state: unknown): Landing | null { + const { nav, book, writer, owner, view } = ctx + if (book.entry) book.scrolls.set(book.entry.id, book.lastScroll) + const expected = book.pendingBack + book.pendingBack = false + clearTimeout(book.backTimer) + const entry = ownedEntry(state, owner) + if (!entry) return landOnForeign(ctx) + if (!expected && popRefused(nav)) { + // The dirty form, if any, says so itself; the page keeps everything mounted. + nav.guards.askAll(false) + book.entry = entry + writer.push(view) + return null + } + book.entry = entry + if (sameView(entry.view, view)) return null + nav.restoreView(entry.view) + return { entry, tabChanged: entry.view.tab !== view.tab } +} + +/** The first location of the editor: an entry of this sheet and account is kept, else replaced. */ +function mount(ctx: PopContext, state: unknown): void { + const entry = ownedEntry(state, ctx.owner) + if (entry) ctx.book.entry = entry + else ctx.writer.first(ctx.view) +} + +/** Scroll, focus and announcement once a Back or Forward has restored a view. */ +function useLanding( + nav: EditorNavigation, + book: Book, + landing: Landing | null, +) { + const moveText = useMoveText() + const { announce } = nav + const landed = useRef(null) + useEffect(() => { + // A new wording (locale switch) re-creates `moveText`: the landing stays one. + if (!landing || landed.current === landing) return + landed.current = landing + const { entry, tabChanged } = landing + const { tab, section } = entry.view + return afterModalsClosed(() => { + window.scrollTo(0, book.scrolls.get(entry.id) ?? 0) + const heading = tabChanged ? null : headingOf(shownPlace(entry.view)) + if (heading) heading.focus({ preventScroll: true }) + else focusActiveTab({ preventScroll: true }) + const shown = tab === 'annotations' ? section : null + announce(moveText({ place: 'tab', tab, section: shown, key: null })) + }) + }, [landing, book, announce, moveText]) +} + +/** + * The browser's history of the editor (R2F-1), kept in step with the view the navigation + * reducer holds. A move dispatches at once and the history follows from one effect that + * compares the view with the last entry this adapter wrote (a ref, never `useLocation()`, + * which lags a transition). A Back or Forward restores the view of the entry it lands on, + * unless a dialog or the citations panel is open: then the pre-move view is pushed back. + * Foreign entries (another sheet, another account) and entries without a view are replaced + * by the default view. + */ +export default function useEditorHistory( + nav: EditorNavigation, + owner: HistoryOwner, + defaultView: EditorView, +): void { + const location = useLocation() + const navType = useNavigationType() + const bookRef = useRef(null) + const book = (bookRef.current ??= newBook()) + const writer = useWriter(book, owner) + const [landing, setLanding] = useState(null) + const { tab, section, finding, reference, referenceFilter } = nav.state + const view = useMemo( + () => ({ tab, section, finding, reference, referenceFilter }), + [tab, section, finding, reference, referenceFilter], + ) + const ctx = { nav, book, writer, owner, defaultView, view } + useEffect(() => { + if (book.handled === location.key) return + book.handled = location.key + if (book.entry === null) mount(ctx, location.state) + else if (navType === 'POP') setLanding(landOn(ctx, location.state)) + // Read once per location: the context is the one this render holds. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [location.key]) + useReconcile(nav, view, book, writer) + useLanding(nav, book, landing) + useEffect(() => { + const onScroll = () => { + book.lastScroll = window.scrollY + } + window.addEventListener('scroll', onScroll, { passive: true }) + return () => window.removeEventListener('scroll', onScroll) + }, [book]) +} diff --git a/apps/app/src/editor/navigation.ts b/apps/app/src/editor/navigation.ts index 775f583f..6b9ed32c 100644 --- a/apps/app/src/editor/navigation.ts +++ b/apps/app/src/editor/navigation.ts @@ -26,9 +26,24 @@ export interface FocusRequest { serial: number } -export interface NavigationState { +/** + * What the browser history records of the editor (R2F-1): where the user is, never what + * they typed. A layer (`finding`, `reference`) is a dialog over a place; `referenceFilter` + * narrows the references library to the citers of an element. Only `tab` and `section` + * are ever set so far: the three others are the room later layers fill. + */ +export interface EditorView { tab: EditorTabId section: AnnotationSection + finding: + | { key: ElementKey; citations: boolean } + | { create: { kind: string; parent: ElementKey | null } } + | null + reference: { edit: string } | { create: true } | null + referenceFilter: ElementKey | null +} + +export interface NavigationState extends EditorView { /** The finding whose citations panel is open; null while it is closed. */ citationsOf: ElementKey | null /** Bumped by `show_all_references`: the library resets its search once per bump. */ @@ -49,6 +64,7 @@ export type NavigationAction = | { type: 'close_citations' } | { type: 'show_all_references' } | { type: 'go_to'; target: EditorTarget } + | { type: 'restore_view'; view: EditorView } | { type: 'focus_consumed'; serial: number } const TAB_OF_KIND = { @@ -97,11 +113,33 @@ function shown(state: NavigationState): NavigationState { return { ...state, visitedTabs, visitedSections } } -export function initialNavigation(tab: EditorTabId): NavigationState { +const DEFAULT_VIEW = { + section: 'drawing', + finding: null, + reference: null, + referenceFilter: null, +} as const + +/** The finding whose citations panel the view shows, null when it shows none. */ +function citationsOfView(view: EditorView): ElementKey | null { + const { finding } = view + return finding && 'key' in finding && finding.citations ? finding.key : null +} + +/** The view a fresh editor shows on `tab`: the drawing, no layer. */ +export function defaultView(tab: EditorTabId): EditorView { + return { ...DEFAULT_VIEW, tab } +} + +/** `view` (a history entry read at mount) or the plain default view of `tab`. */ +export function initialNavigation( + tab: EditorTabId, + view?: EditorView | null, +): NavigationState { + const start = view ?? defaultView(tab) return shown({ - tab, - section: 'drawing', - citationsOf: null, + ...start, + citationsOf: citationsOfView(start), libraryReset: 0, visitedTabs: [], visitedSections: [], @@ -110,6 +148,41 @@ export function initialNavigation(tab: EditorTabId): NavigationState { }) } +/** The part of the state the browser history records. */ +export function viewOf(state: NavigationState): EditorView { + const { tab, section, finding, reference, referenceFilter } = state + return { tab, section, finding, reference, referenceFilter } +} + +/** + * The same place for the history: a section only counts on Annotations (the other tabs + * keep the last one in memory, nobody sees it). + */ +export function sameView(a: EditorView, b: EditorView): boolean { + const section = a.tab !== 'annotations' || a.section === b.section + return ( + a.tab === b.tab && + section && + JSON.stringify([a.finding, a.reference, a.referenceFilter]) === + JSON.stringify([b.finding, b.reference, b.referenceFilter]) + ) +} + +/** A Back or Forward landed on `view`: the page shows it, no request to answer. */ +function restoreView( + state: NavigationState, + view: EditorView, +): NavigationState { + const section = view.tab === 'annotations' ? view.section : state.section + return shown({ + ...state, + ...view, + section, + citationsOf: citationsOfView(view), + focus: undefined, + }) +} + /** * A finding node (kind `finding` below its family, path of two or more ids). A zone and a * family list their citations inline and have no panel. @@ -166,6 +239,8 @@ export function navigationReducer( return showAllReferences(state) case 'go_to': return goTo(state, action.target) + case 'restore_view': + return restoreView(state, action.view) case 'focus_consumed': return state.focus?.serial === action.serial ? { ...state, focus: undefined } diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index 9c0e4486..c07f94af 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, + useMemo, useReducer, useRef, useState, @@ -8,6 +9,7 @@ import { type RefObject, } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' +import { afterModalsClosed } from '@/components/ui/afterModalsClosed' import { useT } from '@/i18n/useT' import { commitFocusedField, @@ -23,6 +25,7 @@ import { navigationReducer, type AnnotationSection, type EditorTarget, + type EditorView, type NavigationAction, type NavigationState, } from './navigation' @@ -55,6 +58,34 @@ export interface LeaveAnswer { } export type CanLeave = (forced: boolean) => LeaveAnswer +/** The layers that can hold a form the user must settle before leaving, top one last. */ +const LAYERS = ['citations', 'finding', 'reference'] as const +export type LayerName = (typeof LAYERS)[number] + +/** One guard per layer (R2F-1): each layer registers its own check while it is mounted. */ +export interface Guards { + register: (layer: LayerName, guard: CanLeave | null) => void + /** The answer of one layer; allowed when the layer registered nothing. */ + ask: (layer: LayerName, forced: boolean) => LeaveAnswer + /** The layers asked top down; one refusal refuses, and each one still shows its own. */ + askAll: (forced: boolean) => LeaveAnswer +} + +/** + * What a move leaves for the history adapter to read once the view has changed: the + * scroll position taken before the dispatch, and whether the move replaces its entry + * (an arrow-key tab move) instead of adding one. The adapter resets it. + */ +export interface MoveTrace { + scrollY: number | null + replace: boolean +} + +/** Options of a tab choice. */ +export interface SelectOptions { + replace?: boolean +} + type Opener = HTMLElement | null | undefined export interface EditorNavigation { @@ -63,7 +94,7 @@ export interface EditorNavigation { live: string navigate: (target: EditorTarget) => void /** False when the open panel refused the tab change (a refused field keeps the page). */ - selectTab: (tab: EditorTabId) => boolean + selectTab: (tab: EditorTabId, options?: SelectOptions) => boolean openSection: (section: AnnotationSection, opener?: Opener) => void backToDrawing: () => void /** Opens the citations panel of a finding node; any other key is ignored. */ @@ -78,8 +109,12 @@ export interface EditorNavigation { exiting: boolean /** The panel's `onExitComplete`: applies the pending move. */ exitComplete: () => void - /** The panel hands its `canLeave` over while it is mounted (P22''). */ + /** The citations panel hands its `canLeave` over while it is mounted (P22''). */ registerCanLeave: (guard: CanLeave | null) => void + guards: Guards + trace: MoveTrace + /** A Back or Forward landed on `view` (the history adapter's way in): no move, no request. */ + restoreView: (view: EditorView) => void consumed: (serial: number, outcome: FocusOutcome) => void announce: (text: string) => void } @@ -87,7 +122,7 @@ export interface EditorNavigation { const isShown = (element: HTMLElement | null): boolean => element !== null && element.isConnected && !element.closest('[hidden]') -const headingOf = (place: PlaceName) => +export const headingOf = (place: PlaceName) => visibleElement(`[data-place="${place}"] [data-place-heading]`) export const CANVAS_BOX = @@ -99,14 +134,16 @@ const tabButton = (tab: EditorTabId) => document.getElementById(MORE_BUTTON_ID) /** The place the shown tab and section name. */ -function shownPlace(state: NavigationState): PlaceName { +export function shownPlace( + state: Pick, +): PlaceName { return state.tab === 'annotations' ? `annotations.${state.section}` : state.tab } /** The text the live region says for a move to `target`. */ -function useMoveText(): (target: EditorTarget) => string { +export function useMoveText(): (target: EditorTarget) => string { const t = useT() return useCallback( (target) => { @@ -118,14 +155,59 @@ function useMoveText(): (target: EditorTarget) => string { ) } +/** + * The live region's text. While a modal dialog is open the page is inert and a screen + * reader would drop the message: what is said meanwhile waits, then goes out as ONE + * announcement once the last dialog has closed. + */ function useLiveRegion() { const [live, setLive] = useState('') + const queued = useRef([]) const announce = useCallback((text: string) => { - setLive((previous) => (previous === text ? `${text} ` : text)) + queued.current.push(text) + if (queued.current.length > 1) return + afterModalsClosed(() => { + const joined = queued.current.splice(0).join('. ') + setLive((previous) => (previous === joined ? `${joined} ` : joined)) + }) }, []) return { live, announce } } +/** The guards of the open layers, keyed by layer so a re-registration keeps its place. */ +function useGuards(): Guards { + const guards = useRef(new Map()).current + return useMemo(() => { + const ask = (layer: LayerName, forced: boolean): LeaveAnswer => + guards.get(layer)?.(forced) ?? { allowed: true } + return { + register: (layer, guard) => { + if (guard) guards.set(layer, guard) + else guards.delete(layer) + }, + ask, + askAll: (forced) => { + const answers = [...LAYERS].reverse().map((l) => ask(l, forced)) + const notes = answers.flatMap((a) => (a.note ? [a.note] : [])) + const note = notes.length > 0 ? notes.join('. ') : undefined + return { allowed: answers.every((a) => a.allowed), note } + }, + } + }, [guards]) +} + +function useMoveTrace() { + const trace = useRef({ scrollY: null, replace: false }).current + const mark = useCallback( + (replace = false) => { + trace.scrollY = window.scrollY + trace.replace = replace + }, + [trace], + ) + return { trace, mark } +} + interface Openers { /** The trigger that opened the citations panel, and the finding it belongs to. */ citations: RefObject @@ -139,25 +221,28 @@ type Go = (action: NavigationAction, kind: MoveKind, text: string) => void * The one way to move: commit the typed text, announce, dispatch, record the move. * `finish` is the same without the commit, for the move a closed panel recorded. */ -function useGo(dispatch: Dispatch) { +function useGo(dispatch: Dispatch, trace: MoveTrace) { const { live, announce } = useLiveRegion() const [move, setMove] = useState(null) const finish = useCallback( (move: PendingClose) => { announce(move.note ? `${move.note}. ${move.text}` : move.text) + trace.scrollY = window.scrollY dispatch(move.action) setMove({ kind: move.kind, afterExit: true }) }, - [announce, dispatch], + [announce, dispatch, trace], ) const go: Go = useCallback( (action, kind, text) => { commitFocusedField() announce(text) + trace.scrollY = window.scrollY + trace.replace = false dispatch(action) setMove({ kind }) }, - [announce, dispatch], + [announce, dispatch, trace], ) return { move, go, finish, live, announce } } @@ -195,7 +280,8 @@ interface PanelContext { dispatch: Dispatch announce: (text: string) => void exit: ReturnType - canLeave: RefObject + guards: Guards + mark: (replace?: boolean) => void } /** @@ -204,22 +290,23 @@ interface PanelContext { * replaces the pending move) and asks nothing: the draft was settled by the first close. */ function useRequestClose(ctx: PanelContext) { - const { open, exit, canLeave } = ctx + const { open, exit, guards, mark } = ctx const { busy, record } = exit return useCallback( (move: PendingClose, forced: boolean): boolean => { if (!open) return true + mark() if (busy()) { record(move) return true } commitFocusedField() - const { allowed, note } = canLeave.current?.(forced) ?? { allowed: true } + const { allowed, note } = guards.ask('citations', forced) if (!allowed) return false record(note ? { ...move, note } : move) return true }, - [open, busy, record, canLeave], + [open, busy, record, guards, mark], ) } @@ -375,46 +462,53 @@ function useTabSelect( request: ReturnType['request'], dispatch: Dispatch, open: boolean, + mark: (replace?: boolean) => void, ) { const t = useT() return useCallback( - (tab: EditorTabId): boolean => { + (tab: EditorTabId, options?: SelectOptions): boolean => { const action = { type: 'select_tab', tab } as const if (open) { const text = t(`editor.tab.${tab}`) - return request({ action, kind: 'tab_selected', text }, false) + const allowed = request({ action, kind: 'tab_selected', text }, false) + if (allowed) mark(options?.replace) + return allowed } commitFocusedField() + mark(options?.replace) dispatch(action) return true }, - [request, dispatch, open, t], + [request, dispatch, open, t, mark], ) } /** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */ -export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation { - const [state, dispatch] = useReducer( - navigationReducer, - initialTab, - initialNavigation, +export function useEditorNavigation( + initialTab: EditorTabId, + initialView?: EditorView | null, +): EditorNavigation { + const [state, dispatch] = useReducer(navigationReducer, null, () => + initialNavigation(initialTab, initialView), ) - const { move, go, finish, live, announce } = useGo(dispatch) + const { trace, mark } = useMoveTrace() + const { move, go, finish, live, announce } = useGo(dispatch, trace) const openers = useRef({ citations: { current: null }, citedBy: { current: null }, section: { current: null }, }).current - const canLeave = useRef(null) + const guards = useGuards() const exit = useCitationsExit(finish) - const registerCanLeave = useCallback((guard: CanLeave | null) => { - canLeave.current = guard - }, []) + const registerCanLeave = useCallback( + (guard: CanLeave | null) => guards.register('citations', guard), + [guards], + ) const open = state.citationsOf !== null const receipts = useReceipts(dispatch) useMoveFocus(move, state, receipts.outcomes, dispatch, openers) const sections = useSectionMoves(go, openers) - const ctx = { open, go, openers, dispatch, announce, exit, canLeave } + const ctx = { open, go, openers, dispatch, announce, exit, guards, mark } const openCitations = useOpenCitations(ctx) const panel = useCloseMoves(ctx) return { @@ -422,7 +516,7 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation { live, announce, consumed: receipts.consumed, - selectTab: useTabSelect(panel.request, dispatch, open), + selectTab: useTabSelect(panel.request, dispatch, open, mark), openSection: sections.openSection, backToDrawing: sections.backToDrawing, navigate: open ? panel.navigate : sections.navigate, @@ -433,5 +527,11 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation { exiting: exit.exiting, exitComplete: exit.complete, registerCanLeave, + guards, + trace, + restoreView: useCallback( + (view: EditorView) => dispatch({ type: 'restore_view', view }), + [], + ), } } diff --git a/apps/app/tests/helpers/editorRoute.tsx b/apps/app/tests/helpers/editorRoute.tsx index f18a9a71..78255b97 100644 --- a/apps/app/tests/helpers/editorRoute.tsx +++ b/apps/app/tests/helpers/editorRoute.tsx @@ -1,6 +1,15 @@ import { StrictMode } from 'react' import { render } from '@testing-library/react' -import { MemoryRouter, Route, Routes } from 'react-router-dom' +import { + MemoryRouter, + Route, + Routes, + useLocation, + useNavigate, + type InitialEntry, + type Location, + type NavigateFunction, +} from 'react-router-dom' import { SheetFailure, type OwnCatalogGrant, @@ -92,6 +101,16 @@ export interface MountOptions { adminFailure?: SheetFailureKind /** Renders inside : effects run twice on mount, as in development. */ strict?: boolean + /** The router's history before the draft: the draft is the last entry (default: only it). */ + entries?: InitialEntry[] + /** Called on every render with the router's navigate and location: Back, Forward, state. */ + probe?: (navigate: NavigateFunction, location: Location) => void +} + +/** Hands the router to a test: MemoryRouter listens to no popstate, a test calls navigate(-1). */ +function RouterProbe({ probe }: { probe: NonNullable }) { + probe(useNavigate(), useLocation()) + return null } /** Mounts the draft route as an editor with the admin role, at a wide screen, by default. */ @@ -115,7 +134,11 @@ export function mountDraft(options: MountOptions = {}) { ) } const page = ( - + + {options.probe && } = {}) => ({ + ...defaultView(tab), + ...patch, +}) +const entry = (patch: Partial = {}): 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']) + }) +}) diff --git a/apps/app/tests/unit/editor-history-guards.test.tsx b/apps/app/tests/unit/editor-history-guards.test.tsx new file mode 100644 index 00000000..1410d5ba --- /dev/null +++ b/apps/app/tests/unit/editor-history-guards.test.tsx @@ -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)[ENTRY_KEY] + +function Page({ guard }: { guard?: () => { allowed: boolean } }) { + const nav = useEditorNavigation('general') + navigate = useNavigate() + location = useLocation() + useEditorHistory(nav, owner, defaultView('general')) + return ( + <> + + + + + +

{nav.live}

+ + ) +} + +const mount = (guard?: () => { allowed: boolean }) => + render( + + + , + ) + +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) + }) +}) diff --git a/apps/app/tests/unit/editor-history.test.tsx b/apps/app/tests/unit/editor-history.test.tsx new file mode 100644 index 00000000..87bfdeb4 --- /dev/null +++ b/apps/app/tests/unit/editor-history.test.tsx @@ -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()), + 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 | 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) => ({ + [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 = { + 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) + }) +})