From bbb16684063d86129aca7b918dd17bd3d5e3cf41 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 12 Nov 2026 12:45:45 +0100 Subject: [PATCH] =?UTF-8?q?feat(app):=20D=C3=A9s=C3=A9lectionner=20and=20t?= =?UTF-8?q?he=20Escape=20priority=20(R1,=20D6,=20A5,=20A6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit « Désélectionner » (secondary sm, deselect glyph) sits left of « Supprimer » in a bordered row of the properties panel, read-only too, hidden while a tracing runs. It commits the typed field, clears the selection, focuses the row (else the drawing) and announces. Escape deselects through one document listener per visible body (not in a text field, only inside the workspace); G1: row focus only from the panel. « Plus » and the references panel close first; a tracing cancel marks its Escape. No existing assertion rewritten. --- .../app/src/components/editor/EditorGlyph.tsx | 3 + apps/app/src/components/editor/EditorTabs.tsx | 25 +- .../src/components/editor/EditorWorkspace.tsx | 11 +- .../annotations/EditableAnnotations.tsx | 11 +- .../editor/annotations/PropertiesPanel.tsx | 37 ++- .../components/editor/tabs/AnnotationsTab.tsx | 68 ++--- apps/app/src/editor/annotations/deselect.ts | 98 +++++++ .../src/editor/annotations/usePlacement.ts | 5 +- apps/app/src/editor/focusRequest.ts | 18 +- apps/app/src/editor/useEditorNavigation.ts | 2 +- apps/app/src/i18n/en.ts | 2 + apps/app/src/i18n/fr.ts | 2 + .../unit/editor-annotations-tab.test.tsx | 145 ++++++++++ apps/app/tests/unit/editor-escape.test.tsx | 248 ++++++++++++++++++ 14 files changed, 633 insertions(+), 42 deletions(-) create mode 100644 apps/app/src/editor/annotations/deselect.ts create mode 100644 apps/app/tests/unit/editor-escape.test.tsx diff --git a/apps/app/src/components/editor/EditorGlyph.tsx b/apps/app/src/components/editor/EditorGlyph.tsx index 0dbb8161..f3862bba 100644 --- a/apps/app/src/components/editor/EditorGlyph.tsx +++ b/apps/app/src/components/editor/EditorGlyph.tsx @@ -9,6 +9,7 @@ export type GlyphName = | 'undo' | 'redo' | 'search' + | 'deselect' /** The editor's one glyph table (24-unit grid strokes); `book` and `close` are in `Icon`. */ const GLYPHS: Record = { @@ -22,6 +23,8 @@ const GLYPHS: Record = { undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10', redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10', search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4', + deselect: + 'M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3M9 9l6 6M15 9l-6 6', } /** A decorative glyph of the editor, drawn in the current text colour. */ diff --git a/apps/app/src/components/editor/EditorTabs.tsx b/apps/app/src/components/editor/EditorTabs.tsx index 33d736fe..e6b668e8 100644 --- a/apps/app/src/components/editor/EditorTabs.tsx +++ b/apps/app/src/components/editor/EditorTabs.tsx @@ -1,4 +1,4 @@ -import { useState, type KeyboardEvent } from 'react' +import { useEffect, useRef, useState, type KeyboardEvent } from 'react' import { useEditorStore } from '@/editor/state/editorStore' import { usePlural } from '@/editor/plural' import { @@ -90,6 +90,28 @@ interface MoreTabsProps { onSelect: (tab: EditorTabId) => void } +/** + * While « Plus » is open, Escape closes it and returns the focus to it. Captured on the + * document so the key is marked handled before any body's deselection sees it; a modal + * dialog keeps its own Escape. + */ +function useMoreEscape(open: boolean, close: () => void) { + const closeRef = useRef(close) + closeRef.current = close + useEffect(() => { + if (!open) return + const onKey = (event: globalThis.KeyboardEvent) => { + if (event.key !== 'Escape' || event.isComposing) return + if (document.querySelector('dialog[open]')) return + event.preventDefault() + closeRef.current() + document.getElementById(MORE_BUTTON_ID)?.focus() + } + document.addEventListener('keydown', onKey, true) + return () => document.removeEventListener('keydown', onKey, true) + }, [open]) +} + /** Below 640 px: « Plus » and its disclosure of the tabs that do not fit. */ function MoreTabs({ more, active, onSelect }: MoreTabsProps) { const t = useT() @@ -98,6 +120,7 @@ function MoreTabs({ more, active, onSelect }: MoreTabsProps) { onSelect(tab) setOpen(false) } + useMoreEscape(open, () => setOpen(false)) return ( <> + ) +} + function GeometrySection(props: PropertiesPanelProps) { const t = useT() const { annotation, readOnly, geometryLocked } = props diff --git a/apps/app/src/components/editor/tabs/AnnotationsTab.tsx b/apps/app/src/components/editor/tabs/AnnotationsTab.tsx index 4d938388..41dd56d7 100644 --- a/apps/app/src/components/editor/tabs/AnnotationsTab.tsx +++ b/apps/app/src/components/editor/tabs/AnnotationsTab.tsx @@ -11,9 +11,11 @@ import SelectionTag from '@/components/editor/annotations/SelectionTag' import EditOnly from '@/components/editor/EditOnly' import KeptPlace from '@/components/editor/KeptPlace' import { ownedBy } from '@/editor/focusRequest' +import { useSelectionEscape } from '@/editor/annotations/deselect' import { useAnnotationRequest } from '@/editor/annotations/focusTarget' import { mainViewId, useViewModel } from '@/editor/annotations/useViewModel' import type { AnnotationSection as SectionId } from '@/editor/navigation' +import { usePlaceVisible } from '@/lib/placeVisibility' import { useSheetDocument } from '@/editor/sheetDocument' import { useEditorStore } from '@/editor/state/editorStore' import type { EditorPlaceProps } from '@/editor/tabs' @@ -163,6 +165,12 @@ function ReadOnlyAnnotations({ const model = useViewModel(doc, viewId) const view = doc.views.find((v) => v.id === viewId) const selected = model.annotations.find((a) => a.id === selectedId) + const visible = usePlaceVisible() + const asideRef = useSelectionEscape( + selected?.id ?? null, + () => setSelectedId(null), + visible && selected !== undefined, + ) // A view of its own has its own list: the filter and the selection start over. const showView = (id: string) => { setViewId(id) @@ -173,11 +181,7 @@ function ReadOnlyAnnotations({ return (
- + {selected && (
- {selected ? ( - undefined} - context={{ t: (key) => key, locale }} - navigate={navigate} - onShowAll={() => setSelectedId(null)} - /> - ) : ( - - )} +
) } diff --git a/apps/app/src/editor/annotations/deselect.ts b/apps/app/src/editor/annotations/deselect.ts new file mode 100644 index 00000000..dab4d37b --- /dev/null +++ b/apps/app/src/editor/annotations/deselect.ts @@ -0,0 +1,98 @@ +import { useContext, useEffect, useRef } from 'react' +import { flushSync } from 'react-dom' +import { + AnnounceContext, + commitFocusedField, + focusRow, + isTextField, + visibleElement, +} from '@/editor/focusRequest' +import { CANVAS_BOX } from '@/editor/useEditorNavigation' +import { useT } from '@/i18n/useT' + +/** The drawing's focusable box of the shown body, when there is one. */ +export function focusDrawing(): boolean { + const box = visibleElement(CANVAS_BOX) + box?.focus({ preventScroll: true }) + return box !== null +} + +/** The row of the annotation that was open; the drawing when a filter hides the row. */ +export function focusRowOrDrawing(id: string): boolean { + return focusRow({ kind: 'annotation', id }) || focusDrawing() +} + +/** + * Deselecting: `id` is the RESOLVED selection (never the raw id, which can name a removed + * annotation). The button always moves the focus to the row; Escape does only when it was + * pressed inside the properties panel, whose focused element is about to leave the page. + * Anywhere else the focus stays where it is. Both answer whether something was deselected. + */ +export function useDeselect(id: string | null, clear: () => void) { + const t = useT() + const tRef = useRef(t) + tRef.current = t + const announce = useContext(AnnounceContext) + const run = (focus: boolean) => { + if (id === null) return false + commitFocusedField() + flushSync(clear) + if (focus) focusRowOrDrawing(id) + announce(tRef.current('editor.annotations.deselected')) + return true + } + return { + byButton: () => run(true), + byKey: (fromPanel: boolean) => run(fromPanel), + } +} + +/** Whether a key event happened in the editor workspace (or with nothing focused). */ +function inWorkspace(target: EventTarget | null): boolean { + if (target === document.body) return true + return ( + target instanceof Element && + target.closest('[data-editor-workspace]') !== null + ) +} + +/** + * While `active`, Escape on the document runs `onEscape`, which answers whether it acted. + * A key already handled (dialogs, the references panel, « Plus »), one typed in a field or + * outside the workspace is left alone. + */ +export function useEscapeDeselect( + active: boolean, + onEscape: (event: KeyboardEvent) => boolean, +): void { + const handler = useRef(onEscape) + handler.current = onEscape + useEffect(() => { + if (!active) return + const onKey = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || event.defaultPrevented) return + if (event.isComposing || isTextField(event.target)) return + if (!inWorkspace(event.target)) return + if (handler.current(event)) event.preventDefault() + } + document.addEventListener('keydown', onKey) + return () => document.removeEventListener('keydown', onKey) + }, [active]) +} + +/** + * A body's Escape: deselects `id` while `active`. Returns the ref of the panel column, which + * tells a key pressed inside the panel (focus follows the row) from one pressed elsewhere. + */ +export function useSelectionEscape( + id: string | null, + clear: () => void, + active: boolean, +) { + const asideRef = useRef(null) + const deselect = useDeselect(id, clear) + useEscapeDeselect(active, (event) => + deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false), + ) + return asideRef +} diff --git a/apps/app/src/editor/annotations/usePlacement.ts b/apps/app/src/editor/annotations/usePlacement.ts index ed06ac82..7d7e8720 100644 --- a/apps/app/src/editor/annotations/usePlacement.ts +++ b/apps/app/src/editor/annotations/usePlacement.ts @@ -79,7 +79,10 @@ function tracingActions(input: PlacementInput) { const onTraceKey = (event: KeyboardEvent) => { if (!ui.tracing) return if (event.key === 'Enter') closeTracing() - if (event.key === 'Escape') dispatch({ type: 'trace_cancel' }) + if (event.key === 'Escape') { + event.preventDefault() + dispatch({ type: 'trace_cancel' }) + } } return { closeTracing, trace, onTraceKey } } diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts index 517a2f6a..77bc2548 100644 --- a/apps/app/src/editor/focusRequest.ts +++ b/apps/app/src/editor/focusRequest.ts @@ -102,6 +102,17 @@ export function useRowFocus(focus: FocusRequest | undefined): void { ) } +/** A field that takes typed text (or a choice): Escape there belongs to the field. */ +export function isTextField(target: EventTarget | null): boolean { + return ( + target instanceof HTMLInputElement || + target instanceof HTMLTextAreaElement || + target instanceof HTMLSelectElement || + (target instanceof HTMLElement && + target.closest('[contenteditable]') !== null) + ) +} + /** * Commits the text being typed before a place is left: blurs the focused field, so its * `TextField` commits on blur. Safari and iPadOS do not move the focus to a tapped button, @@ -109,11 +120,8 @@ export function useRowFocus(focus: FocusRequest | undefined): void { */ export function commitFocusedField(): boolean { const active = document.activeElement - const isField = - active instanceof HTMLInputElement || - active instanceof HTMLTextAreaElement || - active instanceof HTMLSelectElement - if (isField) active.blur() + const isField = isTextField(active) + if (isField) (active as HTMLElement).blur() return isField } diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index 683927a9..8acc2d90 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -67,7 +67,7 @@ const isShown = (element: HTMLElement | null): boolean => const headingOf = (place: PlaceName) => visibleElement(`[data-place="${place}"] [data-place-heading]`) -const CANVAS_BOX = +export const CANVAS_BOX = '[data-place="annotations.drawing"] [role="group"][tabindex="0"]' /** The tab's button, or « Plus » while the tab sits in the closed list. */ diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 28ce5a2b..7bf68f4f 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1225,6 +1225,8 @@ export const en: Dict = { 'editor.overview.uncategorised': 'No category', 'editor.overview.no_match': 'No annotation matches.', 'editor.annotations.show_all': 'All annotations', + 'editor.annotations.deselect': 'Deselect', + 'editor.annotations.deselected': 'No annotation selected.', 'editor.references.open': 'References', 'editor.references.close': 'Close the references', 'editor.references.search': 'Search a reference', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 8187dd80..4699ed85 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1256,6 +1256,8 @@ export const fr: Dict = { 'editor.overview.uncategorised': 'Sans catégorie', 'editor.overview.no_match': 'Aucune annotation ne correspond.', 'editor.annotations.show_all': 'Toutes les annotations', + 'editor.annotations.deselect': 'Désélectionner', + 'editor.annotations.deselected': 'Aucune annotation sélectionnée.', 'editor.references.open': 'Références', 'editor.references.close': 'Fermer les références', 'editor.references.search': 'Rechercher une référence', diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx index 460e1127..1854846c 100644 --- a/apps/app/tests/unit/editor-annotations-tab.test.tsx +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -12,6 +12,7 @@ import { import userEvent from '@testing-library/user-event' import type { Annotation } from '@faunosteo/core-wasm/types' import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' +import { AnnounceContext } from '@/editor/focusRequest' import { useLocaleStore } from '@/state/localeStore' import { ASSET, @@ -944,3 +945,147 @@ describe('the drag and the canvas follow the handle (H8)', () => { await waitFor(() => expect(marker('anno-a')).not.toBe(first)) }) }) + +describe('« Désélectionner » (R1, A6)', () => { + const announce = vi.fn() + const rowOf = (id: string, prefix = '') => + document.querySelector( + `[data-focus-key='{"kind":"annotation","id":"${id}"}']`, + ) ?? document.getElementById(`${prefix}${id}`) + const snapshot = () => { + const state = store.getState() + return [ + state.documentText, + state.handleVersion, + state.undo.length, + state.unsaved, + ] + } + + async function mountSpy(options: { text?: string; readOnly?: boolean } = {}) { + announce.mockReset() + await openReady({ text: options.text ?? text() }) + const readOnly = options.readOnly ?? false + render( + + + , + ) + const drawing = readOnly + ? 'catalogue-canvas-drawing' + : 'annotation-canvas-drawing' + await waitFor(() => + expect(screen.getByTestId(drawing).querySelector('svg')).not.toBeNull(), + ) + } + const button = (panel: HTMLElement, name = 'Désélectionner') => + within(panel).getByRole('button', { name }) + + it('shows the overview, focuses the row, announces, and changes nothing else', async () => { + await mountSpy() + const panel = await selectFromList() + const before = snapshot() + await userEvent.setup().click(button(panel)) + expect(screen.queryByTestId('annotation-properties')).toBeNull() + expect(screen.getByTestId('annotation-overview')).toBeInTheDocument() + expect(document.activeElement).toBe(rowOf('anno-a')) + expect(announce).toHaveBeenCalledWith('Aucune annotation sélectionnée.') + expect(snapshot()).toEqual(before) + }) + + it('focuses the drawing when a filter hides the row', async () => { + await mountSpy() + const panel = await selectFromList() + // The filter lives in the overview: type it there, then reselect from the drawing. + await userEvent.setup().click(button(panel)) + const filter = screen.getByLabelText('Filtrer par nom') + fireEvent.change(filter, { target: { value: 'zzz-no-match' } }) + fireEvent.click( + screen.getByTestId('annotation-canvas-drawing').querySelector( + '[data-anno-id="anno-a"]', + )!, + ) + const reopened = await screen.findByTestId('annotation-properties') + await userEvent.setup().click(button(reopened)) + expect(document.activeElement).toBe(screen.getByTestId('annotation-canvas')) + expect(screen.queryByTestId('annotation-properties')).toBeNull() + }) + + it('undo after it undoes the earlier edit', async () => { + await mountSpy() + const panel = await selectFromList() + const user = userEvent.setup() + await user.clear(within(panel).getByLabelText('Centre x')) + await user.type(within(panel).getByLabelText('Centre x'), '60{Enter}') + expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + await user.click(button(panel)) + act(() => void store.getState().undoStep()) + expect(geometryOf('anno-a')).toMatchObject({ cx: 50 }) + }) + + it('read-only: no « Supprimer », it deselects and focuses the ro- row', async () => { + await mountSpy({ readOnly: true }) + const panel = await selectFromList() + expect(within(panel).queryByRole('button', { name: 'Supprimer' })).toBeNull() + await userEvent.setup().click(button(panel)) + expect(screen.queryByTestId('annotation-properties')).toBeNull() + const row = document.querySelector( + '[data-focus-key=\'{"kind":"annotation","id":"anno-a"}\']', + ) + expect(document.activeElement).toBe(row) + expect(announce).toHaveBeenCalledTimes(1) + }) + + it('commits a valid typed value once when the field is not blurred', async () => { + await mountSpy() + const panel = await selectFromList() + const user = userEvent.setup() + const cx = within(panel).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '60') + const depth = store.getState().undo.length + await user.click(button(panel)) + expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + expect(store.getState().undo.length).toBe(depth + 1) + }) + + it('a refused typed value: the panel closes, the document is unchanged', async () => { + await mountSpy({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) }) + const panel = await selectFromList() + const user = userEvent.setup() + const before = store.getState().documentText + const cx = within(panel).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '1000000') + await user.click(button(panel)) + expect(screen.queryByTestId('annotation-properties')).toBeNull() + expect(store.getState().documentText).toBe(before) + }) + + it('speaks English', async () => { + useLocaleStore.setState({ locale: 'en' }) + await mountSpy() + await screen.findByTestId('annotation-overview') + await userEvent.setup().click(rowOf('anno-a')!) + const panel = await screen.findByTestId('annotation-properties') + await userEvent.setup().click(button(panel, 'Deselect')) + expect(announce).toHaveBeenCalledWith('No annotation selected.') + }) + + it('is not offered while a replace tracing runs', async () => { + await mountSpy({ + text: insert(drawnText(), { + kind: 'annotation', + value: zoneAnnotation({ type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }), + }), + }) + const panel = await selectFromList() + await userEvent.setup().click( + within(panel).getByRole('button', { name: 'Remplacer par un polygone' }), + ) + const open = await screen.findByTestId('annotation-properties') + expect( + within(open).queryByRole('button', { name: 'Désélectionner' }), + ).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/editor-escape.test.tsx b/apps/app/tests/unit/editor-escape.test.tsx new file mode 100644 index 00000000..b9802e83 --- /dev/null +++ b/apps/app/tests/unit/editor-escape.test.tsx @@ -0,0 +1,248 @@ +/** R1 (A5, A6): the Escape priority across the whole editor workspace. */ +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 type { Annotation } from '@faunosteo/core-wasm/types' +import { useLocaleStore } from '@/state/localeStore' +import { drawnText, insert, point } from '../helpers/editorFixtures' +import { resetStore, serverHas, store } 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(), +})) + +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 TWO = () => + insert( + insert(drawnText(), point('anno-a', 50, 50, 5)), + point('anno-b', 20, 20, 3), + ) +const ZONE = () => + insert(drawnText(), { + kind: 'annotation', + value: { + ...(point('zone-a', 0, 0, 1).value as Annotation), + kind: 'zone', + geometry: { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }, + } as Annotation, + }) + +const shown = (selector: string) => + [...document.querySelectorAll(selector)].find( + (element) => !element.closest('[hidden]'), + ) +const panel = () => shown('[data-testid="annotation-properties"]') +const rowOf = (id: string) => + shown(`[data-focus-key='{"kind":"annotation","id":"${id}"}']`) +const live = () => document.querySelector('[aria-live="polite"]')! +const escape = (target: Element | Window = document.body) => + fireEvent.keyDown(target, { key: 'Escape' }) + +async function mount(text = TWO(), width?: number) { + serverHas(text, 3) + const user = userEvent.setup() + mountDraft({ width }) + await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) + await waitFor(() => + expect(shown('[data-testid$="canvas-drawing"] svg')).toBeDefined(), + ) + return user +} + +/** Selects through the overview row (the visible body's). */ +async function select(user: ReturnType, id = 'anno-a') { + await waitFor(() => expect(rowOf(id)).toBeDefined()) + await user.click(rowOf(id)!) + await waitFor(() => expect(panel()).toBeDefined()) +} +const canvasBox = () => + shown('[data-place="annotations.drawing"] [role="group"][tabindex="0"]')! +const inPanel = (name: string) => within(panel()!).getByRole('button', { name }) + +describe('Escape deselects', () => { + it('from the canvas box: deselected, the focus stays, announced', async () => { + const user = await mount() + await select(user) + canvasBox().focus() + escape(canvasBox()) + expect(panel()).toBeUndefined() + expect(document.activeElement).toBe(canvasBox()) + await waitFor(() => + expect(live()).toHaveTextContent('Aucune annotation sélectionnée.'), + ) + }) + + it('from a button of the panel: deselected, the focus on the row', async () => { + const user = await mount() + await select(user) + inPanel('Marquer comme relu').focus() + escape(document.activeElement!) + expect(panel()).toBeUndefined() + expect(document.activeElement).toBe(rowOf('anno-a')) + }) + + it("after A then B, from the panel: the focus on B's row", async () => { + const user = await mount() + await select(user, 'anno-a') + await user.click(inPanel('Toutes les annotations')) + await select(user, 'anno-b') + inPanel('Marquer comme relu').focus() + escape(document.activeElement!) + expect(document.activeElement).toBe(rowOf('anno-b')) + }) + + it('from body and from the history button of the tab row', async () => { + const user = await mount() + await select(user) + escape(document.body) + expect(panel()).toBeUndefined() + await select(user) + act( + () => + void store + .getState() + .commit({ op: 'remove', key: { kind: 'annotation', id: 'anno-b' } }), + ) + const undo = screen.getByRole('button', { name: /Défaire/ }) + await waitFor(() => expect(undo).toBeEnabled()) + undo.focus() + escape(undo) + expect(panel()).toBeUndefined() + expect(document.activeElement).toBe(undo) + }) +}) + +describe('Escape leaves alone', () => { + it('a text field', async () => { + const user = await mount() + await select(user) + const field = within(panel()!).getByLabelText('Nom (FR)') + field.focus() + escape(field) + expect(panel()).toBeDefined() + }) + + it('a target outside the workspace', async () => { + const user = await mount() + await select(user) + const outside = document.createElement('button') + document.body.append(outside) + outside.focus() + escape(outside) + outside.remove() + expect(panel()).toBeDefined() + }) + + it('nothing selected, or the selected annotation deleted: no announcement', async () => { + const user = await mount() + escape(document.body) + expect(live()).toBeEmptyDOMElement() + await select(user) + act( + () => + void store + .getState() + .commit({ op: 'remove', key: { kind: 'annotation', id: 'anno-a' } }), + ) + const before = store.getState().documentText + escape(document.body) + expect(live()).toBeEmptyDOMElement() + expect(store.getState().documentText).toBe(before) + }) + + it('a tracing: the TracingBar keeps its Escape, the canvas box cancels the tracing only', async () => { + const user = await mount(ZONE()) + await select(user, 'zone-a') + await user.click(inPanel('Remplacer par un polygone')) + const bar = await screen.findByTestId('tracing-bar') + bar.focus() + escape(bar) + expect(screen.queryByTestId('tracing-bar')).not.toBeNull() + canvasBox().focus() + escape(canvasBox()) + await waitFor(() => expect(screen.queryByTestId('tracing-bar')).toBeNull()) + expect(panel()).toBeDefined() + }) + + it('a modal dialog open: only its own handling (wiring proof)', async () => { + const user = await mount() + await select(user) + await user.click(inPanel('Supprimer')) + const dialog = document.querySelector('dialog')! + expect(dialog).not.toBeNull() + escape(dialog) + expect(panel()).toBeDefined() + }) +}) + +describe('Escape and the other layers', () => { + it('closes the references panel from the tab row, the selection kept', async () => { + const user = await mount() + await select(user) + await user.click(screen.getByRole('button', { name: 'Références' })) + const tab = screen.getByRole('tab', { name: 'Annotations' }) + escape(tab) + expect(screen.getByRole('button', { name: 'Références' })).toHaveAttribute( + 'aria-expanded', + 'false', + ) + expect(panel()).toBeDefined() + }) + + it('closes « Plus » first (small tier), the twin selection kept', async () => { + const user = await mount(TWO(), 500) + await select(user) + const more = screen.getByRole('button', { name: 'Plus' }) + await user.click(more) + expect(more).toHaveAttribute('aria-expanded', 'true') + canvasBox().focus() + escape(canvasBox()) + expect(more).toHaveAttribute('aria-expanded', 'false') + expect(document.activeElement).toBe(more) + expect(panel()).toBeDefined() + }) + + it('read-only width: only the visible twin deselects, the hidden body keeps its own', async () => { + const user = await mount() + await select(user) + setWidth(500) + act(() => void window.dispatchEvent(new Event('resize'))) + await waitFor(() => + expect(shown('[data-testid="catalogue-canvas"]')).toBeDefined(), + ) + await select(user) + escape(document.body) + expect(panel()).toBeUndefined() + const hidden = [ + ...document.querySelectorAll('[data-testid="annotation-properties"]'), + ].filter((element) => element.closest('[hidden]')) + expect(hidden).toHaveLength(1) + }) +})