From 5ec07af751aaf80843a4e90f7e8b22adf4c5c9ca Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 23 Nov 2026 10:36:47 +0100 Subject: [PATCH] =?UTF-8?q?feat(app):=20access=20label=20buttons=20and=20t?= =?UTF-8?q?he=20=C2=AB=20Autres=20vues=20=C2=BB=20list?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/components/canvas/AccessLabels.tsx | 190 +++++++++++++++ .../src/components/canvas/useAccessLabels.ts | 156 ++++++++++++ apps/app/src/i18n/en.ts | 2 + apps/app/src/i18n/fr.ts | 2 + .../unit/components.AccessLabels.test.tsx | 224 ++++++++++++++++++ 5 files changed, 574 insertions(+) create mode 100644 apps/app/src/components/canvas/AccessLabels.tsx create mode 100644 apps/app/src/components/canvas/useAccessLabels.ts create mode 100644 apps/app/tests/unit/components.AccessLabels.test.tsx diff --git a/apps/app/src/components/canvas/AccessLabels.tsx b/apps/app/src/components/canvas/AccessLabels.tsx new file mode 100644 index 00000000..3bf92816 --- /dev/null +++ b/apps/app/src/components/canvas/AccessLabels.tsx @@ -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 + /** The drawing host holding the core's layer. */ + drawing: RefObject + /** 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[] + 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 }) { + return ( + + ) +} + +/** The hidden measuring copy of a label: same classes, same content. */ +function Twin({ access }: { access: Access }) { + return ( + + {access.name} + + + ) +} + +function MeasureRow(props: { accesses: Access[]; count: number; row: RefObject }) { + const t = useT() + return ( + + ) +} + +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(null) + const trigger = useRef(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 ( +
+ + {open && ( +
    + {items.map((a) => ( +
  • + +
  • + ))} +
+ )} +
+ ) +} + +/** + * 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 ( +
+ + + {shown.map((p) => { + const a = byId.get(p.id) as Access + return ( + + ) + })} + {layout?.button && } +
+ ) +} diff --git a/apps/app/src/components/canvas/useAccessLabels.ts b/apps/app/src/components/canvas/useAccessLabels.ts new file mode 100644 index 00000000..280d5dd0 --- /dev/null +++ b/apps/app/src/components/canvas/useAccessLabels.ts @@ -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 + drawing: RefObject + layoutKey: string + reserved?: RefObject[] + 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 +} + +/** 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, 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(null) + const [accesses, setAccesses] = useState([]) + const [layout, setLayout] = useState(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 } +} diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index fd90988b..f8198a2e 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -209,6 +209,8 @@ export const en: Dict = { '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.", 'core.reload': 'Reload the page', + 'canvas.access.open': 'Open the view “{name}”', + 'canvas.access.more': 'Other views ({count})', '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.', 'core.action_failed': diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 62cfff1c..77d58a11 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -227,6 +227,8 @@ export const fr: Dict = { '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.", 'core.reload': 'Recharger la page', + 'canvas.access.open': 'Ouvrir la vue « {name} »', + 'canvas.access.more': 'Autres vues ({count})', '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é.", 'core.action_failed': diff --git a/apps/app/tests/unit/components.AccessLabels.test.tsx b/apps/app/tests/unit/components.AccessLabels.test.tsx new file mode 100644 index 00000000..7de9b17f --- /dev/null +++ b/apps/app/tests/unit/components.AccessLabels.test.tsx @@ -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()), + placeAccessLabels: place, +})) + +const LONG = 'A very long access name that cannot fit in one hundred and eighty px' +const NAMES: Record = { + 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 { + 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) => + ``, + ) + .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(null) + const drawing = useRef(null) + return ( +
+ +
+ ) +} + +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() + 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() + 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() + 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() + 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() + 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() + 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() + await userEvent.click(screen.getByRole('button', { name: /Membre antérieur/ })) + expect(onActivate).toHaveBeenCalledWith('a2', 'view-a2') + }) + + it('renders nothing when hidden', () => { + const { container } = render(