feat(editor): Plus dropdown overlay with back request, sticky sidebar

This commit is contained in:
bchanot committed 2026-11-13 22:32:51 +01:00
1 parent 8a60128311
commit ca5804a8b7
8 files changed
+536 -55

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
import { fr } from '@/i18n/fr'
import type { Page, TestInfo } from '@playwright/test'
import { stepUpAdmin } from '../support/admin'
import {
expect,
expectAccessible,
expectNoHorizontalOverflow,
test,
} from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
draftPath,
draftTitle,
editorActor,
pointOf,
seedDraft,
shapeWith,
} from '../support/editor'
import { signIn } from '../support/shell'
// V1-2.6 R2F-7 (items 6, 7): « Plus » is an overlay that moves nothing, and the left
// sidebar stays in view while the content scrolls.
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const seedShape = shapeWith(
pointOf('p1', 'main', { cx: 500, cy: 400, r: 40 }, 'Point un'),
)
async function openAt(page: Page, width: number, height = 800) {
const actor = await editorActor('fr')
const seed = await seedDraft(actor, { shape: seedShape })
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await page.setViewportSize({ width, height })
await page.goto(draftPath(seed.sheetId))
await expect(
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
).toBeVisible()
}
const more = (page: Page) =>
page.getByRole('button', { name: dict['editor.tab.more'], exact: true })
const list = (page: Page) => page.locator('#editor-tabs-more')
/** The boxes that must not move when « Plus » opens: the row, the page below it, the document. */
async function layout(page: Page) {
return page.evaluate(() => {
const row = document.querySelector('[data-editor-tabs]')!
const below = row.nextElementSibling
const box = (el: Element | null) => {
const r = el?.getBoundingClientRect()
return r && [r.x, r.y, r.width, r.height].map(Math.round)
}
const root = document.documentElement
return {
row: box(row),
below: box(below),
doc: [root.scrollWidth, root.scrollHeight],
}
})
}
test.describe('« Plus » dropdown', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'the widths are set by the tests themselves') // floor-guard: allow C16 phone width read-only, set by the tests
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
for (const width of [375, 320]) {
test(`at ${width} px it overlays without moving anything, axe open`, async ({
page,
}) => {
await openAt(page, width)
await expect(more(page)).toBeVisible()
const closed = await layout(page)
await more(page).click()
await expect(list(page)).toBeVisible()
expect(await layout(page), 'boxes open vs closed').toEqual(closed)
const menu = await list(page).boundingBox()
expect(menu!.x).toBeGreaterThanOrEqual(0)
expect(menu!.x + menu!.width).toBeLessThanOrEqual(width)
await expectNoHorizontalOverflow(page, `« Plus » open at ${width} px`)
await expectAccessible(page, `« Plus » open at ${width} px`)
})
}
test('closes on a selection, outside tap and Escape, focus kept sane', async ({
page,
}) => {
await openAt(page, 375)
await more(page).click()
await page.keyboard.press('Escape')
await expect(list(page)).toHaveCount(0)
await expect(more(page)).toBeFocused()
await more(page).click()
await page
.getByRole('heading', { level: 1, name: draftTitle(dict) })
.click()
await expect(list(page)).toHaveCount(0)
await more(page).click()
await list(page)
.getByRole('button', { name: dict['editor.tab.findings'] })
.click()
await expect(list(page)).toHaveCount(0)
await expect(more(page)).toHaveAttribute('aria-expanded', 'false')
})
})
test.describe('the sidebar stays fixed', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'the widths are set by the tests themselves') // floor-guard: allow C16 sidebar needs a desktop width
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
const firstLink = (page: Page) =>
page
.getByRole('navigation', { name: dict['shell.nav_label'] })
.getByRole('link')
.first()
async function expectInView(page: Page, state: string) {
const box = await firstLink(page).boundingBox()
const height = await page.evaluate(() => window.innerHeight)
expect(box!.y, `${state}: top`).toBeGreaterThanOrEqual(0)
expect(box!.y + box!.height, `${state}: bottom`).toBeLessThanOrEqual(height)
}
test('at 1280 px the editor sidebar stays while the page scrolls, no sideways scroll', async ({
page,
}) => {
await openAt(page, 1280)
await expectAccessible(page, 'the editor at 1280 px, top')
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight))
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0)
await expectInView(page, 'scrolled editor')
await expectNoHorizontalOverflow(page, 'the editor at 1280 px')
})
test('at 1280 x 500 the sidebar scrolls on its own', async ({ page }) => {
await openAt(page, 1280, 500)
const own = await page.evaluate(() => {
const aside = document.querySelector('aside') as HTMLElement
aside.scrollTop = aside.scrollHeight
return {
scrolls: aside.scrollHeight > aside.clientHeight,
top: aside.scrollTop,
page: window.scrollY,
}
})
expect(own.scrolls).toBe(true)
expect(own.top).toBeGreaterThan(0)
expect(own.page).toBe(0)
})
test('at 1024 px the default shell sidebar stays while the page scrolls', async ({
page,
}) => {
await openAt(page, 1024)
await page.goto('/app')
await expect(firstLink(page)).toBeVisible()
await expectAccessible(page, 'the dashboard at 1024 px, top')
await page.evaluate(() => {
document.querySelector('main')!.style.minHeight = '3000px'
window.scrollTo(0, 1000)
})
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0)
await expectInView(page, 'scrolled dashboard')
await expectNoHorizontalOverflow(page, 'the dashboard at 1024 px')
})
})
+2
View File
@@ -417,6 +417,8 @@ export async function openTab(page: Page, dict: Dict, tab: string) {
.locator('#editor-tabs-more')
.getByRole('button', { name })
.click()
// The dropdown fades out: wait for it to be gone before the next move.
await expect(page.locator('#editor-tabs-more')).toHaveCount(0)
} else {
await page.getByRole('tab', { name }).click()
}
+63 -53
View File
@@ -1,6 +1,10 @@
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import { inWorkspace } from '@/editor/annotations/deselect'
import { isTextField } from '@/editor/focusRequest'
import type { KeyboardEvent } from 'react'
import {
AnimatePresence,
motion,
useIsPresent,
useReducedMotion,
} from 'motion/react'
import { useEditorStore } from '@/editor/state/editorStore'
import { usePlural } from '@/editor/plural'
import {
@@ -13,6 +17,7 @@ import {
import type { TabTier } from '@/editor/useViewport'
import { useT } from '@/i18n/useT'
import HistoryButtons from './HistoryButtons'
import { MORE_LIST_ID, useMoreDismiss, useMoreMenu } from './useMoreMenu'
const BASE =
'min-h-11 whitespace-nowrap border-b-2 px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
@@ -99,71 +104,73 @@ interface MoreTabsProps {
onSelect: SelectTab
}
/**
* While « Plus » is open, Escape closes it and returns the focus to it. Captured on the
* document so the key is marked handled before any body's deselection sees it; a modal
* dialog keeps its own Escape.
*/
function useMoreEscape(open: boolean, close: () => void) {
const closeRef = useRef(close)
closeRef.current = close
useEffect(() => {
if (!open) return
const onKey = (event: globalThis.KeyboardEvent) => {
if (event.key !== 'Escape' || event.isComposing) return
if (document.querySelector('dialog[open]')) return
if (isTextField(event.target) || !inWorkspace(event.target)) return
event.preventDefault()
closeRef.current()
document.getElementById(MORE_BUTTON_ID)?.focus()
}
document.addEventListener('keydown', onKey, true)
return () => document.removeEventListener('keydown', onKey, true)
}, [open])
interface MoreListProps {
more: readonly EditorTabId[]
active: EditorTabId
onPick: (tab: EditorTabId) => void
}
/** Below 640 px: « Plus » and its disclosure of the tabs that do not fit. */
/** The overlay list: a closing list is inert, so nothing in it takes focus or a tap. */
function MoreList({ more, active, onPick }: MoreListProps) {
const t = useT()
const reduced = useReducedMotion()
const present = useIsPresent()
const hidden = { opacity: 0, y: reduced ? 0 : -4 }
return (
<motion.ul
id={MORE_LIST_ID}
inert={!present}
initial={hidden}
animate={{
opacity: 1,
y: 0,
transition: { duration: reduced ? 0 : 0.15 },
}}
exit={{ ...hidden, transition: { duration: reduced ? 0 : 0.12 } }}
className="absolute inset-x-0 top-full z-20 flex flex-wrap gap-1 border border-[var(--color-border)] bg-[var(--color-surface)] p-1 shadow-md"
>
{more.map((tab) => (
<li key={tab}>
<button
id={tabDomId(tab)}
type="button"
aria-pressed={tab === active}
onClick={() => onPick(tab)}
className={`rounded-md px-3 ${BASE} border-b-0 ${tab === active ? ACTIVE : IDLE}`}
>
{t(`editor.tab.${tab}`)}
<ErrorCount tab={tab} />
</button>
</li>
))}
</motion.ul>
)
}
/** Below 640 px: « Plus » and its dropdown of the tabs that do not fit. */
function MoreTabs({ more, active, onSelect }: MoreTabsProps) {
const t = useT()
const [open, setOpen] = useState(false)
const { open, close, toggle } = useMoreMenu(active)
const pick = (tab: EditorTabId) => {
onSelect(tab)
setOpen(false)
close()
}
useMoreEscape(open, () => setOpen(false))
useMoreDismiss(open, close)
return (
<>
<button
id={MORE_BUTTON_ID}
type="button"
aria-expanded={open}
aria-controls="editor-tabs-more"
onClick={() => setOpen((value) => !value)}
aria-controls={MORE_LIST_ID}
onClick={toggle}
className={`-mb-px ${BASE} ${more.includes(active) ? ACTIVE : IDLE}`}
>
{t('editor.tab.more')}
</button>
{open && (
<ul
id="editor-tabs-more"
className="order-last flex w-full flex-wrap gap-1 border-t border-[var(--color-border)] py-1"
>
{more.map((tab) => (
<li key={tab}>
<button
id={tabDomId(tab)}
type="button"
aria-pressed={tab === active}
onClick={() => pick(tab)}
className={`rounded-md px-3 ${BASE} border-b-0 ${tab === active ? ACTIVE : IDLE}`}
>
{t(`editor.tab.${tab}`)}
<ErrorCount tab={tab} />
</button>
</li>
))}
</ul>
)}
<AnimatePresence>
{open && <MoreList more={more} active={active} onPick={pick} />}
</AnimatePresence>
</>
)
}
@@ -177,7 +184,7 @@ interface EditorTabsProps {
/**
* The draft's tab row (boards 04 and 05): the five tabs from 640 px (the row may wrap
* between 640 and 1 023 px, never scroll sideways), Annotations and
* Vérification below it with « Plus » opening a disclosure of the others (no measurement).
* Vérification below it with « Plus » opening a dropdown overlay of the others (no measurement).
* « Défaire » and « Refaire » sit at the right end of the row on every tab.
*/
export default function EditorTabs({
@@ -187,7 +194,10 @@ export default function EditorTabs({
}: EditorTabsProps) {
const { shown, more } = tabsFor(tier)
return (
<div className="flex flex-wrap items-end gap-1 border-b border-[var(--color-border)]">
<div
data-editor-tabs
className="relative flex flex-wrap items-end gap-1 border-b border-[var(--color-border)]"
>
<TabList shown={shown} active={active} onSelect={onSelect} />
{more.length > 0 && (
<MoreTabs more={more} active={active} onSelect={onSelect} />
@@ -0,0 +1,111 @@
import { useCallback, useEffect, useState } from 'react'
import { inWorkspace } from '@/editor/annotations/deselect'
import { isTextField } from '@/editor/focusRequest'
import { MORE_BUTTON_ID, type EditorTabId } from '@/editor/tabs'
export const MORE_LIST_ID = 'editor-tabs-more'
const ROW_MARK = '[data-editor-tabs]'
const MENU_PARTS = `#${MORE_LIST_ID}, #${MORE_BUTTON_ID}`
/** A closing tap's click follows within this delay or never comes (a drag). */
const SWALLOW_MS = 600
/** The platform's back request (Android Back), where the browser offers it. */
interface CloseWatcherLike {
onclose: (() => void) | null
destroy: () => void
}
type CloseWatcherCtor = new () => CloseWatcherLike
const focusMore = () => document.getElementById(MORE_BUTTON_ID)?.focus()
/**
* Open state of « Plus », closed by any change of the active tab (render-time reset, no
* effect).
*/
export function useMoreMenu(active: EditorTabId) {
const [open, setOpen] = useState(false)
const [seen, setSeen] = useState(active)
if (seen !== active) {
setSeen(active)
setOpen(false)
}
const close = useCallback(() => setOpen(false), [])
return { open, close, toggle: () => setOpen((value) => !value) }
}
/**
* While « Plus » is open, Escape closes it and returns the focus to it. Captured on the
* document so the key is marked handled before any body's deselection sees it; a modal
* dialog keeps its own Escape.
*/
function useMoreEscape(open: boolean, close: () => void) {
useEffect(() => {
if (!open) return
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.isComposing) return
if (document.querySelector('dialog[open]')) return
if (isTextField(event.target) || !inWorkspace(event.target)) return
event.preventDefault()
close()
focusMore()
}
document.addEventListener('keydown', onKey, true)
return () => document.removeEventListener('keydown', onKey, true)
}, [open, close])
}
/** Swallows the click that completes a closing tap, once, so the page never sees it. */
function swallowNextClick() {
const stop = (event: Event) => {
event.stopPropagation()
event.preventDefault()
release()
}
const timer = window.setTimeout(() => release(), SWALLOW_MS)
const release = () => {
window.clearTimeout(timer)
document.removeEventListener('click', stop, true)
}
document.addEventListener('click', stop, true)
}
/**
* A press outside « Plus » closes it. Taps outside the tab row never reach the page (no
* deselection, no click); taps inside the row (a tab, Défaire) go on and act.
*/
function useOutsidePress(open: boolean, close: () => void) {
useEffect(() => {
if (!open) return
const onDown = (event: PointerEvent) => {
const target = event.target instanceof Element ? event.target : null
if (target?.closest(MENU_PARTS)) return
close()
if (target?.closest(ROW_MARK)) return
event.stopPropagation()
swallowNextClick()
}
document.addEventListener('pointerdown', onDown, true)
return () => document.removeEventListener('pointerdown', onDown, true)
}, [open, close])
}
/** The platform's back request closes the open menu before history goes back. */
function useBackRequest(open: boolean, close: () => void) {
useEffect(() => {
const Ctor = (window as { CloseWatcher?: CloseWatcherCtor }).CloseWatcher
if (!open || !Ctor) return
const watcher = new Ctor()
watcher.onclose = () => {
close()
focusMore()
}
return () => watcher.destroy()
}, [open, close])
}
/** Every way « Plus » closes besides a selection and a tab change. */
export function useMoreDismiss(open: boolean, close: () => void) {
useMoreEscape(open, close)
useOutsidePress(open, close)
useBackRequest(open, close)
}
@@ -48,7 +48,7 @@ export function Sidebar({ shell }: { shell: ShellBreakpoint }) {
const t = useT()
return (
<aside
className={`${shell.sidebar} border-r border-[var(--color-border)] bg-[var(--color-surface)]`}
className={`${shell.sidebar} sticky top-0 h-dvh self-start overflow-y-auto border-r border-[var(--color-border)] bg-[var(--color-surface)]`}
>
<div className="px-5 py-5">
<Link to="/app" aria-label={t('shell.nav.dashboard')} className="inline-block">
@@ -0,0 +1,168 @@
/** « Plus »: the dropdown overlay and every way it closes. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import EditorTabs from '@/components/editor/EditorTabs'
import type { EditorTabId } from '@/editor/tabs'
import { useLocaleStore } from '@/state/localeStore'
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
const more = () => screen.getByRole('button', { name: 'Plus' })
const list = () => document.getElementById('editor-tabs-more')
const gone = () => waitFor(() => expect(list()).toBeNull())
/** The row in a page: a body that records the presses that reach it. */
function Page({ seen }: { seen: (kind: string) => void }) {
const [active, setActive] = useState<EditorTabId>('annotations')
return (
<div
onPointerDown={() => seen('pointerdown')}
onClick={() => seen('click')}
>
<div data-editor-workspace>
<EditorTabs active={active} tier="small" onSelect={setActive} />
<button type="button">outside</button>
</div>
<button type="button" onClick={() => setActive('general')}>
elsewhere
</button>
</div>
)
}
function mount() {
const seen = vi.fn()
render(<Page seen={seen} />)
return { seen, user: userEvent.setup() }
}
describe('the overlay', () => {
it('opens as an absolute full-width overlay under the row and closes on a second click', async () => {
const { user } = mount()
await user.click(more())
expect(more()).toHaveAttribute('aria-expanded', 'true')
expect(list()).toHaveClass('absolute', 'inset-x-0', 'top-full', 'z-20')
expect(document.querySelector('[data-editor-tabs]')).toHaveClass('relative')
await user.click(more())
expect(more()).toHaveAttribute('aria-expanded', 'false')
await gone()
})
it('a closing list is inert', async () => {
const { user } = mount()
await user.click(more())
expect(list()).not.toHaveAttribute('inert')
await user.click(more())
if (list()) expect(list()).toHaveAttribute('inert')
await gone()
})
it('closes on a selection and on a tab change made elsewhere', async () => {
const { user } = mount()
await user.click(more())
await user.click(screen.getByRole('button', { name: 'Constats' }))
expect(more()).toHaveAttribute('aria-expanded', 'false')
await gone()
await user.click(more())
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(more()).toHaveAttribute('aria-expanded', 'false')
})
})
describe('outside presses', () => {
it('a press outside the row closes the menu and never reaches the page', async () => {
const { user, seen } = mount()
await user.click(more())
seen.mockClear()
await user.click(screen.getByRole('button', { name: 'elsewhere' }))
expect(more()).toHaveAttribute('aria-expanded', 'false')
expect(seen).not.toHaveBeenCalled()
expect(screen.getByRole('tab', { name: 'Annotations' })).toHaveAttribute(
'aria-selected',
'true',
)
})
it('the next press after the closing tap acts normally', async () => {
const { user } = mount()
await user.click(more())
await user.click(screen.getByRole('button', { name: 'elsewhere' }))
await user.click(screen.getByRole('button', { name: 'elsewhere' }))
expect(more()).toHaveClass('text-[var(--color-accent-strong)]')
})
it('a press inside the row closes the menu and goes on to act', async () => {
const { user } = mount()
await user.click(more())
await user.click(screen.getByRole('tab', { name: 'Vérification' }))
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute(
'aria-selected',
'true',
)
})
})
describe('Escape', () => {
it('closes the menu and focuses « Plus »', async () => {
const { user } = mount()
await user.click(more())
await user.keyboard('{Escape}')
expect(more()).toHaveAttribute('aria-expanded', 'false')
expect(document.activeElement).toBe(more())
})
it('leaves the menu to an open modal dialog', async () => {
const { user } = mount()
await user.click(more())
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
document.body.append(dialog)
await user.keyboard('{Escape}')
expect(more()).toHaveAttribute('aria-expanded', 'true')
dialog.remove()
})
})
describe('the platform back request', () => {
class StubWatcher {
static made: StubWatcher[] = []
onclose: (() => void) | null = null
destroyed = false
constructor() {
StubWatcher.made.push(this)
}
destroy() {
this.destroyed = true
}
}
beforeEach(() => {
StubWatcher.made = []
vi.stubGlobal('CloseWatcher', StubWatcher)
})
it('creates a watcher on open, closes on its request, destroys it on close', async () => {
const { user } = mount()
expect(StubWatcher.made).toHaveLength(0)
await user.click(more())
expect(StubWatcher.made).toHaveLength(1)
act(() => StubWatcher.made[0].onclose?.())
await waitFor(() =>
expect(more()).toHaveAttribute('aria-expanded', 'false'),
)
expect(StubWatcher.made[0].destroyed).toBe(true)
})
it('works without CloseWatcher', async () => {
vi.stubGlobal('CloseWatcher', undefined)
const { user } = mount()
await user.click(more())
expect(more()).toHaveAttribute('aria-expanded', 'true')
})
})
+3 -1
View File
@@ -173,7 +173,9 @@ describe('tabs', () => {
])
await user.click(rest[1])
expect(screen.getByTestId('editor-tab-findings')).toBeInTheDocument()
expect(document.getElementById('editor-tabs-more')).toBeNull()
await waitFor(() =>
expect(document.getElementById('editor-tabs-more')).toBeNull(),
)
})
})
@@ -179,6 +179,14 @@ describe('AppLayout, editor sidebar from 1 280 px', () => {
expect(topBarMenu()).toHaveClass('lg:hidden')
})
it('keeps the sidebar fixed while the content scrolls, with its own scroll', () => {
mount('/app/admin/sheets/s-1/draft')
expect(sidebar()).toHaveClass('sticky', 'top-0', 'h-dvh', 'self-start', 'overflow-y-auto')
cleanup()
mount('/app/admin/sheets/s-1')
expect(sidebar()).toHaveClass('sticky', 'top-0', 'h-dvh', 'self-start', 'overflow-y-auto')
})
it('keeps the drawer open at 1 180 px in the editor, closes it from 1 280 px', async () => {
const user = userEvent.setup()
const fire = stubScreen(73.75)