/** * 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 { 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 { 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 = '' + '' + '' 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) => 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 { 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 { 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 { 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) 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) { 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) { 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 { 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 { return Number( await sql( `select revision from public.anatomical_sheet_versions where id = '${draftId}'`, ), ) } export async function serverDocument>( draftId: string, ): Promise { return JSON.parse( await sql( `select content::text from public.anatomical_sheet_versions where id = '${draftId}'`, ), ) as T } /** The visible save line (the hidden status region is another element). */ export const saveLine = (page: Page) => page.getByTestId('save-line') const withRevision = (text: string, revision: number) => text.replace('{revision}', String(revision)) /** « Révision n », the line of a draft with nothing saved in this session. */ export const revisionText = (dict: Dict, revision: number) => withRevision(dict['editor.draft.status.revision'], revision) /** The unsaved line, with or without its count. */ export const UNSAVED_LINE = /non enregistrée|unsaved/i /** « Enregistré · révision n », with or without the server's time of the save. */ export function savedLine(dict: Dict, revision: number): RegExp { const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') const plain = escape( withRevision(dict['editor.draft.status.saved'], revision), ) const timed = escape( withRevision(dict['editor.draft.status.saved_at'], revision), ) return new RegExp( `^(${plain}|${timed.replace('\\{time\\}', '\\d\\d:\\d\\d')})$`, ) } /** The header « Annuler » / « Rétablir » button (enabled ones take a plain click). */ export const historyButton = (page: Page, dict: Dict, kind: 'undo' | 'redo') => page.getByRole('button', { name: dict[`editor.history.${kind}_title`], exact: true, }) /** * Presses a button that may be `aria-disabled` at its box: Playwright's actionability * treats `aria-disabled` as disabled, a person's pointer does not. */ export async function pressAtBox(page: Page, button: Locator) { const box = await button.boundingBox() if (!box) throw new Error('the button has no box') await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2) } /** Saves through « Enregistrer » and waits until the save line shows the new revision. */ export async function saveDraft(page: Page, dict: Dict, revision: number) { await page.getByRole('button', { name: dict['common.save'] }).click() await expect(saveLine(page)).toHaveText(savedLine(dict, revision)) } /** 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) => { 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'] }) /** The tag over the drawing while an annotation is selected (the card is then hidden). */ export const selectionTag = (page: Page) => page.getByTestId('annotation-selection-tag') /** Selects an annotation from the overview card, leaving a selection first when there is one. */ export async function pickAnnotation( page: Page, dict: Dict, name: RegExp | string, ) { const all = page.getByRole('button', { name: dict['editor.annotations.show_all'], exact: true, }) const list = annotationList(page, dict) // Either the card (nothing selected) or the properties panel has settled. await expect(all.or(list)).toBeVisible() if (await all.isVisible()) await all.click() await list.getByRole('button', { name }).click() } 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 { 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 { 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 { 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', ), )