From 79a09f8b25f3d67f8b8e376b90d8f069254e52b0 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 6 Nov 2026 20:57:08 +0100 Subject: [PATCH] test(editor): keep-alive paths, neutral place visibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Place visibility context moves to lib/placeVisibility.ts so the catalogue no longer imports from components/editor. Adds tests: selection survival, unmeasured hint round trip, keyboard tab move and « Aller à » with a field focused, replace-tracing kept, announcements. Parse-sharing test uses object identity. Early exits are two statements; shortcut comment on the parse cache. R-24: - editor-equine.spec.ts:118, editor-geometry.spec.ts:376, editor-recovery.spec.ts:39, editor-signout.spec.ts:26: page.getByLabel ('Nom (FR)') -> place(page, 'general').getByLabel(...) - editor-shell.spec.ts: toHaveCount(0) on the visible query -> count 1 on the raw selector and toBeHidden() - editor-keep-alive.test.tsx: JSON.parse stack-trace count -> same object reference across places --- apps/app/e2e/shell/editor-equine.spec.ts | 6 +- apps/app/e2e/shell/editor-geometry.spec.ts | 10 +- apps/app/e2e/shell/editor-recovery.spec.ts | 5 +- apps/app/e2e/shell/editor-shell.spec.ts | 4 +- apps/app/e2e/shell/editor-signout.spec.ts | 5 +- .../components/catalogue/CatalogueCanvas.tsx | 7 +- apps/app/src/components/editor/KeptPlace.tsx | 18 +-- .../components/editor/views/CropCanvas.tsx | 7 +- .../src/editor/annotations/useCanvasBuild.ts | 7 +- apps/app/src/editor/sheetDocument.ts | 5 +- apps/app/src/lib/placeVisibility.ts | 12 ++ .../app/tests/unit/editor-keep-alive.test.tsx | 152 ++++++++++++++++-- 12 files changed, 192 insertions(+), 46 deletions(-) create mode 100644 apps/app/src/lib/placeVisibility.ts diff --git a/apps/app/e2e/shell/editor-equine.spec.ts b/apps/app/e2e/shell/editor-equine.spec.ts index 6ec2675d..3f70ea86 100644 --- a/apps/app/e2e/shell/editor-equine.spec.ts +++ b/apps/app/e2e/shell/editor-equine.spec.ts @@ -11,6 +11,7 @@ import { stepUpAdmin } from '../support/admin' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + place, type Actor, closeReferences, editorActor, @@ -115,7 +116,10 @@ async function commitName(field: Locator, round: number) { /** SAMPLES commits of the sheet's French name, one probe entry each (after a warm-up). */ async function measureRenames(page: Page, label: string) { await selectTab(page, dict, 'general') - const field = page.getByLabel(dict['editor.general.name_fr'], { exact: true }) + const field = place(page, 'general').getByLabel( + dict['editor.general.name_fr'], + { exact: true }, + ) await startProbe(page) await commitName(field, 0) await takeSamples(page) diff --git a/apps/app/e2e/shell/editor-geometry.spec.ts b/apps/app/e2e/shell/editor-geometry.spec.ts index b3f4438e..ce24bf10 100644 --- a/apps/app/e2e/shell/editor-geometry.spec.ts +++ b/apps/app/e2e/shell/editor-geometry.spec.ts @@ -3,6 +3,7 @@ import type { Page, TestInfo } from '@playwright/test' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + place, clickDrawing, clientOf, editorActor, @@ -373,9 +374,12 @@ test.describe('editor geometry (adversarial)', () => { // An unrelated change is saved: the path is still the seeded one, byte for byte. await selectTab(page, dict, 'general') - const nameFr = page.getByLabel(dict['editor.general.name_fr'], { - exact: true, - }) + const nameFr = place(page, 'general').getByLabel( + dict['editor.general.name_fr'], + { + exact: true, + }, + ) await nameFr.fill('Fiche sans toucher au tracé') await nameFr.press('Tab') await saveDraft(page, dict, seed.revision + 1) diff --git a/apps/app/e2e/shell/editor-recovery.spec.ts b/apps/app/e2e/shell/editor-recovery.spec.ts index 0d41e079..2dc48cf8 100644 --- a/apps/app/e2e/shell/editor-recovery.spec.ts +++ b/apps/app/e2e/shell/editor-recovery.spec.ts @@ -4,6 +4,7 @@ import { rpc } from '../../../../packages/supabase/tests/sandbox/stack' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + place, copyKeyOf, editorActor, expiringEditor, @@ -36,7 +37,9 @@ const dict = fr const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' const nameFr = (page: Page) => - page.getByLabel(dict['editor.general.name_fr'], { exact: true }) + place(page, 'general').getByLabel(dict['editor.general.name_fr'], { + exact: true, + }) async function commitText(field: Locator, value: string) { await field.fill(value) diff --git a/apps/app/e2e/shell/editor-shell.spec.ts b/apps/app/e2e/shell/editor-shell.spec.ts index be9ff113..207c773a 100644 --- a/apps/app/e2e/shell/editor-shell.spec.ts +++ b/apps/app/e2e/shell/editor-shell.spec.ts @@ -60,7 +60,9 @@ test.describe('editor shell, kept places (B2a)', () => { await openSection(page, dict, 'categories') await page.locator('#category-new-fr').fill('Brouillon') await selectTab(page, dict, 'general') - await expect(place(page, 'annotations.categories')).toHaveCount(0) + const hidden = page.locator('[data-place="annotations.categories"]') + await expect(hidden).toHaveCount(1) + await expect(hidden).toBeHidden() await selectTab(page, dict, 'annotations') await expect(page.locator('#category-new-fr')).toHaveValue('Brouillon') diff --git a/apps/app/e2e/shell/editor-signout.spec.ts b/apps/app/e2e/shell/editor-signout.spec.ts index b756ec9f..cc2e3c35 100644 --- a/apps/app/e2e/shell/editor-signout.spec.ts +++ b/apps/app/e2e/shell/editor-signout.spec.ts @@ -3,6 +3,7 @@ import type { Locator, Page, TestInfo } from '@playwright/test' import { expect, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + place, copyKeyOf, editorActor, openDraft, @@ -23,7 +24,9 @@ const dict = fr const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' const nameFr = (page: Page) => - page.getByLabel(dict['editor.general.name_fr'], { exact: true }) + place(page, 'general').getByLabel(dict['editor.general.name_fr'], { + exact: true, + }) const button = (scope: Page | Locator, name: string) => scope.getByRole('button', { name, exact: true }) diff --git a/apps/app/src/components/catalogue/CatalogueCanvas.tsx b/apps/app/src/components/catalogue/CatalogueCanvas.tsx index f156d0b6..86559b78 100644 --- a/apps/app/src/components/catalogue/CatalogueCanvas.tsx +++ b/apps/app/src/components/catalogue/CatalogueCanvas.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import { usePlaceVisible } from '@/components/editor/KeptPlace' +import { usePlaceVisible } from '@/lib/placeVisibility' import Button from '@/components/ui/Button' import Notice from '@/components/ui/Notice' import { coreRuntime, useCoreStopped } from '@/core/runtime' @@ -77,7 +77,10 @@ export default function CatalogueCanvas({ const element = host.current if (!element) return // One composed copy of a view in the page (kept places): the ids repeat otherwise. - if (!visible) return element.replaceChildren() + if (!visible) { + element.replaceChildren() + return + } const build = buildView(preview, viewId) setFailure(build.ok ? null : build.failure) element.replaceChildren(...(build.ok ? [build.svg] : [])) diff --git a/apps/app/src/components/editor/KeptPlace.tsx b/apps/app/src/components/editor/KeptPlace.tsx index 95547e6c..24bb2cd6 100644 --- a/apps/app/src/components/editor/KeptPlace.tsx +++ b/apps/app/src/components/editor/KeptPlace.tsx @@ -1,19 +1,5 @@ -import { - createContext, - useContext, - type HTMLAttributes, - type ReactNode, -} from 'react' - -const PlaceVisibleContext = createContext(true) - -/** - * Whether the place around this component is shown: every enclosing `KeptPlace` is - * visible. Outside any `KeptPlace` (the catalogue pages) it is true. - */ -export function usePlaceVisible(): boolean { - return useContext(PlaceVisibleContext) -} +import type { HTMLAttributes, ReactNode } from 'react' +import { PlaceVisibleContext, usePlaceVisible } from '@/lib/placeVisibility' interface Props extends HTMLAttributes { /** The `data-place` name; omitted for a wrapper that only nests places (tab panel). */ diff --git a/apps/app/src/components/editor/views/CropCanvas.tsx b/apps/app/src/components/editor/views/CropCanvas.tsx index 3d193219..b51b0277 100644 --- a/apps/app/src/components/editor/views/CropCanvas.tsx +++ b/apps/app/src/components/editor/views/CropCanvas.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState, type RefObject } from 'react' import type { ViewBox } from '@faunosteo/core-wasm/types' import Notice from '@/components/ui/Notice' import { buildView } from '@/components/catalogue/CatalogueCanvas' -import { usePlaceVisible } from '@/components/editor/KeptPlace' +import { usePlaceVisible } from '@/lib/placeVisibility' import { useEditorStore } from '@/editor/state/editorStore' import { useT } from '@/i18n/useT' @@ -24,7 +24,10 @@ function useParentFrame( const element = host.current if (!element || !preview) return // One composed copy of a view in the page: the ids repeat otherwise. - if (!visible) return element.replaceChildren() + if (!visible) { + element.replaceChildren() + return + } const built = buildView(preview, parentId) element.replaceChildren(...(built.ok ? [built.svg] : [])) setFrame( diff --git a/apps/app/src/editor/annotations/useCanvasBuild.ts b/apps/app/src/editor/annotations/useCanvasBuild.ts index 565f6df0..861ced7f 100644 --- a/apps/app/src/editor/annotations/useCanvasBuild.ts +++ b/apps/app/src/editor/annotations/useCanvasBuild.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { buildView } from '@/components/catalogue/CatalogueCanvas' -import { usePlaceVisible } from '@/components/editor/KeptPlace' +import { usePlaceVisible } from '@/lib/placeVisibility' import { coreRuntime } from '@/core/runtime' import { useEditorStore } from '../state/editorStore' @@ -52,7 +52,10 @@ export function useCanvasBuild(viewId: string) { const element = host.current if (!element || !handle.preview) return // One composed copy of a view in the page: the ids repeat otherwise. - if (!handle.visible) return element.replaceChildren() + if (!handle.visible) { + element.replaceChildren() + return + } const result = buildView(handle.preview, viewId) element.replaceChildren(...(result.ok ? [result.svg] : [])) setBuilt( diff --git a/apps/app/src/editor/sheetDocument.ts b/apps/app/src/editor/sheetDocument.ts index 169315f7..19b16df6 100644 --- a/apps/app/src/editor/sheetDocument.ts +++ b/apps/app/src/editor/sheetDocument.ts @@ -10,7 +10,10 @@ import { useEditorStore } from './state/editorStore' /** * The last text parsed and its document. Every kept place reads the document, so one parse - * serves them all per commit. A single entry: the store holds one document at a time. + * serves them all per commit. + * + * shortcut: one entry of module state, not store state. Upgrade path: the store holds + * the parsed document next to its text and the places select it. */ let lastParse: { text: string; doc: AnatomicalSheetDocument | null } | null = null diff --git a/apps/app/src/lib/placeVisibility.ts b/apps/app/src/lib/placeVisibility.ts new file mode 100644 index 00000000..14f21d15 --- /dev/null +++ b/apps/app/src/lib/placeVisibility.ts @@ -0,0 +1,12 @@ +import { createContext, useContext } from 'react' + +/** + * Whether the place around a component is shown. A kept-mounted place provides it; a + * component that draws something page-unique (a composed SVG with ids) reads it. + */ +export const PlaceVisibleContext = createContext(true) + +/** True outside any kept place (the catalogue pages). */ +export function usePlaceVisible(): boolean { + return useContext(PlaceVisibleContext) +} diff --git a/apps/app/tests/unit/editor-keep-alive.test.tsx b/apps/app/tests/unit/editor-keep-alive.test.tsx index dc3a4809..918b6a62 100644 --- a/apps/app/tests/unit/editor-keep-alive.test.tsx +++ b/apps/app/tests/unit/editor-keep-alive.test.tsx @@ -12,7 +12,9 @@ import { import userEvent from '@testing-library/user-event' import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' import EditorTabBody from '@/components/editor/EditorTabBody' -import KeptPlace, { usePlaceVisible } from '@/components/editor/KeptPlace' +import KeptPlace from '@/components/editor/KeptPlace' +import { useSheetDocument } from '@/editor/sheetDocument' +import { usePlaceVisible } from '@/lib/placeVisibility' import { FocusConsumedContext } from '@/editor/focusRequest' import { targetOfKey } from '@/editor/navigation' import { useLocaleStore } from '@/state/localeStore' @@ -21,6 +23,7 @@ import { ASSET, drawnText, edit, + emptyText, insert, point, } from '../helpers/editorFixtures' @@ -228,6 +231,35 @@ describe('findings and canvas state across a tab change', () => { 'true', ) expect(layer().style.transform).toBe(zoomed) + const list = drawing.getByRole('list', { name: 'Annotations de la vue' }) + await user.click(within(list).getAllByRole('button')[0]) + const marker = () => + drawing + .getByTestId('annotation-canvas-drawing') + .querySelector('[data-anno-id="anno-a"]') + const stillSelected = () => + waitFor(() => expect(marker()).toHaveAttribute('data-state', 'current')) + await stillSelected() + await user.click(tab('Général')) + await user.click(tab('Annotations')) + await stillSelected() + expect(drawing.getByTestId('annotation-properties')).toBeVisible() + }) + + it('the unmeasured hint opens the views section and « Retour au dessin » restores the same canvas', async () => { + serverHas(emptyText(), 3, false) + const user = userEvent.setup() + mountDraft() + await ready() + await user.click(tab('Annotations')) + const drawing = inPlace('annotations.drawing') + const canvas = drawing.getByTestId('annotation-canvas') + await user.click(drawing.getByRole('button', { name: 'Vues' })) + expect(place('annotations.views')).toBeVisible() + expect(place('annotations.drawing')).not.toBeVisible() + await user.click(screen.getByRole('button', { name: 'Retour au dessin' })) + expect(place('annotations.drawing')).toBeVisible() + expect(drawing.getByTestId('annotation-canvas')).toBe(canvas) }) }) @@ -255,6 +287,49 @@ describe('a field still focused while a place is left', () => { expect(store.getState().documentText).toBe(before) }) + it('an arrow key on the tab list commits it first, as one undo entry', async () => { + const user = await mount() + const before = store.getState().documentText + const field = await generalNameField(user) + fireEvent.keyDown(tab('Général'), { key: 'ArrowRight' }) + expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true') + expect(JSON.parse(store.getState().documentText).name.fr).toBe('Nom saisi') + expect(field).toHaveValue('Nom saisi') + expect(store.getState().unsaved).toBe(true) + act(() => void store.getState().undoStep()) + expect(store.getState().documentText).toBe(before) + }) + + it('« Aller à » activated without a focus move commits it, as one undo entry', async () => { + const bare = point('anno-bare', 10, 10, 2) + const value = { ...bare.value, geometry: null, name: name('Sans tracé') } + const text = insert(referenceText(), { + kind: 'annotation', + value, + } as typeof bare) + const user = await mount(text) + const before = store.getState().documentText + await user.click(tab(/Vérification/)) + await user.click(referencesButton()) + const field = inPlace('references').getByLabelText('Citation', { + selector: '#reference-ref-1-citation', + }) + await user.click(field) + fireEvent.change(field, { target: { value: 'Doe 2023' } }) + fireEvent.click( + inPlace('verification').getAllByRole('button', { + name: 'Aller à Sans tracé', + })[0], + ) + expect( + JSON.parse(store.getState().documentText).references[0].citation, + ).toBe('Doe 2023') + expect(store.getState().unsaved).toBe(true) + expect(place('references')).not.toBeVisible() + act(() => void store.getState().undoStep()) + expect(store.getState().documentText).toBe(before) + }) + it('Escape in a reference field commits the text before the panel hides', async () => { const user = await mount(referenceText()) await user.click(referencesButton()) @@ -357,20 +432,22 @@ describe('ids and parses', () => { expect(ids.some((id) => id.includes('body'))).toBe(true) }) - it('one JSON.parse per document text across the places', async () => { - const user = await mount() - for (const name of ['Général', 'Constats', /Vérification/]) { - await user.click(tab(name)) + it('every place reads the same parsed document per text', async () => { + await mount() + const seen: unknown[] = [] + function Probe() { + seen.push(useSheetDocument()) + return null } - await user.click(tab('Annotations')) - const original = JSON.parse - const fromPlaces: string[] = [] - const parse = vi.spyOn(JSON, 'parse').mockImplementation((...args) => { - if (new Error().stack?.includes('parseDocument')) { - fromPlaces.push(String(args[0])) - } - return original(...args) - }) + const first = render( + <> + + + , + ) + expect(seen[0]).not.toBeNull() + expect(seen[1]).toBe(seen[0]) + first.unmount() act(() => { store.getState().commit({ op: 'insert', @@ -380,8 +457,19 @@ describe('ids and parses', () => { }, }) }) - parse.mockRestore() - expect(fromPlaces).toEqual([store.getState().documentText]) + seen.length = 0 + render( + <> + + + , + ) + expect(seen[1]).toBe(seen[0]) + expect(seen[0]).toMatchObject({ + categories: expect.arrayContaining([ + expect.objectContaining({ id: 'cat-z' }), + ]), + }) }) }) @@ -439,6 +527,9 @@ describe('a request reaches only its owner', () => { }) describe('« Aller à » while a creation or a tracing is in progress', () => { + const liveText = () => + document.querySelector('p[aria-live="polite"]')?.textContent ?? '' + function bareAnnotationText(): string { const bare = point('anno-bare', 10, 10, 2) const value = { ...bare.value, geometry: null, name: name('Sans tracé') } @@ -478,6 +569,35 @@ describe('« Aller à » while a creation or a tracing is in progress', () => { const bar = within(place('annotations.drawing')).getByTestId('tracing-bar') expect(bar).toBeVisible() await waitFor(() => expect(document.activeElement).toBe(bar)) + expect(liveText()).toContain('tracé est en cours') + }) + + it('a « Remplacer par un polygone » tracing is kept and focused (it cannot coexist with a pending creation)', async () => { + const zone = point('zone-a', 0, 0, 1) + const zoneValue = { + ...zone.value, + kind: 'zone', + geometry: { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }, + } + const text = insert(bareAnnotationText(), { + kind: 'annotation', + value: zoneValue, + } as typeof zone) + const user = await mount(text) + await gotoBare(user, async () => { + const drawing = inPlace('annotations.drawing') + const list = drawing.getByRole('list', { name: 'Annotations de la vue' }) + await user.click(within(list).getAllByRole('button')[0]) + await user.click( + await drawing.findByRole('button', { + name: 'Remplacer par un polygone', + }), + ) + expect(drawing.getByTestId('tracing-bar')).toBeVisible() + }) + const bar = within(place('annotations.drawing')).getByTestId('tracing-bar') + await waitFor(() => expect(document.activeElement).toBe(bar)) + expect(liveText()).toContain('tracé est en cours') }) it('a pending creation is kept and focused', async () => {