From 085c56877c0358a926ed535b62cb05f7bb60006b Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 14 Nov 2026 14:24:06 +0100 Subject: [PATCH] fix(editor): deletion undo and Back, Plus focus to the panel --- .../e2e/shell/editor-finding-dialog.spec.ts | 25 +++++++++++ apps/app/e2e/shell/editor-more-menu.spec.ts | 14 ++++++ .../src/components/editor/EditorTabBody.tsx | 6 +++ apps/app/src/components/editor/EditorTabs.tsx | 19 +++++++- .../src/components/editor/EditorWorkspace.tsx | 13 +++++- .../components/editor/tabs/FindingsTab.tsx | 29 ++++++++++-- apps/app/src/editor/findings/tree.ts | 20 +++++++++ apps/app/src/editor/state/editorBase.ts | 5 ++- apps/app/src/editor/state/editorEdit.ts | 19 ++++++-- apps/app/src/editor/state/editorStore.ts | 7 ++- apps/app/src/editor/state/editorTypes.ts | 32 ++++++++++--- .../tests/unit/editor-finding-dialog.test.tsx | 45 +++++++++++++++++++ apps/app/tests/unit/editor-more-menu.test.tsx | 35 +++++++++++++++ apps/app/tests/unit/editor-route.test.tsx | 1 + 14 files changed, 252 insertions(+), 18 deletions(-) diff --git a/apps/app/e2e/shell/editor-finding-dialog.spec.ts b/apps/app/e2e/shell/editor-finding-dialog.spec.ts index 7c1c01a3..8fd89555 100644 --- a/apps/app/e2e/shell/editor-finding-dialog.spec.ts +++ b/apps/app/e2e/shell/editor-finding-dialog.spec.ts @@ -225,6 +225,31 @@ test.describe('finding dialog', () => { await expect(parent).toHaveAttribute('aria-selected', 'true') }) + test('after a deletion the first Back moves and one « Défaire » restores the row', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openFinding(page, dict, 'Constat A') + await inDialog(page, dict['editor.action.delete']).click() + await page + .locator('dialog[open]') + .last() + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await expectNoDialog(page) + await layerWritten(page, 'none') + await undo(page).click() + const row = page.getByRole('treeitem', { name: /Constat A/ }) + await expect(row).toBeVisible() + await expect(row).toHaveAttribute('aria-selected', 'true') + await expect(row).toBeFocused() + await page.goBack() + await expect(page.getByRole('tab', { selected: true })).toHaveText( + new RegExp(`^${dict['editor.tab.annotations']}`), + ) + }) + test('a creation is a layer: « Créer » shows the new element, a Back goes to the tree', async ({ page, }) => { diff --git a/apps/app/e2e/shell/editor-more-menu.spec.ts b/apps/app/e2e/shell/editor-more-menu.spec.ts index 60ebac69..69e7f376 100644 --- a/apps/app/e2e/shell/editor-more-menu.spec.ts +++ b/apps/app/e2e/shell/editor-more-menu.spec.ts @@ -110,6 +110,20 @@ test.describe('« Plus » dropdown', () => { await expect(list(page)).toHaveCount(0) await expect(more(page)).toHaveAttribute('aria-expanded', 'false') }) + + test('Enter on an entry focuses the panel of that tab', async ({ page }) => { + await openAt(page, 375) + await more(page).click() + await list(page) + .getByRole('button', { name: dict['editor.tab.findings'] }) + .focus() + await page.keyboard.press('Enter') + await expect(list(page)).toHaveCount(0) + const panel = page.getByRole('tabpanel', { + name: dict['editor.tab.findings'], + }) + await expect(panel).toBeFocused() + }) }) test.describe('the sidebar stays fixed', () => { diff --git a/apps/app/src/components/editor/EditorTabBody.tsx b/apps/app/src/components/editor/EditorTabBody.tsx index 95c73038..a70a2d91 100644 --- a/apps/app/src/components/editor/EditorTabBody.tsx +++ b/apps/app/src/components/editor/EditorTabBody.tsx @@ -40,6 +40,10 @@ interface Props extends EditorPlaceProps { annotations: AnnotationNav } +/** A panel takes the focus after « Plus »: the ring shows for the keyboard only. */ +const PANEL_FOCUS = + 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]' + function TabPanel({ id, active, @@ -54,6 +58,8 @@ function TabPanel({ visible={active} id={panelDomId(id)} role="tabpanel" + tabIndex={-1} + className={PANEL_FOCUS} aria-label={t(`editor.tab.${id}`)} > {Body ? ( diff --git a/apps/app/src/components/editor/EditorTabs.tsx b/apps/app/src/components/editor/EditorTabs.tsx index 85a485d2..797968fb 100644 --- a/apps/app/src/components/editor/EditorTabs.tsx +++ b/apps/app/src/components/editor/EditorTabs.tsx @@ -1,4 +1,4 @@ -import type { KeyboardEvent } from 'react' +import { useEffect, useState, type KeyboardEvent } from 'react' import { AnimatePresence, motion, @@ -147,12 +147,27 @@ function MoreList({ more, active, onPick }: MoreListProps) { ) } +/** + * The panel of a tab picked in « Plus » takes the focus once that tab is the shown one: the + * entry that held it is gone with the list, so the focus would fall to the page. + */ +function usePanelFocus(active: EditorTabId) { + const [wanted, setWanted] = useState(null) + useEffect(() => { + if (wanted === null || wanted !== active) return + document.getElementById(panelDomId(active))?.focus() + setWanted(null) + }, [wanted, active]) + return setWanted +} + /** Below 640 px: « Plus » and its dropdown of the tabs that do not fit. */ function MoreTabs({ more, active, onSelect }: MoreTabsProps) { const t = useT() const { open, close, toggle } = useMoreMenu(active) + const wantPanel = usePanelFocus(active) const pick = (tab: EditorTabId) => { - onSelect(tab) + if (onSelect(tab) !== false) wantPanel(tab) close() } useMoreDismiss(open, close) diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx index fb494704..641e6590 100644 --- a/apps/app/src/components/editor/EditorWorkspace.tsx +++ b/apps/app/src/components/editor/EditorWorkspace.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState, type ReactNode } from 'react' +import { useEffect, useMemo, useState, type ReactNode } from 'react' import { useLocation } from 'react-router-dom' import type { OfficialSheetAdmin } from '@faunosteo/supabase' import Notice from '@/components/ui/Notice' @@ -140,6 +140,16 @@ function useRestoredView(owner: HistoryOwner) { return view } +/** A step that brought a finding back shows Constats, where its row is revealed. */ +function useShowRestored(nav: EditorNavigation) { + const revealed = useEditorStore((s) => s.revealed) + const { tab } = nav.state + const { selectTab } = nav + useEffect(() => { + if (revealed && tab !== 'findings') selectTab('findings') + }, [revealed, tab, selectTab]) +} + /** * The navigation of this sheet for this account: the first tab known at mount * (`initialTab`), the view a kept entry holds, the browser history in step with it, and @@ -151,6 +161,7 @@ function useWorkspaceNavigation(sheetId: string, tier: TabTier) { const owner = useOwner(sheetId) const nav = useEditorNavigation(tab, useRestoredView(owner)) useEditorHistory(nav, owner, defaultView(tab)) + useShowRestored(nav) return { nav, left: useLeftDraft(nav, owner) } } diff --git a/apps/app/src/components/editor/tabs/FindingsTab.tsx b/apps/app/src/components/editor/tabs/FindingsTab.tsx index 74e010a7..9e87b3f5 100644 --- a/apps/app/src/components/editor/tabs/FindingsTab.tsx +++ b/apps/app/src/components/editor/tabs/FindingsTab.tsx @@ -24,6 +24,7 @@ import { useEditorStore } from '@/editor/state/editorStore' import { useSheetDocument } from '@/editor/sheetDocument' import type { EditorPlaceProps, FindingLayer } from '@/editor/tabs' import { useT } from '@/i18n/useT' +import { usePlaceVisible } from '@/lib/placeVisibility' import { useLocaleStore } from '@/state/localeStore' /** The tree as the store holds it right now (a commit is already in). */ @@ -61,8 +62,8 @@ function useFindingDeletion( const target = { key: item.key, label: item.name[locale] } setAsk({ target, fallback: fallbackAfterRemoval(items, item) }) } - // The element is gone: its dialog closes in the same move (replace, no Back step) and - // the focus lands on the nearest row once every dialog is closed, unless a newer + // The element is gone: its dialog closes in the same move, by the pop of its entry (a + // Back step that was taken, never a dead one left behind) and the focus lands on the nearest row once every dialog is closed, unless a newer // landing supersedes it. const closeDelete = () => { setAsk(null) @@ -229,13 +230,34 @@ function useLayerFollow(focus: EditorPlaceProps['focus'], ctx: TabContext) { useSelectionOfLayer(layer, items, sel.reveal) } +/** + * A step of « Défaire » or « Refaire » brought a finding back: its branch opens, its row is + * selected and takes the focus. Only the shown tab answers; the workspace shows it first. + */ +function useRevealRestored(items: readonly FindingItem[], ctx: TabContext) { + const revealed = useEditorStore((s) => s.revealed) + const visible = usePlaceVisible() + const { sel, land } = ctx + const reveal = useRef({ sel, land }) + reveal.current = { sel, land } + useEffect(() => { + if (!revealed || !visible) return + const found = itemForKey(items, revealed.key) + if (found) { + reveal.current.sel.reveal(found) + reveal.current.land(found.item.id) + } + useEditorStore.getState().clearRevealed() + }, [revealed, visible, items]) +} + /** What the tab does with the layer: creation, a row's dialog, deletion. */ function useFindingActions(ctx: TabContext) { const { layer, sel } = ctx const deletion = useFindingDeletion(ctx.items, sel.selectedId, { select: sel.select, focusItem: ctx.land, - closeLayer: () => layer.replace(null), + closeLayer: () => void layer.close(true), }) const created = ( id: string, @@ -273,6 +295,7 @@ function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) { const ctx = { layer, items: data.items, sel, land: landing.land } useLayerFollow(focus, ctx) useGoneRule(layer, data.doc !== null) + useRevealRestored(data.items, ctx) return { ...data, sel, diff --git a/apps/app/src/editor/findings/tree.ts b/apps/app/src/editor/findings/tree.ts index ff3bcd33..eeef6251 100644 --- a/apps/app/src/editor/findings/tree.ts +++ b/apps/app/src/editor/findings/tree.ts @@ -180,6 +180,26 @@ export function buildItems(doc: AnatomicalSheetDocument): FindingItem[] { }) } +function itemsOfText(text: string): FindingItem[] { + try { + return buildItems(JSON.parse(text)) + } catch { + return [] + } +} + +/** + * The first element `after` holds that `before` lacked (document order, so the top of a + * restored branch): what a step brought back. null when the step added none. + */ +export function appearedFinding( + before: string, + after: string, +): ElementKey | null { + const known = new Set(itemsOfText(before).map((item) => item.id)) + return itemsOfText(after).find((item) => !known.has(item.id))?.key ?? null +} + /** The items whose ancestors are all expanded. */ export function visibleItems( items: readonly FindingItem[], diff --git a/apps/app/src/editor/state/editorBase.ts b/apps/app/src/editor/state/editorBase.ts index 9916c591..3374198e 100644 --- a/apps/app/src/editor/state/editorBase.ts +++ b/apps/app/src/editor/state/editorBase.ts @@ -14,6 +14,7 @@ export function initialData(): EditorData { preview: null, previewState: null, handleVersion: 0, + revealed: null, documentText: '', savedText: '', savedRevision: 0, @@ -51,7 +52,9 @@ export function blockKind(state: EditorState): BlockKind | null { } /** The handle of a state that accepts document changes, else the reason it does not. */ -export function editablePreview(state: EditorState): CataloguePreview | BlockKind { +export function editablePreview( + state: EditorState, +): CataloguePreview | BlockKind { return blockKind(state) ?? state.preview ?? 'not_ready' } diff --git a/apps/app/src/editor/state/editorEdit.ts b/apps/app/src/editor/state/editorEdit.ts index 12d99b71..b6353038 100644 --- a/apps/app/src/editor/state/editorEdit.ts +++ b/apps/app/src/editor/state/editorEdit.ts @@ -10,6 +10,7 @@ import type { EditorState, StoreApi, } from './editorTypes' +import { appearedFinding } from '../findings/tree' import { recordCommit, stepBack, stepForward, type History } from './undo' function blocked(kind: BlockKind): CommitOutcome { @@ -68,7 +69,10 @@ export function commit( return commitBatch(api, [command], accept) } -export function stepHistory(api: StoreApi, direction: 'undo' | 'redo'): CommitOutcome { +export function stepHistory( + api: StoreApi, + direction: 'undo' | 'redo', +): CommitOutcome { const state = api.get() const preview = editablePreview(state) if (typeof preview === 'string') return blocked(preview) @@ -77,12 +81,17 @@ export function stepHistory(api: StoreApi, direction: 'undo' | 'redo'): CommitOu if (!step) return blocked('empty') const replaced = preview.replaceDocument(step.text) if (!replaced.ok) return replaced - api.set(replacedPatch(state, step.text, replaced.state, step.history)) + const patch = replacedPatch(state, step.text, replaced.state, step.history) + const key = appearedFinding(state.documentText, step.text) + api.set(key ? { ...patch, revealed: { key } } : patch) return { ok: true } } /** A drawing the core accepted becomes part of the handle (and of the copy's list). */ -export function addDrawing(api: StoreApi, drawing: AddedDrawing): CommitOutcome { +export function addDrawing( + api: StoreApi, + drawing: AddedDrawing, +): CommitOutcome { const state = api.get() const preview = editablePreview(state) if (typeof preview === 'string') return blocked(preview) @@ -92,7 +101,9 @@ export function addDrawing(api: StoreApi, drawing: AddedDrawing): CommitOutcome const entry = { asset_id: drawing.assetId, sha256: drawing.sha256 } const others = state.drawings.filter((d) => d.asset_id !== entry.asset_id) const failures = Object.fromEntries( - Object.entries(state.drawingFailures).filter(([id]) => id !== entry.asset_id), + Object.entries(state.drawingFailures).filter( + ([id]) => id !== entry.asset_id, + ), ) api.set({ drawings: [...others, entry], diff --git a/apps/app/src/editor/state/editorStore.ts b/apps/app/src/editor/state/editorStore.ts index a1e3218b..3e413704 100644 --- a/apps/app/src/editor/state/editorStore.ts +++ b/apps/app/src/editor/state/editorStore.ts @@ -26,9 +26,11 @@ export const useEditorStore = create()((set, get) => { close: () => close(api), setCanEdit: (canEdit) => setCanEdit(api, canEdit), commit: (command, options) => commit(api, command, options?.accept), - commitBatch: (commands, options) => commitBatch(api, commands, options?.accept), + commitBatch: (commands, options) => + commitBatch(api, commands, options?.accept), undoStep: () => stepHistory(api, 'undo'), redoStep: () => stepHistory(api, 'redo'), + clearRevealed: () => set({ revealed: null }), addDrawing: (drawing) => addDrawing(api, drawing), discardChanges: (option) => discardChanges(api, option), reloadServerDraft: (option) => reloadServerDraft(api, option), @@ -39,7 +41,8 @@ export const useEditorStore = create()((set, get) => { dismissConflict: () => set({ conflict: null }), restoreCopy: () => restoreCopy(api), ignoreCopy: (option) => ignoreCopy(api, option), - abandonOtherCopy: (versionId, option) => abandonOtherCopy(api, versionId, option), + abandonOtherCopy: (versionId, option) => + abandonOtherCopy(api, versionId, option), retryCopyWrite: () => syncCopy(api), } }) diff --git a/apps/app/src/editor/state/editorTypes.ts b/apps/app/src/editor/state/editorTypes.ts index 4d5f3d2d..52beb2f1 100644 --- a/apps/app/src/editor/state/editorTypes.ts +++ b/apps/app/src/editor/state/editorTypes.ts @@ -1,5 +1,9 @@ import type { CoreFailure } from '@faunosteo/core-wasm' -import type { EditCommand, PreviewState } from '@faunosteo/core-wasm/types' +import type { + EditCommand, + ElementKey, + PreviewState, +} from '@faunosteo/core-wasm/types' import type { SheetAdminPerson, SheetFailureKind } from '@faunosteo/supabase' import type { CataloguePreview, Acceptance } from '@/catalogue/preview' import type { CatalogueFailure } from '@/catalogue/failure' @@ -48,10 +52,20 @@ export interface LoadRefusal { failure: CatalogueFailure } -export type CommitOutcome = { ok: true } | Blocked | CoreRefusal | Refused +export type CommitOutcome = + | { ok: true } + | Blocked + | CoreRefusal + | Refused export type ActionOutcome = { ok: true } | Blocked | CoreRefusal | LoadRefusal -export type SaveOutcome = { ok: true; revision: number } | Blocked | ServerRefusal -export type SubmitOutcome = { ok: true; reviewId: string } | Blocked | ServerRefusal +export type SaveOutcome = + | { ok: true; revision: number } + | Blocked + | ServerRefusal +export type SubmitOutcome = + | { ok: true; reviewId: string } + | Blocked + | ServerRefusal /** A drawing the handle holds. */ export interface DrawingEntry { @@ -110,6 +124,8 @@ export interface EditorData { previewState: PreviewState | null /** Bumped by every accepted replacement and added drawing (canvas rebuild signal). */ handleVersion: number + /** The finding a « Défaire » or « Refaire » brought back: Constats shows it, then clears. */ + revealed: { key: ElementKey } | null documentText: string savedText: string savedRevision: number @@ -144,7 +160,11 @@ export interface ConfirmOption { export interface EditorActions { /** Starts a session and loads the version; returns its token at once. */ - open(versionId: string, userId: string, options?: { canEdit?: boolean }): number + open( + versionId: string, + userId: string, + options?: { canEdit?: boolean }, + ): number close(): void setCanEdit(canEdit: boolean): void commit( @@ -158,6 +178,8 @@ export interface EditorActions { ): CommitOutcome undoStep(): CommitOutcome redoStep(): CommitOutcome + /** Constats has shown the finding the last step brought back. */ + clearRevealed(): void addDrawing(drawing: AddedDrawing): CommitOutcome discardChanges(option: ConfirmOption): Promise reloadServerDraft(option: ConfirmOption): Promise diff --git a/apps/app/tests/unit/editor-finding-dialog.test.tsx b/apps/app/tests/unit/editor-finding-dialog.test.tsx index 733915d0..f58596a7 100644 --- a/apps/app/tests/unit/editor-finding-dialog.test.tsx +++ b/apps/app/tests/unit/editor-finding-dialog.test.tsx @@ -165,6 +165,51 @@ describe('opening', () => { }) }) +/** Deletes the open dialog's element through its confirmation. */ +async function deleteOpen(user: User) { + await user.click(inDialog().getByRole('button', { name: 'Supprimer' })) + const confirm = await screen.findAllByRole('button', { name: 'Supprimer' }) + await user.click(confirm[confirm.length - 1]) + await closed() +} + +describe('deleting (owner item 3)', () => { + it('closes the dialog by popping its entry: the first Back moves', async () => { + const user = await mount() + await openFinding(user, /Node A/) + await deleteOpen(user) + expect(written()?.view.finding).toBeNull() + expect(written()?.view.tab).toBe('findings') + await back() + await waitFor(() => expect(written()?.view.tab).not.toBe('findings')) + }) + + it('one « Défaire » restores the row, selected, shown and focused', async () => { + const user = await mount() + await openFinding(user, /Node A/) + await deleteOpen(user) + expect(screen.queryByRole('treeitem', { name: /Node A/ })).toBeNull() + await user.click(screen.getByRole('button', { name: /^Défaire/ })) + const row = await screen.findByRole('treeitem', { name: /Node A/ }) + expect(row).toHaveAttribute('aria-selected', 'true') + await waitFor(() => expect(row).toHaveFocus()) + }) + + it('« Refaire » of a creation shows its row the same way', async () => { + const user = await mount() + await openFinding(user, /Node A/) + await deleteOpen(user) + await user.click(screen.getByRole('button', { name: /^Défaire/ })) + await user.click(screen.getByRole('button', { name: /^Refaire/ })) + await waitFor(() => + expect(screen.queryByRole('treeitem', { name: /Node A/ })).toBeNull(), + ) + await user.click(screen.getByRole('button', { name: /^Défaire/ })) + const row = await screen.findByRole('treeitem', { name: /Node A/ }) + await waitFor(() => expect(row).toHaveFocus()) + }) +}) + describe('edit mode', () => { it('a pristine « Enregistrer » is no command and no entry; a changed one is one', async () => { const user = await mount() diff --git a/apps/app/tests/unit/editor-more-menu.test.tsx b/apps/app/tests/unit/editor-more-menu.test.tsx index 70bbaab9..d9c0ad4d 100644 --- a/apps/app/tests/unit/editor-more-menu.test.tsx +++ b/apps/app/tests/unit/editor-more-menu.test.tsx @@ -41,6 +41,12 @@ function Page({ >
+