fix(editor): deletion undo and Back, Plus focus to the panel

This commit is contained in:
bchanot committed 2026-11-14 14:24:06 +01:00
1 parent 270444e2ec
commit 085c56877c
14 files changed
+252 -18

No files matched your search

@@ -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,
}) => {
@@ -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', () => {
@@ -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 ? (
+17 -2
View File
@@ -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<EditorTabId | null>(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)
@@ -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) }
}
@@ -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,
+20
View File
@@ -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[],
+4 -1
View File
@@ -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'
}
+15 -4
View File
@@ -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<never> {
@@ -68,7 +69,10 @@ export function commit<R>(
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],
+5 -2
View File
@@ -26,9 +26,11 @@ export const useEditorStore = create<EditorState>()((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<EditorState>()((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),
}
})
+27 -5
View File
@@ -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<R = never> = { ok: true } | Blocked | CoreRefusal | Refused<R>
export type CommitOutcome<R = never> =
| { ok: true }
| Blocked
| CoreRefusal
| Refused<R>
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<R = never>(
@@ -158,6 +178,8 @@ export interface EditorActions {
): CommitOutcome<R>
undoStep(): CommitOutcome
redoStep(): CommitOutcome
/** Constats has shown the finding the last step brought back. */
clearRevealed(): void
addDrawing(drawing: AddedDrawing): CommitOutcome
discardChanges(option: ConfirmOption): Promise<ActionOutcome>
reloadServerDraft(option: ConfirmOption): Promise<ActionOutcome>
@@ -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()
@@ -41,6 +41,12 @@ function Page({
>
<div data-editor-workspace>
<EditorTabs active={active} tier="small" onSelect={setActive} />
<div
id={`editor-panel-${active}`}
role="tabpanel"
tabIndex={-1}
aria-label={active}
/>
<button type="button">outside</button>
</div>
<button type="button" onClick={() => setActive('general')}>
@@ -91,6 +97,35 @@ describe('the overlay', () => {
})
})
describe('the panel takes the focus after a pick', () => {
it('Enter on an entry focuses the panel of that tab once the list is gone', async () => {
const { user } = mount()
await user.click(more())
screen.getByRole('button', { name: 'Constats' }).focus()
await user.keyboard('{Enter}')
await gone()
expect(document.activeElement).toBe(
document.getElementById('editor-panel-findings'),
)
})
it('a pointer pick does the same', async () => {
const { user } = mount()
await user.click(more())
await user.click(screen.getByRole('button', { name: 'Constats' }))
expect(document.activeElement).toBe(
document.getElementById('editor-panel-findings'),
)
})
it('Escape still returns the focus to « Plus »', async () => {
const { user } = mount()
await user.click(more())
await user.keyboard('{Escape}')
expect(document.activeElement).toBe(more())
})
})
describe('the render-time reset', () => {
it('a new active tab closes the open menu with no click in the row', async () => {
const { user, force } = mount()
@@ -143,6 +143,7 @@ describe('tabs', () => {
expect(screen.getByTestId('editor-tab-findings')).toBeInTheDocument()
expect(screen.getByTestId('editor-tab-annotations')).not.toBeVisible()
expect(screen.getByRole('tabpanel')).toHaveAccessibleName('Constats')
expect(screen.getByRole('tabpanel')).toHaveAttribute('tabindex', '-1')
})
it('640 to 1 023 px: the five tabs, no « Plus », the row may wrap', async () => {