fix(editor): bubble clears the strip's commands, announces through a steady region

This commit is contained in:
bchanot committed 2026-11-19 21:04:21 +01:00
1 parent 49f0144729
commit a9252375e1
7 files changed
+313 -56

No files matched your search

+43 -8
View File
@@ -54,27 +54,49 @@ const tool = (page: Page, id: string) =>
const scrollWidth = (page: Page) => const scrollWidth = (page: Page) =>
page.evaluate(() => document.documentElement.scrollWidth) page.evaluate(() => document.documentElement.scrollWidth)
/** The bubble sits in the window, under the top bar, under its button and clear of the other. */ const intersects = (a: Box, b: Box) =>
a.x < b.x + b.width &&
b.x < a.x + a.width &&
a.y < b.y + b.height &&
b.y < a.y + a.height
interface Box {
x: number
y: number
width: number
height: number
}
/**
* The bubble sits in the window, under the top bar, right under its button (within 8 px
* unless the bar pushes it down), and over neither « Défaire » nor the strip's commands.
*/
async function expectBubbleBeside( async function expectBubbleBeside(
page: Page, page: Page,
bubble: Locator, bubble: Locator,
button: Locator, button: Locator,
other: Locator, other: Locator,
) { ) {
const box = await bubble.boundingBox() const boxes = await Promise.all([
const own = await button.boundingBox() bubble.boundingBox(),
const next = await other.boundingBox() button.boundingBox(),
const bar = await page.locator('header').first().boundingBox() other.boundingBox(),
page.locator('header').first().boundingBox(),
page.locator('[data-testid="edit-strip"] > :last-child').boundingBox(),
])
const view = page.viewportSize() const view = page.viewportSize()
if (!box || !own || !next || !bar || !view) const [box, own, next, bar, commands] = boxes
if (!box || !own || !next || !bar || !commands || !view)
throw new Error('a box is missing') throw new Error('a box is missing')
expect(box.x).toBeGreaterThanOrEqual(0) expect(box.x).toBeGreaterThanOrEqual(0)
expect(box.x + box.width).toBeLessThanOrEqual(view.width) expect(box.x + box.width).toBeLessThanOrEqual(view.width)
expect(box.y + box.height).toBeLessThanOrEqual(view.height) expect(box.y + box.height).toBeLessThanOrEqual(view.height)
expect(box.y).toBeGreaterThanOrEqual(bar.y + bar.height) expect(box.y).toBeGreaterThanOrEqual(bar.y + bar.height)
expect(box.y).toBeGreaterThanOrEqual(own.y + own.height) expect(box.y).toBeGreaterThanOrEqual(own.y + own.height)
const apart = box.y >= next.y + next.height || box.x >= next.x + next.width expect(box.y - (own.y + own.height)).toBeLessThanOrEqual(8)
expect(apart).toBe(true) expect(box.width).toBeLessThanOrEqual(288)
expect(intersects(box, next)).toBe(false)
expect(intersects(box, commands)).toBe(false)
} }
interface Names { interface Names {
@@ -288,6 +310,8 @@ test.describe('editor annotations (A3)', () => {
// The resize's own reflow (a breakpoint) settles before the press is measured. // The resize's own reflow (a breakpoint) settles before the press is measured.
await page.waitForTimeout(300) await page.waitForTimeout(300)
await redo.evaluate((el) => el.scrollIntoView({ block: 'center' })) await redo.evaluate((el) => el.scrollIntoView({ block: 'center' }))
// Its scroll event lands before the press, which a scroll would close.
await page.waitForTimeout(150)
const widthBefore = await scrollWidth(page) const widthBefore = await scrollWidth(page)
await expectNoShift(page, async () => { await expectNoShift(page, async () => {
await pressAtBox(page, redo) await pressAtBox(page, redo)
@@ -298,6 +322,17 @@ test.describe('editor annotations (A3)', () => {
await expectAccessible(page, `the bubble open at ${width}`) await expectAccessible(page, `the bubble open at ${width}`)
await expectNoShift(page, () => page.keyboard.press('Escape')) await expectNoShift(page, () => page.keyboard.press('Escape'))
await expect(bubble).toHaveCount(0) await expect(bubble).toHaveCount(0)
// Scrolled, the strip stuck under the bar: the keyboard press keeps the same rules.
await page.evaluate(() => window.scrollTo(0, 150))
await redo.focus()
await page.waitForTimeout(150)
await page.keyboard.press('Enter')
await expect(bubble).toHaveText(reason)
await expectBubbleBeside(page, bubble, redo, undo)
await page.keyboard.press('Escape')
await expect(bubble).toHaveCount(0)
await page.evaluate(() => window.scrollTo(0, 0))
await page.waitForTimeout(150)
} }
await expect(page.getByTestId('gesture-message')).toHaveCount(0) await expect(page.getByTestId('gesture-message')).toHaveCount(0)
// Escape order: the bubble first, alone; the next Escape asks about the creation. // Escape order: the bubble first, alone; the next Escape asks about the creation.
@@ -11,38 +11,50 @@ interface Place {
maxWidth: number maxWidth: number
} }
/** Left edge of the annotations strip's command box while the strip is on screen. */
function stripCommandsLeft(): number | null {
for (const strip of document.querySelectorAll('[data-testid="edit-strip"]')) {
const commands = strip.lastElementChild?.getBoundingClientRect()
if (strip.getBoundingClientRect().width > 0 && commands)
return commands.left
}
return null
}
/** /**
* Under the button, its right edge on the button's, never past the window's edges. Read * Under the button, its right edge on the button's, never past the window's edges. With the
* from the button's box on every scroll and resize so the bubble follows it. * strip on screen the bubble ends left of the strip's commands, which its text may name
* (« Annuler le tracé », « Abandonner »): it lies over the strip's notice, never over them.
*/ */
function placeUnder(anchor: HTMLElement): Place { function placeUnder(anchor: HTMLElement): Place {
const box = anchor.getBoundingClientRect() const box = anchor.getBoundingClientRect()
const width = document.documentElement.clientWidth const width = document.documentElement.clientWidth
const right = Math.max(EDGE, width - box.right) const commands = stripCommandsLeft()
const edge =
commands === null ? box.right : Math.min(box.right, commands - GAP)
const right = Math.max(EDGE, width - edge)
return { top: box.bottom + GAP, right, maxWidth: width - right - EDGE } return { top: box.bottom + GAP, right, maxWidth: width - right - EDGE }
} }
/** Measured once at open and on a resize; a scroll closes the bubble instead. */
function usePlace(anchor: HTMLElement | null): Place | null { function usePlace(anchor: HTMLElement | null): Place | null {
const [place, setPlace] = useState<Place | null>(null) const [place, setPlace] = useState<Place | null>(null)
useLayoutEffect(() => { useLayoutEffect(() => {
if (!anchor) return if (!anchor) return
const measure = () => setPlace(placeUnder(anchor)) const measure = () => setPlace(placeUnder(anchor))
measure() measure()
window.addEventListener('scroll', measure, true)
window.addEventListener('resize', measure) window.addEventListener('resize', measure)
return () => { return () => window.removeEventListener('resize', measure)
window.removeEventListener('scroll', measure, true)
window.removeEventListener('resize', measure)
}
}, [anchor]) }, [anchor])
return place return place
} }
/** /**
* The reason a held « Défaire » / « Refaire » gives, in a small bubble under its button. Out * The reason a held « Défaire » / « Refaire » gives, in a small bubble under its button.
* of the flow (a portal to the body, `fixed`), so nothing of the page moves; z-20 puts it * Out of the flow (a portal to the body, `fixed`), so nothing of the page moves. z-20 puts
* 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 * it over the sticky strip and the pinned drawing column, under the top bar (z-30), which
* modal dialogs (top layer). It never takes a press: one beside it works as usual. * it never rises past, and under the modal dialogs (top layer). It takes no press. Hidden
* from assistive technology: the button's always-mounted status region announces the text.
*/ */
export default function HeldReasonBubble({ export default function HeldReasonBubble({
anchor, anchor,
@@ -55,14 +67,14 @@ export default function HeldReasonBubble({
if (!place) return null if (!place) return null
return createPortal( return createPortal(
<div <div
role="status" aria-hidden="true"
data-testid="history-hold-bubble" 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" 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={ style={
{ {
'--bubble-top': `${place.top}px`, '--bubble-top': `${place.top}px`,
right: place.right, right: place.right,
maxWidth: `min(22rem, ${place.maxWidth}px)`, maxWidth: `min(18rem, ${place.maxWidth}px)`,
} as CSSProperties } as CSSProperties
} }
> >
@@ -151,6 +151,27 @@ function usePress(
} }
} }
/** What a button reads and holds: its reason, its bubble, its press handlers. */
function useHistoryButton(
direction: Direction,
tab: string,
left: RefObject<HTMLElement | null>,
) {
const readOnly = useEditorReadOnly()
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const hold = useAnnotationWork((s) => holdOf(direction, s, steppable))
const button = useRef<HTMLButtonElement>(null)
const bubble = useHeldBubble(hold !== null, tab, button)
return {
hold,
button,
bubble,
press: usePress(direction, readOnly, left, bubble),
disabled: readOnly || !steppable || hold !== null,
reasonId: `history-hold-${direction}`,
}
}
function HistoryButton({ function HistoryButton({
direction, direction,
tab, tab,
@@ -161,25 +182,20 @@ function HistoryButton({
left: RefObject<HTMLElement | null> left: RefObject<HTMLElement | null>
}) { }) {
const t = useT() const t = useT()
const readOnly = useEditorReadOnly() const h = useHistoryButton(direction, tab, left)
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const hold = useAnnotationWork((s) => holdOf(direction, s, steppable))
const name = t(`editor.history.${direction}_title`) const name = t(`editor.history.${direction}_title`)
const button = useRef<HTMLButtonElement>(null) const reason = h.hold ? t(`editor.history.hold_${h.hold}`) : ''
const bubble = useHeldBubble(hold !== null, tab, button)
const press = usePress(direction, readOnly, left, bubble)
const reasonId = `history-hold-${direction}`
return ( return (
<> <>
<button <button
ref={button} ref={h.button}
type="button" type="button"
aria-label={name} aria-label={name}
title={`${name} (${t(`editor.history.${direction}_shortcut`)})`} title={`${name} (${t(`editor.history.${direction}_shortcut`)})`}
aria-disabled={readOnly || !steppable || hold !== null} aria-disabled={h.disabled}
aria-describedby={hold ? reasonId : undefined} aria-describedby={h.hold ? h.reasonId : undefined}
aria-keyshortcuts={SHORTCUT[direction]} aria-keyshortcuts={SHORTCUT[direction]}
{...press} {...h.press}
className={BUTTON} className={BUTTON}
> >
<EditorGlyph name={direction} /> <EditorGlyph name={direction} />
@@ -187,16 +203,24 @@ function HistoryButton({
{t(`editor.history.${direction}`)} {t(`editor.history.${direction}`)}
</span> </span>
</button> </button>
{hold && ( {h.hold && (
<span id={reasonId} className="sr-only"> <span id={h.reasonId} className="sr-only">
{t(`editor.history.hold_${hold}`)} {reason}
</span> </span>
)} )}
{hold && bubble.open && ( {/* Always mounted, so a press's text is announced; the keyed child says it again. */}
<span
role="status"
data-testid={`history-status-${direction}`}
className="sr-only"
>
{h.bubble.open && <span key={h.bubble.serial}>{reason}</span>}
</span>
{h.bubble.open && (
<HeldReasonBubble <HeldReasonBubble
key={bubble.serial} key={h.bubble.serial}
anchor={button.current} anchor={h.button.current}
text={t(`editor.history.hold_${hold}`)} text={reason}
/> />
)} )}
</> </>
@@ -205,8 +229,8 @@ function HistoryButton({
/** /**
* « Défaire » and « Refaire », at the right of the tab row on every tab. A press on a held * « 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 * one says why in a bubble (announced once, by the button's always-mounted status region:
* focus only); `tab` closes it when the tab changes. * the description is read on focus only); `tab` closes it when the tab changes.
*/ */
export default function HistoryButtons({ tab }: { tab: string }) { export default function HistoryButtons({ tab }: { tab: string }) {
const left = useRef<HTMLElement | null>(null) const left = useRef<HTMLElement | null>(null)
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useState, type RefObject } from 'react' import { useCallback, useEffect, useState, type RefObject } from 'react'
import { isTextField } from '@/editor/focusRequest'
/** /**
* A pressed-held button's bubble: open until the hold ends, the tab changes, the focus * 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 * leaves the button, a press lands elsewhere, the page scrolls, a dialog opens or Escape is
* repeated press a new bubble, announced again. Escape is taken first, on the capture * pressed. The serial makes a repeated press a new announcement. Escape is taken first, on
* phase, so the next one reaches what it reached before (a creation asks, pending work * the capture phase, so the next one reaches what it reached before (a creation asks,
* drops); a modal dialog keeps its own. * pending work drops); typed in a field it only closes the bubble, and a modal dialog keeps
* its own.
*/ */
export function useHeldBubble( export function useHeldBubble(
held: boolean, held: boolean,
@@ -20,24 +22,50 @@ export function useHeldBubble(
if (!held) close() if (!held) close()
}, [held, close]) }, [held, close])
useEffect(() => close(), [tab, close]) useEffect(() => close(), [tab, close])
useDismissal(open, close, button)
return { open, serial, show, close }
}
function useDismissal(
open: boolean,
close: () => void,
button: RefObject<HTMLElement | null>,
) {
useEffect(() => { useEffect(() => {
if (!open) return if (!open) return
const onKey = (event: KeyboardEvent) => { const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.isComposing) return if (event.key !== 'Escape' || event.isComposing) return
if (document.querySelector('dialog[open]')) return if (document.querySelector('dialog[open]')) return
close()
if (isTextField(event.target)) return
event.preventDefault() event.preventDefault()
event.stopPropagation() event.stopPropagation()
close()
} }
const onPress = (event: Event) => { const onPress = (event: Event) => {
if (!button.current?.contains(event.target as Node)) close() if (!button.current?.contains(event.target as Node)) close()
} }
const onDialog = () => {
if (document.querySelector('dialog[open]')) close()
}
const watch = new MutationObserver(onDialog)
watch.observe(document.body, {
subtree: true,
attributes: true,
attributeFilter: ['open'],
})
const passive = { capture: true, passive: true }
document.addEventListener('keydown', onKey, true) document.addEventListener('keydown', onKey, true)
document.addEventListener('pointerdown', onPress, true) document.addEventListener('pointerdown', onPress, true)
for (const type of ['scroll', 'wheel', 'touchmove']) {
document.addEventListener(type, close, passive)
}
return () => { return () => {
watch.disconnect()
document.removeEventListener('keydown', onKey, true) document.removeEventListener('keydown', onKey, true)
document.removeEventListener('pointerdown', onPress, true) document.removeEventListener('pointerdown', onPress, true)
for (const type of ['scroll', 'wheel', 'touchmove']) {
document.removeEventListener(type, close, passive)
}
} }
}, [open, close, button]) }, [open, close, button])
return { open, serial, show, close }
} }
@@ -0,0 +1,121 @@
/** The held-reason bubble (D1): its closing rules and its place, apart from the editor. */
import { afterEach, describe, expect, it } from 'vitest'
import { act, cleanup, render, renderHook, screen } from '@testing-library/react'
import HeldReasonBubble from '@/components/editor/HeldReasonBubble'
import { useHeldBubble } from '@/components/editor/useHeldBubble'
afterEach(() => {
cleanup()
document.body.innerHTML = ''
})
function opened(tab = 'annotations') {
const button = document.createElement('button')
document.body.append(button)
const ref = { current: button }
const hook = renderHook(
({ held, tab }) => useHeldBubble(held, tab, ref),
{ initialProps: { held: true, tab } },
)
act(() => hook.result.current.show())
expect(hook.result.current.open).toBe(true)
return { hook, button }
}
const key = (target: EventTarget, init: KeyboardEventInit = {}) => {
const event = new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
...init,
})
act(() => {
target.dispatchEvent(event)
})
return event
}
describe('closing', () => {
it('closes when the tab prop changes, with no press or focus move', () => {
const { hook } = opened()
hook.rerender({ held: true, tab: 'general' })
expect(hook.result.current.open).toBe(false)
})
for (const type of ['scroll', 'wheel', 'touchmove']) {
it(`closes on ${type}`, () => {
const { hook } = opened()
act(() => {
document.dispatchEvent(new Event(type, { bubbles: true }))
})
expect(hook.result.current.open).toBe(false)
})
}
it('closes when a dialog opens', async () => {
const { hook } = opened()
const dialog = document.createElement('dialog')
document.body.append(dialog)
await act(async () => {
dialog.setAttribute('open', '')
await Promise.resolve()
})
expect(hook.result.current.open).toBe(false)
})
it('Escape closes it and is taken from everything else', () => {
const { hook, button } = opened()
const event = key(button)
expect(hook.result.current.open).toBe(false)
expect(event.defaultPrevented).toBe(true)
expect(key(button).defaultPrevented).toBe(false)
})
it('Escape typed in a text field closes it and stays the field\'s', () => {
const { hook } = opened()
const field = document.createElement('input')
document.body.append(field)
const event = key(field)
expect(hook.result.current.open).toBe(false)
expect(event.defaultPrevented).toBe(false)
})
})
describe('the place', () => {
const rect = (left: number, right: number, top = 0, bottom = 40) =>
({ left, right, top, bottom, width: right - left, height: bottom - top }) as DOMRect
function anchor() {
const button = document.createElement('button')
document.body.append(button)
button.getBoundingClientRect = () => rect(900, 960, 10, 50)
Object.defineProperty(document.documentElement, 'clientWidth', {
configurable: true,
value: 1024,
})
return button
}
const strip = (commandsLeft: number) => {
const el = document.createElement('div')
el.dataset.testid = 'edit-strip'
const commands = document.createElement('div')
el.append(commands)
el.getBoundingClientRect = () => rect(100, 980, 70, 134)
commands.getBoundingClientRect = () => rect(commandsLeft, 970, 74, 130)
document.body.append(el)
}
it('sits 4 px under its button, right edge on the button, without a strip', () => {
render(<HeldReasonBubble anchor={anchor()} text="why" />)
const bubble = screen.getByTestId('history-hold-bubble')
expect(bubble.style.getPropertyValue('--bubble-top')).toBe('54px')
expect(bubble.style.right).toBe('64px')
expect(bubble.style.maxWidth).toBe('min(18rem, 952px)')
})
it('ends left of the strip\'s commands when the strip is shown', () => {
strip(760)
render(<HeldReasonBubble anchor={anchor()} text="why" />)
const bubble = screen.getByTestId('history-hold-bubble')
expect(bubble.style.right).toBe('268px')
})
})
@@ -790,10 +790,44 @@ describe('why a button is held (point 6)', () => {
stacks() stacks()
pend() pend()
await user.click(redoButton()) await user.click(redoButton())
expect(bubble()).toHaveAttribute('role', 'status') expect(bubble()).toHaveAttribute('aria-hidden', 'true')
return user return user
} }
it('is announced by the button\'s always-mounted status region, once per press', async () => {
const user = await openAnnotations()
stacks()
pend()
const region = screen.getByTestId('history-status-redo')
expect(region).toHaveAttribute('role', 'status')
expect(region).toBeEmptyDOMElement()
await user.click(redoButton())
expect(region).toBe(screen.getByTestId('history-status-redo'))
expect(region).toHaveTextContent(PENDING)
const first = region.firstElementChild
await user.click(redoButton())
expect(region).toHaveTextContent(PENDING)
expect(region.children).toHaveLength(1)
expect(region.firstElementChild).not.toBe(first)
await user.pointer({ keys: '[MouseLeft]', target: document.body })
expect(region).toBeEmptyDOMElement()
})
it('a second Escape drops the pending work, as before', async () => {
const user = await openAnnotations()
const list = screen.getByRole('list', { name: 'Annotations de la vue' })
await user.click(within(list).getAllByRole('button')[0]!)
stacks()
pend()
redoButton().focus()
await user.keyboard('{Enter}')
await user.keyboard('{Escape}')
noMessage()
expect(useAnnotationWork.getState().preview).not.toBeNull()
await user.keyboard('{Escape}')
expect(useAnnotationWork.getState().preview).toBeNull()
})
it('is portalled out of the row, so nothing in the layout can move', async () => { it('is portalled out of the row, so nothing in the layout can move', async () => {
await heldRedo() await heldRedo()
expect(screen.getByTestId('history-buttons')).not.toContainElement( expect(screen.getByTestId('history-buttons')).not.toContainElement(
@@ -860,7 +894,7 @@ describe('why a button is held (point 6)', () => {
expect(bubble()).toHaveTextContent(PENDING) expect(bubble()).toHaveTextContent(PENDING)
expect(bubble().style.getPropertyValue('--bubble-top')).toBe('54px') expect(bubble().style.getPropertyValue('--bubble-top')).toBe('54px')
expect(bubble().style.right).toBe('64px') expect(bubble().style.right).toBe('64px')
expect(bubble().style.maxWidth).toBe('min(22rem, 952px)') expect(bubble().style.maxWidth).toBe('min(18rem, 952px)')
delete (document.documentElement as { clientWidth?: number }).clientWidth delete (document.documentElement as { clientWidth?: number }).clientWidth
}) })
}) })
+9 -6
View File
@@ -277,12 +277,15 @@ its targets with the strip's height added. It excludes the strip's commands and
dialog's controls, and the bar itself lies outside the workspace. 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 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 that button, on every tab. It is portalled to the body with `position: fixed` (no layout
`position: fixed` (no layout shift), at z-20: over the sticky strip and the pinned column, shift), at z-20: over the sticky strip and the pinned column, under the top bar (z-30, and it
under the top bar (z-30, and it never sits higher than the bar's bottom) and the modal never sits higher than the bar's bottom) and the modal dialogs. At most 18 rem wide, its
dialogs. Its right edge follows the button's, kept 8 px inside the window. It ends with the right edge follows the button's, kept 8 px inside the window; while the strip is on screen
hold, a tab change, the focus leaving the button, a press elsewhere, or Escape, which it it ends 4 px left of the strip's command box, so the commands its text names stay visible.
takes before any other Escape. It is `aria-hidden`: each button carries an always-mounted visually hidden `role="status"`
region whose keyed child holds the text per press. It ends with the hold, a tab change, the
focus leaving the button, a press elsewhere, a scroll, a dialog opening, or Escape, which it
takes before any other Escape (typed in a text field it only closes the bubble).
A creation (U2 Task 7, A2, A4, A12) is drawn by the overlay too, never by the 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 »: core, since the new shape is not in the document until « Créer »: