fix(app): focus the shown tab after a crossing, one commit per typed field

- A field blurred by a 1 024 px crossing or a read-only switch hands its
  focus to the shown tab (or Plus), never to body (focusRequest, useViewport).
- TextField no longer commits a blurred value twice when it unmounts before
  the render that brings the new value: one undo step, one count.
- Annuler and Retablir share the field left by Tab, so Shift+Tab to Annuler
  and Enter still skips the undo of a refused field.
- Adding a reference clears the finding filter and the search.

Unit tests: no-loss (focus on tab and on Plus, one undo entry), history
buttons (field kept across the pair), references panel (add clears, refused
add keeps).
This commit is contained in:
bchanot committed 2026-11-08 20:23:40 +01:00
1 parent 9c03cf2413
commit 0bb150f860
9 files changed
+149 -29

No files matched your search

@@ -1,4 +1,4 @@
import { useRef, type FocusEvent } from 'react'
import { useRef, type FocusEvent, type RefObject } from 'react'
import { useEditorReadOnly } from '@/editor/editingContext'
import { commitFocusedField } from '@/editor/focusRequest'
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
@@ -32,13 +32,22 @@ function asField(element: Element | EventTarget | null): HTMLElement | null {
* The press, in two steps: leaving a field commits the typed text (its blur: forced at
* pointer-down, natural when Tab reaches the button), the click or key then reads the
* store, so the typed text is the last change the undo reverts. A field whose commit was
* refused keeps its error: the step is skipped and focus goes back to it.
* refused keeps its error: the step is skipped and focus goes back to it. The field is
* remembered across the pair: from a field, « Annuler » is two Shift+Tab away.
*/
function usePress(direction: Direction, readOnly: boolean) {
const left = useRef<HTMLElement | null>(null)
function usePress(
direction: Direction,
readOnly: boolean,
left: RefObject<HTMLElement | null>,
) {
const forget = () => {
left.current = null
}
// Tab from « Rétablir » to « Annuler » (or back) is still the same press of the pair.
const onBlur = (event: FocusEvent<HTMLElement>) => {
const pair = event.currentTarget.parentElement
if (!pair?.contains(event.relatedTarget as Node | null)) forget()
}
const onPointerDown = () => {
left.current = asField(document.activeElement)
commitFocusedField()
@@ -62,18 +71,24 @@ function usePress(direction: Direction, readOnly: boolean) {
return {
onPointerDown,
onFocus,
onBlur: forget,
onBlur,
onPointerLeave: forget,
onClick,
}
}
function HistoryButton({ direction }: { direction: Direction }) {
function HistoryButton({
direction,
left,
}: {
direction: Direction
left: RefObject<HTMLElement | null>
}) {
const t = useT()
const readOnly = useEditorReadOnly()
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const name = t(`editor.history.${direction}_title`)
const press = usePress(direction, readOnly)
const press = usePress(direction, readOnly, left)
return (
<button
type="button"
@@ -94,13 +109,14 @@ function HistoryButton({ direction }: { direction: Direction }) {
/** « Annuler » and « Rétablir », at the right of the tab row on every tab. */
export default function HistoryButtons() {
const left = useRef<HTMLElement | null>(null)
return (
<div
className="ml-auto flex items-center gap-1"
data-testid="history-buttons"
>
<HistoryButton direction="undo" />
<HistoryButton direction="redo" />
<HistoryButton direction="undo" left={left} />
<HistoryButton direction="redo" left={left} />
</div>
)
}
@@ -75,7 +75,10 @@ function EditableText({
const commit = () => {
const next = trim ? draft.trim() : draft
if (next !== draft) setDraft(next)
if (next !== value) onCommit(next)
if (next === value) return
// The unmount cleanup runs before a render brings the new value: it must not commit twice.
latest.current.value = next
onCommit(next)
}
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) commit()
@@ -10,8 +10,11 @@ import { REFERENCE_TYPES } from './referenceTypes'
const EMPTY = { type: '', citation: '', url: '', doi: '' }
/** Adds a reference: the type and the citation are required, URL and DOI optional. */
export default function ReferenceForm() {
/**
* Adds a reference: the type and the citation are required, URL and DOI optional.
* `onAdded` runs after a successful add, so the list can show the new reference.
*/
export default function ReferenceForm({ onAdded }: { onAdded?: () => void }) {
const t = useT()
const edit = useEditCommand()
const [form, setForm] = useState(EMPTY)
@@ -41,7 +44,9 @@ export default function ReferenceForm() {
},
},
}))
if (added) setForm(EMPTY)
if (!added) return
setForm(EMPTY)
onAdded?.()
}
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
@@ -225,6 +225,11 @@ export default function ReferencesPanel(props: Props) {
onShowAll?.()
searchRef.current?.focus()
}
// A new reference is neither cited by the filtered finding nor named by the search.
const showAdded = () => {
setQuery('')
if (citedBy !== null) onShowAll?.()
}
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
event.stopPropagation()
@@ -265,7 +270,7 @@ export default function ReferencesPanel(props: Props) {
}
/>
<EditOnly readOnly={readOnly}>
<ReferenceForm />
<ReferenceForm onAdded={showAdded} />
</EditOnly>
</>
)}
+22 -12
View File
@@ -5,7 +5,7 @@ import type {
EditorTarget,
FocusRequest,
} from './navigation'
import type { EditorTabId } from './tabs'
import { MORE_BUTTON_ID, type EditorTabId } from './tabs'
export type { FocusRequest }
@@ -105,25 +105,35 @@ export function useRowFocus(focus: FocusRequest | undefined): void {
/**
* 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,
* so the blur is forced rather than assumed.
* so the blur is forced rather than assumed. Answers whether a field was blurred.
*/
export function commitFocusedField(): void {
export function commitFocusedField(): boolean {
const active = document.activeElement
if (
const isField =
active instanceof HTMLInputElement ||
active instanceof HTMLTextAreaElement ||
active instanceof HTMLSelectElement
) {
active.blur()
}
if (isField) active.blur()
return isField
}
/** The tab shown, or « Plus » while the shown tab sits in the closed list. */
function activeTabButton(): HTMLElement | null {
return (
document.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]') ??
document.getElementById(MORE_BUTTON_ID)
)
}
/** Gives the focus to the shown tab's button: a field that lost the focus must not leave `body`. */
export function focusActiveTab(): void {
activeTabButton()?.focus()
}
/**
* The editor turned read-only: commits the text being typed, then releases any focus left
* inside a hidden part, so no field is focused in a place that left the page.
* The editor turned read-only: commits the text being typed; the field that held the focus
* sits in a part that is now hidden, so the focus goes to the shown tab, never to `body`.
*/
export function releaseEditFocus(): void {
commitFocusedField()
const active = document.activeElement
if (active instanceof HTMLElement && active.closest('[hidden]')) active.blur()
if (commitFocusedField()) focusActiveTab()
}
+12 -3
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react'
import { commitFocusedField } from './focusRequest'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { commitFocusedField, focusActiveTab } from './focusRequest'
import { MIN_EDIT_WIDTH } from './mode'
/** The tab lists of board 05: all, the four of 640 px and over, the two below. */
@@ -21,12 +21,15 @@ function crossesEditWidth(from: TabTier, to: TabTier): boolean {
export function useTabTier(): TabTier {
const [tier, setTier] = useState<TabTier>(() => tierOf(window.innerWidth))
const previous = useRef(tier)
const lostFocus = useRef(false)
useEffect(() => {
const update = () => {
const next = tierOf(window.innerWidth)
// The typed text is committed before the editor turns read-only (or back): a blur
// after the hide would be too late, a hidden field keeps no focus event.
if (crossesEditWidth(previous.current, next)) commitFocusedField()
if (crossesEditWidth(previous.current, next)) {
lostFocus.current = commitFocusedField()
}
previous.current = next
setTier(next)
}
@@ -34,5 +37,11 @@ export function useTabTier(): TabTier {
window.addEventListener('resize', update)
return () => window.removeEventListener('resize', update)
}, [])
// The tab row of the new tier is rendered: the blurred field's focus goes to the shown tab.
useLayoutEffect(() => {
if (!lostFocus.current) return
lostFocus.current = false
focusActiveTab()
}, [tier])
return tier
}
@@ -269,6 +269,26 @@ describe('typed text and the press', () => {
expect(store.getState().undo).toHaveLength(1)
})
it('a field left through « Rétablir » to « Annuler » still skips the undo', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const field = await selectAnnotation(user)
await user.clear(field)
field.blur()
const redo = screen.getByRole('button', {
name: 'Rétablir la dernière modification annulée',
})
act(() => redo.focus())
fireEvent.focus(redo, { relatedTarget: field })
act(() => undoButton().focus())
fireEvent.focus(undoButton(), { relatedTarget: redo })
await user.keyboard('{Enter}')
expect(field).toHaveFocus()
expect(store.getState().undo).toHaveLength(1)
})
it('Ctrl+Z is ignored while a DeleteDialog is open', async () => {
mountDraft()
await ready()
@@ -245,9 +245,27 @@ describe('the guards of a width change', () => {
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 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 () => {
@@ -282,3 +282,37 @@ describe('« Aller à » a reference', () => {
)
})
})
describe('adding a reference', () => {
async function add(user: ReturnType<typeof userEvent.setup>) {
const byId = (id: string) => panel().querySelector<HTMLElement>(id)!
await user.selectOptions(byId('#reference-new-type'), 'book')
await user.type(byId('#reference-new-citation'), 'Nouvelle source')
await user.click(
within(panel()).getByRole('button', { name: 'Ajouter la référence' }),
)
}
it('clears the finding filter and the search so the new reference shows', async () => {
const user = await mount()
await openFromFinding(user)
await user.type(search(), 'Barone')
expect(cards()).toHaveLength(1)
await add(user)
expect(search()).toHaveValue('')
expect(within(panel()).queryByTestId('references-filter-chip')).toBeNull()
expect(cards()).toHaveLength(4)
expect(within(panel()).getByText('Nouvelle source')).toBeInTheDocument()
})
it('a refused add keeps the filter and the search', async () => {
const user = await mount()
await openFromFinding(user)
await user.type(search(), 'Barone')
await user.click(
within(panel()).getByRole('button', { name: 'Ajouter la référence' }),
)
expect(search()).toHaveValue('Barone')
expect(within(panel()).getByTestId('references-filter-chip')).toBeInTheDocument()
})
})