import { randomUUID } from 'node:crypto' import { en } from '@/i18n/en' import { fr } from '@/i18n/fr' import type { Dict } from '@/i18n/types' import type { Page, Response } from '@playwright/test' import { rpc, sql } from '../../../../packages/supabase/tests/sandbox/stack' import { allSheetsLink, escaped, stepUpAdmin } from '../support/admin' import { expect, expectAccessible, expectNoHorizontalOverflow, test, } from '../support/browser' import { seedOfficialSheet, type SheetNames } from '../support/catalogue' import { editorActor, serverDocument, type Actor } from '../support/editor' import { literal } from '../support/records' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { signIn } from '../support/shell' // V1-2.6 R3 on the isolated stack: the official sheet list searched by name, // sorted by last modification or name, counted, dated in Paris time, and the // Administration home's five latest sheets. Three draft sheets of this run, the // oldest saved last: only the true last modification (M9) puts it first. FR and // EN, desktop and 375 px; one editor per project. Never opens /app/admin/access // (BLK-015). D7: the teardown soft-deletes the ids this run created, one by one. const LANGUAGES = [ ['fr', fr], ['en', en], ] as const type Locale = (typeof LANGUAGES)[number][0] /** The three sheets' names, seeded in this order (fr and en sort alike). */ const WORDS = [ { fr: 'Alpha', en: 'Alpha' }, { fr: 'Émeu', en: 'Emu' }, { fr: 'Zèbre', en: 'Zebra' }, ] as const const SHORT_MONTHS: Record = { fr: 'janv\\.|févr\\.|mars|avr\\.|mai|juin|juil\\.|août|sept\\.|oct\\.|nov\\.|déc\\.', en: 'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept?|Oct|Nov|Dec', } interface Fixtures { actor: Actor token: string /** Alpha, Émeu, Zèbre: ids and names, in seeding order. */ sheets: { id: string; names: SheetNames }[] } const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ /** An id as an SQL literal, refused unless it has the uuid shape. */ function uuidLiteral(id: string): string { if (!UUID.test(id)) throw new Error('fixture: an id without the uuid shape') return literal(id) } const main = (page: Page) => page.getByRole('main') const heading = (page: Page, name: string) => main(page).getByRole('heading', { level: 1, name }) const searchField = (page: Page, dict: Dict) => page.getByRole('searchbox', { name: dict['admin.sheets.search'] }) const countLine = (page: Page) => main(page).locator('p[aria-live="polite"]') const rows = (page: Page, dict: Dict) => page .getByRole('list', { name: dict['admin.sheets.results_label'] }) .getByRole('listitem') const sheetsCard = (page: Page) => page.locator('section[aria-labelledby="admin-sheets-title"]') /** « Modifiée le 9 nov. 2026, 12:06 » / « Modified on 9 Nov 2026, 12:06 » (A8). */ function ratifiedDate(dict: Dict, locale: Locale): RegExp { const date = `\\d{1,2} (${SHORT_MONTHS[locale]}) \\d{4}, \\d{2}:\\d{2}` const [before, after] = dict['admin.sheets.modified'].split('{date}') return new RegExp(`^${escaped(before!)}${date}${escaped(after!)}$`) } /** The hour and minute of `iso` on a Paris clock, as the row must show them. */ const parisClock = (iso: string) => new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23', timeZone: 'Europe/Paris', }).format(new Date(iso)) /** The admin list answer of the next load of the page. */ const listAnswer = (page: Page): Promise => page.waitForResponse((response) => response.url().includes('/rest/v1/rpc/list_official_sheets_admin'), ) /** Seeds the three sheets, each id kept for the teardown as soon as it exists. */ async function seedSheets(token: string, created: string[]) { const sheets: Fixtures['sheets'] = [] for (const word of WORDS) { const names = { fr: `R3 ${token} ${word.fr}`, en: `R3 ${token} ${word.en}` } const sheet = await seedOfficialSheet(names, 'draft') created.push(sheet.id) sheets.push(sheet) } return sheets } /** One more save of Alpha's draft by the editor: its versions move, its sheet row does not. */ async function saveAlpha(actor: Actor, sheetId: string, token: string) { const draftId = await sql( `select id from public.anatomical_sheet_versions where sheet_id = ${uuidLiteral(sheetId)} and status = 'draft'`, ) const revision = Number( await sql( `select revision from public.anatomical_sheet_versions where id = ${uuidLiteral(draftId)}`, ), ) const document = await serverDocument(draftId) document.description = { fr: `R3 ${token}`, en: `R3 ${token}` } const args = { version_id: draftId, expected_revision: revision, document } const saved = await rpc('save_sheet_draft', args, actor.aal2) if (saved.status !== 200) throw new Error(`fixture save: HTTP ${saved.status}`) } /** D7: soft-deletes each id of this run on its own; every failure is reported at the end. */ async function deleteCreated(actor: Actor, created: string[]) { const failures: string[] = [] for (const id of created) { try { const answer = await rpc( 'delete_anatomical_sheet', { sheet_id: id }, actor.aal2, ) if (answer.status !== 200 || JSON.parse(answer.text) !== id) failures.push(`${id}: HTTP ${answer.status}`) } catch (error) { failures.push(`${id}: ${String(error)}`) } } expect(failures, 'sheets of this run soft-deleted').toEqual([]) } /** The editor, its profile in `locale` (its own preference, set earlier), at aal2 on /app/admin. */ async function openAdmin(page: Page, dict: Dict, locale: Locale, actor: Actor) { await sql( `update public.profiles set locale = ${literal(locale)} where id = ${uuidLiteral(actor.account.id)}`, ) await signIn(page, actor.account, dict) await page.goto('/app/admin') await stepUpAdmin(page, dict, actor.secret) await expect(heading(page, dict['shell.nav.admin'])).toBeVisible() } /** * Check 5: the latest changes, newest first, at most five; the footer link opens * the list. Resolves with the list's server answer of that load. */ async function checkHome(page: Page, dict: Dict) { const card = sheetsCard(page) await expect( card.getByRole('heading', { name: dict['admin.home.latest'] }), ).toBeVisible() const items = card.getByRole('list').getByRole('listitem') await expect(items.first()).toBeVisible() expect(await items.count()).toBeLessThanOrEqual(5) const times = ( await card .locator('time') .evaluateAll((nodes) => nodes.map((node) => node.getAttribute('datetime') ?? ''), ) ).map((iso) => Date.parse(iso)) expect(times, 'one date per home item').toHaveLength(await items.count()) for (let i = 1; i < times.length; i += 1) expect( times[i], `home item ${i} not newer than the one above`, ).toBeLessThanOrEqual(times[i - 1]!) await expectAccessible(page, 'the Administration home') await expectNoHorizontalOverflow(page, 'the Administration home') const link = allSheetsLink(card, dict) await expect(link).toHaveText(/\d/) const answer = listAnswer(page) await link.click() await expect(heading(page, dict['admin.sheets.title'])).toBeVisible() return (await (await answer).json()) as { sheet_id: string last_modified_at: string }[] } /** The rows, in order, are these sheets: link, name, and the server's date shown in Paris time. */ async function expectRows( page: Page, dict: Dict, locale: Locale, expected: { id: string; name: string; modified: string }[], ) { const list = rows(page, dict) await expect(list).toHaveCount(expected.length) for (const [i, sheet] of expected.entries()) { const row = list.nth(i) await expect(row.getByRole('link')).toHaveAttribute( 'href', `/app/admin/sheets/${sheet.id}`, ) await expect(row).toContainText(sheet.name) const time = row.locator('time') await expect(time).toHaveText(ratifiedDate(dict, locale)) await expect(time).toContainText(parisClock(sheet.modified)) await expect(time).toHaveAttribute( 'datetime', new Date(sheet.modified).toISOString(), ) } } /** The count line's sentence, in the plural form `locale` gives `shown` (fr: 0 is singular). */ function countText( dict: Dict, locale: Locale, key: 'count' | 'count_of', shown: number, total: number, ): string { const form = new Intl.PluralRules(locale).select(shown) === 'one' ? 'one' : 'other' return dict[`admin.sheets.${key}_${form}`] .replace('{count}', String(shown)) .replace('{total}', String(total)) } /** * Check 3: a search longer than the field, cut at 100; the no-result sentence, then * cleared by its button; typed again, then cleared by Escape. */ async function checkLongSearch( page: Page, dict: Dict, locale: Locale, token: string, total: number, ) { const field = searchField(page, dict) const typed = `${token}${'x'.repeat(100)}`.slice(0, 100) await field.fill(`${token}${'x'.repeat(100)}`) await expect(field).toHaveValue(typed) await expect( main(page).getByText(dict['admin.sheets.no_result'].replace('{q}', typed), { exact: true, }), ).toBeVisible() await expect(countLine(page)).toHaveText( countText(dict, locale, 'count_of', 0, total), ) await expectNoHorizontalOverflow(page, 'the empty search') await expectAccessible(page, 'the empty search') const clear = dict['admin.sheets.clear_search'] await main(page) .getByRole('button', { name: clear, exact: true }) .filter({ hasText: clear }) .click() await expect(field).toHaveValue('') await expect(field).toBeFocused() await expect(countLine(page)).toHaveText( countText(dict, locale, 'count', total, total), ) // Escape in a field that holds text clears it, keeps the focus, brings the count back. await field.fill(typed) await expect(countLine(page)).toHaveText( countText(dict, locale, 'count_of', 0, total), ) await field.press('Escape') await expect(field).toHaveValue('') await expect(field).toBeFocused() await expect(countLine(page)).toHaveText( countText(dict, locale, 'count', total, total), ) } const PHONE_MAX_WIDTH = 639 /** The four filters' selects, by their label, and the panel that holds them. */ const filterSelect = (page: Page, dict: Dict, key: string) => page.getByLabel(dict[`admin.sheets.filter.${key}` as keyof Dict]) const filtersToggle = (page: Page, dict: Dict) => page.getByRole('button', { name: new RegExp(`^${escaped(dict['admin.sheets.filters'])}`), }) /** Desktop (`sm` and up): the filters are always there and no button asks for them. */ async function checkDesktopFilters(page: Page, dict: Dict) { await expect(filtersToggle(page, dict)).toBeHidden() for (const key of [ 'species', 'sheet_status', 'version_status', 'round_status', ]) await expect(filterSelect(page, dict, key)).toBeVisible() } /** Phone: collapsed by default, search and sort in view, closed means untabbable. */ async function checkClosedFilters(page: Page, dict: Dict) { const toggle = filtersToggle(page, dict) await expect(toggle).toHaveText(dict['admin.sheets.filters']) await expect(toggle).toHaveAttribute('aria-expanded', 'false') await expect(searchField(page, dict)).toBeVisible() await expect(page.getByLabel(dict['admin.sheets.sort_by'])).toBeVisible() await expect(filterSelect(page, dict, 'species')).toBeHidden() await expect(countLine(page)).toBeVisible() const box = await page.locator('#admin-sheets-filters').boundingBox() expect(box?.height, 'the closed panel takes no height').toBeLessThanOrEqual(1) await toggle.focus() await page.keyboard.press('Tab') const inPanel = await page.evaluate(() => Boolean(document.activeElement?.closest('#admin-sheets-filters')), ) expect(inPanel, 'Tab never enters the closed panel').toBe(false) } /** Phone: open, filter, count on the button, close keeps them, reset. */ async function checkPhoneFilters(page: Page, dict: Dict, token: string) { const toggle = filtersToggle(page, dict) await checkClosedFilters(page, dict) // The sandbox list is long: narrow it to this run's sheets before axe scans the page. await searchField(page, dict).fill(token) await toggle.click() await expect(toggle).toHaveAttribute('aria-expanded', 'true') for (const key of [ 'species', 'sheet_status', 'version_status', 'round_status', ]) await expect(filterSelect(page, dict, key)).toBeVisible() await filterSelect(page, dict, 'version_status').selectOption('draft') await filterSelect(page, dict, 'sheet_status').selectOption('active') const label = (n: number) => dict['admin.sheets.filters_active'].replace('{count}', String(n)) await expect(toggle).toHaveText(label(2)) await expectAccessible(page, 'the open filters') await expectNoHorizontalOverflow(page, 'the open filters') await toggle.click() await expect(filterSelect(page, dict, 'version_status')).toBeHidden() await expect(toggle).toHaveText(label(2)) await toggle.click() await expect(filterSelect(page, dict, 'version_status')).toHaveValue('draft') await expect(filterSelect(page, dict, 'sheet_status')).toHaveValue('active') await page .getByRole('button', { name: dict['admin.sheets.filters_reset'] }) .click() await expect(toggle).toHaveText(dict['admin.sheets.filters']) await expect(toggle).toBeFocused() await expect(filterSelect(page, dict, 'version_status')).toHaveValue('') } test.describe.configure({ mode: 'serial' }) test.describe('official sheet list: search, sort and dates (R3)', () => { // A browser clock in UTC: a row still in Paris time proves the zone is the page's own. test.use({ timezoneId: 'UTC' }) const created: string[] = [] let editor: Actor | null = null let fixtures: Fixtures | null = null test.beforeAll(async () => { test.setTimeout(120_000) editor = await editorActor('fr') const actor = editor const token = randomUUID().slice(0, 8) const sheets = await seedSheets(token, created) await saveAlpha(actor, sheets[0]!.id, token) fixtures = { actor, token, sheets } }) test.afterAll(async () => { if (editor) await deleteCreated(editor, created) }) for (const [locale, dict] of LANGUAGES) { test.describe(locale, () => { test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' }) test.beforeEach(async ({ context }) => { await routeToSandbox(context) }) test.afterEach(async ({ context }) => { await dropLateReplays(context) }) test('the home lists the latest changes; the list searches, sorts, counts and dates', async ({ page, requests, }) => { test.setTimeout(240_000) const { actor, token, sheets } = fixtures! const { email, password, displayName } = actor.account requests.forbid(email, password, displayName, token) await openAdmin(page, dict, locale, actor) const answer = await checkHome(page, dict) const total = answer.length const modified = (id: string) => answer.find((sheet) => sheet.sheet_id === id)?.last_modified_at ?? '' const shown = (index: number) => ({ id: sheets[index]!.id, name: sheets[index]!.names[locale], modified: modified(sheets[index]!.id), }) // 1. The token finds the three sheets, newest modification first: Alpha, Zèbre, Émeu. await searchField(page, dict).fill(token) await expect(countLine(page)).toHaveText( countText(dict, locale, 'count_of', 3, total), ) await expectRows(page, dict, locale, [shown(0), shown(2), shown(1)]) await expectAccessible(page, 'the searched list') await expectNoHorizontalOverflow(page, 'the searched list') // 2. « Nom »: Alpha, Émeu, Zèbre. await page.getByLabel(dict['admin.sheets.sort_by']).selectOption('name') await expectRows(page, dict, locale, [shown(0), shown(1), shown(2)]) // 3. A search past the field's limit, its sentence, then « Effacer la recherche ». await checkLongSearch(page, dict, locale, token, total) }) test('the filters are collapsible on a phone, always shown on a desktop', async ({ page, }) => { test.setTimeout(240_000) const { actor, token } = fixtures! await openAdmin(page, dict, locale, actor) await page.goto('/app/admin/sheets') await expect(heading(page, dict['admin.sheets.title'])).toBeVisible() const width = page.viewportSize()?.width ?? 0 if (width > PHONE_MAX_WIDTH) return checkDesktopFilters(page, dict) await checkPhoneFilters(page, dict, token) }) }) } })