diff --git a/apps/app/src/components/catalogue/CatalogueCanvas.tsx b/apps/app/src/components/catalogue/CatalogueCanvas.tsx
index 994fb177..e4cc57fe 100644
--- a/apps/app/src/components/catalogue/CatalogueCanvas.tsx
+++ b/apps/app/src/components/catalogue/CatalogueCanvas.tsx
@@ -72,8 +72,11 @@ export default function CatalogueCanvas({
)
const tap = useEmptyTap()
const { takeClick } = tap
+ const onEmptyRef = useRef(onEmpty)
+ onEmptyRef.current = onEmpty
const emptyHandlers = onEmpty
? {
+ ...handlers,
onPointerDown: (e: PointerEvent) => {
handlers.onPointerDown(e)
tap.onPointerDown(e)
@@ -125,16 +128,16 @@ export default function CatalogueCanvas({
if (!element) return
const onClick = (event: Event) => {
if (swallowClick()) return
- const answer = onEmpty ? takeClick(event.target) : 'normal'
+ const answer = onEmptyRef.current ? takeClick(event.target) : 'normal'
if (answer === 'swallow') return
- if (answer === 'deselect') return onEmpty?.()
+ if (answer === 'deselect') return onEmptyRef.current?.()
const target = event.target instanceof Element ? event.target.closest(ANNOTATED) : null
const id = target?.getAttribute('data-anno-id')
if (id) onAnnotation(id)
}
element.addEventListener('click', onClick)
return () => element.removeEventListener('click', onClick)
- }, [onAnnotation, onEmpty, swallowClick, takeClick])
+ }, [onAnnotation, swallowClick, takeClick])
return (
diff --git a/apps/app/src/components/editor/EditorTabs.tsx b/apps/app/src/components/editor/EditorTabs.tsx
index e6b668e8..9ee21c14 100644
--- a/apps/app/src/components/editor/EditorTabs.tsx
+++ b/apps/app/src/components/editor/EditorTabs.tsx
@@ -1,4 +1,6 @@
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
+import { inWorkspace } from '@/editor/annotations/deselect'
+import { isTextField } from '@/editor/focusRequest'
import { useEditorStore } from '@/editor/state/editorStore'
import { usePlural } from '@/editor/plural'
import {
@@ -103,6 +105,7 @@ function useMoreEscape(open: boolean, close: () => void) {
const onKey = (event: globalThis.KeyboardEvent) => {
if (event.key !== 'Escape' || event.isComposing) return
if (document.querySelector('dialog[open]')) return
+ if (isTextField(event.target) || !inWorkspace(event.target)) return
event.preventDefault()
closeRef.current()
document.getElementById(MORE_BUTTON_ID)?.focus()
diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx
index 55859dbc..c528bd1a 100644
--- a/apps/app/src/components/editor/EditorWorkspace.tsx
+++ b/apps/app/src/components/editor/EditorWorkspace.tsx
@@ -1,4 +1,4 @@
-import type { ReactNode } from 'react'
+import { useEffect, useRef, type ReactNode } from 'react'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
import Notice from '@/components/ui/Notice'
import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext'
@@ -130,6 +130,28 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
)
}
+/**
+ * A keydown aimed at `body` (nothing focused) never reaches the workspace's own handler:
+ * while the references panel is open, Escape there closes it all the same, unless a
+ * modal dialog is open or the key was already handled.
+ */
+function useBodyEscape(open: boolean, close: () => void) {
+ const closeRef = useRef(close)
+ closeRef.current = close
+ useEffect(() => {
+ if (!open) return
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape' || event.defaultPrevented) return
+ if (event.isComposing || event.target !== document.body) return
+ if (document.querySelector('dialog[open]')) return
+ event.preventDefault()
+ closeRef.current()
+ }
+ document.addEventListener('keydown', onKey)
+ return () => document.removeEventListener('keydown', onKey)
+ }, [open])
+}
+
/**
* The draft page once the version is ready: header, notices, tab row, the references
* panel and the shown place. Owns the navigation state, so the first tab is known at
@@ -146,6 +168,7 @@ export default function EditorWorkspace(props: Props) {
state.references.open
? nav.closeReferences()
: nav.openReferences(null, opener)
+ useBodyEscape(state.references.open, nav.closeReferences)
return (
void) {
}
/** Whether a key event happened in the editor workspace (or with nothing focused). */
-function inWorkspace(target: EventTarget | null): boolean {
+export function inWorkspace(target: EventTarget | null): boolean {
if (target === document.body) return true
return (
target instanceof Element &&
@@ -79,6 +80,9 @@ export function useEscapeDeselect(
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.isComposing || isTextField(event.target)) return
if (!inWorkspace(event.target)) return
+ // A keydown aimed at body never reaches the React root: the layers above (a modal,
+ // the phone drawer) are checked here.
+ if (document.querySelector('dialog[open]')) return
if (handler.current(event)) event.preventDefault()
}
document.addEventListener('keydown', onKey)
@@ -98,7 +102,8 @@ export function useSelectionEscape(
) {
const asideRef = useRef
(null)
const deselect = useDeselect(id, clear)
- useEscapeDeselect(active, (event) =>
+ const referencesOpen = useContext(ReferencesOpenContext)
+ useEscapeDeselect(active && !referencesOpen, (event) =>
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
)
return { asideRef, byDrawing: deselect.byDrawing }
diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts
index 77bc2548..0e98da2a 100644
--- a/apps/app/src/editor/focusRequest.ts
+++ b/apps/app/src/editor/focusRequest.ts
@@ -102,14 +102,27 @@ export function useRowFocus(focus: FocusRequest | undefined): void {
)
}
+/** Input types that take no typed text: Escape there is not the field's. */
+const NON_TEXT_INPUTS = new Set([
+ 'checkbox',
+ 'radio',
+ 'range',
+ 'button',
+ 'submit',
+ 'reset',
+ 'color',
+ 'file',
+ 'image',
+])
+
/** A field that takes typed text (or a choice): Escape there belongs to the field. */
export function isTextField(target: EventTarget | null): boolean {
+ if (target instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(target.type)
return (
- target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
(target instanceof HTMLElement &&
- target.closest('[contenteditable]') !== null)
+ target.closest('[contenteditable="true"]') !== null)
)
}
diff --git a/apps/app/tests/unit/editor-escape.test.tsx b/apps/app/tests/unit/editor-escape.test.tsx
index b9802e83..c9711f8b 100644
--- a/apps/app/tests/unit/editor-escape.test.tsx
+++ b/apps/app/tests/unit/editor-escape.test.tsx
@@ -4,12 +4,14 @@ import {
act,
cleanup,
fireEvent,
+ render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation } from '@faunosteo/core-wasm/types'
+import ModalDialog from '@/components/ui/ModalDialog'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { resetStore, serverHas, store } from '../helpers/editorHarness'
@@ -202,6 +204,53 @@ describe('Escape leaves alone', () => {
})
})
+describe('Escape with the focus on the page', () => {
+ it('a delete dialog open: the selection is kept', async () => {
+ const user = await mount()
+ await select(user)
+ await user.click(inPanel('Supprimer'))
+ expect(document.querySelector('dialog[open]')).not.toBeNull()
+ document.body.focus()
+ escape(document.body)
+ expect(panel()).toBeDefined()
+ })
+
+ it('the references panel open: it closes, the selection is kept', async () => {
+ const user = await mount()
+ await select(user)
+ const toggle = screen.getByRole('button', { name: 'Références' })
+ await user.click(toggle)
+ expect(toggle).toHaveAttribute('aria-expanded', 'true')
+ escape(document.body)
+ expect(toggle).toHaveAttribute('aria-expanded', 'false')
+ expect(panel()).toBeDefined()
+ })
+
+ it('a dialog outside the workspace open: the selection is kept', async () => {
+ const user = await mount()
+ await select(user)
+ render(
+ undefined} label="Outside">
+ Outside
+ ,
+ )
+ escape(document.body)
+ expect(panel()).toBeDefined()
+ })
+
+ it('« Plus » open, Escape in the twin filter: the menu and the field stay', async () => {
+ const user = await mount(TWO(), 500)
+ const more = screen.getByRole('button', { name: 'Plus' })
+ await user.click(more)
+ const filter = within(shown('[data-testid="annotation-overview"]')!)
+ .getByRole('searchbox', { name: 'Filtrer par nom' })
+ filter.focus()
+ escape(filter)
+ expect(more).toHaveAttribute('aria-expanded', 'true')
+ expect(document.activeElement).toBe(filter)
+ })
+})
+
describe('Escape and the other layers', () => {
it('closes the references panel from the tab row, the selection kept', async () => {
const user = await mount()
diff --git a/apps/app/tests/unit/editor-focus-request.test.tsx b/apps/app/tests/unit/editor-focus-request.test.tsx
index a233264f..41dbb6d8 100644
--- a/apps/app/tests/unit/editor-focus-request.test.tsx
+++ b/apps/app/tests/unit/editor-focus-request.test.tsx
@@ -21,6 +21,7 @@ import ReferencesPanel from '@/components/editor/references/ReferencesPanel'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import {
FocusConsumedContext,
+ isTextField,
ownedBy,
type FocusRequest,
} from '@/editor/focusRequest'
@@ -373,3 +374,28 @@ describe('a consumed request', () => {
expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull()
})
})
+
+describe('isTextField', () => {
+ const input = (type: string) => {
+ const element = document.createElement('input')
+ element.type = type
+ return element
+ }
+
+ it('is true for what takes typed text', () => {
+ for (const type of ['text', 'search', 'email']) {
+ expect(isTextField(input(type))).toBe(true)
+ }
+ expect(isTextField(document.createElement('textarea'))).toBe(true)
+ expect(isTextField(document.createElement('select'))).toBe(true)
+ })
+
+ it('is false for a checkbox, a radio, a range, a button input', () => {
+ for (const type of ['checkbox', 'radio', 'range', 'button', 'file']) {
+ expect(isTextField(input(type))).toBe(false)
+ }
+ const off = document.createElement('div')
+ off.setAttribute('contenteditable', 'false')
+ expect(isTextField(off)).toBe(false)
+ })
+})