Files
faunosteo/apps/app/e2e/shell/editor-equine.spec.ts
T
bchanot bc2dba7c14 feat(editor): four tabs, Annotations sections, references from the header
U1 Lot B1. Four tabs (Général, Annotations, Constats, Vérification); views,
categories and regions become full-width Annotations sections opened from the
overview panel; references move to a header-toggled panel (minimal, Lot D
completes it); « Aller à » goes through EditorTarget and the navigation hook.
EditorWorkspace owns the navigation; DraftHeader split in HeaderActions and
SaveLine; EditorTabs split in TabList and MoreTabs.

R-24, assertions removed or rewritten (file: old -> new):
unit
- editor-route.test: seven tab names -> four; « Plus » at 800 px with
  Références clicked -> no « Plus »; below 640 px five others -> Général,
  Constats, and Constats opens the findings tab; + references panel cases
- editor-route-recovery.test: tab Références + editor-tab-references label ->
  header button + editor-references-panel labelled by its heading
- editor-mode.test: small tier `more` of five -> [general, findings]
- editor-focus-request.test: {key,serial} -> {target,serial}; ReferencesTab and
  VertebraeTab -> ReferencesPanel and RegionsSection; issueTarget tab/key ->
  target place/section/key (vertebrae tab -> annotations/regions); consumed
  context (serial) -> (serial, outcome); annotation case adds heading focus
- editor-verification.test: onGoTo('annotations', key) -> navigate(targetOfKey
  (key), opener); props onSelectTab/onGoTo -> navigate
- editor-annotations-tab.test: props onSelectTab -> navigate + section props;
  no_category text « (onglet Général) » -> « (Annotations, section
  Catégories) »
- editor-tabs-general.test: categories cases render GeneralTab ->
  CategoriesSection(doc); + Général holds no categories editor
- editor-tabs-lists.test: tab imports -> panel and section; read-only
  references « no button » -> only « Fermer les références »
- editor-tabs-views, editor-drawing-upload, editor-repair.test: ViewsTab ->
  ViewsSection import, assertions kept; editor-findings.test: navigate prop
e2e
- support/editor selectTab: exact name -> pattern (error badge in the name);
  + place, openSection, showDrawing, backToDrawing, openReferences, TABS
- support/warm-up: seven tabs -> four + sections + references panel
- editor-access: seven-tab axe loops -> four tabs + three sections + panel
  (edit and read-only); narrow widths add panel overflow and axe
- editor-drawings: tab Vues -> openSection views; tab Annotations ->
  showDrawing
- editor-structures: tab Général (categories) -> openSection categories, axe
  label « general tab » -> « categories section »; tab Références ->
  openReferences/closeReferences; tab Vertèbres -> openSection regions; tab
  Annotations -> showDrawing
- editor-geometry: three tab Vues -> openSection views
- editor-equine: tab Général (categories add) -> openSection categories; five
  tabs loop -> two tabs + sections + panel; tab Annotations -> showDrawing
- editor-journey: tab Vues, tab Général (category), tab Annotations ->
  openSection views/categories, showDrawing; frozen axe scrolls to the header
- lan/trial-lan (not run): tab Vues -> Annotations tab + views entry

Verified: typecheck, lint, vitest 107 files / 1125 tests, whole shell suite on
the sandbox 151 passed, 49 skipped, 0 failed.
2026-11-06 20:25:35 +01:00

378 lines
13 KiB
TypeScript

import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fr } from '@/i18n/fr'
import type { Locator, Page } from '@playwright/test'
import {
rpc,
sql,
stack,
} from '../../../../packages/supabase/tests/sandbox/stack'
import { stepUpAdmin } from '../support/admin'
import { expect, expectAccessible, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
type Actor,
closeReferences,
editorActor,
openEditor,
openReferences,
openSection,
SECTIONS,
seedDraft,
selectTab,
serverDocument,
showDrawing,
standardShape,
toolButton,
} from '../support/editor'
import { signIn } from '../support/shell'
// V1-2.6 equine working copy and commit latency (contract C31, plan « Edge cases »): the
// historical equine sheet opened as a working copy in the editor (a copy left active by
// an earlier run is set aside first, as sheets-concurrency.sandbox.ts does), the commit
// latency measured on it and on a synthetic document near 2 MiB. The numbers are
// reported (console, test annotations); the budget is 500 ms per commit on the equine copy.
const dict = fr
const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916'
const REPO = join(__dirname, '../../../..')
const BUDGET_MS = 500
const SAMPLES = 15
interface Sample {
handler: number
paint: number
}
/** Time from the Enter or click that commits to the end of its task, and to the 2nd frame. */
async function startProbe(page: Page) {
await page.evaluate(() => {
const w = window as unknown as { __latency?: Sample[] }
if (w.__latency) {
w.__latency.length = 0
return
}
const samples: Sample[] = []
w.__latency = samples
const mark = (event: Event) => {
const start = performance.now()
setTimeout(() => {
const handler = performance.now() - start
requestAnimationFrame(() =>
requestAnimationFrame(() =>
samples.push({ handler, paint: performance.now() - start }),
),
)
}, 0)
void event
}
window.addEventListener(
'keydown',
(e) => e.key === 'Enter' && mark(e),
true,
)
window.addEventListener('click', mark, true)
})
}
function takeSamples(page: Page): Promise<Sample[]> {
return page.evaluate(() => {
const w = window as unknown as { __latency: Sample[] }
return w.__latency.splice(0)
})
}
function stats(values: number[]) {
const sorted = [...values].sort((a, b) => a - b)
const at = (share: number) => sorted[Math.floor(share * (sorted.length - 1))]
return {
n: sorted.length,
median: Math.round(at(0.5)),
p95: Math.round(at(0.95)),
max: Math.round(sorted[sorted.length - 1]),
}
}
function report(label: string, samples: Sample[]) {
const line = {
label,
handler: stats(samples.map((s) => s.handler)),
paint: stats(samples.map((s) => s.paint)),
}
console.log(`LATENCY ${JSON.stringify(line)}`)
test.info().annotations.push({
type: 'latency',
description: JSON.stringify(line),
})
return line
}
async function commitName(field: Locator, round: number) {
await field.fill(`Nom mesuré ${round}`)
await field.press('Enter')
}
/** SAMPLES commits of the sheet's French name, one probe entry each (after a warm-up). */
async function measureRenames(page: Page, label: string) {
await selectTab(page, dict, 'general')
const field = page.getByLabel(dict['editor.general.name_fr'], { exact: true })
await startProbe(page)
await commitName(field, 0)
await takeSamples(page)
for (let round = 1; round <= SAMPLES; round++) await commitName(field, round)
await expect(field).toHaveValue(`Nom mesuré ${SAMPLES}`)
await page.waitForTimeout(200)
return report(label, await takeSamples(page))
}
async function measureAdditions(page: Page, label: string) {
await openSection(page, dict, 'categories')
await startProbe(page)
for (let round = 0; round <= SAMPLES; round++) {
await page.locator('#category-new-fr').fill(`Catégorie ${round}`)
await page.locator('#category-new-en').fill(`Category ${round}`)
await page.locator('#category-new-fr').press('Tab')
await page
.getByRole('button', { name: dict['editor.general.category_add'] })
.click()
await expect(page.locator('#category-new-fr')).toHaveValue('')
}
await page.waitForTimeout(200)
// The first round is the warm-up.
return report(label, (await takeSamples(page)).slice(1))
}
async function confirmHistoricalDrawing() {
const row = (
await sql(`select id || ' ' || sha256 || ' ' || (uploaded_at is null)::text
from public.anatomical_sheet_assets where sheet_id = '${HISTORICAL}'`)
).split(' ')
if (row[2] !== 'true') return
const bytes = await readFile(
join(REPO, 'supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg'),
)
const stored = await fetch(
`${stack.storageUrl}/object/anatomical-sheet-assets/${row[1]}.svg`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${stack.serviceKey}`,
'Content-Type': 'image/svg+xml',
},
body: new Uint8Array(bytes),
},
)
await stored.arrayBuffer()
const confirmed = await rpc(
'confirm_sheet_asset_upload',
{ asset_id: row[0] },
stack.serviceKey,
)
expect(confirmed.status).toBe(200)
}
/** Finding nodes with long descriptions, up to about 1.9 MiB of document text. */
function nearCapShape(document: Record<string, unknown>) {
standardShape(document)
const filler = (letter: string) => letter.repeat(260)
const zones = []
for (let z = 0; z < 20; z++) {
const categories = []
for (let c = 0; c < 10; c++) {
const children = []
for (let n = 0; n < 12; n++) {
children.push({
id: `node-${z}-${c}-${n}`,
name: { fr: `Constat ${z}.${c}.${n}`, en: `Finding ${z}.${c}.${n}` },
description: { fr: filler('a'), en: filler('b') },
requires_vet_referral: false,
reference_ids: [],
review_status: 'reviewed',
children: [],
})
}
categories.push({
id: `fcat-${z}-${c}`,
kind: 'dysfunction',
name: { fr: `Catégorie ${z}.${c}`, en: `Category ${z}.${c}` },
description: {},
reference_ids: [],
review_status: 'reviewed',
children,
})
}
zones.push({
id: `zone-${z}`,
name: { fr: `Zone ${z}`, en: `Zone ${z}` },
categories,
})
}
document.finding_zones = zones
}
test.describe.configure({ mode: 'serial' })
test.describe('equine working copy and commit latency', () => {
test.use({ locale: 'fr-FR', actionTimeout: 30_000 })
// Skipped as a whole on the phone project: beforeAll and afterAll toggle the copies'
// status and must run in one worker only.
test.skip(({ isMobile }) => isMobile, 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
let actor: Actor
let setAside: string[] = []
let copyId = ''
test.beforeAll(async () => {
actor = await editorActor('fr')
await confirmHistoricalDrawing()
// A copy left active by an earlier run is set aside and put back after.
setAside = (
await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now()
where status = 'active' and private.is_historical_working_copy(id) returning id`)
)
.split('\n')
.filter(Boolean)
})
test.afterAll(async () => {
// Archived as postgres, like the set-aside below: the sheet is a fixture of this run.
if (copyId)
await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now()
where id = '${copyId}'`)
if (setAside.length > 0)
await sql(`update public.anatomical_sheets set status = 'active', archived_at = null
where id in (${setAside.map((id) => `'${id}'`).join(', ')})`)
})
test.beforeEach(async ({ context }) => {
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('the historical equine sheet opens as a working copy in the editor', async ({
page,
requests,
}) => {
test.setTimeout(120_000)
requests.forbid(actor.account.email, actor.account.password)
const errors: string[] = []
page.on('pageerror', (error) => errors.push(error.message))
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await page.goto(`/app/admin/sheets/${HISTORICAL}`)
await page
.getByRole('button', { name: dict['admin.working_copy.create'] })
.first()
.click()
const dialog = page.getByRole('dialog', {
name: dict['admin.working_copy.create'],
})
// The proposed slug is taken by the copies of earlier runs: one of its own.
await dialog
.getByLabel(dict['admin.sheet_form.slug'])
.fill(`e2e-copie-${actor.account.id.slice(0, 8)}`)
await dialog
.getByRole('button', { name: dict['admin.working_copy.confirm'] })
.click()
await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}\/draft$/)
copyId = new URL(page.url()).pathname.split('/')[4]
await expect(
page.getByText(dict['admin.badge.working_copy'], { exact: true }),
).toBeVisible()
await expect(toolButton(page, dict, 'point')).toBeEnabled()
const rows = page
.getByRole('list', { name: dict['editor.annotations.list'] })
.getByRole('listitem')
await expect(rows.first()).toBeVisible()
expect(await rows.count()).toBeGreaterThan(5)
await expectAccessible(page, 'the equine working copy')
// Every tab opens on the real equine data without a page error (the findings tree
// once blanked the page on nodes that omit their defaulted fields).
await selectTab(page, dict, 'findings')
await expect(page.getByTestId('finding-item').first()).toBeVisible()
for (const tab of ['general', 'verification'])
await selectTab(page, dict, tab)
for (const section of SECTIONS) await openSection(page, dict, section)
await openReferences(page, dict)
await closeReferences(page, dict)
expect(errors, 'page errors on the equine copy').toEqual([])
})
test('commit latency on the equine copy', async ({ page, requests }) => {
test.setTimeout(180_000)
expect(copyId).not.toBe('')
requests.forbid(actor.account.email, actor.account.password)
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await page.goto(`/app/admin/sheets/${copyId}/draft`)
await expect(toolButton(page, dict, 'point')).toBeEnabled()
const renames = await measureRenames(page, 'equine: rename (update)')
const additions = await measureAdditions(
page,
'equine: add category (insert)',
)
// A geometry edit: the first annotation's centre, through the geometry group.
await showDrawing(page, dict)
await page
.getByRole('list', { name: dict['editor.annotations.list'] })
.getByRole('button')
.first()
.click()
const cx = page.getByLabel(dict['editor.annotations.geometry.cx'], {
exact: true,
})
const base = Number(await cx.inputValue())
await startProbe(page)
for (let round = 0; round <= SAMPLES; round++) {
await cx.fill(String(base + ((round % 2) + 1) * 0.5))
await cx.press('Enter')
}
await page.waitForTimeout(200)
const moves = report(
'equine: geometry edit',
(await takeSamples(page)).slice(1),
)
for (const line of [renames, additions, moves])
expect(line.handler.max, line.handler.max + ' ms').toBeLessThan(BUDGET_MS)
})
test('commit latency on a synthetic document near 2 MiB', async ({
page,
requests,
}) => {
test.setTimeout(180_000)
requests.forbid(actor.account.email, actor.account.password)
const seed = await seedDraft(actor, { shape: nearCapShape })
const bytes = Number(
await sql(
`select octet_length(content::text) from public.anatomical_sheet_versions where id = '${seed.draftId}'`,
),
)
console.log(`SYNTHETIC document ${bytes} bytes`)
expect(bytes).toBeGreaterThan(1_800_000)
expect(bytes).toBeLessThanOrEqual(2_097_152)
expect(
Object.keys(await serverDocument(seed.draftId)).length,
).toBeGreaterThan(5)
await openEditor(page, dict, actor, seed.sheetId)
const renames = await measureRenames(
page,
`synthetic ${bytes} B: rename (update)`,
)
const additions = await measureAdditions(
page,
`synthetic ${bytes} B: add category (insert)`,
)
test.info().annotations.push({
type: 'synthetic-bytes',
description: String(bytes),
})
expect(renames.handler.n).toBeGreaterThan(0)
expect(additions.handler.n).toBeGreaterThan(0)
})
})