feat(anatomy): detail views shown whole between neutral bands

This commit is contained in:
bchanot committed 2026-11-23 13:20:37 +01:00
1 parent 224d1051b2
commit 04360feb75
13 files changed
+309 -10

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
import { useEffect, type RefObject } from 'react'
import { parseFrame } from '@/editor/annotations/frame'
export interface Size {
w: number
h: number
}
export interface Insets {
top: number
right: number
bottom: number
left: number
}
/** The neutral band behind a detail view (D7), the token of `tokens.css`. */
export const BAND_BACKGROUND = 'bg-[var(--color-frame-band)]'
const NONE: Insets = { top: 0, right: 0, bottom: 0, left: 0 }
/**
* D7: the bands `meet` leaves around a frame of `frame` proportions in a box of `box`
* size, in CSS px; zero when either size is empty.
*/
export function bandInsets(box: Size, frame: Size): Insets {
if (box.w <= 0 || box.h <= 0 || frame.w <= 0 || frame.h <= 0) return NONE
const scale = Math.min(box.w / frame.w, box.h / frame.h)
const x = (box.w - frame.w * scale) / 2
const y = (box.h - frame.h * scale) / 2
return { top: y, right: x, bottom: y, left: x }
}
/** The CSS `clip-path` hiding everything of the drawing outside the frame. */
export function bandClip(i: Insets): string {
return `inset(${i.top}px ${i.right}px ${i.bottom}px ${i.left}px)`
}
/**
* Clips the drawing's `<svg>` in `host` to its frame (a detail view), or lifts any clip
* (the main view). The host is the svg's box: the svg fills it, `meet` leaves the bands
* inside the svg. Called when a view's svg is inserted and again when the box resizes;
* the clip lives on the svg, inside the transformed element, so it follows every zoom.
*/
export function fitBands(host: HTMLElement, detail: boolean): void {
const svg = host.querySelector<SVGSVGElement>(':scope > svg')
if (!svg) return
const frame = parseFrame(svg.getAttribute('viewBox'))
if (!detail || !frame) {
svg.style.removeProperty('clip-path')
return
}
const box = { w: host.clientWidth, h: host.clientHeight }
svg.style.setProperty(
'clip-path',
bandClip(bandInsets(box, { w: frame.w, h: frame.h })),
)
}
/**
* Fits the bands again whenever the host's box resizes. The host is observed, not the
* svg: each view swaps in a new svg, the host stays.
*/
export function useBandResize(
host: RefObject<HTMLElement | null>,
detail: boolean,
): void {
useEffect(() => {
const element = host.current
if (!element || typeof ResizeObserver === 'undefined') return
const observer = new ResizeObserver(() => fitBands(element, detail))
observer.observe(element)
return () => observer.disconnect()
}, [host, detail])
}
@@ -151,6 +151,7 @@ function LoadedSheet({ versions, version, preview, state }: LoadedSheetProps) {
preview={preview}
viewId={viewId}
viewName={pickLabel(view.name, locale)}
detail={view.kind === 'detail'}
selectedId={selectedId}
onAnnotation={onAnnotation}
/>
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { annotationAt } from '@/anatomy/annotationPick'
import { BAND_BACKGROUND } from '@/anatomy/frameBands'
import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { coreRuntime, useCoreStopped } from '@/core/runtime'
@@ -136,6 +137,9 @@ export default function AnatomyCanvas({
}
}, [showTooltip])
// The probe (Task 22): the svg takes the frame's ratio here, so the bands need the
// background alone, no clip.
const detail = index.view(viewId)?.kind === 'detail'
return (
<div
data-testid="anatomy-canvas"
@@ -145,7 +149,7 @@ export default function AnatomyCanvas({
>
<div
ref={svgRef}
className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto"
className={`w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto ${detail ? BAND_BACKGROUND : ''}`}
/>
<div ref={tooltipRef} className="zone-tooltip" style={{ opacity: 0 }} />
{failure && (
@@ -1,4 +1,5 @@
import { annotationAt } from '@/anatomy/annotationPick'
import { BAND_BACKGROUND, fitBands, useBandResize } from '@/anatomy/frameBands'
import { useCallback, useEffect, useRef, useState, type PointerEvent } from 'react'
import { usePlaceVisible } from '@/lib/placeVisibility'
import Button from '@/components/ui/Button'
@@ -15,6 +16,8 @@ export interface CatalogueCanvasProps {
preview: CataloguePreview
viewId: string
viewName: string
/** A detail view: shown whole between neutral bands (D7). */
detail?: boolean
selectedId: string | null
onAnnotation: (annotationId: string) => void
/** A tap on the empty drawing; without it the canvas behaves as the reader always did. */
@@ -56,6 +59,7 @@ export default function CatalogueCanvas({
preview,
viewId,
viewName,
detail = false,
selectedId,
onAnnotation,
onEmpty,
@@ -115,7 +119,10 @@ export default function CatalogueCanvas({
const build = buildView(preview, viewId)
setFailure(build.ok ? null : build.failure)
element.replaceChildren(...(build.ok ? [build.svg] : []))
}, [preview, viewId, attempt, visible])
fitBands(element, detail)
}, [preview, viewId, attempt, visible, detail])
useBandResize(host, detail)
useEffect(() => {
host.current?.querySelectorAll<Element>(ANNOTATED).forEach((el) => {
@@ -156,7 +163,7 @@ export default function CatalogueCanvas({
<div
ref={host}
data-testid="catalogue-canvas-drawing"
className="h-full w-full origin-top-left [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
className={`h-full w-full origin-top-left [&>svg]:block [&>svg]:h-full [&>svg]:w-full ${detail ? BAND_BACKGROUND : ''}`}
style={{ transform: transformOf(framing) }}
/>
</div>
@@ -7,6 +7,7 @@ import {
type RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import { BAND_BACKGROUND, useBandResize } from '@/anatomy/frameBands'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { coreFailureMessage } from '@/core/failure'
@@ -44,6 +45,8 @@ export type HandleData = Pick<
export interface AnnotationCanvasProps {
viewId: string
viewName: string
/** A detail view: shown whole between neutral bands (D7). */
detail: boolean
tool: ToolId
selectedId: string | null
/** The point tool's next size (A5), shown under a mouse pointer; null: no preview. */
@@ -79,7 +82,8 @@ export interface AnnotationCanvasProps {
export default function AnnotationCanvas(props: AnnotationCanvasProps) {
const overlay = useRef<SVGSVGElement | null>(null)
const viewport = useRef<HTMLDivElement | null>(null)
const build = useCanvasBuild(props.viewId)
const build = useCanvasBuild(props.viewId, props.detail)
useBandResize(build.host, props.detail)
const gestures = useCanvasGestures({
...props,
target: props.moveTarget,
@@ -166,6 +170,7 @@ function withPreview(box: BoxProps, preview: Preview) {
function CanvasBox({
viewId,
viewName,
detail,
tool,
creating,
selectedId,
@@ -180,7 +185,7 @@ function CanvasBox({
boxProps: BoxProps
/** A finger's drag in flight: the loupe above it (board 13). */
finger: XY | null
layer: Omit<LayerProps, 'host' | 'root'>
layer: Omit<LayerProps, 'host' | 'root' | 'detail'>
}) {
const root = build.root?.viewId === viewId ? build.root : null
const cursor = tool === 'select' ? 'cursor-grab' : 'cursor-crosshair'
@@ -196,7 +201,12 @@ function CanvasBox({
className={`svg-canvas aspect-[4/3] w-full select-none ${cursor} ${FOCUS_RING}`}
{...boxProps}
>
<DrawingLayer host={build.host} root={root} {...layer} />
<DrawingLayer
host={build.host}
root={root}
detail={detail}
{...layer}
/>
</div>
{finger && root && (
<Loupe
@@ -224,6 +234,7 @@ const FOCUS_RING =
interface LayerProps {
host: RefObject<HTMLDivElement | null>
detail: boolean
root: RootAttributes | null
transform: string
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
@@ -238,7 +249,14 @@ interface LayerProps {
* The transformed box: the core's drawing and, in the same coordinates, the overlay and
* the handle layer above it.
*/
function DrawingLayer({ host, root, transform, overlay, handles }: LayerProps) {
function DrawingLayer({
host,
root,
detail,
transform,
overlay,
handles,
}: LayerProps) {
return (
<div
className="relative h-full w-full origin-top-left"
@@ -247,7 +265,7 @@ function DrawingLayer({ host, root, transform, overlay, handles }: LayerProps) {
<div
ref={host}
data-testid="annotation-canvas-drawing"
className="h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
className={`h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full ${detail ? BAND_BACKGROUND : ''}`}
/>
{root?.viewBox && (
<>
@@ -421,6 +421,7 @@ function CanvasStage({
<AnnotationCanvas
viewId={scene.viewId}
viewName={view.name[locale]}
detail={view.kind === 'detail'}
tool={subject.tool}
selectedId={subject.selectedId}
previewRadius={previewRadiusOf(scene)}
@@ -327,6 +327,7 @@ function ReadOnlyAnnotations(props: TwinProps) {
preview={preview}
viewId={viewId}
viewName={view.name[locale]}
detail={view.kind === 'detail'}
selectedId={selectedId}
onAnnotation={pick}
onEmpty={byDrawing}
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { fitBands } from '@/anatomy/frameBands'
import { buildView } from '@/components/catalogue/CatalogueCanvas'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { coreRuntime } from '@/core/runtime'
@@ -42,7 +43,7 @@ function useHandle() {
* failure come from the same build; a failure is the engine notice (retry) or the view
* notice.
*/
export function useCanvasBuild(viewId: string) {
export function useCanvasBuild(viewId: string, detail: boolean) {
const handle = useHandle()
const host = useRef<HTMLDivElement | null>(null)
const [attempt, setAttempt] = useState(0)
@@ -58,12 +59,13 @@ export function useCanvasBuild(viewId: string) {
}
const result = buildView(handle.preview, viewId)
element.replaceChildren(...(result.ok ? [result.svg] : []))
fitBands(element, detail)
setBuilt(
result.ok
? { root: rootOf(viewId, result.svg), failure: null }
: { root: null, failure: result.failure },
)
}, [handle.preview, viewId, handle.version, attempt, handle.visible])
}, [handle.preview, viewId, handle.version, attempt, handle.visible, detail])
const retry = useCallback(() => {
void coreRuntime()
+1
View File
@@ -5,6 +5,7 @@
--color-ink: #1f1b16;
--color-ink-muted: #6b6359;
--color-border: #e7e0d2;
--color-frame-band: #ece7df;
--color-accent: #b85a3f;
--color-accent-strong: #9c4831;
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { bandClip, bandInsets } from '@/anatomy/frameBands'
describe('bandInsets (D7)', () => {
it('leaves bands above and below a wide frame', () => {
const i = bandInsets({ w: 400, h: 300 }, { w: 7, h: 1 })
const band = (300 - 400 / 7) / 2
expect(i.top).toBeCloseTo(band)
expect(i.bottom).toBeCloseTo(band)
expect(i.left).toBe(0)
expect(i.right).toBe(0)
})
it('leaves bands left and right of a tall frame', () => {
const i = bandInsets({ w: 400, h: 300 }, { w: 1, h: 3 })
expect(i.left).toBeCloseTo((400 - 100) / 2)
expect(i.right).toBeCloseTo(150)
expect(i.top).toBe(0)
expect(i.bottom).toBe(0)
})
it('leaves no band for a frame of the box proportions', () => {
expect(bandInsets({ w: 400, h: 300 }, { w: 4, h: 3 })).toEqual({
top: 0,
right: 0,
bottom: 0,
left: 0,
})
})
it('answers zeros when either size is empty', () => {
const zeros = { top: 0, right: 0, bottom: 0, left: 0 }
expect(bandInsets({ w: 0, h: 300 }, { w: 4, h: 3 })).toEqual(zeros)
expect(bandInsets({ w: 400, h: 0 }, { w: 4, h: 3 })).toEqual(zeros)
expect(bandInsets({ w: 400, h: 300 }, { w: 0, h: 3 })).toEqual(zeros)
expect(bandInsets({ w: 400, h: 300 }, { w: 4, h: 0 })).toEqual(zeros)
})
})
describe('bandClip', () => {
it('writes the insets as a CSS inset() in top right bottom left order', () => {
expect(bandClip({ top: 1, right: 2, bottom: 3, left: 4 })).toBe(
'inset(1px 2px 3px 4px)',
)
})
})
+86
View File
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, waitFor } from '@testing-library/react'
import CatalogueCanvas from '@/components/catalogue/CatalogueCanvas'
import { bandClip, bandInsets } from '@/anatomy/frameBands'
import type { CataloguePreview } from '@/catalogue/preview'
/**
* D7 on the catalogue canvas: each view's svg gets its own clip when it is inserted,
* a detail view only, whatever the order of the switches.
*/
const BOX = { w: 400, h: 300 }
const FRAMES: Record<string, string> = {
main: '0 0 1000 800',
wide: '0 0 700 100',
tall: '0 0 100 300',
}
const preview = {
canvas: (id: string) => ({
ok: true,
value: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${FRAMES[id]}"></svg>`,
}),
} as unknown as CataloguePreview
beforeEach(() => {
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(BOX.w)
vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(BOX.h)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
const expected = (id: string) => {
const [, , w, h] = FRAMES[id].split(' ').map(Number)
return bandClip(bandInsets(BOX, { w, h }))
}
function show(rerender: ReturnType<typeof render>['rerender'], id: string) {
rerender(
<CatalogueCanvas
preview={preview}
viewId={id}
viewName={id}
detail={id !== 'main'}
selectedId={null}
onAnnotation={() => undefined}
/>,
)
}
const clipOf = (container: HTMLElement) =>
container
.querySelector<SVGSVGElement>('[data-testid="catalogue-canvas-drawing"] > svg')!
.style.getPropertyValue('clip-path')
describe('CatalogueCanvas bands (D7)', () => {
it('gives each view its own clip and the main view none, whatever the order', async () => {
const { container, rerender } = render(
<CatalogueCanvas
preview={preview}
viewId="main"
viewName="main"
selectedId={null}
onAnnotation={() => undefined}
/>,
)
const drawing = container.querySelector('[data-testid="catalogue-canvas-drawing"]')!
await waitFor(() => expect(drawing.querySelector('svg')).not.toBeNull())
expect(clipOf(container)).toBe('')
expect(drawing.className).not.toContain('frame-band')
show(rerender, 'wide')
await waitFor(() => expect(clipOf(container)).toBe(expected('wide')))
expect(drawing.className).toContain('frame-band')
show(rerender, 'tall')
await waitFor(() => expect(clipOf(container)).toBe(expected('tall')))
expect(expected('tall')).not.toBe(expected('wide'))
show(rerender, 'main')
await waitFor(() => expect(clipOf(container)).toBe(''))
expect(drawing.className).not.toContain('frame-band')
})
})
@@ -73,6 +73,21 @@ describe('buildViewSvg', () => {
})
describe('AnatomyCanvas', () => {
it('gives a detail view the band background and the main view none (D7)', async () => {
const shown = (viewId: string) =>
render(
<AnatomyCanvas index={sheet} viewId={viewId} states={new Map()} onZoneClick={() => undefined} />,
).container
const head = shown('head')
await waitFor(() => expect(head.querySelector('svg')).not.toBeNull())
expect(head.querySelector('[class*="frame-band"]')).not.toBeNull()
expect(head.querySelector('svg')!.style.getPropertyValue('clip-path')).toBe('')
cleanup()
const main = shown('main')
await waitFor(() => expect(main.querySelector('svg')).not.toBeNull())
expect(main.querySelector('[class*="frame-band"]')).toBeNull()
})
it('renders the view and delegates clicks on the generated markers to onZoneClick with the view id', async () => {
const onZoneClick = vi.fn()
const { container } = render(
@@ -15,6 +15,7 @@ import type { Annotation } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import EditStrip from '@/components/editor/annotations/EditStrip'
import { selectionLead } from '@/editor/annotations/stripLead'
import { bandClip, bandInsets } from '@/anatomy/frameBands'
import { initialUi } from '@/editor/annotations/uiState'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { fr } from '@/i18n/fr'
@@ -887,6 +888,48 @@ describe('the frame follows the view (H7)', () => {
})
})
describe('detail views between neutral bands (D7)', () => {
const detail = (id: string, name: string, width: number, height: number) => ({
kind: 'view' as const,
value: {
kind: 'detail' as const,
id,
name: { fr: name, en: name },
svg_asset_id: null,
view_box: { min_x: 0, min_y: 0, width, height },
parent_view_id: 'view-main',
},
})
const clip = () =>
screen
.getByTestId('annotation-canvas-drawing')
.querySelector('svg')!
.style.getPropertyValue('clip-path')
it('gives each chip its own clip and the main view none', async () => {
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(400)
vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(300)
const two = insert(
insert(drawnText(), detail('view-wide', 'Large', 70, 10)),
detail('view-tall', 'Haute', 10, 30),
)
await mount({ text: two })
const user = userEvent.setup()
const expected = (w: number, h: number) =>
bandClip(bandInsets({ w: 400, h: 300 }, { w, h }))
expect(clip()).toBe('')
await user.click(screen.getByRole('button', { name: 'Large' }))
await waitFor(() => expect(clip()).toBe(expected(70, 10)))
await user.click(screen.getByRole('button', { name: 'Haute' }))
await waitFor(() => expect(clip()).toBe(expected(10, 30)))
expect(expected(10, 30)).not.toBe(expected(70, 10))
await user.click(screen.getByRole('button', { name: 'Vue principale' }))
await waitFor(() => expect(clip()).toBe(''))
vi.restoreAllMocks()
})
})
describe('refusals through the tab (H8)', () => {
const zoneText = (geometry: object) =>
insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) })