From 8e4f02620aba8f930cad0683835c93047a1de1e2 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 13 Nov 2026 18:12:19 +0100 Subject: [PATCH] fix(editor): Task 1 review round 1, section back pops, scroll proof --- apps/app/e2e/shell/editor-history.spec.ts | 51 ++++++- apps/app/src/editor/history/entry.ts | 23 +++- .../src/editor/history/useEditorHistory.ts | 125 +++++++++++------- apps/app/src/editor/useEditorNavigation.ts | 6 +- .../tests/unit/editor-history-entry.test.ts | 23 ++++ .../tests/unit/editor-history-guards.test.tsx | 15 +++ apps/app/tests/unit/editor-history.test.tsx | 72 ++++++++-- 7 files changed, 251 insertions(+), 64 deletions(-) diff --git a/apps/app/e2e/shell/editor-history.spec.ts b/apps/app/e2e/shell/editor-history.spec.ts index 0855fe7f..14cb8ced 100644 --- a/apps/app/e2e/shell/editor-history.spec.ts +++ b/apps/app/e2e/shell/editor-history.spec.ts @@ -3,6 +3,7 @@ import type { Page, TestInfo } from '@playwright/test' import { expect, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + backToDrawing, editorActor, openEditor, openSection, @@ -26,8 +27,9 @@ 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). + * Waits until the entry on top of the history names `tab`. The adapter writes from an + * effect a few milliseconds after a click, so a script pressing Back at once would land + * on the wrong entry (a user cannot be that quick): every Back below waits through this. */ async function written(page: Page, tab: string) { await page.waitForFunction( @@ -88,7 +90,7 @@ test.describe('editor browser history', () => { 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 ({ + test('an Annotations section is an entry: Back shows the drawing, Forward it', async ({ page, }) => { await open(page) @@ -118,6 +120,49 @@ test.describe('editor browser history', () => { await expect(selected(page)).toHaveText(tabName('annotations')) }) + test('« Retour au dessin » pops the section: Back leaves the drawing', async ({ + page, + }) => { + await open(page) + await selectTab(page, dict, 'general') + await written(page, 'general') + await selectTab(page, dict, 'annotations') + await written(page, 'annotations') + await openSection(page, dict, 'views') + await sectionWritten(page, 'views') + await backToDrawing(page, dict) + await sectionWritten(page, 'drawing') + // no duplicate drawing entry: this Back lands on Général + await page.goBack() + await expect(selected(page)).toHaveText(tabName('general')) + }) + + test('the scroll offset of a view comes back with Back and Forward', async ({ + page, + }) => { + await open(page) + await page.evaluate(() => { + const spacer = document.createElement('div') + spacer.style.height = '4000px' + document.body.append(spacer) + window.scrollTo(0, 600) + }) + // The keyboard: a real click would scroll the tab row into view first, and a script + // event carries no user activation (Chromium skips such entries on Back). + await page + .getByRole('tab', { name: tabName('findings') }) + .evaluate((tab) => tab.focus({ preventScroll: true })) + await page.keyboard.press('Enter') + await written(page, 'findings') + await page.evaluate(() => window.scrollTo(0, 200)) + await page.goBack() + await expect(selected(page)).toHaveText(tabName('annotations')) + await page.waitForFunction(() => Math.abs(window.scrollY - 600) <= 2) + await page.goForward() + await expect(selected(page)).toHaveText(tabName('findings')) + await page.waitForFunction(() => Math.abs(window.scrollY - 200) <= 2) + }) + test('a reload reopens the view of the entry', async ({ page }) => { await open(page) await selectTab(page, dict, 'findings') diff --git a/apps/app/src/editor/history/entry.ts b/apps/app/src/editor/history/entry.ts index 062831ff..55b3e619 100644 --- a/apps/app/src/editor/history/entry.ts +++ b/apps/app/src/editor/history/entry.ts @@ -68,6 +68,8 @@ export function ownedEntry( owner: HistoryOwner, ): HistoryEntry | null { const entry = readEntry(state) + // An empty id is no owner: nobody signed in, no sheet known. + if (!owner.sheetId || !owner.userId) return null const mine = entry?.sheetId === owner.sheetId && entry.userId === owner.userId return mine ? entry : null } @@ -79,13 +81,26 @@ export function layerCount(view: EditorView): number { return (view.finding ? 1 : 0) + (view.reference ? 1 : 0) } +/** An Annotations section other than the drawing is a step over it, like a layer. */ +function isStepOver(view: EditorView): boolean { + return view.tab === 'annotations' && view.section !== 'drawing' +} + +/** True when the move took a layer away, or left a section for its drawing. */ +function isRemoval(top: EditorView, view: EditorView): boolean { + if (layerCount(view) < layerCount(top)) return true + const backToDrawing = view.tab === top.tab && isStepOver(top) + return backToDrawing && !isStepOver(view) && layerCount(view) === 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. + * A user move to `view`. A layer taken away, or a section left for its drawing ("Retour + * au dessin"), goes back when the entry holds the view the move lands on (the entry that + * opened it), else it replaces; a layer, tab or section added pushes, unless the move + * asked for a replace. */ export function planWrite( top: HistoryEntry, @@ -93,7 +108,7 @@ export function planWrite( replace: boolean, ): HistoryWrite { if (sameView(top.view, view)) return 'none' - if (layerCount(view) < layerCount(top.view)) { + if (isRemoval(top.view, view)) { return top.below && sameView(top.below, view) ? 'back' : 'replace' } return replace ? 'replace' : 'push' diff --git a/apps/app/src/editor/history/useEditorHistory.ts b/apps/app/src/editor/history/useEditorHistory.ts index a5dae84e..1a0dec99 100644 --- a/apps/app/src/editor/history/useEditorHistory.ts +++ b/apps/app/src/editor/history/useEditorHistory.ts @@ -34,7 +34,6 @@ interface Book { backTimer: ReturnType | undefined /** Scroll position of the entries left, by entry id. */ scrolls: Map - lastScroll: number counter: number takeWrite: (now: number) => boolean } @@ -46,7 +45,6 @@ function newBook(): Book { pendingBack: false, backTimer: undefined, scrolls: new Map(), - lastScroll: 0, counter: 0, takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS), } @@ -84,6 +82,9 @@ function useWriter(book: Book, owner: HistoryOwner) { } const write = (entry: HistoryEntry, replace: boolean) => { book.entry = entry + // shortcut: past the write budget a push is kept in memory only, so a later Back + // lands on the real previous entry. Fine at one push per user move; upgrade path: + // coalesce the skipped views into one replace once the window slides. if (replace || book.takeWrite(Date.now())) send(entry, replace) } return { @@ -155,22 +156,29 @@ function landOnForeign(ctx: PopContext): Landing | null { return book.entry && { entry: book.entry, tabChanged: true } } +/** + * Something the history does not carry is on screen: the view stays, the pre-POP view is + * pushed again above the entry landed on. A dirty form shows its own confirmation. + */ +function refusePop(ctx: PopContext, landed: HistoryEntry | null): null { + const { nav, book, writer, view } = ctx + nav.guards.askAll(false) + if (landed) book.entry = landed + writer.push(view) + return null +} + /** 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 { nav, book, owner, view } = ctx + // Scrolling is manual while the editor is mounted: the leaving page's offset is intact. + if (book.entry) book.scrolls.set(book.entry.id, window.scrollY) const expected = book.pendingBack book.pendingBack = false clearTimeout(book.backTimer) const entry = ownedEntry(state, owner) + if (!expected && popRefused(nav)) return refusePop(ctx, entry) 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) @@ -184,6 +192,13 @@ function mount(ctx: PopContext, state: unknown): void { else ctx.writer.first(ctx.view) } +/** Focus after a Back or Forward: the tab button, or the heading of a section reached. */ +function landFocus({ entry, tabChanged }: Landing): void { + const heading = tabChanged ? null : headingOf(shownPlace(entry.view)) + if (heading) heading.focus({ preventScroll: true }) + else focusActiveTab({ preventScroll: true }) +} + /** Scroll, focus and announcement once a Back or Forward has restored a view. */ function useLanding( nav: EditorNavigation, @@ -191,23 +206,64 @@ function useLanding( 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 + const { id, view } = landing.entry 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 })) + window.scrollTo(0, book.scrolls.get(id) ?? 0) + landFocus(landing) + const section = view.tab === 'annotations' ? view.section : null + nav.announce( + moveText({ place: 'tab', tab: view.tab, section, key: null }), + ) }) - }, [landing, book, announce, moveText]) + }, [landing, book, nav, moveText]) +} + +/** The view the reducer holds, as one object that changes only when the view does. */ +function useViewOf(state: EditorNavigation['state']): EditorView { + const { tab, section, finding, reference, referenceFilter } = state + return useMemo( + () => ({ tab, section, finding, reference, referenceFilter }), + [tab, section, finding, reference, referenceFilter], + ) +} + +/** + * The router's own restoration would scroll before the adapter has read the leaving + * page's offset: it is manual while the editor is mounted, the adapter restores itself. + */ +function useManualScroll(): void { + useEffect(() => { + const previous = window.history.scrollRestoration + window.history.scrollRestoration = 'manual' + return () => { + window.history.scrollRestoration = previous + } + }, []) +} + +/** Each new location is read once: the first is the mount, a POP after it is a landing. */ +function usePop(ctx: PopContext): Landing | null { + const location = useLocation() + const navType = useNavigationType() + const [landing, setLanding] = useState(null) + const { book } = ctx + useEffect(() => { + // The type is part of the stamp: a POP back onto a key this adapter pushed, with the + // transition of a later push never rendered, is still a landing to read. + const stamp = `${location.key}|${navType}` + if (book.handled === stamp) return + book.handled = stamp + 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, navType]) + return landing } /** @@ -224,33 +280,12 @@ export default function useEditorHistory( 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]) + const view = useViewOf(nav.state) + const landing = usePop({ nav, book, writer, owner, defaultView, view }) 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]) + useManualScroll() } diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index c07f94af..5d64c17c 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -163,10 +163,12 @@ export function useMoveText(): (target: EditorTarget) => string { function useLiveRegion() { const [live, setLive] = useState('') const queued = useRef([]) + const waiting = useRef<() => void>(() => undefined) const announce = useCallback((text: string) => { queued.current.push(text) - if (queued.current.length > 1) return - afterModalsClosed(() => { + // Each message re-arms the wait, so a wait that never fires cannot hold later ones. + waiting.current() + waiting.current = afterModalsClosed(() => { const joined = queued.current.splice(0).join('. ') setLive((previous) => (previous === joined ? `${joined} ` : joined)) }) diff --git a/apps/app/tests/unit/editor-history-entry.test.ts b/apps/app/tests/unit/editor-history-entry.test.ts index ed5a8289..9c1b7459 100644 --- a/apps/app/tests/unit/editor-history-entry.test.ts +++ b/apps/app/tests/unit/editor-history-entry.test.ts @@ -68,6 +68,14 @@ describe('readEntry and ownership', () => { expect(ownedEntry(stateOf(entry()), { ...mine, userId: 'V' })).toBeNull() }) + it('refuses an owner without a sheet or an account', () => { + const blank = entry({ sheetId: '', userId: '' }) + expect(ownedEntry(stateOf(blank), { sheetId: '', userId: '' })).toBeNull() + expect( + ownedEntry(stateOf(entry()), { sheetId: 'S', userId: '' }), + ).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') @@ -92,6 +100,21 @@ describe('planWrite', () => { expect(planWrite(onAnnotations, views, false)).toBe('push') }) + it('goes back for a section left for its drawing, else replaces', () => { + const drawing = view('annotations') + const inSection = entry({ + view: view('annotations', { section: 'views' }), + below: drawing, + }) + expect(planWrite(inSection, drawing, false)).toBe('back') + const reloaded = entry({ view: inSection.view, below: null }) + expect(planWrite(reloaded, drawing, false)).toBe('replace') + // another section, or another tab, is a step forward + const regions = view('annotations', { section: 'regions' }) + expect(planWrite(inSection, regions, false)).toBe('push') + expect(planWrite(inSection, view('general'), 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') }) diff --git a/apps/app/tests/unit/editor-history-guards.test.tsx b/apps/app/tests/unit/editor-history-guards.test.tsx index 1410d5ba..0736ed1e 100644 --- a/apps/app/tests/unit/editor-history-guards.test.tsx +++ b/apps/app/tests/unit/editor-history-guards.test.tsx @@ -128,6 +128,21 @@ describe('the announcer', () => { }) }) +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), { diff --git a/apps/app/tests/unit/editor-history.test.tsx b/apps/app/tests/unit/editor-history.test.tsx index 87bfdeb4..66e03d5e 100644 --- a/apps/app/tests/unit/editor-history.test.tsx +++ b/apps/app/tests/unit/editor-history.test.tsx @@ -99,7 +99,7 @@ describe('mount', () => { }) describe('tab and section moves', () => { - it('a tab click pushes, Back and Forward restore it, the tab button holds the focus', async () => { + it('a tab click pushes, Back and Forward restore it, the tab holds focus', async () => { const user = userEvent.setup() mountDraft({ probe }) await ready() @@ -132,22 +132,24 @@ describe('tab and section moves', () => { expect(selected()).not.toBe('Constats') }) - it('an Annotations section pushes, « Retour au dessin » too, Back returns to the section', async () => { + // R-24: the first version of this case expected « Retour au dessin » to push and Back to + // return to the section; R2F-1 makes it a removal (a pop), so no duplicate entry remains. + it('a section is an entry; « Retour au dessin » pops it: no duplicate', async () => { const user = userEvent.setup() - mountDraft({ probe }) + mountDraft({ probe, entries: ['/app/admin', path] }) await ready() await user.click(tab('Annotations')) + await waitFor(() => expect(written()?.view.tab).toBe('annotations')) + const drawing = written()?.id await user.click(screen.getByRole('button', { name: 'Vues' })) await waitFor(() => expect(written()?.view.section).toBe('views')) + expect(written()?.below?.section).toBe('drawing') await user.click(screen.getByRole('button', { name: 'Retour au dessin' })) - await waitFor(() => expect(written()?.view.section).toBe('drawing')) + await waitFor(() => expect(written()?.id).toBe(drawing)) + expect(written()?.view.section).toBe('drawing') + // one more Back leaves the drawing for the entry before it, not for the section back() - await waitFor(() => - expect( - screen.getByRole('button', { name: 'Retour au dessin' }), - ).toBeVisible(), - ) - expect(written()?.view.section).toBe('views') + await waitFor(() => expect(selected()).not.toBe('Annotations')) }) it('a move that changes nothing writes nothing', async () => { @@ -161,7 +163,57 @@ describe('tab and section moves', () => { }) }) +describe('scroll', () => { + const scrollAt = (y: number) => + Object.defineProperty(window, 'scrollY', { configurable: true, value: y }) + afterEach(() => scrollAt(0)) + + it('takes the offset in the move, restores it on Back', async () => { + const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {}) + const user = userEvent.setup() + mountDraft({ probe }) + await ready() + await waitFor(() => expect(written()).toBeTruthy()) + scrollAt(300) + await user.click(tab('Constats')) + await waitFor(() => expect(written()?.view.tab).toBe('findings')) + scrollAt(40) + back() + await waitFor(() => expect(scrollTo).toHaveBeenCalledWith(0, 300)) + back(1) + await waitFor(() => expect(scrollTo).toHaveBeenCalledWith(0, 40)) + }) + + it('is manual while the editor is mounted, as it was after', async () => { + window.history.scrollRestoration = 'auto' + const view = mountDraft({ probe }) + await ready() + expect(window.history.scrollRestoration).toBe('manual') + view.unmount() + expect(window.history.scrollRestoration).toBe('auto') + }) +}) + describe('a Back that must not unmount what is on screen', () => { + it('also refuses to replace a foreign entry while a dialog is open', async () => { + const entries = [{ pathname: path, state: foreign({ sheetId: 'x' }) }, path] + mountDraft({ probe, entries }) + await ready() + await waitFor(() => expect(written()?.sheetId).toBe(SHEET)) + const before = selected() + const dialog = document.createElement('dialog') + dialog.setAttribute('open', '') + document.body.append(dialog) + const id = written()?.id + back() + await waitFor(() => expect(written()?.id).not.toBe(id)) + expect(selected()).toBe(before) + expect(written()?.sheetId).toBe(SHEET) + // pushed again above the landed entry, not replaced by a first entry + expect(written()?.below).not.toBeNull() + dialog.remove() + }) + it('keeps the view and pushes it again while a dialog is open', async () => { const user = userEvent.setup() mountDraft({ probe })