feat(app): access label buttons and the « Autres vues » list
This commit is contained in:
1 parent
760a4bf7e1
commit
5ec07af751
5 files changed
+574
No files matched your search
@@ -0,0 +1,190 @@
|
|||||||
|
import { useEffect, useRef, useState, type KeyboardEvent, type RefObject } from 'react'
|
||||||
|
import type { Box, PlacedLabel } from '@/anatomy/accessLabels'
|
||||||
|
import { LABEL_H, LABEL_MAX_W } from '@/anatomy/accessLabels'
|
||||||
|
import Icon from '@/components/ui/Icon'
|
||||||
|
import { useT } from '@/i18n/useT'
|
||||||
|
import { useAccessLabels, type Access } from './useAccessLabels'
|
||||||
|
|
||||||
|
export interface AccessLabelsProps {
|
||||||
|
/** The canvas box the labels sit in (the element `area` is measured from). */
|
||||||
|
box: RefObject<HTMLElement | null>
|
||||||
|
/** The drawing host holding the core's layer. */
|
||||||
|
drawing: RefObject<Element | null>
|
||||||
|
/** Recompute triggers: view, the surface's build counter (bumped after each svg rebuild),
|
||||||
|
* framing transform, selection (handles), locale. */
|
||||||
|
layoutKey: string
|
||||||
|
/** Boxes over the canvas the labels must leave free (the catalogue's zoom buttons, A8). */
|
||||||
|
reserved?: RefObject<HTMLElement | null>[]
|
||||||
|
hidden: boolean
|
||||||
|
onActivate: (accessId: string, opensViewId: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const PILL =
|
||||||
|
'inline-flex items-center gap-1 rounded-full border bg-white px-2 text-xs ' +
|
||||||
|
'leading-none text-ink'
|
||||||
|
const CHIP_STYLE = { maxWidth: LABEL_MAX_W, height: LABEL_H }
|
||||||
|
|
||||||
|
function boxStyle(b: Box) {
|
||||||
|
return { left: b.x, top: b.y, width: b.w, height: b.h }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Leaders({ placed, byId }: { placed: PlacedLabel[]; byId: Map<string, Access> }) {
|
||||||
|
return (
|
||||||
|
<svg aria-hidden="true" className="pointer-events-none absolute inset-0 h-full w-full">
|
||||||
|
{placed.map(({ id, leader }) => {
|
||||||
|
const color = byId.get(id)?.color
|
||||||
|
if (!leader || !color) return null
|
||||||
|
return (
|
||||||
|
<g key={id} stroke={color} fill={color}>
|
||||||
|
<line x1={leader.x1} y1={leader.y1} x2={leader.x2} y2={leader.y2} strokeWidth={1} />
|
||||||
|
<circle cx={leader.x2} cy={leader.y2} r={2.2} stroke="none" />
|
||||||
|
</g>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The hidden measuring copy of a label: same classes, same content. */
|
||||||
|
function Twin({ access }: { access: Access }) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-measure="label"
|
||||||
|
className={PILL}
|
||||||
|
style={{ ...CHIP_STYLE, borderColor: access.color }}
|
||||||
|
>
|
||||||
|
<span className="min-w-0 truncate">{access.name}</span>
|
||||||
|
<span aria-hidden="true">›</span>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MeasureRow(props: { accesses: Access[]; count: number; row: RefObject<HTMLDivElement | null> }) {
|
||||||
|
const t = useT()
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={props.row}
|
||||||
|
aria-hidden="true"
|
||||||
|
className="invisible absolute left-0 top-0 flex flex-col items-start"
|
||||||
|
>
|
||||||
|
{props.accesses.map((a) => (
|
||||||
|
<Twin key={a.id} access={a} />
|
||||||
|
))}
|
||||||
|
<span data-measure="more" className={`${PILL} border-border`} style={{ height: LABEL_H }}>
|
||||||
|
{t('canvas.access.more').replace('{count}', String(props.count))}
|
||||||
|
<Icon name="chevron-down" className="h-3 w-3" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MoreProps {
|
||||||
|
box: Box
|
||||||
|
items: Access[]
|
||||||
|
onActivate: AccessLabelsProps['onActivate']
|
||||||
|
}
|
||||||
|
|
||||||
|
/** « Autres vues (N) » and its list. Escape and an outside press close it. */
|
||||||
|
function MoreViews({ box, items, onActivate }: MoreProps) {
|
||||||
|
const t = useT()
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const root = useRef<HTMLDivElement | null>(null)
|
||||||
|
const trigger = useRef<HTMLButtonElement | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
const onPress = (event: Event) => {
|
||||||
|
if (event.target instanceof Node && !root.current?.contains(event.target)) setOpen(false)
|
||||||
|
}
|
||||||
|
document.addEventListener('pointerdown', onPress)
|
||||||
|
return () => document.removeEventListener('pointerdown', onPress)
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (!open || event.key !== 'Escape') return
|
||||||
|
// Neither the bilan's detail window nor the editor's deselect may see this Escape.
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
setOpen(false)
|
||||||
|
trigger.current?.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={root}
|
||||||
|
onKeyDown={onKeyDown}
|
||||||
|
className="pointer-events-none absolute"
|
||||||
|
style={{ left: box.x, top: box.y, width: box.w }}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
ref={trigger}
|
||||||
|
type="button"
|
||||||
|
aria-expanded={open}
|
||||||
|
onClick={() => setOpen(!open)}
|
||||||
|
className={`${PILL} pointer-events-auto border-border`}
|
||||||
|
style={{ height: box.h, width: box.w }}
|
||||||
|
>
|
||||||
|
{t('canvas.access.more').replace('{count}', String(items.length))}
|
||||||
|
<Icon name="chevron-down" className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
{open && (
|
||||||
|
<ul className="pointer-events-auto absolute right-0 top-full z-10 mt-1 flex w-max max-w-[220px] flex-col gap-1 rounded-md border border-border bg-white p-1 shadow">
|
||||||
|
{items.map((a) => (
|
||||||
|
<li key={a.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={a.name}
|
||||||
|
aria-label={t('canvas.access.open').replace('{name}', a.name)}
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false)
|
||||||
|
onActivate(a.id, a.opensViewId)
|
||||||
|
}}
|
||||||
|
className="w-full truncate rounded px-2 py-1 text-left text-xs"
|
||||||
|
>
|
||||||
|
{a.name}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The access labels over a drawing (D12, D21, D25): one button per detail-view access,
|
||||||
|
* placed by `placeAccessLabels`, and « Autres vues (N) » for those that do not fit. The
|
||||||
|
* layer lets pointers through; only the buttons catch them.
|
||||||
|
*/
|
||||||
|
export default function AccessLabels(props: AccessLabelsProps) {
|
||||||
|
const t = useT()
|
||||||
|
const { accesses, layout, measureRow } = useAccessLabels(props)
|
||||||
|
if (props.hidden) return null
|
||||||
|
const byId = new Map(accesses.map((a) => [a.id, a]))
|
||||||
|
const shown = (layout?.placed ?? []).filter((p) => byId.has(p.id))
|
||||||
|
const overflow = (layout?.overflow ?? []).flatMap((id) => byId.get(id) ?? [])
|
||||||
|
return (
|
||||||
|
<div data-testid="access-labels" className="pointer-events-none absolute inset-0 overflow-hidden">
|
||||||
|
<MeasureRow accesses={accesses} count={accesses.length} row={measureRow} />
|
||||||
|
<Leaders placed={shown} byId={byId} />
|
||||||
|
{shown.map((p) => {
|
||||||
|
const a = byId.get(p.id) as Access
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={p.id}
|
||||||
|
type="button"
|
||||||
|
title={a.name}
|
||||||
|
aria-label={t('canvas.access.open').replace('{name}', a.name)}
|
||||||
|
onClick={() => props.onActivate(a.id, a.opensViewId)}
|
||||||
|
className={`${PILL} pointer-events-auto absolute`}
|
||||||
|
style={{ ...CHIP_STYLE, ...boxStyle(p.box), borderColor: a.color }}
|
||||||
|
>
|
||||||
|
<span className="min-w-0 truncate">{a.name}</span>
|
||||||
|
<span aria-hidden="true">›</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{layout?.button && <MoreViews box={layout.button} items={overflow} onActivate={props.onActivate} />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react'
|
||||||
|
import {
|
||||||
|
LABEL_MAX_W,
|
||||||
|
placeAccessLabels,
|
||||||
|
type Box,
|
||||||
|
type Disc,
|
||||||
|
type LabelLayout,
|
||||||
|
} from '@/anatomy/accessLabels'
|
||||||
|
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||||
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
|
|
||||||
|
/** An access label's content, read from the drawing's layer. */
|
||||||
|
export interface Access {
|
||||||
|
id: string
|
||||||
|
opensViewId: string
|
||||||
|
name: string
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccessLabelsInput {
|
||||||
|
box: RefObject<HTMLElement | null>
|
||||||
|
drawing: RefObject<Element | null>
|
||||||
|
layoutKey: string
|
||||||
|
reserved?: RefObject<HTMLElement | null>[]
|
||||||
|
hidden: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccessLabelsState {
|
||||||
|
accesses: Access[]
|
||||||
|
layout: LabelLayout | null
|
||||||
|
/** The hidden row holding one measuring twin per label, then the list button's. */
|
||||||
|
measureRow: RefObject<HTMLDivElement | null>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Radius of the hit ring kept clear around a point marker or a handle. */
|
||||||
|
const MIN_HIT_RADIUS = 11
|
||||||
|
const RING = 4
|
||||||
|
|
||||||
|
const ACCESS_SELECTOR = '[data-anno-kind="detail_trigger"]'
|
||||||
|
const POINT_SELECTOR = '[data-anno-kind="point"][fill="transparent"]'
|
||||||
|
|
||||||
|
function readAccesses(drawing: Element | null, locale: 'fr' | 'en'): Access[] {
|
||||||
|
if (!drawing) return []
|
||||||
|
return Array.from(drawing.querySelectorAll(ACCESS_SELECTOR)).map((el) => ({
|
||||||
|
id: el.getAttribute('data-anno-id') ?? '',
|
||||||
|
opensViewId: el.getAttribute('data-anno-opens-view') ?? '',
|
||||||
|
name: pickLocaleLabel(
|
||||||
|
el.getAttribute('data-anno-name-fr') ?? '',
|
||||||
|
el.getAttribute('data-anno-name-en') ?? '',
|
||||||
|
locale,
|
||||||
|
),
|
||||||
|
color: el.getAttribute('stroke') ?? 'currentColor',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
function relativeBox(el: Element, origin: DOMRect): Box {
|
||||||
|
const r = el.getBoundingClientRect()
|
||||||
|
return { x: r.left - origin.left, y: r.top - origin.top, w: r.width, h: r.height }
|
||||||
|
}
|
||||||
|
|
||||||
|
function discOf(el: Element, origin: DOMRect): Disc {
|
||||||
|
const b = relativeBox(el, origin)
|
||||||
|
return {
|
||||||
|
cx: b.x + b.w / 2,
|
||||||
|
cy: b.y + b.h / 2,
|
||||||
|
r: Math.max(b.w / 2, MIN_HIT_RADIUS) + RING,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function obstaclesOf(box: HTMLElement, drawing: Element, origin: DOMRect): Disc[] {
|
||||||
|
const points = Array.from(drawing.querySelectorAll(POINT_SELECTOR))
|
||||||
|
const handles = Array.from(box.querySelectorAll('[data-handle]'))
|
||||||
|
return [...points, ...handles].map((el) => discOf(el, origin))
|
||||||
|
}
|
||||||
|
|
||||||
|
function measuredWidths(row: HTMLElement | null): number[] {
|
||||||
|
const twins = Array.from(row?.querySelectorAll('[data-measure="label"]') ?? [])
|
||||||
|
return twins.map((el) => Math.min(el.getBoundingClientRect().width, LABEL_MAX_W))
|
||||||
|
}
|
||||||
|
|
||||||
|
function measuredButton(row: HTMLElement | null): { w: number; h: number } {
|
||||||
|
const r = row?.querySelector('[data-measure="more"]')?.getBoundingClientRect()
|
||||||
|
return { w: r?.width ?? 0, h: r?.height ?? 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeLayout(
|
||||||
|
input: AccessLabelsInput,
|
||||||
|
accesses: Access[],
|
||||||
|
row: HTMLElement | null,
|
||||||
|
): LabelLayout | null {
|
||||||
|
const box = input.box.current
|
||||||
|
const drawing = input.drawing.current
|
||||||
|
if (!box || !drawing) return null
|
||||||
|
const origin = box.getBoundingClientRect()
|
||||||
|
const nodes = Array.from(drawing.querySelectorAll(ACCESS_SELECTOR))
|
||||||
|
const widths = measuredWidths(row)
|
||||||
|
return placeAccessLabels({
|
||||||
|
area: { x: 0, y: 0, w: origin.width, h: origin.height },
|
||||||
|
// `accesses` may lag the drawing by one pass: a missing node is skipped.
|
||||||
|
labels: accesses.flatMap((a, i) =>
|
||||||
|
nodes[i] ? [{ id: a.id, access: relativeBox(nodes[i], origin), w: widths[i] ?? 0 }] : [],
|
||||||
|
),
|
||||||
|
obstacles: obstaclesOf(box, drawing, origin),
|
||||||
|
reserved: (input.reserved ?? []).flatMap((ref) =>
|
||||||
|
ref.current ? [relativeBox(ref.current, origin)] : [],
|
||||||
|
),
|
||||||
|
button: measuredButton(row),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Redraws once per frame when the box is resized. */
|
||||||
|
function useResizeTick(box: RefObject<HTMLElement | null>, off: boolean): number {
|
||||||
|
const [tick, setTick] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const element = box.current
|
||||||
|
if (off || !element || typeof ResizeObserver === 'undefined') return
|
||||||
|
let frame = 0
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
cancelAnimationFrame(frame)
|
||||||
|
frame = requestAnimationFrame(() => setTick((n) => n + 1))
|
||||||
|
})
|
||||||
|
observer.observe(element)
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(frame)
|
||||||
|
observer.disconnect()
|
||||||
|
}
|
||||||
|
}, [box, off])
|
||||||
|
return tick
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the accesses from the drawing's layer, measures the room around them after layout
|
||||||
|
* and asks `placeAccessLabels` where each label goes. Nothing reaches the core (BDR-050).
|
||||||
|
*/
|
||||||
|
export function useAccessLabels(input: AccessLabelsInput): AccessLabelsState {
|
||||||
|
const { drawing, layoutKey, hidden } = input
|
||||||
|
const locale = useLocaleStore((s) => s.locale)
|
||||||
|
const tick = useResizeTick(input.box, hidden)
|
||||||
|
const measureRow = useRef<HTMLDivElement | null>(null)
|
||||||
|
const [accesses, setAccesses] = useState<Access[]>([])
|
||||||
|
const [layout, setLayout] = useState<LabelLayout | null>(null)
|
||||||
|
|
||||||
|
// Pass 1: the drawing's accesses, so the measuring row can render them.
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
setAccesses(hidden ? [] : readAccesses(drawing.current, locale))
|
||||||
|
}, [drawing, hidden, layoutKey, locale, tick])
|
||||||
|
|
||||||
|
// Pass 2: the row is in the DOM for these accesses; measure and place.
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
setLayout(hidden ? null : computeLayout(input, accesses, measureRow.current))
|
||||||
|
// `input` is read as of this render; its refs are stable and its changes ride the keys.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [accesses, hidden, layoutKey, locale, tick])
|
||||||
|
|
||||||
|
return { accesses, layout, measureRow }
|
||||||
|
}
|
||||||
@@ -209,6 +209,8 @@ export const en: Dict = {
|
|||||||
'core.stopped_unsaved':
|
'core.stopped_unsaved':
|
||||||
"Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading.",
|
"Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading.",
|
||||||
'core.reload': 'Reload the page',
|
'core.reload': 'Reload the page',
|
||||||
|
'canvas.access.open': 'Open the view “{name}”',
|
||||||
|
'canvas.access.more': 'Other views ({count})',
|
||||||
'canvas.view_unavailable':
|
'canvas.view_unavailable':
|
||||||
'This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.',
|
'This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.',
|
||||||
'core.action_failed':
|
'core.action_failed':
|
||||||
|
|||||||
@@ -227,6 +227,8 @@ export const fr: Dict = {
|
|||||||
'core.stopped_unsaved':
|
'core.stopped_unsaved':
|
||||||
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger.",
|
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger.",
|
||||||
'core.reload': 'Recharger la page',
|
'core.reload': 'Recharger la page',
|
||||||
|
'canvas.access.open': 'Ouvrir la vue « {name} »',
|
||||||
|
'canvas.access.more': 'Autres vues ({count})',
|
||||||
'canvas.view_unavailable':
|
'canvas.view_unavailable':
|
||||||
"Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.",
|
"Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.",
|
||||||
'core.action_failed':
|
'core.action_failed':
|
||||||
|
|||||||
@@ -0,0 +1,224 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { useRef } from 'react'
|
||||||
|
import { render, screen, within } from '@testing-library/react'
|
||||||
|
import userEvent from '@testing-library/user-event'
|
||||||
|
import ModalDialog from '@/components/ui/ModalDialog'
|
||||||
|
import AccessLabels from '@/components/canvas/AccessLabels'
|
||||||
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
|
import type { LabelLayout } from '@/anatomy/accessLabels'
|
||||||
|
|
||||||
|
const place = vi.hoisted(() => vi.fn())
|
||||||
|
vi.mock('@/anatomy/accessLabels', async (original) => ({
|
||||||
|
...(await original<typeof import('@/anatomy/accessLabels')>()),
|
||||||
|
placeAccessLabels: place,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const LONG = 'A very long access name that cannot fit in one hundred and eighty px'
|
||||||
|
const NAMES: Record<string, [string, string]> = {
|
||||||
|
a1: ['Tête', 'Head'],
|
||||||
|
a2: ['Membre antérieur', 'Foreleg'],
|
||||||
|
a3: [LONG, LONG],
|
||||||
|
}
|
||||||
|
|
||||||
|
function rect(x: number, y: number, w: number, h: number): DOMRect {
|
||||||
|
return { x, y, left: x, top: y, width: w, height: h, right: x + w, bottom: y + h, toJSON() {} }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** happy-dom has no layout: boxes come from the element's role in the test. */
|
||||||
|
function stubLayout() {
|
||||||
|
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
|
||||||
|
if (this.getAttribute('data-testid') === 'box') return rect(10, 20, 400, 300)
|
||||||
|
const id = this.getAttribute('data-anno-id')
|
||||||
|
if (id) return rect(110, 120, 60, 40)
|
||||||
|
if (this.getAttribute('data-measure') === 'more') return rect(0, 0, 90, 20)
|
||||||
|
if (this.getAttribute('data-measure') === 'label') return rect(0, 0, 70, 20)
|
||||||
|
return rect(0, 0, 0, 0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function layoutOf(over: Partial<LabelLayout> = {}): LabelLayout {
|
||||||
|
return {
|
||||||
|
placed: [
|
||||||
|
{ id: 'a1', box: { x: 100, y: 97, w: 70, h: 20 }, leader: null },
|
||||||
|
{ id: 'a2', box: { x: 200, y: 50, w: 80, h: 20 }, leader: { x1: 210, y1: 70, x2: 220, y2: 100 } },
|
||||||
|
],
|
||||||
|
overflow: [],
|
||||||
|
button: null,
|
||||||
|
...over,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function accessMarkup(ids: string[]): string {
|
||||||
|
return ids
|
||||||
|
.map(
|
||||||
|
(id) =>
|
||||||
|
`<rect data-anno-id="${id}" data-anno-kind="detail_trigger" data-anno-opens-view="view-${id}"` +
|
||||||
|
` data-anno-name-fr="${NAMES[id][0]}" data-anno-name-en="${NAMES[id][1]}" stroke="#336699"/>`,
|
||||||
|
)
|
||||||
|
.join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HarnessProps {
|
||||||
|
ids?: string[]
|
||||||
|
hidden?: boolean
|
||||||
|
onActivate?: (a: string, v: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function Harness({ ids = ['a1', 'a2'], hidden = false, onActivate = () => {} }: HarnessProps) {
|
||||||
|
const box = useRef<HTMLDivElement | null>(null)
|
||||||
|
const drawing = useRef<SVGSVGElement | null>(null)
|
||||||
|
return (
|
||||||
|
<div ref={box} data-testid="box">
|
||||||
|
<svg ref={drawing} dangerouslySetInnerHTML={{ __html: accessMarkup(ids) }} />
|
||||||
|
<AccessLabels
|
||||||
|
box={box}
|
||||||
|
drawing={drawing}
|
||||||
|
layoutKey="v1"
|
||||||
|
hidden={hidden}
|
||||||
|
onActivate={onActivate}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
stubLayout()
|
||||||
|
place.mockReturnValue(layoutOf())
|
||||||
|
})
|
||||||
|
afterEach(() => vi.restoreAllMocks())
|
||||||
|
|
||||||
|
describe('AccessLabels', () => {
|
||||||
|
it('places each label at the box the placement returns, in document order', () => {
|
||||||
|
render(<Harness />)
|
||||||
|
const buttons = screen.getAllByRole('button')
|
||||||
|
expect(buttons.map((b) => b.getAttribute('title'))).toEqual(['Tête', 'Membre antérieur'])
|
||||||
|
expect(buttons[0]).toHaveStyle({ left: '100px', top: '97px', width: '70px' })
|
||||||
|
expect(buttons[1]).toHaveStyle({ left: '200px', top: '50px' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('measures the accesses relative to the box and hands them over in order', () => {
|
||||||
|
render(<Harness />)
|
||||||
|
const input = place.mock.calls.at(-1)?.[0]
|
||||||
|
expect(input.area).toEqual({ x: 0, y: 0, w: 400, h: 300 })
|
||||||
|
expect(input.labels.map((l: { id: string }) => l.id)).toEqual(['a1', 'a2'])
|
||||||
|
expect(input.labels[0].access).toEqual({ x: 100, y: 100, w: 60, h: 40 })
|
||||||
|
expect(input.labels[0].w).toBe(70)
|
||||||
|
expect(input.button).toEqual({ w: 90, h: 20 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('names the buttons with the locale name and « Ouvrir la vue »', () => {
|
||||||
|
render(<Harness />)
|
||||||
|
expect(screen.getByRole('button', { name: 'Ouvrir la vue « Tête »' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByRole('button', { name: 'Ouvrir la vue « Membre antérieur »' })).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses the English name and wording in English', () => {
|
||||||
|
useLocaleStore.setState({ locale: 'en' })
|
||||||
|
render(<Harness />)
|
||||||
|
expect(screen.getByRole('button', { name: 'Open the view “Head”' })).toHaveAttribute('title', 'Head')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the full accessible name of a long name, ellipsed by CSS', () => {
|
||||||
|
place.mockReturnValue(layoutOf({ placed: [{ id: 'a3', box: { x: 5, y: 5, w: 180, h: 20 }, leader: null }] }))
|
||||||
|
render(<Harness ids={['a3']} />)
|
||||||
|
const button = screen.getByRole('button', { name: `Ouvrir la vue « ${LONG} »` })
|
||||||
|
expect(button).toHaveAttribute('title', LONG)
|
||||||
|
expect(button).toHaveStyle({ maxWidth: '180px' })
|
||||||
|
expect(button.querySelector('.truncate')).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('draws the leaders in one aria-hidden svg in the access colour', () => {
|
||||||
|
const { container } = render(<Harness />)
|
||||||
|
const svg = container.querySelector('[data-testid="access-labels"] > svg')
|
||||||
|
expect(svg).toHaveAttribute('aria-hidden', 'true')
|
||||||
|
expect(svg?.querySelectorAll('line')).toHaveLength(1)
|
||||||
|
expect(svg?.querySelector('g')).toHaveAttribute('stroke', '#336699')
|
||||||
|
expect(svg?.querySelector('circle')).toHaveAttribute('r', '2.2')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports the access id and the view id', async () => {
|
||||||
|
const onActivate = vi.fn()
|
||||||
|
render(<Harness onActivate={onActivate} />)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: /Membre antérieur/ }))
|
||||||
|
expect(onActivate).toHaveBeenCalledWith('a2', 'view-a2')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders nothing when hidden', () => {
|
||||||
|
const { container } = render(<Harness hidden />)
|
||||||
|
expect(container.querySelector('[data-testid="access-labels"]')).toBeNull()
|
||||||
|
expect(screen.queryByRole('button')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('AccessLabels, « Autres vues »', () => {
|
||||||
|
const overflowing = () =>
|
||||||
|
place.mockReturnValue(
|
||||||
|
layoutOf({ overflow: ['a1', 'a2', 'a3'], button: { x: 300, y: 6, w: 90, h: 20 } }),
|
||||||
|
)
|
||||||
|
|
||||||
|
it('lists the overflow and activates an entry', async () => {
|
||||||
|
overflowing()
|
||||||
|
const onActivate = vi.fn()
|
||||||
|
render(<Harness ids={['a1', 'a2', 'a3']} onActivate={onActivate} />)
|
||||||
|
const more = screen.getByRole('button', { name: 'Autres vues (3)' })
|
||||||
|
expect(more).toHaveAttribute('aria-expanded', 'false')
|
||||||
|
await userEvent.click(more)
|
||||||
|
expect(more).toHaveAttribute('aria-expanded', 'true')
|
||||||
|
const list = screen.getAllByRole('listitem')
|
||||||
|
expect(list).toHaveLength(3)
|
||||||
|
await userEvent.click(within(list[2]).getByRole('button'))
|
||||||
|
expect(onActivate).toHaveBeenCalledWith('a3', 'view-a3')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows no button without overflow', () => {
|
||||||
|
render(<Harness />)
|
||||||
|
expect(screen.queryByRole('button', { name: /Autres vues/ })).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('closes on Escape and gives the focus back', async () => {
|
||||||
|
overflowing()
|
||||||
|
render(<Harness ids={['a1', 'a2', 'a3']} />)
|
||||||
|
const more = screen.getByRole('button', { name: 'Autres vues (3)' })
|
||||||
|
await userEvent.click(more)
|
||||||
|
await userEvent.tab()
|
||||||
|
await userEvent.keyboard('{Escape}')
|
||||||
|
expect(screen.queryAllByRole('listitem')).toHaveLength(0)
|
||||||
|
expect(more).toHaveFocus()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('closes on a press outside', async () => {
|
||||||
|
overflowing()
|
||||||
|
render(<Harness ids={['a1', 'a2', 'a3']} />)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Autres vues (3)' }))
|
||||||
|
await userEvent.click(document.body)
|
||||||
|
expect(screen.queryAllByRole('listitem')).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves a surrounding ModalDialog open on that Escape', async () => {
|
||||||
|
overflowing()
|
||||||
|
const onClose = vi.fn()
|
||||||
|
render(
|
||||||
|
<ModalDialog onClose={onClose} label="Detail">
|
||||||
|
<Harness ids={['a1', 'a2', 'a3']} />
|
||||||
|
</ModalDialog>,
|
||||||
|
)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Autres vues (3)' }))
|
||||||
|
await userEvent.keyboard('{Escape}')
|
||||||
|
expect(screen.queryAllByRole('listitem')).toHaveLength(0)
|
||||||
|
expect(onClose).not.toHaveBeenCalled()
|
||||||
|
await userEvent.keyboard('{Escape}')
|
||||||
|
expect(onClose).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('tabs through the labels, then « Autres vues »', async () => {
|
||||||
|
place.mockReturnValue(layoutOf({ overflow: ['a3'], button: { x: 300, y: 6, w: 90, h: 20 } }))
|
||||||
|
render(<Harness ids={['a1', 'a2', 'a3']} />)
|
||||||
|
await userEvent.tab()
|
||||||
|
expect(screen.getByRole('button', { name: /Tête/ })).toHaveFocus()
|
||||||
|
await userEvent.tab()
|
||||||
|
expect(screen.getByRole('button', { name: /Membre/ })).toHaveFocus()
|
||||||
|
await userEvent.tab()
|
||||||
|
expect(screen.getByRole('button', { name: 'Autres vues (1)' })).toHaveFocus()
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user