833 lines
27 KiB
TypeScript
833 lines
27 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 move pops its section entry from an effect: a click made before the pop lands
|
||
// would be undone by it (a user cannot be that quick, a script can).
|
||
await page.waitForFunction(() => {
|
||
const view = history.state?.usr?.editorEntry?.view
|
||
return !view || view.section === 'drawing'
|
||
})
|
||
}
|
||
|
||
/** 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 tab's place to be visible (Annotations names
|
||
* its sections, so any of them).
|
||
*/
|
||
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()
|
||
// The dropdown fades out: wait for it to be gone before the next move.
|
||
await expect(page.locator('#editor-tabs-more')).toHaveCount(0)
|
||
} else {
|
||
await page.getByRole('tab', { name }).click()
|
||
}
|
||
await expect(
|
||
tab === 'annotations'
|
||
? page.locator('[data-place^=annotations]:visible').first()
|
||
: place(page, tab),
|
||
).toBeVisible()
|
||
}
|
||
|
||
/** The open finding dialog: the layer dialog that is neither the sheet nor the reference form. */
|
||
export const findingDialog = (page: Page): Locator =>
|
||
page.locator('dialog[open][data-layer]').filter({
|
||
hasNot: page.locator('[data-place="citations"], #reference-form-citation'),
|
||
})
|
||
|
||
/** The open reference dialog (R2F-5): the layer dialog that holds the reference form. */
|
||
export const referenceDialog = (page: Page): Locator =>
|
||
page
|
||
.locator('dialog[open][data-layer]')
|
||
.filter({ has: page.locator('#reference-form-citation') })
|
||
|
||
/**
|
||
* Waits for the history to settle on a view without the reference layer (or, with
|
||
* `keepDialog`, with one): a close pops its entry from an effect, and a move made before
|
||
* the pop lands would be undone by it (a user cannot be that quick, a script can).
|
||
*/
|
||
export async function referenceSettled(page: Page, keepDialog = false) {
|
||
await page.waitForFunction((stays) => {
|
||
const view = history.state?.usr?.editorEntry?.view
|
||
if (!view) return true
|
||
return stays ? view.reference !== null : view.reference === null
|
||
}, keepDialog)
|
||
}
|
||
|
||
/** Opens « Ajouter une référence » (the References tab is shown): the form is ready. */
|
||
export async function startReference(page: Page, dict: Dict) {
|
||
await libraryRoot(page)
|
||
.getByRole('button', { name: dict['editor.references.add'] })
|
||
.click()
|
||
await expect(referenceDialog(page)).toBeVisible()
|
||
}
|
||
|
||
/**
|
||
* Creates a reference through the dialog and waits for every layer to be gone. The list
|
||
* does not move and the focus goes back to « Ajouter » (R2F-5): nothing is focused on the
|
||
* new tile.
|
||
*/
|
||
export async function addReference(
|
||
page: Page,
|
||
dict: Dict,
|
||
citation: string,
|
||
type = 'book',
|
||
) {
|
||
await startReference(page, dict)
|
||
const form = referenceDialog(page)
|
||
await form.locator('#reference-form-type').selectOption(type)
|
||
await form.locator('#reference-form-citation').fill(citation)
|
||
await form.getByRole('button', { name: dict['editor.reference.add'] }).click()
|
||
await expectNoDialog(page)
|
||
await referenceSettled(page)
|
||
}
|
||
|
||
/** Waits until no modal dialog is open: nothing is typed or pressed before (LRN-111/116). */
|
||
export const expectNoDialog = (page: Page) =>
|
||
expect(page.locator('dialog[open]')).toHaveCount(0)
|
||
|
||
/**
|
||
* The tree expanded down to the row named `element`, from the keyboard (a click on a row
|
||
* opens its dialog): depth-first from the first zone, one node per step, at most
|
||
* `expansions` steps (4 is enough for a small fixture).
|
||
*/
|
||
export async function revealFinding(
|
||
page: Page,
|
||
element: string,
|
||
expansions = 4,
|
||
): Promise<Locator> {
|
||
const item = page.getByRole('treeitem', { name: element })
|
||
for (let step = 0; step < expansions && (await item.count()) === 0; step++) {
|
||
const closed = page.getByRole('treeitem', { expanded: false }).first()
|
||
await closed.focus()
|
||
await closed.press('ArrowRight')
|
||
}
|
||
return item
|
||
}
|
||
|
||
/**
|
||
* Opens the dialog of the finding named `element`: the Constats tab, the tree expanded
|
||
* down to it, its row activated (a click), the dialog open.
|
||
*/
|
||
export async function openFinding(
|
||
page: Page,
|
||
dict: Dict,
|
||
element: string,
|
||
expansions = 4,
|
||
) {
|
||
await openTab(page, dict, 'findings')
|
||
const item = await revealFinding(page, element, expansions)
|
||
await item.click()
|
||
await expect(findingDialog(page)).toBeVisible()
|
||
}
|
||
|
||
/**
|
||
* Waits for the history to settle on a view without the finding layer (or without its
|
||
* sheet): a close pops its entry from an effect, and a move made before the pop lands
|
||
* would be undone by it (a user cannot be that quick, a script can).
|
||
*/
|
||
export async function layersSettled(page: Page, keepDialog = false) {
|
||
await page.waitForFunction((dialogStays) => {
|
||
const view = history.state?.usr?.editorEntry?.view
|
||
if (!view) return true
|
||
if (dialogStays) return !view.finding?.citations
|
||
return view.finding === null
|
||
}, keepDialog)
|
||
}
|
||
|
||
/** Closes the finding dialog with its ✕ and waits until no dialog is left. */
|
||
export async function closeFinding(page: Page, dict: Dict) {
|
||
await findingDialog(page)
|
||
.getByRole('button', { name: dict['common.close'], exact: true })
|
||
.click()
|
||
await expectNoDialog(page)
|
||
await layersSettled(page)
|
||
}
|
||
|
||
/**
|
||
* Opens the citations sheet of the finding named `element`: its dialog, then its
|
||
* « n références » trigger. The sheet lies over the dialog and holds the focus.
|
||
*/
|
||
export async function openCitations(
|
||
page: Page,
|
||
dict: Dict,
|
||
element: string,
|
||
expansions = 4,
|
||
) {
|
||
await openFinding(page, dict, element, expansions)
|
||
await showCitations(page)
|
||
}
|
||
|
||
/** From the open finding dialog: « n références » opens the sheet over it. */
|
||
export async function showCitations(page: Page) {
|
||
await page.locator('[data-citations-trigger]:visible').click()
|
||
await expect(place(page, 'citations')).toBeVisible()
|
||
await expect(page.locator('dialog[open]')).toHaveCount(2)
|
||
}
|
||
|
||
/** Closes the citations sheet with its ✕: the finding dialog under it stays open. */
|
||
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)
|
||
await expect(page.locator('dialog[open]')).toHaveCount(1)
|
||
await layersSettled(page, true)
|
||
}
|
||
|
||
/** 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',
|
||
),
|
||
)
|