fix(editor): message line lifecycle, own row, sound no-shift check

Task 3 review, fix round 1.
- The gesture message closes for good on any document or history
  change (store subscription): undo then redo no longer revives it.
- Hover and focus hold only the message they were taken on: after
  « Défaire » the next message expires.
- An accepted drop clears the strip's refusal hint again.
- Controller ruling: the message has its own fixed row under the add
  buttons, column width; a refused gesture's full text also shows in
  the strip notice (red, aria-hidden copy of the row's alert).
- expectNoShift: native requestAnimationFrame kept before page.clock
  (keepNativeFrames), every part box asserted non-null, message row
  measured; the e2e checks the message is not truncated.
No assertion removed; the refused-drop unit test gains the strip copy.
This commit is contained in:
bchanot committed 2026-11-17 18:10:24 +01:00
1 parent 1deb037fac
commit 7a45f1d885
9 files changed
+198 -49

No files matched your search

@@ -22,7 +22,7 @@ import {
standardShape,
UNSAVED_LINE,
} from '../support/editor'
import { expectNoShift } from '../support/layout'
import { expectNoShift, keepNativeFrames } from '../support/layout'
// V1-2.6 A3 (contract C7, C8, C21): points, zones and links by clicks and by keyboard,
// move by drag, numeric edits, undo and redo, then the save that carries them.
@@ -300,6 +300,7 @@ test.describe('editor annotations (A3)', () => {
async function openWithPoint(page: Page, width: number) {
await page.setViewportSize({ width, height: 800 })
// Installed before any timer: the message's 6 s run on this clock (fast-forwarded below).
await keepNativeFrames(page)
await page.clock.install()
const actor = await editorActor('fr')
const point = pointOf('p-a', 'main', { cx: 500, cy: 300, r: 40 }, 'Pt A')
@@ -350,6 +351,12 @@ test.describe('editor annotations (A3)', () => {
},
swaps,
)
// Its own row, the column's width: the message is read whole.
const cut = await line(page)
.locator('span')
.first()
.evaluate((span) => span.scrollWidth > span.clientWidth)
expect(cut, 'the message is cut short').toBe(false)
// Its expiry, 6 s later.
await expectNoShift(page, async () => {
await page.clock.fastForward(6_100)
+35 -6
View File
@@ -1,8 +1,8 @@
/**
* The no-shift probe of U2 (adjustment A14, plan Task 3): a state change of the annotations
* tab moves no box. The boxes of the canvas, the strip, the aside and the draft header,
* the page's scroll height, its scrollbar gutter and its client width are read before and
* after `act`; a layout-shift observer adds up every entry in between, the ones following
* tab moves no box. The boxes of the canvas, the strip, the message row, the aside and the
* draft header, the page's scroll height, its scrollbar gutter and its client width are read
* before and after `act`; a layout-shift observer adds up every entry in between, the ones following
* an input included (a message appearing after a drop is still a shift).
*/
import { expect, type Page } from '@playwright/test'
@@ -31,6 +31,7 @@ interface Snapshot {
const PARTS = {
canvas: '[data-testid="annotation-canvas"]',
strip: '[data-testid="edit-strip"]',
line: '[data-testid="gesture-line"]',
aside: '[data-testid="editor-tab-annotations"] aside',
header: 'header:has(> nav + div > h1)',
} as const
@@ -62,6 +63,23 @@ function snapshot(page: Page): Promise<Snapshot> {
interface ShiftScope {
__shift: { total: number; moved: string[] }
__shiftObserver?: PerformanceObserver
/** The browser's own requestAnimationFrame, kept before `page.clock` replaces it. */
__nativeRaf?: (callback: FrameRequestCallback) => number
}
/**
* Keeps the native requestAnimationFrame: call it before `page.clock.install()`, whose fake
* frames would let the two-frame wait end before the real layout (and its shift) happens.
*/
export async function keepNativeFrames(page: Page): Promise<void> {
await page.addInitScript(() => {
const scope = window as unknown as ShiftScope
const raf = window.requestAnimationFrame
// Kept only when this script ran before the clock's (else the probe would wait on fakes).
if (String(raf).includes('[native code]'))
scope.__nativeRaf = raf.bind(window)
else throw new Error('keepNativeFrames ran after page.clock.install()')
})
}
/** Starts summing layout-shift entries; read back with `shiftTotal`. */
@@ -100,10 +118,17 @@ function observeShifts(page: Page, asideExempt: boolean): Promise<void> {
/** Two frames for layout to settle, then the pending entries and the total. */
function shiftTotal(page: Page): Promise<ShiftScope['__shift']> {
return page.evaluate(async () => {
await new Promise((done) =>
requestAnimationFrame(() => requestAnimationFrame(done)),
)
const scope = window as unknown as ShiftScope
const faked = !String(window.requestAnimationFrame).includes(
'[native code]',
)
if (faked && !scope.__nativeRaf) {
throw new Error(
'page.clock fakes the frames: call keepNativeFrames first',
)
}
const frame = scope.__nativeRaf ?? window.requestAnimationFrame.bind(window)
await new Promise((done) => frame(() => frame(done)))
const observer = scope.__shiftObserver!
const pending = observer.takeRecords()
observer.disconnect()
@@ -125,6 +150,10 @@ export async function expectNoShift(
exempt: readonly ShiftExemption[] = [],
): Promise<void> {
const before = await snapshot(page)
// A selector that stops matching would compare null with null: every part must be there.
for (const [name, box] of Object.entries(before.boxes)) {
expect(box, `${name} box before the act`).not.toBeNull()
}
const loose = exempt.includes('aside-content')
await observeShifts(page, loose)
await act()
@@ -12,6 +12,8 @@ export interface StripNotice {
/** How many more of the same kind are not shown (« +n »). */
more?: number
link?: { label: string; onClick(): void }
/** Already announced elsewhere (the gesture line's alert): shown, not announced twice. */
quiet?: boolean
}
/**
@@ -86,7 +88,8 @@ function Notice({ notice }: { notice: StripNotice }) {
const error = notice.tone === 'error'
return (
<p
role={error ? 'alert' : undefined}
role={error && !notice.quiet ? 'alert' : undefined}
aria-hidden={notice.quiet || undefined}
className={`flex min-w-0 items-start gap-1 text-xs ${
error
? 'text-[var(--color-danger-strong)]'
@@ -14,6 +14,7 @@ import { usePlacement } from '@/editor/annotations/usePlacement'
import { stripLeadOf } from '@/editor/annotations/stripLead'
import {
useGestureMessage,
type GestureMessage as ShownMessage,
type GestureMessages,
} from '@/editor/annotations/useGestureMessage'
import {
@@ -152,7 +153,7 @@ export default function EditableAnnotations(props: Props) {
)
return (
<div className="space-y-3">
<SceneStrip scene={scene} placement={placement} />
<SceneStrip scene={scene} placement={placement} message={message} />
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn
scene={scene}
@@ -336,13 +337,15 @@ function overlayOf(
function SceneStrip({
scene,
placement,
message,
}: {
scene: Scene
placement: Placement
message: GestureMessages
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const notice = useStripNotice(scene)
const notice = useStripNotice(scene, message.message)
const { ui, selected, doc } = scene
return (
<EditStrip
@@ -362,14 +365,21 @@ function SceneStrip({
}
/**
* The strip's middle, first match wins: a refusal, the selection's geometry issues (the
* first, then « +n »), then why a tool cannot be used now.
* The strip's middle, first match wins: a refusal (the strip's own, then a refused gesture
* whose line under the drawing may be cut short: its full text here, A6), the selection's
* geometry issues (the first, then « +n »), then why a tool cannot be used now.
*/
function useStripNotice(scene: Scene): StripNotice | null {
function useStripNotice(
scene: Scene,
message: ShownMessage | null,
): StripNotice | null {
const t = useT()
const issues = useGeometryIssues(scene.selected?.id ?? '')
const { ui, model, doc } = scene
if (ui.hint) return { tone: 'error', text: ui.hint }
if (message?.tone === 'error') {
return { tone: 'error', text: message.text, quiet: true }
}
if (scene.selected && issues.length > 0) {
return { tone: 'error', text: issues[0]!, more: issues.length - 1 }
}
@@ -4,9 +4,8 @@ import type { GestureMessages } from '@/editor/annotations/useGestureMessage'
import { canUndo, useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
// Compact: at 1 280 px the column leaves about 145 px beside the three add buttons.
const PILL =
'inline-flex h-9 max-w-full items-center gap-1.5 rounded-md px-2 text-xs'
'inline-flex h-9 max-w-full items-center gap-2 rounded-md px-3 text-sm'
/** The header's undo (T15): the same store step, under the same conditions. */
function undoLast(readOnly: boolean): void {
@@ -15,9 +14,10 @@ function undoLast(readOnly: boolean): void {
}
/**
* The fixed line under the drawing (A14, R-2): the add buttons on the left, the message on
* the right, one line truncated. Its height never changes, so a message showing or leaving
* moves nothing. The status region (polite) is always mounted; a refusal is an alert of its own.
* Under the drawing (A14, R-2): the add buttons, then the message on a row of its own, the
* drawing column's full width, one line truncated. The row is always there at a fixed
* height, so a message showing or leaving moves nothing. The status region (polite) is
* always mounted; a refusal is an alert of its own (its full text is also in the strip).
*/
export default function GestureMessage({
messages,
@@ -27,18 +27,16 @@ export default function GestureMessage({
children: ReactNode
}) {
return (
<div
data-testid="gesture-line"
className="flex h-11 items-center gap-2 overflow-hidden"
>
<div className="shrink-0">{children}</div>
<>
{children}
<div
data-testid="gesture-line"
role="status"
className="flex min-w-0 flex-1 justify-end py-1 pr-0.5"
className="flex h-11 items-center justify-end overflow-hidden px-1"
>
<Message messages={messages} />
</div>
</div>
</>
)
}
@@ -64,6 +62,7 @@ function Message({ messages }: { messages: GestureMessages }) {
</span>
{message.undo && !error && (
<>
<span aria-hidden="true">·</span>
<button
type="button"
aria-label={t('editor.history.undo_title')}
@@ -21,7 +21,7 @@ export default function KeyboardAdd({
}) {
const t = useT()
return (
<div className="flex flex-nowrap gap-2">
<div className="flex flex-wrap gap-2">
{KINDS.map((kind) => (
<Button
key={kind}
@@ -1,4 +1,10 @@
import { useEffect, useState, type FocusEvent, type PointerEvent } from 'react'
import {
useCallback,
useEffect,
useState,
type FocusEvent,
type PointerEvent,
} from 'react'
import { useEditorStore } from '../state/editorStore'
/** A6/A14: how long a message stays (R-2) and how long a hint does (R-1). */
@@ -26,34 +32,49 @@ function currentStamp(): Stamp {
return { text: documentText, undo: undo.length, redo: redo.length }
}
/** The shown message while the document and both history stacks are those it was shown on. */
function useLive(message: GestureMessage | null): GestureMessage | null {
const text = useEditorStore((s) => s.documentText)
const undo = useEditorStore((s) => s.undo.length)
const redo = useEditorStore((s) => s.redo.length)
if (!message) return null
const { stamp } = message
const same = stamp.text === text && stamp.undo === undo && stamp.redo === redo
return same ? message : null
const sameStamp = (a: Stamp, b: Stamp) =>
a.text === b.text && a.undo === b.undo && a.redo === b.redo
/**
* Any change of the document or of either history stack closes the shown message for
* good: an undo then a redo restores the same stamp, which must not bring it back (R-2).
*/
function useCloseOnChange(close: (now: Stamp) => void): void {
useEffect(
() =>
useEditorStore.subscribe((state, before) => {
const changed =
state.documentText !== before.documentText ||
state.undo.length !== before.undo.length ||
state.redo.length !== before.redo.length
if (changed) close(currentStamp())
}),
[close],
)
}
/** Hover with a mouse and focus inside hold the message; a touch never does (R-2). */
function useHold() {
const [hovered, setHovered] = useState(false)
const [focused, setFocused] = useState(false)
/**
* Hover with a mouse and focus inside hold the message; a touch never does (R-2). The hold
* belongs to the message it was taken on: a message that closes (« Défaire » pressed, the
* pill unmounted without pointerleave or blur) leaves no hold on the next one.
*/
function useHold(message: GestureMessage | null) {
const [hovered, setHovered] = useState<GestureMessage | null>(null)
const [focused, setFocused] = useState<GestureMessage | null>(null)
const handlers = {
onPointerEnter: (event: PointerEvent) => {
if (event.pointerType === 'mouse') setHovered(true)
if (event.pointerType === 'mouse') setHovered(message)
},
onPointerLeave: () => setHovered(false),
onFocus: () => setFocused(true),
onPointerLeave: () => setHovered(null),
onFocus: () => setFocused(message),
onBlur: (event: FocusEvent<HTMLElement>) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
setFocused(false)
setFocused(null)
}
},
}
return { held: hovered || focused, handlers }
const held = message !== null && (hovered === message || focused === message)
return { held, handlers }
}
/**
@@ -62,9 +83,17 @@ function useHold() {
* mouse hovers it or the focus is inside; any commit, undo or redo closes it.
*/
export function useGestureMessage() {
const [shown, setShown] = useState<GestureMessage | null>(null)
const message = useLive(shown)
const { held, handlers } = useHold()
const [message, setShown] = useState<GestureMessage | null>(null)
const { held, handlers } = useHold(message)
// A message shown after its own commit carries that commit's stamp: it stays.
const close = useCallback(
(now: Stamp) =>
setShown((shown) =>
shown && sameStamp(shown.stamp, now) ? shown : null,
),
[],
)
useCloseOnChange(close)
useEffect(() => {
if (!message || held) return
const timer = setTimeout(
@@ -95,12 +95,14 @@ function tracingActions(input: PlacementInput) {
}
/** A drop commits one update; the line under the drawing says it, or the core's refusal. */
function dropAction({ doc, context, message }: PlacementInput) {
function dropAction({ doc, context, message, dispatch }: PlacementInput) {
return (id: string, geometry: Geometry) => {
const annotation = doc.annotations.find((a) => a.id === id)
if (!annotation) return
const result = updateGeometry(annotation, geometry, context)
if (result.ok) {
// A kept move ends any refusal the strip still shows.
dispatch({ type: 'hint', hint: null })
const text = context.t(
`editor.annotations.message.moved.${annotation.kind}`,
)
@@ -5,6 +5,7 @@ import {
cleanup,
fireEvent,
render,
renderHook,
screen,
waitFor,
within,
@@ -14,6 +15,8 @@ import type { Annotation } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import EditStrip from '@/components/editor/annotations/EditStrip'
import { selectionLead } from '@/editor/annotations/stripLead'
import { initialUi } from '@/editor/annotations/uiState'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { fr } from '@/i18n/fr'
import { AnnounceContext } from '@/editor/focusRequest'
import { useLocaleStore } from '@/state/localeStore'
@@ -1822,6 +1825,73 @@ describe('the strip', () => {
expect(alert).toHaveTextContent(/^Déplacement refusé : /)
expect(alert.className).toContain('danger')
expect(within(line()).queryByRole('button', { name: /Défaire/ })).toBeNull()
// Its full text in the strip too (A6), shown but not announced a second time.
const copy = within(notice())
.getByText(/^Déplacement refusé : /)
.closest('p')!
expect(copy).toHaveAttribute('aria-hidden', 'true')
expect(copy).not.toHaveAttribute('role')
expect(copy.className).toContain('danger')
})
it('the message sits on its own row under the add buttons, always mounted', async () => {
await mount()
const add = screen.getByRole('button', { name: 'Ajouter un point' })
expect(line()).not.toContainElement(add)
expect(line()).toHaveClass('h-11', 'overflow-hidden')
expect(line()).toHaveAttribute('role', 'status')
})
it('an undo then a redo never brings the message back', async () => {
await mount()
await selectFromList()
drag(marker('anno-a'), [60, 40])
expect(line()).toHaveTextContent('Point déplacé')
act(() => void store.getState().undoStep())
act(() => void store.getState().redoStep())
expect(line()).not.toHaveTextContent('Point déplacé')
})
it('a hold ends with its message: after « Défaire » the next message still expires', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
await mount()
await selectFromList()
drag(marker('anno-a'), [60, 40])
const message = within(line()).getByTestId('gesture-message')
const undo = within(message).getByRole('button')
fireEvent.pointerEnter(message, { pointerType: 'mouse' })
act(() => undo.focus())
fireEvent.click(undo)
expect(line()).not.toHaveTextContent('Point déplacé')
drag(marker('anno-a'), [70, 40])
expect(line()).toHaveTextContent('Point déplacé')
act(() => void vi.advanceTimersByTime(6_100))
expect(line()).not.toHaveTextContent('Point déplacé')
} finally {
vi.useRealTimers()
}
})
it('a kept drop clears a refusal the strip still shows', async () => {
await mount()
const doc = store.getState().previewState!.document
const dispatch = vi.fn()
const { result } = renderHook(() =>
usePlacement({
ui: { ...initialUi, hint: 'Refusé' },
dispatch,
frame: null,
doc,
context: { t: (key) => key, locale: 'fr' },
message: { show: vi.fn() },
}),
)
act(() =>
result.current.onDrop('anno-a', { type: 'circle', cx: 60, cy: 40, r: 5 }),
)
expect(geometryOf('anno-a')).toMatchObject({ cx: 60, cy: 40 })
expect(dispatch).toHaveBeenCalledWith({ type: 'hint', hint: null })
})
it('expires after 6 s; a mouse hover pauses it, a touch does not', async () => {