feat(editor): view chips in one scrolling row, pinned budget follows

This commit is contained in:
bchanot committed 2026-11-21 20:11:10 +01:00
1 parent 9148bb273e
commit b4ebc2d288
14 files changed
+719 -46

No files matched your search

+1 -1
View File
@@ -167,7 +167,7 @@ test.describe('editor drawings (A2)', () => {
await showDrawing(page, dict)
await page
.getByRole('group', { name: dict['editor.annotations.views'] })
.getByRole('toolbar', { name: dict['editor.annotations.views'] })
.getByRole('button', { name: 'Détail A' })
.click()
// The view shows the crop of the parent drawing, not the whole drawing.
+4 -4
View File
@@ -46,7 +46,7 @@ const tool = (page: Page, id: string) =>
const viewChip = (page: Page, name: string) =>
page
.getByRole('group', { name: dict['editor.annotations.views'] })
.getByRole('toolbar', { name: dict['editor.annotations.views'] })
.getByRole('button', { name })
/**
@@ -680,8 +680,8 @@ function focusedUnderStrip(page: Page) {
}
/**
* A window too short for the pinned drawing column (U2 Task 17: pinned from 40.75 rem, 652 px,
* high below 1 280 px wide, 40.25 rem, 644 px, from there):
* A window too short for the pinned drawing column (U2 Task 17: pinned from 41.125 rem, 658 px,
* high below 1 280 px wide, 40.625 rem, 650 px, from there):
* the drawing scrolls under the strip as before, and the strip's margin brings a focus out.
*/
const belowPinnedHeight = (page: Page) =>
@@ -1308,7 +1308,7 @@ for (const viewport of CHIP_WINDOWS) {
await openEditor(page, dict, actor, seed.sheetId)
await expect(tool(page, 'point')).toBeEnabled()
const rows = await page
.getByRole('group', { name: dict['editor.annotations.views'] })
.getByRole('toolbar', { name: dict['editor.annotations.views'] })
.getByRole('button')
.evaluateAll(
(chips) =>
@@ -308,6 +308,7 @@ function CanvasColumn({
return (
<div data-drawing-column className="min-w-0 space-y-3">
<ViewSwitcher
className="mb-1"
views={doc.views}
current={scene.viewId}
onSelect={(id, chip) =>
@@ -1,46 +1,167 @@
import { useEffect, useRef, useState } from 'react'
import type { FocusEvent, KeyboardEvent } from 'react'
import type { SheetView } from '@faunosteo/core-wasm/types'
import Icon from '@/components/ui/Icon'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { useViewRow } from './viewRow'
import type { HintState } from './viewRow'
const CHIP =
'rounded-full border border-[var(--color-border)] px-3 py-1 text-sm ' +
'focus-visible:outline-none focus-visible:ring-2 ' +
'focus-visible:ring-[var(--color-accent)]'
const PILL =
'flex h-[1.875rem] items-center gap-1.5 whitespace-nowrap rounded-full border ' +
'px-3 text-sm group-focus-visible:outline group-focus-visible:outline-2 ' +
'group-focus-visible:outline-offset-2 ' +
'group-focus-visible:outline-[var(--color-accent)] '
const PILL_ACTIVE =
'border-[var(--color-ink)] bg-[var(--color-ink)] font-medium text-white'
const PILL_IDLE =
'border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-ink)]'
const HINT =
'pointer-events-none absolute inset-y-0 z-[2] flex w-[72px] items-center ' +
'px-1 '
const CHEVRON =
'pointer-events-auto relative flex h-7 w-7 items-center justify-center ' +
'rounded-full border border-[var(--color-border)] bg-[var(--color-surface)] ' +
'text-[var(--color-ink)] before:absolute before:-inset-2 before:content-[""]'
const DOT =
'absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--color-ink)] ' +
'ring-2 ring-white'
/** A fade at one edge of the row; its chevron is a mouse aid, never a tab stop. */
function Hint({
side,
state,
onPress,
}: {
side: 'start' | 'end'
state: HintState
onPress: () => void
}) {
const t = useT()
const start = side === 'start'
return (
<div
aria-hidden="true"
className={`${HINT} ${start ? 'left-0 justify-start' : 'right-0 justify-end'} ${
state[side] ? '' : 'invisible'
}`}
style={{
background: `linear-gradient(to ${start ? 'left' : 'right'}, transparent, var(--color-bg))`,
}}
>
<span
className={CHEVRON}
title={t(
start
? 'editor.annotations.views_previous'
: 'editor.annotations.views_next',
)}
onMouseDown={(event) => event.preventDefault()}
onClick={onPress}
>
<Icon
name="chevron-right"
size={14}
className={start ? 'rotate-180' : undefined}
/>
{state.dot === side && <span className={DOT} />}
</span>
</div>
)
}
/** One chip per view (board 04): the main view, then each detail view. */
export default function ViewSwitcher({
views,
current,
onSelect,
className,
}: {
views: readonly SheetView[]
current: string
/** `chip` is the pressed chip: the focus may land on it (Safari). */
onSelect: (viewId: string, chip: HTMLElement) => void
className?: string
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const rowRef = useRef<HTMLDivElement>(null)
const [focused, setFocused] = useState<string | null>(null)
const namesKey = `${locale}|${views.map((view) => view.name[locale]).join('|')}`
const { hints, reveal, page } = useViewRow(rowRef, current, namesKey)
const tabStop =
focused && views.some((view) => view.id === focused) ? focused : current
useEffect(() => setFocused(null), [current])
const onFocus = (event: FocusEvent<HTMLElement>) => {
const id = (event.target as HTMLElement).dataset.viewChip
if (id) setFocused(id)
}
const onBlur = (event: FocusEvent<HTMLElement>) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null))
setFocused(null)
}
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.altKey || event.ctrlKey || event.metaKey) return
const at = views.findIndex((view) => view.id === tabStop)
const last = views.length - 1
const to = {
ArrowRight: Math.min(at + 1, last),
ArrowLeft: Math.max(at - 1, 0),
Home: 0,
End: last,
}[event.key]
if (to === undefined || views.length === 0) return
event.preventDefault()
const id = views[to].id
const chips =
rowRef.current?.querySelectorAll<HTMLElement>('[data-view-chip]')
Array.from(chips ?? [])
.find((chip) => chip.dataset.viewChip === id)
?.focus({ preventScroll: true })
reveal(id)
}
const press = (side: 'start' | 'end') =>
hints.dot === side ? reveal(current) : page(side === 'start' ? -1 : 1)
return (
<div
role="group"
aria-label={t('editor.annotations.views')}
className="flex flex-wrap gap-2"
>
{views.map((view) => (
<button
key={view.id}
type="button"
aria-pressed={view.id === current}
onClick={(event) => onSelect(view.id, event.currentTarget)}
className={`${CHIP} ${
view.id === current
? 'bg-[var(--color-ink)] text-white'
: 'bg-[var(--color-surface)]'
}`}
>
{view.name[locale]}
</button>
))}
<div data-view-band className={`relative isolate h-11 ${className ?? ''}`}>
<div
ref={rowRef}
role="toolbar"
aria-label={t('editor.annotations.views')}
data-view-row
onFocus={onFocus}
onBlur={onBlur}
onKeyDown={onKeyDown}
className="flex h-11 flex-nowrap items-center overflow-x-auto overflow-y-hidden px-1 overscroll-x-contain touch-pan-x touch-pan-y touch-pinch-zoom scroll-px-[72px] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
>
{views.map((view) => {
const active = view.id === current
return (
<button
key={view.id}
type="button"
aria-pressed={active}
tabIndex={tabStop === view.id ? 0 : -1}
data-view-chip={view.id}
onClick={(event) =>
view.id !== current && onSelect(view.id, event.currentTarget)
}
className="group h-11 shrink-0 px-1 outline-none"
>
<span className={PILL + (active ? PILL_ACTIVE : PILL_IDLE)}>
{active && <Icon name="check" size={14} />}
{view.name[locale]}
</span>
</button>
)
})}
</div>
<Hint side="start" state={hints} onPress={() => press('start')} />
<Hint side="end" state={hints} onPress={() => press('end')} />
</div>
)
}
@@ -0,0 +1,175 @@
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from 'react'
import type { RefObject } from 'react'
import { useReducedMotion } from 'motion/react'
/** Width of a fade hint: a revealed chip lands clear of it. */
const HINT_WIDTH = 72
/** Page step of a chevron, as a share of the row's visible width. */
const PAGE_SHARE = 0.8
/**
* After the row opens, its view arrives in an effect after the first commit (the
* layer's, « Aller à »'s): every reveal in that window is instant, never a slide.
*/
export const OPENING_MS = 500
interface RowGeometry {
scrollLeft: number
clientWidth: number
scrollWidth: number
}
/** Chip edges relative to the row's content (scroll included). */
interface ChipSpan {
left: number
right: number
}
export interface HintState {
start: boolean
end: boolean
/** The side whose hint hides the active chip entirely. */
dot: 'start' | 'end' | null
}
/** Target `scrollLeft` that brings the chip clear of the hints, null when none. */
export function revealLeft(
row: RowGeometry,
chip: ChipSpan,
margin = HINT_WIDTH,
): number | null {
const { scrollLeft, clientWidth, scrollWidth } = row
const leftTarget = chip.left - margin
let target: number
if (chip.right - chip.left > clientWidth - 2 * margin) target = leftTarget
else if (chip.left < scrollLeft + margin) target = leftTarget
else if (chip.right > scrollLeft + clientWidth - margin)
target = chip.right - clientWidth + margin
else return null
target = Math.min(Math.max(target, 0), scrollWidth - clientWidth)
return Math.abs(target - scrollLeft) < 1 ? null : target
}
export function hintState(
row: RowGeometry,
active: ChipSpan | null,
margin = HINT_WIDTH,
): HintState {
const { scrollLeft, clientWidth, scrollWidth } = row
const start = scrollLeft > 1
const end = scrollLeft + clientWidth < scrollWidth - 1
let dot: HintState['dot'] = null
if (active && start && active.right <= scrollLeft + margin) dot = 'start'
else if (active && end && active.left >= scrollLeft + clientWidth - margin)
dot = 'end'
return { start, end, dot }
}
function chipOf(row: HTMLElement, id: string): HTMLElement | null {
const chips = row.querySelectorAll<HTMLElement>('[data-view-chip]')
return Array.from(chips).find((chip) => chip.dataset.viewChip === id) ?? null
}
function spanOf(row: HTMLElement, chip: HTMLElement): ChipSpan {
const box = chip.getBoundingClientRect()
const origin = row.getBoundingClientRect().left - row.scrollLeft
return { left: box.left - origin, right: box.right - origin }
}
const NO_HINTS: HintState = { start: false, end: false, dot: null }
/**
* The row's scroll behaviour: hint state, reveal of the active chip when `current`
* changes (never at a press), keyboard reveal and chevron paging. `namesKey` changes
* when the chip widths can (names or locale).
*/
export function useViewRow(
rowRef: RefObject<HTMLElement | null>,
current: string,
namesKey: string,
) {
const reduced = useReducedMotion()
const [hints, setHints] = useState<HintState>(NO_HINTS)
const opening = useRef(true)
const openingTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
)
const openWindow = useCallback(() => {
opening.current = true
clearTimeout(openingTimer.current)
openingTimer.current = setTimeout(() => {
opening.current = false
}, OPENING_MS)
}, [])
const refresh = useCallback(() => {
const row = rowRef.current
if (!row) return
const chip = chipOf(row, current)
setHints(hintState(row, chip && spanOf(row, chip)))
}, [rowRef, current])
const refreshRef = useRef(refresh)
refreshRef.current = refresh
const reveal = useCallback(
(id: string) => {
const row = rowRef.current
const chip = row && chipOf(row, id)
if (!row || !chip) return
const left = revealLeft(row, spanOf(row, chip))
if (left === null) return
const instant = opening.current || reduced
row.scrollTo({ left, behavior: instant ? 'auto' : 'smooth' })
},
[rowRef, reduced],
)
const page = useCallback(
(direction: 1 | -1) => {
const row = rowRef.current
if (!row) return
const left = direction * PAGE_SHARE * row.clientWidth
row.scrollBy({ left, behavior: reduced ? 'auto' : 'smooth' })
},
[rowRef, reduced],
)
useLayoutEffect(() => {
openWindow()
return () => clearTimeout(openingTimer.current)
}, [openWindow])
useLayoutEffect(() => {
reveal(current)
}, [current, reveal])
useLayoutEffect(() => {
refresh()
}, [refresh, namesKey])
useEffect(() => {
const row = rowRef.current
if (!row) return
const onScroll = () => refreshRef.current()
row.addEventListener('scroll', onScroll, { passive: true })
if (typeof ResizeObserver === 'undefined')
return () => row.removeEventListener('scroll', onScroll)
let width = row.clientWidth
const observer = new ResizeObserver(() => {
if (width === 0 && row.clientWidth > 0) openWindow()
width = row.clientWidth
refreshRef.current()
})
observer.observe(row)
return () => {
row.removeEventListener('scroll', onScroll)
observer.disconnect()
}
}, [rowRef, openWindow])
return { hints, reveal, page }
}
+2
View File
@@ -1753,6 +1753,8 @@ export const en: Dict = {
'editor.annotations.tool.zone': 'Zone',
'editor.annotations.tool.link': 'Link to a detail view',
'editor.annotations.views': 'Views',
'editor.annotations.views_previous': 'Previous views',
'editor.annotations.views_next': 'Next views',
'editor.annotations.unmeasured.hint':
'This drawing cannot be measured: add or fix its illustration (Annotations, Views section) before placing or moving elements.',
'editor.annotations.outside': 'Click inside the drawing.',
+2
View File
@@ -1819,6 +1819,8 @@ export const fr: Dict = {
'editor.annotations.tool.zone': 'Zone',
'editor.annotations.tool.link': 'Accès à une vue détaillée',
'editor.annotations.views': 'Vues',
'editor.annotations.views_previous': 'Vues précédentes',
'editor.annotations.views_next': 'Vues suivantes',
'editor.annotations.unmeasured.hint':
"Ce dessin n'est pas mesurable : ajoutez ou corrigez son illustration (Annotations, section Vues) avant de placer ou de déplacer des éléments.",
'editor.annotations.outside': "Cliquez à l'intérieur du dessin.",
+19 -13
View File
@@ -43,7 +43,10 @@ body,
under the strip, rev 4 I-3), except the strip's own commands, whose focus must not
scroll, and a dialog's controls, which scroll inside the dialog. The place is `hidden`
while another section shows, and the strip is sticky from 1 024 px only. Where the
drawing column is pinned (block below), its controls take the bar's margin instead. */
drawing column is pinned (block below), its controls take the bar's margin instead.
The chip row is scrolled sideways, not by these margins: its own `scroll-padding-inline:
72px` (the fade width) keeps a chip the browser focus-scrolls into view, a Tab entry for
one, clear of the fades in this Chromium; other browsers do it best effort. */
@media (min-width: 1024px) {
[data-place='annotations.drawing']:not([hidden])
:is(
@@ -63,17 +66,17 @@ body,
}
/* The drawing column (chips, tools, canvas, add row, message line) is pinned under the
strip, so no part of the drawing is ever under it while the side panel scrolls (U2 Task
17). Only where the column fits: below 40.75rem (652 px) of window height under 1 280 px
wide, 40.25rem (644 px) from there, the 365 px tool column beside a capped canvas does
17). Only where the column fits: below 41.125rem (658 px) of window height under 1 280 px
wide, 40.625rem (650 px) from there, the 365 px tool column beside a capped canvas does
not, nothing here applies and nothing is pinned. Under 1 280 px the add row is 44 px
high (a finger target, owner trial 2026-11-20), 8 px more than from 1 280 px. The
negative bottom margin lets the pinned travel run into the page's bottom space
(workspace gap + main padding): without it, the page's end pushed the column's top
under the strip at 1 180 x 820. */
@media (min-width: 1024px) and (max-width: 1279.98px) and (min-height: 40.75rem),
(min-width: 1280px) and (min-height: 40.25rem) {
@media (min-width: 1024px) and (max-width: 1279.98px) and (min-height: 41.125rem),
(min-width: 1280px) and (min-height: 40.625rem) {
[data-drawing-column] {
--edit-column-parts: 9.75rem;
--edit-column-parts: 10.125rem;
position: sticky;
top: var(--edit-pinned-top);
align-self: start;
@@ -81,11 +84,14 @@ body,
}
/* The column fits the window: the 4:3 box's width is capped by the small viewport height
less the pinned top and the column's other parts, plus its 2 px border. The parts:
chips 30 + gaps 36 + add row 44 + line 44 + border 2 = 156 px, 9.75rem; from 1 280 px
the add row is 36 px, 148 px, 9.25rem. svh: a toolbar collapsing during a scroll
never resizes the box. Unchanged when the browser window (not the screen) is
1 024 x 768, 1 180 x 820 or 1 280 x 800; smaller in shorter windows (capped below
680, 797 and 672 px of window height). */
chip band 44 + gaps 4 (band to canvas) + 12 + 12 + add row 44 + line 44 + border 2 =
162 px, 10.125rem; from 1 280 px the add row is 36 px, 154 px, 9.625rem. The chips are
one scrolling row of a fixed height, never several rows. The pinned threshold is the
parts plus 496 px (the room the canvas and the pinned top need): 658 and 650 px,
41.125rem and 40.625rem. svh: a toolbar collapsing during a scroll never resizes the
box. Unchanged when the browser window (not the screen) is 1 024 x 768, 1 180 x 820 or
1 280 x 800; smaller in shorter windows (capped below 686, 803 and 678 px of window
height). */
[data-drawing-column] [data-canvas-box] {
max-width: calc(
(100svh - var(--edit-pinned-top) - var(--edit-column-parts)) * 4 / 3 + 2px
@@ -109,9 +115,9 @@ body,
scroll-margin-top: calc(var(--shell-top-bar-height) + 0.5rem);
}
}
@media (min-width: 1280px) and (min-height: 40.25rem) {
@media (min-width: 1280px) and (min-height: 40.625rem) {
[data-drawing-column] {
--edit-column-parts: 9.25rem;
--edit-column-parts: 9.625rem;
}
}
/* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */
@@ -0,0 +1,59 @@
/** The view row's pure rules: where to scroll to reveal a chip, which hints to show. */
import { describe, expect, it } from 'vitest'
import { hintState, revealLeft } from '@/components/editor/annotations/viewRow'
const row = (scrollLeft: number, clientWidth = 300, scrollWidth = 900) => ({
scrollLeft,
clientWidth,
scrollWidth,
})
describe('revealLeft', () => {
it('is null when the chip is already clear of both hints', () => {
expect(revealLeft(row(100), { left: 200, right: 300 })).toBeNull()
})
it('brings a chip under the start hint 72 px in', () => {
expect(revealLeft(row(200), { left: 220, right: 300 })).toBe(148)
})
it('brings a chip under the end hint 72 px from the end', () => {
expect(revealLeft(row(0), { left: 200, right: 280 })).toBe(52)
})
it('clamps at 0 and at the end of the content', () => {
expect(revealLeft(row(50), { left: 10, right: 60 })).toBe(0)
expect(revealLeft(row(500), { left: 880, right: 900 })).toBe(600)
})
it('treats a chip wider than the clear span the same from both sides', () => {
const wide = { left: 300, right: 500 }
const fromLeft = revealLeft(row(0), wide)
const fromRight = revealLeft(row(600), wide)
expect(fromLeft).toBe(228)
expect(fromRight).toBe(fromLeft)
expect(revealLeft(row(228), wide)).toBeNull()
})
})
describe('hintState', () => {
it('shows each hint only where content continues', () => {
expect(hintState(row(0), null)).toMatchObject({ start: false, end: true })
expect(hintState(row(300), null)).toMatchObject({ start: true, end: true })
expect(hintState(row(600), null)).toMatchObject({
start: true,
end: false,
})
})
it('puts the dot on the side whose hint hides the active chip', () => {
expect(hintState(row(300), { left: 310, right: 360 }).dot).toBe('start')
expect(hintState(row(300), { left: 560, right: 640 }).dot).toBe('end')
expect(hintState(row(300), { left: 400, right: 450 }).dot).toBeNull()
})
it('never puts the dot on a side that is not shown', () => {
expect(hintState(row(0), { left: 10, right: 60 }).dot).toBeNull()
expect(hintState(row(600), { left: 850, right: 890 }).dot).toBeNull()
})
})
@@ -821,7 +821,7 @@ describe('keys while tracing (H3)', () => {
it('Enter on a view chip or a list row never closes the tracing', async () => {
await traced()
const views = screen.getByRole('group', { name: 'Vues' })
const views = screen.getByRole('toolbar', { name: 'Vues' })
fireEvent.keyDown(within(views).getAllByRole('button')[0], {
key: 'Enter',
})
+1 -1
View File
@@ -95,7 +95,7 @@ const canvas = (readOnly: boolean) =>
)
const rows = () => within(card()).getAllByRole('button')
const chip = (name: string) =>
within(screen.getByRole('group', { name: 'Vues' })).getByRole('button', {
within(screen.getByRole('toolbar', { name: 'Vues' })).getByRole('button', {
name,
})
@@ -717,7 +717,7 @@ describe('fix round 1: no silent loss on the way out', () => {
await select()
await userEvent.setup().click(moveButton())
fireEvent.click(arrow('la droite'))
const views = screen.getByRole('group', { name: 'Vues' })
const views = screen.getByRole('toolbar', { name: 'Vues' })
fireEvent.click(within(views).getByRole('button', { name: 'Tête' }))
expect(useAnnotationWork.getState().question?.work).toBe('move')
expect(screen.getByTestId('move-mode-bar')).toBeInTheDocument()
@@ -0,0 +1,307 @@
/** U2 criterion 32: the view chips in one scrolling row (roving tab stop, hints, reveal). */
import '../helpers/motion'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { SheetView } from '@faunosteo/core-wasm/types'
import ViewSwitcher from '@/components/editor/annotations/ViewSwitcher'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import { OPENING_MS } from '@/components/editor/annotations/viewRow'
import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { openReady, resetStore } from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const NAMES = ['Vue 1', 'Vue 2', 'Vue 3', 'Vue 4', 'Vue 5']
const viewsOf = (names = NAMES) =>
names.map((name, index) => ({
kind: index === 0 ? 'main' : 'detail',
id: `v${index + 1}`,
name: { fr: name, en: `${name} en` },
})) as unknown as SheetView[]
const toolbar = () => screen.getByRole('toolbar', { name: 'Vues' })
const chip = (name: string) =>
within(toolbar()).getByRole('button', { name: new RegExp(name) })
const chips = () => within(toolbar()).getAllByRole('button')
const tabStops = () => chips().filter((c) => c.tabIndex === 0)
function renderRow(onSelect = vi.fn(), views = viewsOf(), current = 'v3') {
const view = render(
<ViewSwitcher views={views} current={current} onSelect={onSelect} />,
)
return {
onSelect,
again: (next: { views?: SheetView[]; current?: string }) =>
view.rerender(
<ViewSwitcher
views={next.views ?? views}
current={next.current ?? current}
onSelect={onSelect}
/>,
),
}
}
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
resetWork()
vi.useRealTimers()
delete (Element.prototype as unknown as Record<string, unknown>).scrollTo
})
describe('the roving tab stop and the keys', () => {
it('has one tab stop, on the active chip', () => {
renderRow()
expect(tabStops()).toEqual([chip('Vue 3')])
})
it('moves the focus by arrow, Home and End without activating', async () => {
const { onSelect } = renderRow()
const user = userEvent.setup()
act(() => chip('Vue 3').focus())
await user.keyboard('{ArrowRight}')
expect(chip('Vue 4')).toHaveFocus()
await user.keyboard('{ArrowLeft}{ArrowLeft}')
expect(chip('Vue 2')).toHaveFocus()
await user.keyboard('{End}')
expect(chip('Vue 5')).toHaveFocus()
await user.keyboard('{ArrowRight}')
expect(chip('Vue 5')).toHaveFocus()
await user.keyboard('{Home}')
expect(chip('Vue 1')).toHaveFocus()
await user.keyboard('{ArrowLeft}')
expect(chip('Vue 1')).toHaveFocus()
expect(tabStops()).toEqual([chip('Vue 1')])
expect(chip('Vue 3')).toHaveAttribute('aria-pressed', 'true')
expect(chip('Vue 1')).toHaveAttribute('aria-pressed', 'false')
expect(onSelect).not.toHaveBeenCalled()
})
it.each(['altKey', 'ctrlKey', 'metaKey'])(
'ignores an arrow with %s',
(modifier) => {
renderRow()
act(() => chip('Vue 3').focus())
fireEvent.keyDown(chip('Vue 3'), { key: 'ArrowRight', [modifier]: true })
expect(chip('Vue 3')).toHaveFocus()
},
)
it('activates a non-active chip with Enter, once', async () => {
const { onSelect } = renderRow()
act(() => chip('Vue 2').focus())
await userEvent.setup().keyboard('{Enter}')
expect(onSelect).toHaveBeenCalledTimes(1)
expect(onSelect).toHaveBeenCalledWith('v2', chip('Vue 2'))
})
it('does not select the active chip', async () => {
const { onSelect } = renderRow()
await userEvent.setup().click(chip('Vue 3'))
expect(onSelect).not.toHaveBeenCalled()
})
it('puts the tab stop back on the active chip when the focus leaves', async () => {
renderRow()
act(() => chip('Vue 3').focus())
await userEvent.setup().keyboard('{End}')
expect(tabStops()).toEqual([chip('Vue 5')])
act(() => chip('Vue 5').blur())
expect(tabStops()).toEqual([chip('Vue 3')])
})
it('keeps a tab stop when the focused chip is removed', async () => {
const views = viewsOf()
const { again } = renderRow(vi.fn(), views)
act(() => chip('Vue 3').focus())
await userEvent.setup().keyboard('{End}')
await act(async () => again({ views: views.slice(0, 4) }))
expect(tabStops()).toEqual([chip('Vue 3')])
})
})
describe('the chips and their hints', () => {
it('marks only the active chip with the check', () => {
renderRow()
expect(chip('Vue 3').querySelector('svg')).not.toBeNull()
expect(chips().filter((c) => c.querySelector('svg') !== null)).toHaveLength(
1,
)
})
it('keeps the hints out of the tab order and the accessibility tree', () => {
const { container } = render(
<ViewSwitcher views={viewsOf()} current="v3" onSelect={vi.fn()} />,
)
const hints = container.querySelectorAll('[data-view-band] > [aria-hidden]')
expect(hints).toHaveLength(2)
for (const hint of hints) {
expect(hint.querySelector('button, [tabindex]')).toBeNull()
}
expect(hints[0].querySelector('[title]')).toHaveAttribute(
'title',
'Vues précédentes',
)
expect(hints[1].querySelector('[title]')).toHaveAttribute(
'title',
'Vues suivantes',
)
})
})
/** Row geometry: 300 px wide showing 900 of content, each chip 100 px. */
function stubGeometry(scrollWidth = 900, clientWidth = 300) {
const row = toolbar()
Object.defineProperty(row, 'clientWidth', {
configurable: true,
value: clientWidth,
})
Object.defineProperty(row, 'scrollWidth', {
configurable: true,
value: scrollWidth,
})
row.getBoundingClientRect = () => ({ left: 0, right: clientWidth }) as DOMRect
chips().forEach((c, index) => {
c.getBoundingClientRect = () =>
({ left: index * 100, right: index * 100 + 100 }) as DOMRect
})
}
describe('the reveal of the active chip', () => {
let scrollTo: ReturnType<typeof vi.fn>
beforeEach(() => {
scrollTo = vi.fn()
Object.defineProperty(Element.prototype, 'scrollTo', {
configurable: true,
value: scrollTo,
})
})
it('slides to the chip past the end hint after the opening window', () => {
vi.useFakeTimers()
const { again } = renderRow(vi.fn(), viewsOf(), 'v1')
act(() => void vi.advanceTimersByTime(OPENING_MS + 1))
stubGeometry()
again({ current: 'v5' })
// chip 400 to 500: its right lands 72 px from the end of the 300 px row.
expect(scrollTo).toHaveBeenCalledTimes(1)
expect(scrollTo).toHaveBeenCalledWith({ left: 272, behavior: 'smooth' })
})
it('places it instantly inside the opening window', () => {
vi.useFakeTimers()
const { again } = renderRow(vi.fn(), viewsOf(), 'v1')
stubGeometry()
again({ current: 'v5' })
expect(scrollTo).toHaveBeenCalledWith({ left: 272, behavior: 'auto' })
})
it('shows the end hint again when a name change widens the content', () => {
const { container } = render(
<ViewSwitcher views={viewsOf()} current="v1" onSelect={vi.fn()} />,
)
const endHint = () =>
container.querySelectorAll('[data-view-band] > [aria-hidden]')[1]
expect(endHint()).toHaveClass('invisible')
stubGeometry()
act(() => useLocaleStore.setState({ locale: 'en' }))
expect(endHint()).not.toHaveClass('invisible')
})
})
describe('a press refused by the drawing guard', () => {
const withView = (text: string) =>
insert(text, {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 10, width: 80, height: 80 },
parent_view_id: 'view-main',
},
})
it('leaves the active view, and the row does not move', async () => {
const scrollTo = vi.fn()
Object.defineProperty(Element.prototype, 'scrollTo', {
configurable: true,
value: scrollTo,
})
await openReady({ text: withView(withPoints()) })
render(
<div data-editor-workspace>
<AnnotationsTab
readOnly={false}
navigate={vi.fn()}
reloadSheet={vi.fn()}
section="drawing"
visited={['drawing']}
onOpenSection={vi.fn()}
onBack={vi.fn()}
/>
<DrawingGuardDialog />
</div>,
)
await screen.findByRole('list', { name: 'Annotations de la vue' })
const user = userEvent.setup()
await user.click(
within(
screen.getByRole('list', { name: 'Annotations de la vue' }),
).getAllByRole('button')[0],
)
await user.click(
await screen.findByRole('button', { name: 'Déplacer le point' }),
)
fireEvent.click(
within(screen.getByTestId('move-mode-bar')).getByRole('button', {
name: 'Déplacer vers la droite',
}),
)
// Geometry that would reveal the detail chip (the second, past the end hint).
stubGeometry(700, 200)
scrollTo.mockClear()
const head = chip('Tête')
await user.click(head)
expect(useAnnotationWork.getState().question?.work).toBe('move')
await user.click(await screen.findByRole('button', { name: 'Continuer' }))
expect(chip('Tête')).toHaveAttribute('aria-pressed', 'false')
expect(scrollTo).not.toHaveBeenCalled()
// Positive control: « Abandonner » makes the change, and that reveals the chip.
await user.click(head)
await user.click(await screen.findByRole('button', { name: 'Abandonner' }))
await waitFor(() =>
expect(chip('Tête')).toHaveAttribute('aria-pressed', 'true'),
)
expect(scrollTo).toHaveBeenCalled()
})
})
const withPoints = () =>
[point('a', 50, 50, 5), point('b', 20, 20, 8)].reduce(
(text, p) => insert(text, p),
drawnText(),
)
@@ -1422,7 +1422,7 @@ describe('Safari: the focus after a press that commits a pending series', () =>
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
const held = vertex(1)
const seen = watchCommitFocus()
const views = screen.getByRole('group', { name: 'Vues' })
const views = screen.getByRole('toolbar', { name: 'Vues' })
const chip = within(views).getByRole('button', { name: 'Tête' })
fireEvent.click(chip)
expect(pointsOf('z')![0]).toEqual([20.5, 20])