/** U1 Lot B2b: a 1 024 px crossing or a recovery decision never loses typed input. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, screen, waitFor, within, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { useAuthStore } from '@/state/authStore' import { useLocaleStore } from '@/state/localeStore' import { drawnText, emptyText, insert, point } from '../helpers/editorFixtures' import { SHEET, USER, VERSION, baseText, copyKeyOf, resetStore, serverHas, storedCopy, store, sb, } from '../helpers/editorHarness' import { adminAnswer, grant, mountDraft, round, 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(), })) beforeEach(() => { useLocaleStore.setState({ locale: 'fr' }) const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', { configurable: true, value: () => ({ ...identity, inverse: () => identity }), }) }) afterEach(() => { cleanup() resetStore() setWidth(1024) }) const ready = () => screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) const tab = (name: string | RegExp) => screen.getByRole('tab', { name }) const button = (name: string | RegExp) => screen.getByRole('button', { name }) const place = (name: string) => document.querySelector(`[data-place="${name}"]`)! const byId = (id: string) => document.getElementById(id) as HTMLInputElement /** A real window resize across the 1 024 px edit threshold. */ function cross(width: number) { act(() => { setWidth(width) window.dispatchEvent(new Event('resize')) }) } async function mount(text = baseText()) { serverHas(text, 3) const user = userEvent.setup() mountDraft() await ready() return user } function duplicateIds(): string[] { const seen = new Map() for (const element of document.querySelectorAll('[id]')) { seen.set(element.id, (seen.get(element.id) ?? 0) + 1) } return [...seen].filter(([, count]) => count > 1).map(([id]) => id) } const detail = (extra: object = {}) => ({ kind: 'view', value: { kind: 'detail', id: 'view-d', name: { fr: 'Détail', en: 'Detail' }, svg_asset_id: null, view_box: { min_x: 0, min_y: 0, width: 50, height: 50 }, parent_view_id: 'view-main', ...extra, }, }) as Parameters[1] const spareCategory = (text: string) => insert(text, { kind: 'category', value: { id: 'cat-spare', name: { fr: 'Libre', en: 'Free' }, color: null }, }) type User = ReturnType /** Types in `#id`, crosses below 1 024 px, checks the part left the page, widens, checks it is back. */ async function keepsTypedValue( user: User, id: string, controlName: string, addName: string, ) { const field = byId(id) await user.type(field, 'Saisie') cross(800) expect(field.closest('[hidden]')).not.toBeNull() expect(screen.queryByRole('textbox', { name: controlName })).toBeNull() expect(screen.queryByRole('button', { name: addName })).toBeNull() cross(1280) expect(byId(id)).toBe(field) expect(field).toBeVisible() expect(field).toHaveValue('Saisie') expect(store.getState().unsaved).toBe(false) } describe('typed values come back after a 1 024 px crossing', () => { it('the category creation form', async () => { const user = await mount() await user.click(tab('Annotations')) await user.click(button('Modifier les catégories')) await keepsTypedValue( user, 'category-new-fr', 'Nom de la catégorie (FR)', 'Ajouter la catégorie', ) }) it('the reference creation form, in the references panel', async () => { const user = await mount() await user.click(button('Références')) await keepsTypedValue( user, 'reference-new-citation', 'Citation', 'Ajouter la référence', ) }) it('the region creation form', async () => { const user = await mount() await user.click(tab('Annotations')) await user.click( document.querySelector('[data-section-entry="regions"]')!, ) await keepsTypedValue(user, 'region-new-code', 'Code', 'Ajouter la région') }) it('the detail view creation form', async () => { const user = await mount() await user.click(tab('Annotations')) await user.click(button('Gérer les vues')) await keepsTypedValue(user, 'view-new-fr', 'Nom (FR)', 'Ajouter la vue') }) it('the findings creation form', async () => { const user = await mount() await user.click(tab('Constats')) await user.click(button('Ajouter une zone')) await keepsTypedValue( user, 'finding-new-name-fr', 'Nom (FR)', 'Ajouter une zone', ) }) it('the submission note', async () => { const user = await mount() await user.click(tab(/Vérification/)) await keepsTypedValue( user, 'verification-note', 'Note de soumission (obligatoire)', 'Soumettre à la revue', ) }) it('the crop group editor, open, with the typed numbers', async () => { const user = await mount(insert(drawnText(), detail())) await user.click(tab('Annotations')) await user.click(button('Gérer les vues')) await user.click(button('Modifier le recadrage')) const field = byId('view-view-d-crop-min_x') await user.clear(field) await user.type(field, '7x') cross(800) expect(field.closest('[hidden]')).not.toBeNull() expect(screen.queryByRole('group', { name: 'Recadrage' })).toBeNull() expect(byId('ro-view-view-d-crop-min_x')).toBeTruthy() cross(1280) expect(byId('view-view-d-crop-min_x')).toBe(field) expect(field).toHaveValue('7x') expect(store.getState().unsaved).toBe(false) }) it('the annotation edit body: tool, pending creation with its name', async () => { const user = await mount(baseText()) const drawing = within(place('annotations.drawing')) await waitFor(() => expect(drawing.getByRole('button', { name: 'Zone' })).toBeEnabled(), ) await user.click(drawing.getByRole('button', { name: 'Zone' })) await user.click(drawing.getByRole('button', { name: 'Ajouter un point' })) const name = await screen.findByLabelText('Nom (FR)') await user.type(name, 'Futur point') cross(800) expect(name.closest('[hidden]')).not.toBeNull() expect(screen.queryByRole('region', { name: 'Nouveau point' })).toBeNull() expect(screen.queryByRole('button', { name: 'Zone' })).toBeNull() cross(1280) expect(screen.getByLabelText('Nom (FR)')).toBe(name) expect(name).toHaveValue('Futur point') expect(drawing.getByRole('button', { name: 'Zone' })).toHaveAttribute( 'aria-pressed', 'true', ) expect(store.getState().unsaved).toBe(false) }) }) describe('the guards of a width change', () => { it('commits a typed, unblurred field before the editor turns read-only', async () => { const user = await mount() await user.click(tab('Général')) const field = byId('general-name-fr') await user.click(field) fireEvent.change(field, { target: { value: 'Nom saisi' } }) expect(store.getState().unsaved).toBe(false) cross(800) expect(store.getState().undo).toHaveLength(1) expect(JSON.parse(store.getState().documentText).name.fr).toBe('Nom saisi') expect(store.getState().unsaved).toBe(true) await waitFor(() => expect(storedCopy()).not.toBeNull()) expect(document.activeElement).toBe(tab('Général')) }) it('the focus of a typed field goes to « Plus » when the shown tab left the row', async () => { const user = await mount() await user.click(tab('Général')) await user.click(byId('general-name-fr')) cross(500) expect(document.activeElement).toBe(button('Plus')) }) it('a focused button of a hidden part hands its focus to the shown tab', async () => { const user = await mount() await user.click(tab('Annotations')) await user.click(button('Modifier les catégories')) const add = button('Ajouter la catégorie') act(() => add.focus()) cross(800) expect(add.closest('[hidden]')).not.toBeNull() expect(document.activeElement).toBe(tab('Annotations')) }) it('a focused drawing tool hands its focus to the shown tab', async () => { const user = await mount() await waitFor(() => expect(button('Zone')).toBeEnabled(), ) await user.click(button('Zone')) expect(document.activeElement).toBe(button('Zone')) cross(800) expect(document.activeElement).toBe(tab('Annotations')) }) it('a focused header button stays where it is', async () => { await mount() const refs = button('Références') act(() => refs.focus()) cross(800) expect(document.activeElement).toBe(refs) }) it('the references search, shown in both modes, keeps its focus and its text', async () => { const user = await mount() await user.click(button('Références')) const panel = screen.getByTestId('editor-references-panel') const search = within(panel).getByRole('searchbox', { name: 'Rechercher une référence', }) await user.type(search, 'code') expect(document.activeElement).toBe(search) cross(800) expect(document.activeElement).toBe(search) expect(search).toHaveValue('code') cross(1280) expect(document.activeElement).toBe(search) }) it('a crossing with the focus on no field leaves the focus alone', async () => { const user = await mount() await user.click(tab('Général')) ;(document.activeElement as HTMLElement).blur() cross(800) expect(document.activeElement).toBe(document.body) }) it('a field that switches in place loses a refused value, a field of a kept part keeps it', async () => { const user = await mount() await user.click(tab('Général')) const general = byId('general-name-fr') await user.clear(general) cross(800) cross(1280) expect(byId('general-name-fr')).toHaveValue('Fiche') await user.click(tab('Annotations')) await user.click(button('Modifier les catégories')) await user.type(byId('category-new-en'), 'Gardé') cross(800) cross(1280) expect(byId('category-new-en')).toHaveValue('Gardé') }) it('drops a drag in flight without a commit', async () => { const user = await mount() const drawing = place('annotations.drawing') await user.click( within(drawing).getAllByRole('button', { name: /Point|anno-a/ })[0], ) const marker = () => drawing.querySelector('[data-anno-id="anno-a"]')! await waitFor(() => expect(marker()).not.toBeNull()) fireEvent.pointerDown(marker(), { clientX: 50, clientY: 50, button: 0, pointerId: 1, }) fireEvent.pointerMove(marker(), { clientX: 70, clientY: 50, pointerId: 1 }) const version = store.getState().handleVersion cross(800) cross(1280) await waitFor(() => expect(marker()).not.toBeNull()) fireEvent.pointerUp(marker(), { clientX: 70, clientY: 50, pointerId: 1 }) expect(store.getState().handleVersion).toBe(version) expect(store.getState().unsaved).toBe(false) }) it('closes a delete confirmation and the discard confirmation when the editor turns read-only', async () => { const user = await mount(spareCategory(baseText())) await user.click(tab('Annotations')) await user.click(button('Modifier les catégories')) await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[1]) expect(document.querySelectorAll('dialog[open]')).toHaveLength(1) cross(800) await waitFor(() => expect(document.querySelectorAll('dialog[open]')).toHaveLength(0), ) cross(1280) expect(document.querySelectorAll('dialog[open]')).toHaveLength(0) expect(JSON.parse(store.getState().documentText).categories).toHaveLength(2) // the discard confirmation: opened on unsaved work, closed by a recovery block fireEvent.change(byId('category-new-fr'), { target: { value: 'x' } }) act( () => void store.getState().commit({ op: 'update', key: { kind: 'annotation', id: 'anno-a' }, element: point('anno-a', 60, 50, 5), }), ) await user.click(button('Abandonner les modifications')) expect(document.querySelectorAll('dialog[open]')).toHaveLength(1) act(() => store.setState({ recovery: 'pending' })) await waitFor(() => expect(document.querySelectorAll('dialog[open]')).toHaveLength(0), ) }) }) describe('ids stay unique', () => { async function everyPlace(user: User) { for (const name of ['Général', 'Constats', /Vérification/, 'Annotations']) { await user.click(tab(name)) } await user.click(button('Gérer les vues')) await user.click(button('Modifier le recadrage')) await user.click(button('Retour au dessin')) await user.click(button('Références')) } const text = () => insert(baseText(), detail()) it('in edit mode and after a crossing, nothing selected', async () => { const user = await mount(text()) await everyPlace(user) expect(duplicateIds()).toEqual([]) cross(800) expect(duplicateIds()).toEqual([]) cross(1280) expect(duplicateIds()).toEqual([]) }) it('with a selection, the read-only twin takes its own ids', async () => { const user = await mount(text()) await everyPlace(user) const list = within(place('annotations.drawing')).getByRole('list', { name: 'Annotations de la vue', }) await user.click(within(list).getAllByRole('button')[0]) expect(duplicateIds()).toEqual([]) cross(800) expect(duplicateIds()).toEqual([]) const twin = screen .getAllByRole('list', { name: 'Annotations de la vue' }) .find((candidate) => !candidate.closest('[hidden]'))! await user.click(within(twin).getAllByRole('button')[0]) expect(duplicateIds()).toEqual([]) expect(document.getElementById('ro-annotation-name-fr')).not.toBeNull() expect(document.getElementById('annotation-name-fr')).not.toBeNull() cross(1280) expect(duplicateIds()).toEqual([]) }) }) describe('focus requests', () => { it('go to the visible annotation body only', async () => { const bare = point('anno-bare', 10, 10, 2) const value = { ...bare.value, geometry: null, name: { fr: 'Sans tracé', en: 'Bare' }, } const user = await mount( insert(baseText(), { kind: 'annotation', value } as typeof bare), ) cross(800) await user.click(tab(/Vérification/)) fireEvent.click( screen.getAllByRole('button', { name: 'Aller à Sans tracé' })[0], ) const visible = (id: string) => [...document.querySelectorAll(`[data-testid="${id}"]`)].filter( (element) => !element.closest('[hidden]'), ) await waitFor(() => expect(visible('annotation-properties')).toHaveLength(1), ) cross(1280) expect(visible('annotation-properties')).toHaveLength(0) expect(visible('annotation-overview')).toHaveLength(1) }) }) describe('edit-only parts of a page opened read-only', () => { it('a page opened narrow has no edit body and no creation form', async () => { serverHas(baseText(), 3) mountDraft({ width: 800 }) await ready() expect(document.querySelector('[data-place] [data-place]')).toBeNull() expect(screen.queryByRole('button', { name: 'Zone' })).toBeNull() expect(screen.queryByTestId('annotation-canvas')).toBeNull() cross(1280) await waitFor(() => expect(screen.getByTestId('annotation-canvas')).toBeVisible(), ) }) }) describe('recovery decisions', () => { function seedCopy() { sessionStorage.setItem( copyKeyOf(), JSON.stringify({ v: 1, user_id: USER, version_id: VERSION, sheet_id: SHEET, sheet_name: 'Fiche', revision: 3, written_at: '2026-11-03T10:00:00Z', document: JSON.parse(emptyText()), drawings: [], }), ) } it('a pending offer at opening: no edit part, empty forms after the answer', async () => { seedCopy() const user = await mount() expect(byId('category-new-fr')).toBeNull() expect(screen.getByTestId('catalogue-canvas')).toBeVisible() await user.click(button('Ignorer la copie')) await user.click( within(await screen.findByRole('dialog')).getByRole('button', { name: 'Abandonner la copie', }), ) await waitFor(() => expect(store.getState().recovery).toBe('none')) await user.click(tab('Annotations')) await user.click(button('Modifier les catégories')) expect(byId('category-new-fr')).toHaveValue('') }) it('rights to edit inside one mount with a copy: no edit part before the offer', async () => { seedCopy() serverHas(baseText(), 3) mountDraft({ grants: [grant('sheet_reviewer')] }) await ready() act(() => useAuthStore.setState({ catalogGrants: [grant('sheet_editor')] })) await waitFor(() => expect(store.getState().recovery).toBe('pending')) expect(byId('category-new-fr')).toBeNull() expect(screen.getByTestId('catalogue-canvas')).toBeVisible() }) it('an offer pending mid-session keeps the hidden drafts across the answer', async () => { const user = await mount() await user.click(tab('Annotations')) await user.click(button('Modifier les catégories')) await user.type(byId('category-new-fr'), 'Brouillon') act(() => useAuthStore.setState({ catalogGrants: [grant('sheet_reviewer')] }), ) await waitFor(() => expect(byId('category-new-fr').closest('[hidden]')).not.toBeNull(), ) seedCopy() act(() => useAuthStore.setState({ catalogGrants: [grant('sheet_editor')] })) await waitFor(() => expect(store.getState().recovery).toBe('pending')) expect(byId('category-new-fr').closest('[hidden]')).not.toBeNull() await user.click(button('Ignorer la copie')) await user.click( within(await screen.findByRole('dialog')).getByRole('button', { name: 'Abandonner la copie', }), ) await waitFor(() => expect(store.getState().recovery).toBe('none')) expect(byId('category-new-fr')).toHaveValue('Brouillon') expect(byId('category-new-fr')).toBeVisible() }) }) describe('the route after a submission', () => { it.each(['verification_failed', 'changes_requested', 'withdrawn'])( 'a refresh that keeps the draft editable (%s) re-enables editing', async (status) => { const user = await mount() sb.submitSheetReview.mockResolvedValue('review-1' as never) await user.click(tab(/Vérification/)) await user.type(byId('verification-note'), 'Prête') sb.getOfficialSheetAdmin.mockResolvedValue( adminAnswer({ rounds: [round(status)] }) as never, ) await user.click(button('Soumettre à la revue')) await waitFor(() => expect(sb.submitSheetReview).toHaveBeenCalled()) await waitFor(() => expect(store.getState().canEdit).toBe(true)) await waitFor(() => expect(byId('verification-note')).toBeVisible()) expect(button('Soumettre à la revue')).toBeTruthy() }, ) })