feat(editor): cancel adding a reference by button or Escape

Draft tile gets « Annuler l'ajout »; Escape cancels from non-text targets and
from a pristine text field, never while composing or already handled. Nothing
reaches the document, history untouched, focus back on the add button.
This commit is contained in:
bchanot committed 2026-11-13 12:39:57 +01:00
1 parent 1e19479853
commit d1779928a9
10 files changed
+1138 -524

No files matched your search

@@ -9,6 +9,7 @@ import {
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
editorActor,
historyButton,
libraryRoot,
openEditor,
openTab,
@@ -419,6 +420,47 @@ test.describe('reference tiles, search, sort and add', () => {
await expect(libraryRoot(page).getByText('Étude')).toHaveCount(0)
})
test("« Annuler l'ajout » and Escape drop the draft and write nothing", async ({
page,
requests,
}) => {
test.setTimeout(150_000)
const { actor } = await open(page, sortShape)
requests.forbid(actor.account.email, actor.account.password)
await openTab(page, dict, 'references')
const root = libraryRoot(page)
const add = root.getByRole('button', {
name: dict['editor.references.add'],
})
const count = await headers(page).count()
const states = async () => [
await historyButton(page, dict, 'undo').isEnabled(),
await historyButton(page, dict, 'redo').isEnabled(),
]
const before = await states()
const draft = root.getByRole('region', {
name: dict['editor.reference.new'],
})
const type = root.getByLabel(dict['editor.reference.type'])
await add.click()
await type.selectOption('manual')
await root.getByLabel(dict['editor.reference.citation']).fill('Brouillon')
await root
.getByRole('button', { name: dict['editor.references.add_cancel'] })
.click()
await expect(draft).toHaveCount(0)
await expect(headers(page)).toHaveCount(count)
await expect(add).toBeFocused()
expect(await states()).toEqual(before)
await add.click()
await type.focus()
await page.keyboard.press('Escape')
await expect(draft).toHaveCount(0)
await expect(headers(page)).toHaveCount(count)
await expect(add).toBeFocused()
expect(await states()).toEqual(before)
})
test('a tile in edit keeps its place under a sort and under a search', async ({
page,
requests,
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'
import { useEffect, useState, type KeyboardEvent } from 'react'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
@@ -17,14 +17,27 @@ interface Props {
focusSerial: number
/** The reference was created in one modification, under this id. */
onAdded: (id: string) => void
/** « Annuler l'ajout »: the draft goes, nothing was written. */
onCancel: () => void
}
const isTextTarget = (target: EventTarget) =>
target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement
const isPristine = (form: typeof EMPTY) =>
Object.values(form).every((v) => v === '')
const isComposing = (event: KeyboardEvent) =>
event.nativeEvent.isComposing || event.keyCode === 229
/**
* The draft tile of « Ajouter une référence » (board 24 E): type « Choisir… » and citation
* required, DOI and URL optional. Nothing reaches the document before « Ajouter la
* référence », which inserts the reference as one modification.
*/
export default function NewReferenceTile({ focusSerial, onAdded }: Props) {
export default function NewReferenceTile({
focusSerial,
onAdded,
onCancel,
}: Props) {
const t = useT()
const edit = useEditCommand()
const [form, setForm] = useState(EMPTY)
@@ -63,9 +76,18 @@ export default function NewReferenceTile({ focusSerial, onAdded }: Props) {
})
if (added) onAdded(created)
}
// Escape cancels from anywhere in the tile; a text field with typed text keeps it.
const escape = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (isComposing(event)) return
if (isTextTarget(event.target) && !isPristine(form)) return
event.preventDefault()
onCancel()
}
return (
<section
aria-label={t('editor.reference.new')}
onKeyDown={escape}
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
>
<div className="flex items-center gap-3 p-3">
@@ -110,6 +132,9 @@ export default function NewReferenceTile({ focusSerial, onAdded }: Props) {
<ActionButton readOnly={false} variant="primary" onClick={create}>
{t('editor.reference.add')}
</ActionButton>
<ActionButton readOnly={false} variant="secondary" onClick={onCancel}>
{t('editor.references.add_cancel')}
</ActionButton>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.add_help')}
</p>
@@ -6,6 +6,7 @@ import Select from '@/components/ui/Select'
import { usePlural } from '@/editor/plural'
import { REFERENCE_SORTS, type ReferenceSort } from '@/editor/references/sort'
import { useT } from '@/i18n/useT'
import { ADD_BUTTON_ID } from './addButton'
interface Props {
query: string
@@ -90,6 +91,7 @@ export default function ReferenceToolbar(props: Props) {
<div className="flex flex-wrap items-center justify-between gap-3">
<CountLine shown={props.shown} total={props.total} />
<ActionButton
id={ADD_BUTTON_ID}
readOnly={!props.canAdd}
variant="secondary"
size="sm"
@@ -0,0 +1,2 @@
/** The add button's id: « Annuler l'ajout » gives it the focus back. */
export const ADD_BUTTON_ID = 'tab-reference-add'
@@ -10,6 +10,7 @@ import { referenceMatches } from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import { tileKeys, useTileState } from './useTileState'
import { useReferenceView } from './useReferenceView'
import { ADD_BUTTON_ID } from './addButton'
const NO_CITERS = new Map<string, never[]>()
@@ -95,6 +96,11 @@ export function useReferenceActions(
tiles.reveal(`${id}#0`)
later({ kind: 'reference', id })
},
// C2: nothing was written; the search and sort reset by the add stay as they are.
cancelAdd: () => {
setDraft(null)
document.getElementById(ADD_BUTTON_ID)?.focus()
},
edit: (position: number) => {
if (tiles.startEdit(keys[position])) shown.markEdited(keys[position])
},
@@ -86,7 +86,11 @@ function Library({ readOnly, navigate, focus, resetSignal }: Props) {
/>
<EditOnly readOnly={readOnly}>
{act.draft !== null && (
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
<NewReferenceTile
focusSerial={act.draft}
onAdded={act.added}
onCancel={act.cancelAdd}
/>
)}
</EditOnly>
</>
+435 -252
View File
File diff suppressed because it is too large. Load diff
+491 -269
View File
File diff suppressed because it is too large. Load diff
@@ -351,6 +351,133 @@ describe('adding a reference', () => {
})
})
describe("« Annuler l'ajout » (C2)", () => {
const addButton = () =>
within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' })
const field = (id: string) =>
tabPanel().querySelector<HTMLElement>(`#tab-reference-new-${id}`)!
const draftTile = () =>
within(tabPanel()).queryByLabelText('Nouvelle référence')
const cancelButton = () =>
within(tabPanel()).getByRole('button', { name: "Annuler l'ajout" })
const history = () => ({
undo: store.getState().undo.length,
redo: store.getState().redo.length,
})
const refs = () => JSON.parse(store.getState().documentText).references
/** One real change undone, so a redo is pending; then the draft is opened. */
async function openWithPendingRedo() {
const user = await mount()
await startEditAndType(user)
act(() => store.getState().undoStep())
await user.click(addButton())
return user
}
async function startEditAndType(user: User) {
await user.click(header('Barone, Ostéologie'))
const item = header('Barone, Ostéologie').closest('li')!
await user.click(within(item).getByRole('button', { name: 'Modifier' }))
await user.type(within(item).getByLabelText('DOI'), '10.1/x')
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
}
function expectCancelled(before: { refs: unknown; history: object }) {
expect(draftTile()).toBeNull()
expect(refs()).toEqual(before.refs)
expect(history()).toEqual(before.history)
expect(document.activeElement).toBe(addButton())
}
const snapshot = () => ({ refs: refs(), history: history() })
it('the button removes the tile, writes nothing, keeps a pending redo', async () => {
const user = await openWithPendingRedo()
expect(history().redo).toBe(1)
const before = snapshot()
await user.click(cancelButton())
expectCancelled(before)
})
it('Escape on the type select and on a button does the same', async () => {
const user = await openWithPendingRedo()
const before = snapshot()
await user.type(field('citation'), 'Brouillon')
fireEvent.keyDown(field('type'), { key: 'Escape' })
expectCancelled(before)
await user.click(addButton())
await user.type(field('citation'), 'Brouillon')
fireEvent.keyDown(cancelButton(), { key: 'Escape' })
expectCancelled(before)
})
it('Escape in a field cancels while the form is pristine, not once typed', async () => {
const user = await openWithPendingRedo()
const before = snapshot()
fireEvent.keyDown(field('citation'), { key: 'Escape' })
expectCancelled(before)
await user.click(addButton())
await user.type(field('citation'), 'Brouillon')
fireEvent.keyDown(field('citation'), { key: 'Escape' })
expect(draftTile()).not.toBeNull()
expect(field('citation')).toHaveValue('Brouillon')
})
it('Escape while composing, or already handled, does nothing', async () => {
const user = await mount()
await user.click(addButton())
fireEvent.keyDown(field('type'), { key: 'Escape', isComposing: true })
fireEvent.keyDown(field('type'), { key: 'Escape', keyCode: 229 })
expect(draftTile()).not.toBeNull()
const handled = new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
})
handled.preventDefault()
act(() => void field('type').dispatchEvent(handled))
expect(draftTile()).not.toBeNull()
})
it('Escape that cancels is marked handled', async () => {
const user = await mount()
await user.click(addButton())
const event = new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
})
act(() => void field('type').dispatchEvent(event))
expect(event.defaultPrevented).toBe(true)
})
it('goes with its refusal message, and a new add starts from an empty form', async () => {
const user = await mount()
await user.click(addButton())
await user.type(field('citation'), 'Brouillon')
await user.click(
within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }),
)
expect(within(tabPanel()).getByRole('alert')).toBeInTheDocument()
await user.click(cancelButton())
expect(within(tabPanel()).queryByRole('alert')).toBeNull()
await user.click(addButton())
expect(field('citation')).toHaveValue('')
expect(field('type')).toHaveValue('')
expect(within(tabPanel()).queryByRole('alert')).toBeNull()
})
it('« Défaire » after a cancel undoes the previous real change', async () => {
const user = await mount()
await startEditAndType(user)
expect(history().undo).toBe(1)
await user.click(addButton())
await user.click(cancelButton())
expect(history().undo).toBe(1)
act(() => store.getState().undoStep())
expect(history()).toEqual({ undo: 0, redo: 1 })
expect(refs()[0].doi).toBeNull()
})
})
const tile = (citation: string) => header(citation).closest('li')!
const doc = () => JSON.parse(store.getState().documentText)
+1
View File
@@ -45,6 +45,7 @@ Règles de lecture :
| `editor.references.delete_hint` | Pour supprimer cette référence, retirez d'abord chacune de ses citations : « Aller à », puis « Retirer » dans le détail du constat ou de la famille. | To delete this reference, first remove each of its citations: “Go to”, then “Remove” in the finding's or family's detail. | Tuile ouverte d'une référence citée, à la place de « Supprimer » | nouveau | Cite deux libellés existants : « Aller à » et « Retirer ». |
| `editor.references.add` | Ajouter une référence | Add a reference | Onglet Références, barre d'outils, bouton | nouveau | |
| `editor.references.add_help` | Type et citation obligatoires. | Type and citation required. | Tuile d'ajout, aide sous le formulaire | nouveau | |
| `editor.references.add_cancel` | Annuler l'ajout | Cancel adding (provisional) | Tuile d'ajout, bouton secondaire après « Ajouter la référence » ; Échap fait de même | nouveau | Rien n'est écrit dans le document. |
| `editor.references.clear_search` | Effacer la recherche | Clear the search | Barre d'outils (bouton ✕) et état sans résultat | nouveau | |
| `editor.references.sort_by` | Trier par | Sort by | Barre d'outils, étiquette du sélecteur de tri | nouveau | |
| `editor.references.sort.sheet` | Ordre de la fiche | Sheet order | Barre d'outils, option de tri | nouveau | Seul tri où « Monter » et « Descendre » agissent. |