feat(editor): one tab order, vertical Plus list with the error count

This commit is contained in:
bchanot committed 2026-11-15 15:52:28 +01:00
1 parent b41c24b29d
commit ff21b0315e
11 files changed
+153 -73

No files matched your search

+37 -2
View File
@@ -12,6 +12,7 @@ import {
draftPath, draftPath,
draftTitle, draftTitle,
editorActor, editorActor,
morePlus,
pointOf, pointOf,
seedDraft, seedDraft,
shapeWith, shapeWith,
@@ -40,8 +41,7 @@ async function openAt(page: Page, width: number, height = 800) {
).toBeVisible() ).toBeVisible()
} }
const more = (page: Page) => const more = (page: Page) => morePlus(page, dict)
page.getByRole('button', { name: dict['editor.tab.more'], exact: true })
const list = (page: Page) => page.locator('#editor-tabs-more') 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. */ /** The boxes that must not move when « Plus » opens: the row, the page below it, the document. */
@@ -90,6 +90,41 @@ test.describe('« Plus » dropdown', () => {
}) })
} }
for (const width of [375, 320]) {
test(`at ${width} px the entries stack in tab order inside the viewport`, async ({
page,
}) => {
await openAt(page, width)
await expect(page.getByRole('tablist').getByRole('tab')).toHaveText([
dict['editor.tab.general'],
dict['editor.tab.annotations'],
])
await more(page).click()
const rows = list(page).getByRole('button')
await expect(rows).toHaveCount(3)
// Vérification may carry its error count.
await expect(rows).toHaveText([
dict['editor.tab.findings'],
dict['editor.tab.references'],
new RegExp(`^${dict['editor.tab.verification']}`),
])
const boxes = await rows.evaluateAll((els) =>
els.map((el) => el.getBoundingClientRect().toJSON()),
)
boxes.forEach((box, at) => {
expect(box.height, `row ${at} height`).toBeGreaterThanOrEqual(44)
expect(box.x, `row ${at} left`).toBeGreaterThanOrEqual(0)
expect(box.right, `row ${at} right`).toBeLessThanOrEqual(width)
if (at > 0) {
expect(box.y, `row ${at} below`).toBeGreaterThanOrEqual(
boxes[at - 1].bottom,
)
}
})
await expectAccessible(page, `« Plus » list at ${width} px`)
})
}
test('closes on a selection, outside tap and Escape, focus kept sane', async ({ test('closes on a selection, outside tap and Escape, focus kept sane', async ({
page, page,
}) => { }) => {
+28 -29
View File
@@ -345,13 +345,34 @@ export const TABS = [
/** The Annotations sections and the panel, in the order the overview offers them. */ /** The Annotations sections and the panel, in the order the overview offers them. */
export const SECTIONS = ['views', 'categories', 'regions'] as const export const SECTIONS = ['views', 'categories', 'regions'] as const
/** Below this width only the tabs of SHOWN_SMALL stay in the row, the others sit under « Plus ». */
const SMALL_TIER_WIDTH = 640
const SHOWN_SMALL = ['general', 'annotations']
/** /**
* Clicks a tab by role. The name is a pattern: the Vérification tab adds « n erreur(s) » * Clicks a tab by role, whatever the width: from 640 px the tab button, below it « Plus »
* to its name while the in-page check has errors. * opened and the tab picked in its list. The name is a pattern: the Vérification tab adds
* « n erreur(s) » to its name while the in-page check has errors.
*/ */
export async function selectTab(page: Page, dict: Dict, tab: string) { export async function selectTab(page: Page, dict: Dict, tab: string) {
const name = dict[`editor.tab.${tab}`] const width = page.viewportSize()?.width ?? SMALL_TIER_WIDTH
await page.getByRole('tab', { name: new RegExp(`^${name}( |$)`) }).click() const name = new RegExp(`^${dict[`editor.tab.${tab}`]}( |$)`)
if (width >= SMALL_TIER_WIDTH || SHOWN_SMALL.includes(tab)) {
await page.getByRole('tab', { name }).click()
return
}
const more = morePlus(page, dict)
if ((await more.getAttribute('aria-expanded')) !== 'true') await more.click()
await page.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)
}
/** « Plus », located without an exact name: it carries the Vérification error count. */
export function morePlus(page: Page, dict: Dict): Locator {
return page.getByRole('button', {
name: new RegExp(`^${dict['editor.tab.more']}( |$)`),
})
} }
/** The visible place with this `data-place` name; a hidden copy never answers. */ /** The visible place with this `data-place` name; a hidden copy never answers. */
@@ -395,34 +416,12 @@ export function libraryRoot(page: Page): Locator {
return place(page, 'references') return place(page, 'references')
} }
/** Below this width the tabs other than Annotations and Vérification sit under « Plus ». */
const SMALL_TIER_WIDTH = 640
/** /**
* Shows a tab whatever the width: the tab button from 640 px, below it « Plus » opened and * Shows a tab whatever the width (selectTab). Waits for the tab's place to be visible
* the tab picked in its list. Waits for the tab's place to be visible (Annotations names * (Annotations names its sections, so any of them).
* its sections, so any of them).
*/ */
export async function openTab(page: Page, dict: Dict, tab: string) { export async function openTab(page: Page, dict: Dict, tab: string) {
const width = page.viewportSize()?.width ?? SMALL_TIER_WIDTH await selectTab(page, dict, tab)
const name = new RegExp(`^${dict[`editor.tab.${tab}`]}( |$)`)
const listed = ['annotations', 'verification'].includes(tab)
if (width < SMALL_TIER_WIDTH && !listed) {
const more = page.getByRole('button', {
name: dict['editor.tab.more'],
exact: true,
})
if ((await more.getAttribute('aria-expanded')) !== 'true')
await more.click()
await page
.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()
}
await expect( await expect(
tab === 'annotations' tab === 'annotations'
? page.locator('[data-place^=annotations]:visible').first() ? page.locator('[data-place^=annotations]:visible').first()
+22 -7
View File
@@ -15,6 +15,7 @@ import {
type EditorTabId, type EditorTabId,
} from '@/editor/tabs' } from '@/editor/tabs'
import type { TabTier } from '@/editor/useViewport' import type { TabTier } from '@/editor/useViewport'
import Icon from '@/components/ui/Icon'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import HistoryButtons from './HistoryButtons' import HistoryButtons from './HistoryButtons'
import { MORE_LIST_ID, useMoreDismiss, useMoreMenu } from './useMoreMenu' import { MORE_LIST_ID, useMoreDismiss, useMoreMenu } from './useMoreMenu'
@@ -26,15 +27,25 @@ const ACTIVE =
const IDLE = const IDLE =
'border-transparent text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]' 'border-transparent text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]'
const ROW =
'flex min-h-12 w-full items-center justify-between gap-3 rounded-md px-4 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
const ROW_ACTIVE =
'bg-[var(--color-accent)]/10 font-medium text-[var(--color-accent-strong)]'
/** The blocking-error count on the Vérification tab, as text; absent at zero. */ /** The blocking-error count on the Vérification tab, as text; absent at zero. */
function ErrorCount({ tab }: { tab: EditorTabId }) { function ErrorCount({ tab }: { tab: EditorTabId }) {
return tab === 'verification' ? <ErrorBadge /> : null
}
/** The count badge itself; also shown on « Plus » while Vérification sits under it. */
function ErrorBadge() {
const plural = usePlural() const plural = usePlural()
const count = useEditorStore( const count = useEditorStore(
(s) => (s) =>
s.previewState?.report.issues.filter((i) => i.severity === 'error') s.previewState?.report.issues.filter((i) => i.severity === 'error')
.length ?? 0, .length ?? 0,
) )
if (tab !== 'verification' || count === 0) return null if (count === 0) return null
return ( return (
<> <>
{' '} {' '}
@@ -127,19 +138,22 @@ function MoreList({ more, active, onPick }: MoreListProps) {
transition: { duration: reduced ? 0 : 0.15 }, transition: { duration: reduced ? 0 : 0.15 },
}} }}
exit={{ ...hidden, transition: { duration: reduced ? 0 : 0.12 } }} 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" className="absolute inset-x-0 top-full z-20 mt-1 flex flex-col gap-1 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-2 shadow-lg"
> >
{more.map((tab) => ( {more.map((tab) => (
<li key={tab}> <li key={tab}>
<button <button
id={tabDomId(tab)} id={tabDomId(tab)}
type="button" type="button"
aria-pressed={tab === active} aria-current={tab === active ? 'true' : undefined}
onClick={() => onPick(tab)} onClick={() => onPick(tab)}
className={`rounded-md px-3 ${BASE} border-b-0 ${tab === active ? ACTIVE : IDLE}`} className={`${ROW} ${tab === active ? ROW_ACTIVE : IDLE}`}
> >
<span>
{t(`editor.tab.${tab}`)} {t(`editor.tab.${tab}`)}
<ErrorCount tab={tab} /> <ErrorCount tab={tab} />
</span>
{tab === active && <Icon name="check" size={18} />}
</button> </button>
</li> </li>
))} ))}
@@ -169,7 +183,7 @@ function usePanelPick(
} }
} }
/** Below 640 px: « Plus » and its dropdown of the tabs that do not fit. */ /** Below 640 px: « Plus » (with the Vérification count) and its list of the other tabs. */
function MoreTabs({ more, active, onSelect }: MoreTabsProps) { function MoreTabs({ more, active, onSelect }: MoreTabsProps) {
const t = useT() const t = useT()
const { open, close, toggle } = useMoreMenu(active) const { open, close, toggle } = useMoreMenu(active)
@@ -186,6 +200,7 @@ function MoreTabs({ more, active, onSelect }: MoreTabsProps) {
className={`-mb-px ${BASE} ${more.includes(active) ? ACTIVE : IDLE}`} className={`-mb-px ${BASE} ${more.includes(active) ? ACTIVE : IDLE}`}
> >
{t('editor.tab.more')} {t('editor.tab.more')}
{more.includes('verification') && <ErrorBadge />}
</button> </button>
<AnimatePresence> <AnimatePresence>
{open && <MoreList more={more} active={active} onPick={pick} />} {open && <MoreList more={more} active={active} onPick={pick} />}
@@ -202,8 +217,8 @@ interface EditorTabsProps {
/** /**
* The draft's tab row (boards 04 and 05): the five tabs from 640 px (the row may wrap * 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 * between 640 and 1 023 px, never scroll sideways), Général and Annotations below it with
* Vérification below it with « Plus » opening a dropdown overlay of the others (no measurement). * « Plus » opening a vertical dropdown overlay of the others, in the same order (no measurement).
* « Défaire » and « Refaire » sit at the right end of the row on every tab. * « Défaire » and « Refaire » sit at the right end of the row on every tab.
*/ */
export default function EditorTabs({ export default function EditorTabs({
@@ -187,9 +187,9 @@ function useShowRestored(nav: EditorNavigation) {
* confirmation before a history jump leaves with a dirty dialog, and whether the last * confirmation before a history jump leaves with a dirty dialog, and whether the last
* editor left a dirty dialog behind. * editor left a dirty dialog behind.
*/ */
function useWorkspaceNavigation(sheetId: string, tier: TabTier, who: Who) { function useWorkspaceNavigation(sheetId: string, who: Who) {
const previewState = useEditorStore((s) => s.previewState) const previewState = useEditorStore((s) => s.previewState)
const tab = previewState ? initialTab(previewState, tier) : 'annotations' const tab = previewState ? initialTab(previewState) : 'annotations'
const owner = useOwner(sheetId, who.tag) const owner = useOwner(sheetId, who.tag)
const nav = useEditorNavigation(tab, useRestoredView(owner)) const nav = useEditorNavigation(tab, useRestoredView(owner))
useEditorHistory(nav, owner, defaultView(tab)) useEditorHistory(nav, owner, defaultView(tab))
@@ -212,11 +212,7 @@ function LeftDraftNotice({ shown }: { shown: boolean }) {
*/ */
function Workspace(props: Props & Who) { function Workspace(props: Props & Who) {
const { sheet, mode, readOnly } = props const { sheet, mode, readOnly } = props
const { nav, left } = useWorkspaceNavigation( const { nav, left } = useWorkspaceNavigation(sheet.sheet_id, props)
sheet.sheet_id,
props.tier,
props,
)
return ( return (
<EditingState readOnly={readOnly} mode={mode}> <EditingState readOnly={readOnly} mode={mode}>
<div className="space-y-4" data-editor-workspace> <div className="space-y-4" data-editor-workspace>
+5 -6
View File
@@ -14,11 +14,11 @@ export const EDITOR_TABS = [
] as const ] as const
export type EditorTabId = (typeof EDITOR_TABS)[number] export type EditorTabId = (typeof EDITOR_TABS)[number]
/** Board 05: the tabs shown beside « Plus » at each width; the rest sit under « Plus ». */ /** The tabs shown beside « Plus » at each width; the rest sit under « Plus », in tab order. */
const SHOWN: Record<TabTier, readonly EditorTabId[]> = { const SHOWN: Record<TabTier, readonly EditorTabId[]> = {
wide: EDITOR_TABS, wide: EDITOR_TABS,
medium: EDITOR_TABS, medium: EDITOR_TABS,
small: ['annotations', 'verification'], small: ['general', 'annotations'],
} }
export function tabsFor(tier: TabTier): { export function tabsFor(tier: TabTier): {
@@ -31,13 +31,12 @@ export function tabsFor(tier: TabTier): {
/** /**
* The tab a version opens on: Annotations once a view can be annotated, Général while * The tab a version opens on: Annotations once a view can be annotated, Général while
* there is nothing to annotate yet. A tier that does not list Général keeps Annotations. * there is nothing to annotate yet. Both are shown at every width.
*/ */
export function initialTab(state: PreviewState, tier: TabTier): EditorTabId { export function initialTab(state: PreviewState): EditorTabId {
const unmeasured = unmeasuredViews(state) const unmeasured = unmeasuredViews(state)
const measurable = state.document.views.some((v) => !unmeasured.has(v.id)) const measurable = state.document.views.some((v) => !unmeasured.has(v.id))
const wanted = measurable ? 'annotations' : 'general' return measurable ? 'annotations' : 'general'
return SHOWN[tier].includes(wanted) ? wanted : 'annotations'
} }
/** /**
@@ -28,14 +28,10 @@ async function stateOf(text: string) {
describe('initialTab', () => { describe('initialTab', () => {
it('opens an empty new draft on Général', async () => { it('opens an empty new draft on Général', async () => {
expect(initialTab(await stateOf(emptyText()), 'wide')).toBe('general') expect(initialTab(await stateOf(emptyText()))).toBe('general')
}) })
it('opens a draft with a measured view on Annotations', async () => { it('opens a draft with a measured view on Annotations', async () => {
expect(initialTab(await stateOf(baseText()), 'wide')).toBe('annotations') expect(initialTab(await stateOf(baseText()))).toBe('annotations')
})
it('keeps Annotations on a tier that does not list Général', async () => {
expect(initialTab(await stateOf(emptyText()), 'small')).toBe('annotations')
}) })
}) })
+2 -2
View File
@@ -106,11 +106,11 @@ describe('tabsFor', () => {
'references', 'references',
'verification', 'verification',
]) ])
expect(tabsFor('small').shown).toEqual(['annotations', 'verification']) expect(tabsFor('small').shown).toEqual(['general', 'annotations'])
expect(tabsFor('small').more).toEqual([ expect(tabsFor('small').more).toEqual([
'general',
'findings', 'findings',
'references', 'references',
'verification',
]) ])
}) })
}) })
+26 -4
View File
@@ -49,7 +49,7 @@ function Page({
/> />
<button type="button">outside</button> <button type="button">outside</button>
</div> </div>
<button type="button" onClick={() => setActive('general')}> <button type="button" onClick={() => setActive('findings')}>
elsewhere elsewhere
</button> </button>
</div> </div>
@@ -92,11 +92,33 @@ describe('the overlay', () => {
expect(more()).toHaveAttribute('aria-expanded', 'false') expect(more()).toHaveAttribute('aria-expanded', 'false')
await gone() await gone()
await user.click(more()) await user.click(more())
await user.click(screen.getByRole('tab', { name: 'Vérification' })) await user.click(screen.getByRole('tab', { name: 'Général' }))
expect(more()).toHaveAttribute('aria-expanded', 'false') expect(more()).toHaveAttribute('aria-expanded', 'false')
}) })
}) })
describe('the vertical list', () => {
it('stacks the entries in tab order, the active one marked', async () => {
const { user } = mount()
await user.click(more())
expect(list()).toHaveClass('flex-col')
const rows = [...list()!.querySelectorAll('button')]
expect(rows.map((row) => row.id)).toEqual([
'editor-tab-findings',
'editor-tab-references',
'editor-tab-verification',
])
expect(list()!.querySelector('[aria-current]')).toBeNull()
rows.forEach((row) => expect(row).toHaveClass('min-h-12', 'w-full'))
await user.click(rows[0])
await user.click(more())
const current = list()!.querySelectorAll('[aria-current="true"]')
expect(current).toHaveLength(1)
expect(current[0].id).toBe('editor-tab-findings')
expect(current[0].querySelector('svg')).not.toBeNull()
})
})
describe('the panel takes the focus after a pick', () => { describe('the panel takes the focus after a pick', () => {
it('Enter on an entry focuses the panel of that tab once the list is gone', async () => { it('Enter on an entry focuses the panel of that tab once the list is gone', async () => {
const { user } = mount() const { user } = mount()
@@ -184,8 +206,8 @@ describe('outside presses', () => {
it('a press inside the row closes the menu and goes on to act', async () => { it('a press inside the row closes the menu and goes on to act', async () => {
const { user } = mount() const { user } = mount()
await user.click(more()) await user.click(more())
await user.click(screen.getByRole('tab', { name: 'Vérification' })) await user.click(screen.getByRole('tab', { name: 'Général' }))
expect(screen.getByRole('tab', { name: 'Vérification' })).toHaveAttribute( expect(screen.getByRole('tab', { name: 'Général' })).toHaveAttribute(
'aria-selected', 'aria-selected',
'true', 'true',
) )
+4 -3
View File
@@ -256,10 +256,11 @@ describe('the guards of a width change', () => {
expect(document.activeElement).toBe(tab('Général')) expect(document.activeElement).toBe(tab('Général'))
}) })
it('the focus of a typed field goes to « Plus » when the shown tab left the row', async () => { it('the focus of an editing control goes to « Plus » when the shown tab left the row', async () => {
const user = await mount() const user = await mount()
await user.click(tab('Général')) await user.click(tab('Références'))
await user.click(byId('general-name-fr')) const add = button('Ajouter une référence')
act(() => add.focus())
cross(500) cross(500)
expect(document.activeElement).toBe(button('Plus')) expect(document.activeElement).toBe(button('Plus'))
}) })
+4 -4
View File
@@ -155,24 +155,24 @@ describe('tabs', () => {
expect(screen.queryByRole('button', { name: 'Plus' })).toBeNull() expect(screen.queryByRole('button', { name: 'Plus' })).toBeNull()
}) })
it('below 640 px: two tabs and « Plus » listing Général, Constats and Références', async () => { it('below 640 px: two tabs and « Plus » listing Constats, Références and Vérification', async () => {
const user = userEvent.setup() const user = userEvent.setup()
mountDraft({ width: 375 }) mountDraft({ width: 375 })
await ready() await ready()
const shown = within(screen.getByRole('tablist')).getAllByRole('tab') const shown = within(screen.getByRole('tablist')).getAllByRole('tab')
expect(shown.map((tab) => tab.textContent)).toEqual([ expect(shown.map((tab) => tab.textContent)).toEqual([
'Général',
'Annotations', 'Annotations',
'Vérification',
]) ])
await user.click(screen.getByRole('button', { name: 'Plus' })) await user.click(screen.getByRole('button', { name: 'Plus' }))
const more = document.getElementById('editor-tabs-more') as HTMLElement const more = document.getElementById('editor-tabs-more') as HTMLElement
const rest = within(more).getAllByRole('button') const rest = within(more).getAllByRole('button')
expect(rest.map((b) => b.textContent)).toEqual([ expect(rest.map((b) => b.textContent)).toEqual([
'Général',
'Constats', 'Constats',
'Références', 'Références',
'Vérification',
]) ])
await user.click(rest[1]) await user.click(rest[0])
expect(screen.getByTestId('editor-tab-findings')).toBeInTheDocument() expect(screen.getByTestId('editor-tab-findings')).toBeInTheDocument()
await waitFor(() => await waitFor(() =>
expect(document.getElementById('editor-tabs-more')).toBeNull(), expect(document.getElementById('editor-tabs-more')).toBeNull(),
+20 -3
View File
@@ -51,9 +51,7 @@ describe('the Vérification tab badge', () => {
])('says « n erreur(s) » for %i blocking error(s)', async (count, name) => { ])('says « n erreur(s) » for %i blocking error(s)', async (count, name) => {
await openReady() await openReady()
render(<EditorTabs active="general" tier="wide" onSelect={vi.fn()} />) render(<EditorTabs active="general" tier="wide" onSelect={vi.fn()} />)
reportIssues( reportIssues(Array.from({ length: count }, (_, at) => issue('error', at)))
Array.from({ length: count }, (_, at) => issue('error', at)),
)
expect(verificationTab()).toHaveTextContent(new RegExp(`^${name}$`)) expect(verificationTab()).toHaveTextContent(new RegExp(`^${name}$`))
}) })
@@ -76,3 +74,22 @@ describe('the Vérification tab badge', () => {
) )
}) })
}) })
describe('« Plus » carries the count while Vérification sits under it', () => {
const plus = () => screen.getByRole('button', { name: /^Plus/ })
it('shows the count at the small tier, nothing at zero', async () => {
await openReady()
render(<EditorTabs active="general" tier="small" onSelect={vi.fn()} />)
reportIssues([])
expect(plus()).toHaveTextContent(/^Plus$/)
reportIssues([issue('error', 0), issue('error', 1)])
expect(plus()).toHaveTextContent(/^Plus 2 erreurs$/)
})
it('wide rows have no Plus button', async () => {
await openReady()
render(<EditorTabs active="general" tier="wide" onSelect={vi.fn()} />)
expect(screen.queryByRole('button', { name: /^Plus/ })).toBeNull()
})
})