The reference library moves into a fifth editor tab (Général,
Annotations, Constats, Références, Vérification; under « Plus » below
640 px with Général and Constats). The header « Références » button is
removed. The side panel becomes the citations list of one finding,
opened only from a finding's trigger (owner GO 2026-11-12: never from a
family; the family keeps its inline list with « Retirer »). Selecting a
tab closes it; every close records one pending move applied after the
panel is gone, focus back to the trigger else the active tab button.
Vérification's reference issues land on the tab. e2e seed gains a
reference cited by « Constat A ».
Gates: typecheck, lint, test:run (app 1396), build, e2e:ui 251 passed;
e2e:shell 15 specs on db:sandbox (editor-equine never listed): 107
passed / 95 skipped / 2 failed (test remap dropped its edit), fixed and
rerun: editor-shell.spec 11 passed; full-row data guard: no
pre-existing row changed in any table. editor-equine.spec.ts helper
calls updated, not run.
## R-24 table (removed or rewritten assertions; old = fc3fec7 line, new = current file)
Unit tests:
| file:old line | old | new |
|---|---|---|
| editor-verification.test.tsx:87-96 | `navigate` called with target AND `expect.any(HTMLElement)` | called with the target only (opener dropped) |
| editor-verification.test.tsx:238-241 | `references[0]` path -> `{place:'references', citedBy:null}` | `{place:'tab', tab:'references', section:null}` |
| editor-verification.test.tsx:262-264 | `placeKey(references[9])` = `editor.place.references` | `editor.tab.references` |
| editor-navigation.test.ts:63 | targetOfKey reference -> `{place:'references', key, citedBy:null}` | `{place:'tab', tab:'references', section:null, key}` |
| editor-navigation.test.ts:80 | `referencesMounted` false at start | `citationsOf` null and `libraryReset` 0 |
| editor-navigation.test.ts:95-110 | go_to a reference opens the panel over the place | go_to a reference shows the Références tab with its focus request |
| editor-navigation.test.ts:112-122 | go_to a tab closes the panel (`references` object) | same, via `citationsOf` null |
| editor-navigation.test.ts:124-136 | select_tab keeps the panel | select_tab CLOSES the panel (P21), keeps section, no request |
| editor-navigation.test.ts:138-146 | `clear_cited_by` drops the filter | removed (action gone); replaced by `open_citations` refuses family/zone/view, `show_all_references` (closes, tab, reset bump), plain go_to leaves reset alone |
| editor-navigation.test.ts:160-175 | open/close references keep tab and section | open/close citations, same assertions on `citationsOf` |
| editor-mode.test.ts:100-109 | tabsFor four tabs, small more = general, findings | five tabs, small more = general, findings, references |
| editor-route.test.tsx:46,50 | TABS four, title « four tabs » | five |
| editor-route.test.tsx:139-146 | 640-1023 px four tabs | five tabs, tablist has `flex-wrap` |
| editor-route.test.tsx:149-161 | « Plus » lists Général, Constats | lists Général, Constats, Références |
| editor-route.test.tsx:168-190 | header button opens panel, ✕ returns focus to button | no header button, panel not mounted at start (full panel flow moved to editor-references-panel.test.tsx) |
| editor-route.test.tsx:192-206 | Escape closes, panel content kept for next opening | removed: the panel is no longer kept mounted (design choice 3); Escape/close covered in editor-references-panel + editor-escape |
| editor-route.test.tsx:208-218 | read-only: panel lists references, no edit control | read-only: the Références tab lists them, no textbox, no add button; plus new: tab keeps mounted when left |
| editor-tabs-lists.test.tsx:47,75,114,130 | render `ReferencesPanel` | render `ReferencesTab` |
| editor-tabs-lists.test.tsx:77 | selector `#reference-ref-a-url` | `#tab-reference-ref-a-url` |
| editor-tabs-lists.test.tsx:131-135 | read-only buttons = only « Fermer les références » | no button at all |
| editor-focus-request.test.tsx:166-171,200-202,346 | `ReferencesPanel` with `panel` props and focus | `ReferenceLibrary` with focus (same assertions) |
| editor-focus-request.test.tsx:226 | `ownedBy(ref,'citations')` is the request | `ownedBy(ref,'references')` is the request, `'citations'` undefined |
| editor-focus-request.test.tsx (Probe) | none | new: Vérification « Aller à » reference -> tab + focused row; reference path naming no element -> tab heading |
| editor-keep-alive.test.tsx:71,178-190 | add form survives closing/reopening the panel | survives leaving/returning to the Références tab (`#tab-reference-new-citation`) |
| editor-keep-alive.test.tsx:300-326 | « Aller à » without focus move commits Références text | a tab click without focus move commits it (one undo entry): « Aller à » is not reachable from the Références tab in R2.1 |
| editor-keep-alive.test.tsx:333-347 | Escape in panel reference field commits, panel hides | same, panel opened from a finding node, field `#panel-reference-ref-1-citation` |
| editor-keep-alive.test.tsx:350-363 | header toggle (no focus move) closes after committing | scrim click (no focus move) closes after committing |
| editor-keep-alive.test.tsx:425 | `referencesButton` click in the all-places sweep | `Références` added to the tab loop |
| editor-escape.test.tsx:218-227 | header button toggle, Escape on body closes panel, annotation selection kept | trigger-opened panel (A5), Escape closes it, `aria-expanded` back to false, selection kept after returning to Annotations |
| editor-escape.test.tsx:255-266 | Escape from tab row closes panel | same from the Constats tab button |
| editor-no-loss.test.tsx:146-153 | reference creation form, in the panel | in the Références tab, id `tab-reference-new-citation` |
| editor-no-loss.test.tsx:285-291 | focused header button survives crossing | focused tab button (Constats) survives crossing: no header button left |
| editor-no-loss.test.tsx:293-307 | references search in panel keeps focus/text | same in the Références tab body |
| editor-no-loss.test.tsx:390-400 | `everyPlace` ends by opening the panel | visits Références in the tab loop, no panel open |
| editor-no-loss-decisions.test.tsx:248-259 | open references panel holds the decision back | REMOVED: the panel exists only over Constats, decisions live in Annotations (hidden then); « a widening on another tab opens nothing » (same file) covers the withholding |
| editor-route-recovery.test.tsx:93-97 | recovery offer: header button opens panel, `aria-labelledby` | tab Références shows `editor-tab-references` labelled by `editor-references-title` |
| editor-references-panel.test.tsx (all) | header-button-driven panel tests incl. search, order, add, « Aller à » | split: panel tests (finding path only) stay in this file; library tests moved to new editor-references-tab.test.tsx (search matching, ↑/↓ only without search, counts, Ctrl+Z, read-only, « Aller à », add clears search, refused add keeps it); new: reset signal, ids unique with both mounted (P14), P6 fallback under « Plus » |
e2e (updated only, not run):
| file:old line | old | new |
|---|---|---|
| editor-shell.spec.ts:95-108 | panel keeps form text, no id repeats | Références tab keeps form text (`#tab-reference-new-citation`), ids unique with the panel open |
| editor-shell.spec.ts:121-142 | open panel leaves header and tab row clickable (incl. header Références button, add form) | `openCitations`; header button target and form steps dropped |
| editor-shell-journeys.spec.ts:113-123 | four tabs, `old` list includes « Références » | five tabs, « Références » removed from the old-layout list |
| editor-shell-journeys.spec.ts:246-249 | Aller à reference -> panel visible, close | `place('references')` visible, tab Références selected, row focus key, no close |
| editor-shell-layout.spec.ts:84-103 | overflow on four tabs + panel over drawing | five tabs + `openCitations`/`closeCitations` |
| editor-shell-layout.spec.ts:54-63 | local `goToTab` | removed, uses `openTab` |
| editor-shell-layout.spec.ts:140-158 | canvas width without/with panel over the drawing | E1: width measured before open and after a P21 switch to Annotations, asserted equal |
| editor-shell-layout.spec.ts:161-189 | axe on four tabs + open panel | five tabs + citations panel |
| editor-shell-layout.spec.ts:~255-310 | keyboard order began with `header` (the Références button) | `header` dropped from both orders (no focusable header control while the draft is clean); panel test selects Annotations before walking to `side` |
| editor-access.spec.ts:150-152,191-194,219-220 | axe/overflow with the panel at 320/375/768/800, 1024, read-only | same checks through `openCitations` (`showDrawing` calls dropped) |
| editor-shell-crossing.spec.ts:194-206 | references form with panel open, tab `annotations` | in the tab, focus expected on `editor-tab-references` |
| editor-shell-crossing.spec.ts:264-282 | panel open + add-form text across crossing | citations panel over a crossing, no typed-text step |
| editor-shell-crossing.spec.ts:~385-410 | decision withheld while panel open, Reprendre | REMOVED (state unreachable, see unit row) |
| editor-deselect.spec.ts:226-229 | Escape closes header-opened panel, selection kept | opened via Constats, Escape, back to Annotations, selection kept |
| editor-structures.spec.ts:80-122 | two references added, counts 2/1 | shape now holds `ref-a`: counts 3/2, `nth(1)` after move, saved list `['Référence A','Seconde référence']`, no panel |
| editor-equine.spec.ts:304-305,404-405 | openReferences/closeReferences | `openTab(page, dict, 'references')`: mis à jour, non exécuté, non vérifié |
Fix round 1: 1. e2e/shell/editor-shell.spec.ts « the open citations panel leaves the header and the tab row clickable »: before `openCitations`, the test now opens the Références tab and adds a reference through the library form (`#tab-reference-new-type` book, `#tab-reference-new-citation` « Smith 1999 », « Ajouter la référence »), so the draft is dirty and Save is enabled. All original assertion
697 lines
23 KiB
TypeScript
697 lines
23 KiB
TypeScript
/**
|
||
* 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.references = [
|
||
{
|
||
id: 'ref-a',
|
||
type: 'book',
|
||
citation: 'Référence A',
|
||
url: null,
|
||
doi: null,
|
||
},
|
||
]
|
||
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: ['ref-a'],
|
||
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 five tabs of the editor (R2.1), in the order of the row. */
|
||
export const TABS = [
|
||
'general',
|
||
'annotations',
|
||
'findings',
|
||
'references',
|
||
'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()
|
||
}
|
||
|
||
/** Where the references library shows: the Références tab. */
|
||
export function libraryRoot(page: Page): Locator {
|
||
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
|
||
* the tab picked in its list. Waits for the body of a tab that has a `data-place` of its
|
||
* own (every one but Annotations, which names its sections).
|
||
*/
|
||
export async function openTab(page: Page, dict: Dict, tab: string) {
|
||
const width = page.viewportSize()?.width ?? SMALL_TIER_WIDTH
|
||
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()
|
||
} else {
|
||
await page.getByRole('tab', { name }).click()
|
||
}
|
||
if (tab !== 'annotations') await expect(place(page, tab)).toBeVisible()
|
||
}
|
||
|
||
/**
|
||
* Opens the citations panel of the finding named `element`: the Constats tab, the tree
|
||
* expanded down to it, the element selected, its « n références » trigger pressed.
|
||
*/
|
||
export async function openCitations(page: Page, dict: Dict, element: string) {
|
||
await openTab(page, dict, 'findings')
|
||
const item = page.getByRole('treeitem', { name: element })
|
||
for (let depth = 0; depth < 4 && (await item.count()) === 0; depth++) {
|
||
const closed = page.getByRole('treeitem', { expanded: false }).first()
|
||
await closed.focus()
|
||
await closed.press('ArrowRight')
|
||
}
|
||
await item.click()
|
||
await page.locator('[data-citations-trigger]:visible').click()
|
||
await expect(place(page, 'citations')).toBeVisible()
|
||
}
|
||
|
||
/** Closes the citations panel with its ✕ button. */
|
||
export async function closeCitations(page: Page, dict: Dict) {
|
||
await page
|
||
.getByRole('button', { name: dict['editor.references.close'] })
|
||
.click()
|
||
await expect(place(page, 'citations')).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
|
||
}
|
||
|
||
/** 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 « Défaire » / « Refaire » 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<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'] })
|
||
|
||
/** The screen-reader-only tag rendered while an annotation is selected. */
|
||
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<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',
|
||
),
|
||
)
|