feat(editor): the held reason shows in a bubble by its button

This commit is contained in:
bchanot committed 2026-11-19 20:50:56 +01:00
1 parent 031826dced
commit 49f0144729
11 files changed
+313 -79

No files matched your search

+61 -8
View File
@@ -1,5 +1,5 @@
import { fr } from '@/i18n/fr'
import type { Page, TestInfo } from '@playwright/test'
import type { Locator, Page, TestInfo } from '@playwright/test'
import { expect, expectAccessible, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
@@ -51,6 +51,32 @@ const tool = (page: Page, id: string) =>
exact: true,
})
const scrollWidth = (page: Page) =>
page.evaluate(() => document.documentElement.scrollWidth)
/** The bubble sits in the window, under the top bar, under its button and clear of the other. */
async function expectBubbleBeside(
page: Page,
bubble: Locator,
button: Locator,
other: Locator,
) {
const box = await bubble.boundingBox()
const own = await button.boundingBox()
const next = await other.boundingBox()
const bar = await page.locator('header').first().boundingBox()
const view = page.viewportSize()
if (!box || !own || !next || !bar || !view)
throw new Error('a box is missing')
expect(box.x).toBeGreaterThanOrEqual(0)
expect(box.x + box.width).toBeLessThanOrEqual(view.width)
expect(box.y + box.height).toBeLessThanOrEqual(view.height)
expect(box.y).toBeGreaterThanOrEqual(bar.y + bar.height)
expect(box.y).toBeGreaterThanOrEqual(own.y + own.height)
const apart = box.y >= next.y + next.height || box.x >= next.x + next.width
expect(apart).toBe(true)
}
interface Names {
fr: string
en: string
@@ -222,7 +248,7 @@ test.describe('editor annotations (A3)', () => {
).toBe('zone-a')
})
test('a held « Refaire » says why: description on focus, message on press, nothing moves', async ({
test('a held « Refaire » says why: description on focus, a bubble on press at three sizes, nothing moves', async ({
page,
requests,
}) => {
@@ -251,11 +277,38 @@ test.describe('editor annotations (A3)', () => {
dict['editor.history.hold_creation'],
)
await expectAccessible(page, 'a held « Refaire » during a creation')
await expectNoShift(page, async () => {
await pressAtBox(page, redo)
await expect(page.getByTestId('gesture-line')).toContainText(reason)
})
await expect(page.getByTestId('gesture-message')).toHaveCount(1)
const bubble = page.getByTestId('history-hold-bubble')
const undo = historyButton(page, dict, 'undo')
for (const [width, height] of [
[1024, 768],
[1180, 820],
[1280, 800],
]) {
await page.setViewportSize({ width, height })
// The resize's own reflow (a breakpoint) settles before the press is measured.
await page.waitForTimeout(300)
await redo.evaluate((el) => el.scrollIntoView({ block: 'center' }))
const widthBefore = await scrollWidth(page)
await expectNoShift(page, async () => {
await pressAtBox(page, redo)
await expect(bubble).toHaveText(reason)
})
await expectBubbleBeside(page, bubble, redo, undo)
expect(await scrollWidth(page)).toBe(widthBefore)
await expectAccessible(page, `the bubble open at ${width}`)
await expectNoShift(page, () => page.keyboard.press('Escape'))
await expect(bubble).toHaveCount(0)
}
await expect(page.getByTestId('gesture-message')).toHaveCount(0)
// Escape order: the bubble first, alone; the next Escape asks about the creation.
await redo.focus()
await page.keyboard.press('Enter')
await expect(bubble).toHaveText(reason)
await page.keyboard.press('Escape')
await expect(bubble).toHaveCount(0)
await expect(page.getByRole('dialog')).toHaveCount(0)
await page.keyboard.press('Escape')
await expect(page.getByRole('dialog')).toHaveCount(1)
})
test('a mouse click on « Refaire » during an arrow series says why; « Défaire » cancels and keeps the redo', async ({
@@ -293,7 +346,7 @@ test.describe('editor annotations (A3)', () => {
// bar, then press it at its box (the mouse events are real).
await redo.evaluate((el) => el.scrollIntoView({ block: 'center' }))
await pressAtBox(page, redo)
await expect(page.getByTestId('gesture-line')).toContainText(
await expect(page.getByTestId('history-hold-bubble')).toHaveText(
dict['editor.history.hold_pending'],
)
await expect(handle).toBeFocused()
@@ -254,7 +254,7 @@ export default function EditorTabs({
{more.length > 0 && (
<MoreTabs more={more} active={active} onSelect={onSelect} />
)}
<HistoryButtons />
<HistoryButtons tab={active} />
</div>
)
}
@@ -0,0 +1,73 @@
import { useLayoutEffect, useState, type CSSProperties } from 'react'
import { createPortal } from 'react-dom'
/** Gap between the button and its bubble, and the space kept from the window's edge. */
const GAP = 4
const EDGE = 8
interface Place {
top: number
right: number
maxWidth: number
}
/**
* Under the button, its right edge on the button's, never past the window's edges. Read
* from the button's box on every scroll and resize so the bubble follows it.
*/
function placeUnder(anchor: HTMLElement): Place {
const box = anchor.getBoundingClientRect()
const width = document.documentElement.clientWidth
const right = Math.max(EDGE, width - box.right)
return { top: box.bottom + GAP, right, maxWidth: width - right - EDGE }
}
function usePlace(anchor: HTMLElement | null): Place | null {
const [place, setPlace] = useState<Place | null>(null)
useLayoutEffect(() => {
if (!anchor) return
const measure = () => setPlace(placeUnder(anchor))
measure()
window.addEventListener('scroll', measure, true)
window.addEventListener('resize', measure)
return () => {
window.removeEventListener('scroll', measure, true)
window.removeEventListener('resize', measure)
}
}, [anchor])
return place
}
/**
* The reason a held « Défaire » / « Refaire » gives, in a small bubble under its button. Out
* of the flow (a portal to the body, `fixed`), so nothing of the page moves; z-20 puts it
* over the sticky strip and the pinned drawing column and under the top bar (z-30, and the bubble never goes up past it) and the
* modal dialogs (top layer). It never takes a press: one beside it works as usual.
*/
export default function HeldReasonBubble({
anchor,
text,
}: {
anchor: HTMLElement | null
text: string
}) {
const place = usePlace(anchor)
if (!place) return null
return createPortal(
<div
role="status"
data-testid="history-hold-bubble"
className="pointer-events-none fixed top-[max(var(--bubble-top),calc(var(--shell-top-bar-height)+4px))] z-20 w-max rounded-md border border-[var(--color-border)] bg-[var(--color-surface)] px-3 py-2 text-sm text-[var(--color-ink)] shadow-lg"
style={
{
'--bubble-top': `${place.top}px`,
right: place.right,
maxWidth: `min(22rem, ${place.maxWidth}px)`,
} as CSSProperties
}
>
{text}
</div>,
document.body,
)
}
@@ -12,12 +12,13 @@ import {
cancelPending,
hasPending,
holdsRedo,
pressHeldHistory,
useAnnotationWork,
type HistoryHold,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from './EditorGlyph'
import HeldReasonBubble from './HeldReasonBubble'
import { useHeldBubble } from './useHeldBubble'
type Direction = 'undo' | 'redo'
@@ -95,6 +96,7 @@ function usePress(
direction: Direction,
readOnly: boolean,
left: RefObject<HTMLElement | null>,
bubble: { show: () => void; close: () => void },
) {
const forget = () => {
left.current = null
@@ -103,6 +105,7 @@ function usePress(
const onBlur = (event: FocusEvent<HTMLElement>) => {
const pair = event.currentTarget.parentElement
if (!pair?.contains(event.relatedTarget as Node | null)) forget()
bubble.close()
}
const onPointerLeave = (event: PointerEvent<HTMLElement>) => {
if (event.pointerType === 'mouse') forget()
@@ -121,7 +124,7 @@ function usePress(
const onClick = () => {
// A12, I-1: a held button does nothing but say why; an inactive one does nothing.
const hold = holdNow(direction)
if (hold) return pressHeldHistory(hold)
if (hold) return bubble.show()
if (inactive(direction, useAnnotationWork.getState())) return
const field = left.current
forget()
@@ -150,9 +153,11 @@ function usePress(
function HistoryButton({
direction,
tab,
left,
}: {
direction: Direction
tab: string
left: RefObject<HTMLElement | null>
}) {
const t = useT()
@@ -160,11 +165,14 @@ function HistoryButton({
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const hold = useAnnotationWork((s) => holdOf(direction, s, steppable))
const name = t(`editor.history.${direction}_title`)
const press = usePress(direction, readOnly, left)
const button = useRef<HTMLButtonElement>(null)
const bubble = useHeldBubble(hold !== null, tab, button)
const press = usePress(direction, readOnly, left, bubble)
const reasonId = `history-hold-${direction}`
return (
<>
<button
ref={button}
type="button"
aria-label={name}
title={`${name} (${t(`editor.history.${direction}_shortcut`)})`}
@@ -184,20 +192,31 @@ function HistoryButton({
{t(`editor.history.hold_${hold}`)}
</span>
)}
{hold && bubble.open && (
<HeldReasonBubble
key={bubble.serial}
anchor={button.current}
text={t(`editor.history.hold_${hold}`)}
/>
)}
</>
)
}
/** « Défaire » and « Refaire », at the right of the tab row on every tab. */
export default function HistoryButtons() {
/**
* « Défaire » and « Refaire », at the right of the tab row on every tab. A press on a held
* one says why in a bubble (announced once, by its status role: the description is read on
* focus only); `tab` closes it when the tab changes.
*/
export default function HistoryButtons({ tab }: { tab: string }) {
const left = useRef<HTMLElement | null>(null)
return (
<div
className="ml-auto flex items-center gap-1"
data-testid="history-buttons"
>
<HistoryButton direction="undo" left={left} />
<HistoryButton direction="redo" left={left} />
<HistoryButton direction="undo" tab={tab} left={left} />
<HistoryButton direction="redo" tab={tab} left={left} />
</div>
)
}
@@ -1,4 +1,4 @@
import { useEffect, useReducer, useRef, useState, type Dispatch } from 'react'
import { useEffect, useReducer, useState, type Dispatch } from 'react'
import { flushSync } from 'react-dom'
import type {
AnatomicalSheetDocument,
@@ -207,36 +207,6 @@ function resumedOf({ creation, model }: Scene): ZoneTarget | null {
return geometry.type === 'polygon' ? { id: PENDING_ID, geometry } : null
}
/**
* A press on a held « Défaire » / « Refaire » (the header's buttons, outside this tree) says
* why on the line under the drawing. A press from before this tab mounted, or made while
* another tab hides the line, is not replayed: the button's description says it there.
*/
function useHeldHistoryMessage(
message: GestureMessages,
t: CommitContext['t'],
) {
const press = useAnnotationWork((s) => s.historyPress)
const seen = useRef(press)
const visible = usePlaceVisible()
// `show` and `t` are rebuilt per render: the effect reads the latest, runs on a new press.
const latest = useRef({ message, t, visible })
useEffect(() => {
latest.current = { message, t, visible }
})
useEffect(() => {
if (press === seen.current) return
seen.current = press
const now = latest.current
if (press && now.visible) {
now.message.show(now.t(`editor.history.hold_${press.reason}`), {
undo: false,
tone: 'info',
})
}
}, [press])
}
/**
* The tab's work: the commit context, the line under the drawing, the placement, the
* editing of the movable selection (point handle keys, slider, move mode) and of a
@@ -246,7 +216,6 @@ function useHeldHistoryMessage(
function useWork(scene: Scene) {
const context = useCommitContext()
const message = useGestureMessage()
useHeldHistoryMessage(message, context.t)
const placement = usePlacement({ ...scene, context, message })
useCreationFollow({ ...scene, message, t: context.t })
const target = movableOf(scene.selected, scene.model, scene.ui.tool)
@@ -0,0 +1,43 @@
import { useCallback, useEffect, useState, type RefObject } from 'react'
/**
* A pressed-held button's bubble: open until the hold ends, the tab changes, the focus
* leaves the button, a press lands elsewhere or Escape is pressed. The serial makes a
* repeated press a new bubble, announced again. Escape is taken first, on the capture
* phase, so the next one reaches what it reached before (a creation asks, pending work
* drops); a modal dialog keeps its own.
*/
export function useHeldBubble(
held: boolean,
tab: string,
button: RefObject<HTMLElement | null>,
) {
const [serial, setSerial] = useState(0)
const open = held && serial > 0
const close = useCallback(() => setSerial(0), [])
const show = useCallback(() => setSerial((n) => n + 1), [])
useEffect(() => {
if (!held) close()
}, [held, close])
useEffect(() => close(), [tab, close])
useEffect(() => {
if (!open) return
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.isComposing) return
if (document.querySelector('dialog[open]')) return
event.preventDefault()
event.stopPropagation()
close()
}
const onPress = (event: Event) => {
if (!button.current?.contains(event.target as Node)) close()
}
document.addEventListener('keydown', onKey, true)
document.addEventListener('pointerdown', onPress, true)
return () => {
document.removeEventListener('keydown', onKey, true)
document.removeEventListener('pointerdown', onPress, true)
}
}, [open, close, button])
return { open, serial, show, close }
}
@@ -87,11 +87,6 @@ interface Work {
question: DrawingQuestion | null
/** A two-finger pan or zoom worked in this editor visit: the hint never shows again (R-1). */
twoFingers: boolean
/**
* A press on a held « Défaire » / « Refaire »: the tab's message line says why. The serial
* makes a repeated press a new message, announced again.
*/
historyPress: { reason: HistoryHold; serial: number } | null
}
const NO_WORK: Work = {
creation: null,
@@ -103,7 +98,6 @@ const NO_WORK: Work = {
dropped: null,
question: null,
twoFingers: false,
historyPress: null,
}
export const useAnnotationWork = create<Work>(() => NO_WORK)
@@ -111,12 +105,6 @@ export const useAnnotationWork = create<Work>(() => NO_WORK)
/** Why « Défaire » or « Refaire » is held (point 6): a creation, or pending work. */
export type HistoryHold = 'creation' | 'creation_redo' | 'pending'
/** A press on a held history button: the message line says why (see `historyPress`). */
export function pressHeldHistory(reason: HistoryHold): void {
const serial = (useAnnotationWork.getState().historyPress?.serial ?? 0) + 1
useAnnotationWork.setState({ historyPress: { reason, serial } })
}
/** R-12: what a navigation must ask about; an unstarted mode asks nothing and simply ends. */
export function guardWork(work: Work): GuardWork {
if (work.creation !== null) return 'creation'
@@ -82,7 +82,7 @@ function Page({ readOnly = false }: { readOnly?: boolean }) {
useUndoShortcuts(true)
return (
<>
<HistoryButtons />
<HistoryButtons tab="annotations" />
<LayeredTab {...props} readOnly={readOnly} />
</>
)
@@ -572,13 +572,13 @@ describe('why a button is held (point 6)', () => {
'Refaire est suspendu pendant la modification en cours : annulez-la avec Défaire pour pouvoir refaire.'
const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 }
afterEach(() => act(() => resetWork()))
const line = () => screen.getByTestId('gesture-line')
const bubble = () => screen.getByTestId('history-hold-bubble')
const reason = (button: HTMLElement) => {
const id = button.getAttribute('aria-describedby')
return id ? document.getElementById(id)?.textContent : null
}
const noMessage = () =>
expect(within(line()).queryByTestId('gesture-message')).toBeNull()
expect(screen.queryByTestId('history-hold-bubble')).toBeNull()
async function openAnnotations() {
const user = userEvent.setup()
mountDraft()
@@ -639,17 +639,17 @@ describe('why a button is held (point 6)', () => {
expect(reason(redoButton())).toBe(REDO_CREATION)
expect(disabled(redoButton())).toBe(true)
await user.click(redoButton())
expect(line()).toHaveTextContent(REDO_CREATION)
const first = within(line()).getByTestId('gesture-message')
expect(bubble()).toHaveTextContent(REDO_CREATION)
const first = bubble()
redoButton().focus()
await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(REDO_CREATION)
expect(within(line()).getByTestId('gesture-message')).not.toBe(first)
expect(bubble()).toHaveTextContent(REDO_CREATION)
expect(bubble()).not.toBe(first)
await user.keyboard(' ')
expect(within(line()).getAllByTestId('gesture-message')).toHaveLength(1)
expect(screen.getAllByTestId('history-hold-bubble')).toHaveLength(1)
undoButton().focus()
await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(CREATION)
expect(bubble()).toHaveTextContent(CREATION)
})
it('pending work holds redo only, with its own reason', async () => {
@@ -659,7 +659,7 @@ describe('why a button is held (point 6)', () => {
expect(reason(redoButton())).toBe(PENDING)
expect(reason(undoButton())).toBeNull()
await user.click(redoButton())
expect(line()).toHaveTextContent(PENDING)
expect(bubble()).toHaveTextContent(PENDING)
})
it('a mouse press on a held « Refaire » leaves the focused pending work alone', async () => {
@@ -674,7 +674,7 @@ describe('why a button is held (point 6)', () => {
expect(handle).toHaveFocus()
expect(useAnnotationWork.getState().preview).not.toBeNull()
expect(store.getState().redo).toHaveLength(1)
expect(line()).toHaveTextContent(PENDING)
expect(bubble()).toHaveTextContent(PENDING)
handle.remove()
})
@@ -733,12 +733,12 @@ describe('why a button is held (point 6)', () => {
create()
undoButton().focus()
await user.keyboard(' ')
expect(line()).toHaveTextContent(CREATION)
expect(bubble()).toHaveTextContent(CREATION)
act(() => resetWork())
pend()
redoButton().focus()
await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(PENDING)
expect(bubble()).toHaveTextContent(PENDING)
})
it('say it in English', async () => {
@@ -759,7 +759,7 @@ describe('why a button is held (point 6)', () => {
'Unavailable during a creation: create the annotation or discard it.',
)
await user.click(redo)
expect(line()).toHaveTextContent('Redo is paused during a creation')
expect(bubble()).toHaveTextContent('Redo is paused during a creation')
act(() => resetWork())
pend()
expect(reason(redo)).toBe(
@@ -767,7 +767,7 @@ describe('why a button is held (point 6)', () => {
)
})
it('on another tab a held « Refaire » keeps its description, and a press does nothing', async () => {
it('on another tab a held « Refaire » says why in its bubble too, and nothing is committed', async () => {
const user = await openAnnotations()
stacks()
await user.click(screen.getByRole('tab', { name: 'Général' }))
@@ -775,15 +775,96 @@ describe('why a button is held (point 6)', () => {
const before = store.getState().documentText
await user.click(redoButton())
expect(reason(redoButton())).toBe(PENDING)
expect(bubble()).toHaveTextContent(PENDING)
expect(useAnnotationWork.getState().preview).not.toBeNull()
expect(store.getState().documentText).toBe(before)
expect(store.getState().redo).toHaveLength(1)
noMessage()
// Back on Annotations, the press made elsewhere is not shown in the line.
// A tab change closes it, and a later press shows it again.
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
noMessage()
})
describe('the bubble', () => {
async function heldRedo() {
const user = await openAnnotations()
stacks()
pend()
await user.click(redoButton())
expect(bubble()).toHaveAttribute('role', 'status')
return user
}
it('is portalled out of the row, so nothing in the layout can move', async () => {
await heldRedo()
expect(screen.getByTestId('history-buttons')).not.toContainElement(
bubble(),
)
expect(bubble().parentElement).toBe(document.body)
expect(bubble().style.position || bubble().className).toMatch(/fixed/)
})
it('closes when the hold ends', async () => {
await heldRedo()
act(() => useAnnotationWork.setState({ preview: null }))
noMessage()
pend()
noMessage()
})
it('closes when the focus leaves the button', async () => {
const user = await openAnnotations()
stacks()
pend()
redoButton().focus()
await user.keyboard('{Enter}')
expect(bubble()).toBeInTheDocument()
await user.tab()
noMessage()
})
for (const [kind, keys] of [
['mouse', '[MouseLeft]'],
['touch', '[TouchA]'],
] as const) {
it(`closes on a ${kind} press elsewhere, not on the button itself`, async () => {
const user = await heldRedo()
await user.pointer({ keys, target: redoButton() })
expect(bubble()).toBeInTheDocument()
await user.pointer({ keys, target: document.body })
noMessage()
})
}
it('Escape closes it first and alone, the pending work stays', async () => {
const user = await openAnnotations()
stacks()
pend()
redoButton().focus()
await user.keyboard('{Enter}')
await user.keyboard('{Escape}')
noMessage()
expect(useAnnotationWork.getState().preview).not.toBeNull()
})
it('sits under the pressed button, its right edge on the button, inside the window', async () => {
const user = await openAnnotations()
stacks()
pend()
const rect = { top: 10, bottom: 50, left: 900, right: 960 } as DOMRect
vi.spyOn(redoButton(), 'getBoundingClientRect').mockReturnValue(rect)
Object.defineProperty(document.documentElement, 'clientWidth', {
configurable: true,
value: 1024,
})
await user.click(redoButton())
expect(bubble()).toHaveTextContent(PENDING)
expect(bubble().style.getPropertyValue('--bubble-top')).toBe('54px')
expect(bubble().style.right).toBe('64px')
expect(bubble().style.maxWidth).toBe('min(22rem, 952px)')
delete (document.documentElement as { clientWidth?: number }).clientWidth
})
})
it('give no reason when nothing is pending, nothing to redo or read-only', async () => {
const user = await openAnnotations()
expect(reason(redoButton())).toBeNull()
@@ -1054,7 +1054,7 @@ describe('final review I-1: a redo or a handle key never drops pending work', ()
it('the header « Refaire » is off in a started move and keeps it', async () => {
await withRedo()
render(<HistoryButtons />)
render(<HistoryButtons tab="annotations" />)
await startedMove()
const redo = screen.getByRole('button', {
name: 'Refaire la dernière modification défaite',
@@ -1086,7 +1086,7 @@ describe('final review I-1: a redo or a handle key never drops pending work', ()
it('the header « Refaire » is off in a started redraw and keeps it', async () => {
await withRedo()
render(<HistoryButtons />)
render(<HistoryButtons tab="annotations" />)
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
+8
View File
@@ -276,6 +276,14 @@ is one rule in `styles/index.css`, scoped to `[data-editor-workspace]` through
its targets with the strip's height added. It excludes the strip's commands and a
dialog's controls, and the bar itself lies outside the workspace.
A press on a held « Défaire » or « Refaire » (D1, criterion 33) says why in a bubble under
that button, on every tab. It is a `role="status"` element portalled to the body with
`position: fixed` (no layout shift), at z-20: over the sticky strip and the pinned column,
under the top bar (z-30, and it never sits higher than the bar's bottom) and the modal
dialogs. Its right edge follows the button's, kept 8 px inside the window. It ends with the
hold, a tab change, the focus leaving the button, a press elsewhere, or Escape, which it
takes before any other Escape.
A creation (U2 Task 7, A2, A4, A12) is drawn by the overlay too, never by the
core, since the new shape is not in the document until « Créer »: