Files
faunosteo/apps/app/e2e/support/editor.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

592 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* V1-2.6 setup of the editor suites (Lot K): editor accounts with a verified factor and an
* aal2 token of their own, draft sheets written the way the sandbox suites do (RPC with
* that token, the drawing through the Storage policy), and the page-side helpers the
* editor specs share (opening the draft, tabs, drawing coordinates, save). What a test
* proves goes through the page; fixtures only prepare what a person did earlier.
*/
import { createHash, randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import type { Dict } from '@/i18n/types'
import type { Browser, BrowserContext, Locator, Page } from '@playwright/test'
import {
enrolTotp,
refusal,
verifyTotp,
} from '../../../../packages/supabase/tests/sandbox/mfa'
import {
rpc,
sql,
stack,
} from '../../../../packages/supabase/tests/sandbox/stack'
import { assignRole, passwordToken, seedGrant, stepUpAdmin } from './admin'
import type { GrantKind } from './admin'
import { expect } from './browser'
import { core } from './catalogue'
import { parseOutcome } from '@faunosteo/core-wasm'
import {
createAccount,
FAKE_SUPABASE_ORIGIN,
routeToSandbox,
type SandboxAccount,
} from './sandbox'
import { signIn } from './shell'
export interface Actor {
account: SandboxAccount
secret: string
/** An aal2 access token for the sandbox REST and Storage calls of fixtures. */
aal2: string
}
/** An account with its role and grants and one verified factor; the secret serves the page. */
export async function makeActor(
locale: 'fr' | 'en',
role: 'owner' | 'admin' | null,
grants: GrantKind[],
): Promise<Actor> {
const account = await createAccount(locale, false)
if (role) await assignRole(account, role)
for (const kind of grants) await seedGrant(account, kind)
const token = await passwordToken(account)
const enrolment = await enrolTotp(token, 'Téléphone')
if (!enrolment.factor)
throw new Error(`editor fixture: enrol ${refusal(enrolment)}`)
const verified = await verifyTotp(token, enrolment.factor)
const aal2 = verified.body.access_token
if (typeof aal2 !== 'string')
throw new Error(`editor fixture: no aal2 ${refusal(verified)}`)
return { account, secret: enrolment.factor.secret, aal2 }
}
export const editorActor = (locale: 'fr' | 'en') =>
makeActor(locale, 'admin', ['sheet_editor'])
/** An admin whose editor grant ends soon (the grant is written by hand, not seeded). */
export async function expiringEditor(
locale: 'fr' | 'en',
seconds: number,
): Promise<Actor> {
const actor = await makeActor(locale, 'admin', [])
await seedExpiringGrant(actor.account, 'sheet_editor', seconds)
return actor
}
/** The drawing of the fixtures: a 1000 × 800 box with a body shape. */
export const DRAWING_SVG =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 800">' +
'<rect x="50" y="50" width="900" height="700" fill="#f4efe6" stroke="#444"/>' +
'<circle cx="500" cy="400" r="200" fill="#d8b98a"/></svg>'
const text = (fr: string) => ({ fr, en: fr })
export interface DraftSeed {
sheetId: string
draftId: string
names: { fr: string; en: string }
assetId: string | null
/** The revision the server holds once seeded (0 for a blank draft). */
revision: number
}
export interface SeedOptions {
/** SVG bytes of the main view's drawing; null leaves the blank starting document. */
drawing?: string | null
species?: string
/** Adjusts the document before it is saved (categories, detail views, findings). */
shape?: (document: Record<string, unknown>) => void
}
const sha256 = (bytes: Buffer) =>
createHash('sha256').update(bytes).digest('hex')
function blankDocument(species: string, name: string) {
return {
schema_version: 2,
species_id: species,
name: text(name),
description: {},
scope_disclaimer: {},
attribution: { authors: [], license: null, notes: null },
vertebral_config: { regions: [] },
references: [],
categories: [],
views: [
{
id: 'main',
kind: 'main',
name: { fr: 'Vue principale', en: 'Main view' },
svg_asset_id: null as string | null,
view_box: null,
},
],
annotations: [],
finding_zones: [],
}
}
function succeeded(result: { status: number; text: string }, what: string) {
if (result.status !== 200)
throw new Error(`editor fixture ${what}: HTTP ${result.status}`)
return result
}
/** The drawing as the core stores it: the form the page uploads after its own cleaning. */
async function storedForm(svg: string): Promise<string> {
const loaded = await core()
const outcome = loaded.invoke<{ stored: string | null }>((glue) =>
parseOutcome<{ stored: string | null }>(
glue.clean_svg(new TextEncoder().encode(svg)),
),
)
if (!outcome.ok || !outcome.value.stored)
throw new Error('editor fixture: the core refused the drawing')
return outcome.value.stored
}
async function attachDrawing(
actor: Actor,
sheetId: string,
svg: string,
): Promise<string> {
const bytes = Buffer.from(await storedForm(svg))
const registered = succeeded(
await rpc(
'register_sheet_asset',
{
sheet_id: sheetId,
sha256: sha256(bytes),
byte_size: bytes.length,
file_name: 'fixture.svg',
},
actor.aal2,
),
'register',
)
const response = await fetch(
`${stack.storageUrl}/object/anatomical-sheet-assets/${sha256(bytes)}.svg`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${actor.aal2}`,
'Content-Type': 'image/svg+xml',
},
body: new Uint8Array(bytes),
},
)
await response.arrayBuffer()
if (response.status !== 200 && response.status !== 400)
throw new Error(`editor fixture upload: HTTP ${response.status}`)
const assetId = JSON.parse(registered.text) as string
succeeded(
await rpc('confirm_sheet_asset_upload', { asset_id: assetId }, actor.aal2),
'confirm',
)
return assetId
}
/** A non-equine draft sheet by `actor`, its drawing and content saved as revision 1. */
export async function seedDraft(
actor: Actor,
options: SeedOptions = {},
): Promise<DraftSeed> {
const tag = randomUUID().slice(0, 8)
const names = { fr: `Fiche e2e ${tag}`, en: `E2E sheet ${tag}` }
const document = blankDocument(options.species ?? 'canine', names.fr)
document.name = names
const created = succeeded(
await rpc(
'create_official_sheet',
{ slug: `e2e-${tag}`, document },
actor.aal2,
),
'create',
)
const sheetId = JSON.parse(created.text) as string
const draftId = await sql(
`select id from public.anatomical_sheet_versions where sheet_id = '${sheetId}' and status = 'draft'`,
)
const drawing = options.drawing === undefined ? DRAWING_SVG : options.drawing
const assetId = drawing ? await attachDrawing(actor, sheetId, drawing) : null
if (assetId) document.views[0].svg_asset_id = assetId
options.shape?.(document as unknown as Record<string, unknown>)
const changed = assetId !== null || options.shape !== undefined
if (changed) {
succeeded(
await rpc(
'save_sheet_draft',
{
version_id: draftId,
expected_revision: 0,
document,
change_note: 'fixture',
},
actor.aal2,
),
'save',
)
}
const revision = changed ? 1 : 0
return { sheetId, draftId, names, assetId, revision }
}
/**
* The categories, zone and detail view most editor specs start from, written in full.
* `bareShape` below omits the defaulted fields (the loader fills them from the core).
*/
export function standardShape(document: Record<string, unknown>) {
document.categories = [
{ id: 'cat-a', name: text('Catégorie A'), color: null },
]
document.finding_zones = [
{
id: 'zone-a',
name: text('Zone A'),
categories: [
{
id: 'fcat-a',
kind: 'dysfunction',
name: text('Dysfonction A'),
description: {},
reference_ids: [],
review_status: 'reviewed',
children: [
{
id: 'node-a',
name: text('Constat A'),
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'reviewed',
children: [],
},
],
},
],
},
]
;(document.views as unknown[]).push({
id: 'detail-a',
kind: 'detail',
name: text('Détail A'),
svg_asset_id: null,
view_box: { min_x: 100, min_y: 100, width: 300, height: 240 },
parent_view_id: 'main',
})
}
/** Like `standardShape`, but nodes and categories omit what the core defaults. */
export function bareShape(document: Record<string, unknown>) {
standardShape(document)
document.finding_zones = [
{
id: 'zone-bare',
name: text('Zone nue'),
categories: [
{
id: 'fcat-bare',
kind: 'dysfunction',
name: text('Catégorie nue'),
children: [{ id: 'node-bare', name: text('Constat nu') }],
},
],
},
]
}
export const draftPath = (sheetId: string) =>
`/app/admin/sheets/${sheetId}/draft`
export const draftTitle = (dict: Dict, number = 1) =>
dict['editor.draft.title'].replace('{number}', String(number))
/** Signs in, steps up and opens the draft editor of `sheetId`; resolves once it is ready. */
export async function openEditor(
page: Page,
dict: Dict,
actor: Actor,
sheetId: string,
): Promise<void> {
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await openDraft(page, dict, sheetId)
}
/** Opens the draft page (already signed in and stepped up). */
export async function openDraft(page: Page, dict: Dict, sheetId: string) {
await page.goto(draftPath(sheetId))
await expect(
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
).toBeVisible()
await expect(page.getByRole('tablist')).toBeVisible()
}
/** The four tabs of the editor (U1): the references moved to a panel, the rest to Annotations. */
export const TABS = [
'general',
'annotations',
'findings',
'verification',
] as const
/** The Annotations sections and the panel, in the order the overview offers them. */
export const SECTIONS = ['views', 'categories', 'regions'] as const
/**
* Clicks a tab by role. 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) {
const name = dict[`editor.tab.${tab}`]
await page.getByRole('tab', { name: new RegExp(`^${name}( |$)`) }).click()
}
/** The visible place with this `data-place` name; a hidden copy never answers. */
export function place(page: Page, name: string): Locator {
return page.locator(`[data-place="${name}"]:visible`)
}
/** « Retour au dessin »: leaves an Annotations section for the drawing. */
export async function backToDrawing(page: Page, dict: Dict) {
await page.getByRole('button', { name: dict['editor.section.back'] }).click()
await expect(place(page, 'annotations.drawing')).toBeVisible()
}
/** The Annotations tab on its drawing, whatever section it was left on. */
export async function showDrawing(page: Page, dict: Dict) {
await selectTab(page, dict, 'annotations')
const back = page.getByRole('button', { name: dict['editor.section.back'] })
if (await back.isVisible()) await backToDrawing(page, dict)
await expect(place(page, 'annotations.drawing')).toBeVisible()
}
/** Opens an Annotations section through its overview entry. */
export async function openSection(
page: Page,
dict: Dict,
section: (typeof SECTIONS)[number],
) {
await showDrawing(page, dict)
await page.locator(`[data-section-entry="${section}"]`).click()
await expect(place(page, `annotations.${section}`)).toBeVisible()
}
/** Opens the references panel from the header button. */
export async function openReferences(page: Page, dict: Dict) {
const toggle = page.getByRole('button', {
name: dict['editor.references.open'],
exact: true,
})
if ((await toggle.getAttribute('aria-expanded')) !== 'true')
await toggle.click()
await expect(place(page, 'references')).toBeVisible()
}
export async function closeReferences(page: Page, dict: Dict) {
await page
.getByRole('button', { name: dict['editor.references.close'] })
.click()
await expect(place(page, 'references')).toHaveCount(0)
}
/** The revision the server holds for the draft. */
export async function serverRevision(draftId: string): Promise<number> {
return Number(
await sql(
`select revision from public.anatomical_sheet_versions where id = '${draftId}'`,
),
)
}
export async function serverDocument<T = Record<string, unknown>>(
draftId: string,
): Promise<T> {
return JSON.parse(
await sql(
`select content::text from public.anatomical_sheet_versions where id = '${draftId}'`,
),
) as T
}
/** Saves through « Enregistrer » and waits until the server revision line moves. */
export async function saveDraft(page: Page, dict: Dict, revision: number) {
await page.getByRole('button', { name: dict['common.save'] }).click()
await expect(
page.getByText(
dict['editor.draft.status.revision'].replace(
'{revision}',
String(revision),
),
{ exact: true },
),
).toBeVisible()
}
/** Client coordinates of a drawing point, through the overlay's own matrix. */
export async function clientOf(
page: Page,
x: number,
y: number,
): Promise<{ x: number; y: number }> {
return page.getByTestId('annotation-overlay').evaluate(
(svg, at) => {
const root = svg as unknown as SVGSVGElement
const point = root.createSVGPoint()
point.x = at.x
point.y = at.y
const mapped = point.matrixTransform(root.getScreenCTM()!)
return { x: mapped.x, y: mapped.y }
},
{ x, y },
)
}
/** A click at a drawing point on the annotation canvas. */
export async function clickDrawing(page: Page, x: number, y: number) {
const at = await clientOf(page, x, y)
await page.mouse.click(at.x, at.y)
}
/** The geometry fields of the open creation panel or properties panel. */
export const geometryField = (page: Page, dict: Dict, key: string) =>
page.getByLabel(dict[`editor.annotations.geometry.${key}`], { exact: true })
/** A point annotation of the fixtures (a circle in drawing units, reviewed). */
export function pointOf(
id: string,
viewId: string,
circle: { cx: number; cy: number; r: number },
name = id,
) {
return {
id,
kind: 'point',
view_id: viewId,
category_id: 'cat-a',
laterality: 'unpaired',
geometry: { type: 'circle', ...circle },
review_status: 'reviewed',
name: text(name),
finding_zone_id: 'zone-a',
vertebral_region_code: null,
}
}
/** The standard shape plus the given annotations. */
export function shapeWith(...annotations: unknown[]) {
return (document: Record<string, unknown>) => {
standardShape(document)
document.annotations = annotations
}
}
export const creationPanel = (page: Page) =>
page.getByTestId('annotation-creation')
export const annotationList = (page: Page, dict: Dict) =>
page.getByRole('list', { name: dict['editor.annotations.list'] })
export const toolButton = (page: Page, dict: Dict, id: string) =>
page.getByRole('button', {
name: dict[`editor.annotations.tool.${id}`],
exact: true,
})
/** Fills the creation panel; the category keeps its first choice. */
export async function fillCreation(
page: Page,
dict: Dict,
names: { fr: string; en: string },
opens?: string,
) {
const panel = creationPanel(page)
await panel.getByLabel(dict['editor.annotations.name_fr']).fill(names.fr)
await panel.getByLabel(dict['editor.annotations.name_en']).fill(names.en)
await panel
.getByLabel(dict['editor.annotations.laterality'])
.selectOption('unpaired')
if (opens)
await panel.getByLabel(dict['editor.annotations.opens']).selectOption(opens)
}
export async function createFromPanel(page: Page, dict: Dict) {
await creationPanel(page)
.getByRole('button', { name: dict['editor.annotations.create'] })
.click()
await expect(creationPanel(page)).toHaveCount(0)
}
/**
* A second signed-in session of `actor` or another account in a fresh browser context,
* under the same replay and the same request allowlist as the suite's pages.
*/
export async function secondSession(
browser: Browser,
baseURL: string,
locale: string,
): Promise<{ context: BrowserContext; page: Page }> {
const context = await browser.newContext({ baseURL, locale })
await routeToSandbox(context)
const allowed = [new URL(baseURL).origin, FAKE_SUPABASE_ORIGIN]
await context.route(
(url) => !allowed.includes(url.origin),
(route) => route.abort('blockedbyclient'),
)
return { context, page: await context.newPage() }
}
/** The storage key of the tab's recovery copy of a draft (state/recovery.ts). */
export const copyKeyOf = (userId: string, versionId: string) =>
`osteo:sheet-draft:${userId}:${versionId}`
export function storedCopy(page: Page, key: string): Promise<string | null> {
return page.evaluate((name) => sessionStorage.getItem(name), key)
}
/** Reloads with the beforeunload dialog of a page holding unsaved changes accepted. */
export async function reloadAccepting(page: Page): Promise<string[]> {
const kinds: string[] = []
const accept = (dialog: import('@playwright/test').Dialog) => {
kinds.push(dialog.type())
void dialog.accept()
}
page.on('dialog', accept)
await page.reload()
page.off('dialog', accept)
return kinds
}
/** An aal2 owner, for the calls that change another account's rights. */
export const ownerActor = (locale: 'fr' | 'en') =>
makeActor(locale, 'owner', [])
/** The id of the account's active grant of `kind`. */
export function grantIdOf(account: SandboxAccount, kind: string) {
return sql(
`select id from public.anatomical_catalog_grants where user_id = '${account.id}'
and grant_kind = '${kind}' and revoked_at is null`,
)
}
/** A grant that ends `seconds` from now (granted earlier, so the expiry check holds). */
export async function seedExpiringGrant(
account: SandboxAccount,
kind: GrantKind,
seconds: number,
): Promise<void> {
await sql(`insert into public.anatomical_catalog_grants
(user_id, grant_kind, reason, verification_note, granted_by, granted_at, expires_at)
values ('${account.id}', '${kind}', 'sandbox', 'sandbox', '${account.id}',
now() - interval '1 hour', now() + interval '${seconds} seconds')`)
}
/** The committed Inkscape 1.4.3 export (viewBox 0 0 200 150), read from disk, never edited. */
export const INKSCAPE_EXPORT = readFileSync(
join(
__dirname,
'../../../../crates/core/tests/fixtures/svg/exports/inkscape-1.4.3-inkscape-svg.svg',
),
)