feat(editor): point handle, size slider with core minimum, move mode

HandleLayer: its own svg over the overlay, not aria-hidden; the selected
point (or link circle) gets a focusable « Point {nom} » handle whose hit
circle (data-handle) the press machine reads, sized in CSS px under zoom
(R-9, read once from any-pointer: coarse). The Task 2 stand-in (the
selected marker as its own handle) is removed.

Keys on the handle: arrows step 0.5 % of the frame (Shift x10) as a
stamped series, Enter or blur commit once, Escape drops it (R-11, R-13).
SizeSlider in the strip for a selected point and for the Point tool (A5):
the view's sizes as ticks, the core minimum as a red mark, snap 8 px,
arrows 1 %, Page Up/Down next size, one commit on release, Enter or blur;
a refusal restores the size and draws the refused place in red dashes.
« Déplacer le point » opens the move mode (board 06 B): drag anywhere or
four arrows move a preview only, clicks select nothing, « Valider la
position » commits once, « Annuler » and Escape restore; the focus comes
back to the button. Escape follows board 32 (escapeAction). The overlay
reads the preview from the work store and draws the old place in grey
dashes. Ctrl+Z now also works from a slider (not a text field).

Rewritten assertions:
- editor-annotations-tab « a finger drags the selected point »:
  drag(marker('anno-a')) -> drag(pointHandle()), same expected geometry.
- editor-geometry.spec « a point inherited out of its frame is repaired
  through the geometry group » (cx/cy typed 200) -> « ... repaired with
  the move mode »: a partial move refused and restored (cx 110, issue
  kept), then a move inside kept (issue gone, fewer errors).
This commit is contained in:
bchanot committed 2026-11-17 18:50:29 +01:00
1 parent 2882821661
commit 91e94952f0
23 files changed
+1679 -149

No files matched your search

@@ -10,6 +10,7 @@ export type GlyphName =
| 'redo'
| 'search'
| 'deselect'
| 'move'
/** The editor's one glyph table (24-unit grid strokes); `book` and `close` are in `Icon`. */
const GLYPHS: Record<GlyphName, string> = {
@@ -23,6 +24,7 @@ const GLYPHS: Record<GlyphName, string> = {
undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10',
redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10',
search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4',
move: 'M12 3v18M3 12h18M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3',
deselect:
'M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3M9 9l6 6M15 9l-6 6',
}
@@ -16,6 +16,7 @@ import type { MoveTarget } from '@/editor/annotations/useBlockDrag'
import type { ToolId } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
import HandleLayer, { type HandleLayerProps } from './HandleLayer'
import ToolColumn, { type ToolColumnProps } from './ToolColumn'
type OverlayData = Omit<
@@ -23,6 +24,12 @@ type OverlayData = Omit<
'svgRef' | 'viewBox' | 'ratio' | 'dragged'
>
/** The handle layer's content: the handle and its keys (the layer measures itself). */
export type HandleData = Pick<
HandleLayerProps,
'handle' | 'onKeyDown' | 'onBlur'
>
export interface AnnotationCanvasProps {
viewId: string
viewName: string
@@ -31,6 +38,7 @@ export interface AnnotationCanvasProps {
/** The selected annotation when it can be moved now. */
moveTarget: MoveTarget | null
overlay: OverlayData
handles: HandleData
tools: Omit<ToolColumnProps, 'onZoomIn' | 'onZoomOut' | 'onFit'>
/** The composed root as rebuilt (with its view); null on failure. */
onRoot: (root: RootAttributes | null) => void
@@ -80,6 +88,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
svgRef: overlay,
dragged: gestures.drag,
},
handles: { ...props.handles, scale: gestures.framing.framing.scale },
}}
/>
</div>
@@ -135,10 +144,14 @@ interface LayerProps {
root: RootAttributes | null
transform: string
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
handles: HandleData & { scale: number }
}
/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */
function DrawingLayer({ host, root, transform, overlay }: 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) {
return (
<div
className="relative h-full w-full origin-top-left"
@@ -150,11 +163,14 @@ function DrawingLayer({ host, root, transform, overlay }: LayerProps) {
className="h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
/>
{root?.viewBox && (
<AnnotationOverlay
{...overlay}
viewBox={root.viewBox}
ratio={root.ratio}
/>
<>
<AnnotationOverlay
{...overlay}
viewBox={root.viewBox}
ratio={root.ratio}
/>
<HandleLayer {...handles} viewBox={root.viewBox} ratio={root.ratio} />
</>
)}
</div>
)
@@ -3,6 +3,7 @@ import type { Geometry, Point } from '@faunosteo/core-wasm/types'
import type { Correction } from '@/editor/annotations/correction'
import type { Frame } from '@/editor/annotations/frame'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
export interface OverlayProps {
svgRef: Ref<SVGSVGElement>
@@ -10,8 +11,11 @@ export interface OverlayProps {
viewBox: string
ratio: string
frame: Frame | null
selectedId: string | null
selected: Geometry | null
dragged: Geometry | null
/** The place the core just refused (red dashes while its message shows). */
refused: Geometry | null
pending: Geometry | null
tracing: Point[] | null
correction: Correction | null
@@ -105,16 +109,28 @@ function TracingPath({ points, size }: { points: Point[]; size: number }) {
)
}
/** The selection's pending preview (move mode, slider, keys), read without the tab. */
function usePreviewOf(selectedId: string | null): Geometry | null {
return useAnnotationWork((s) =>
selectedId !== null && s.preview?.annotationId === selectedId
? s.preview.geometry
: null,
)
}
/**
* The page-drawn overlay (docs/ANNOTATION-RENDERING.md « Editor overlay »): numbers only,
* no annotation. Selection outline, vertex circles, the tracing in progress, the pending
* or dragged outline, a corrected position with the click marked apart. It never takes
* the pointer: the canvas box does.
* or dragged outline, a corrected position with the click marked apart; during a gesture
* the old place in grey dashes, after a refusal the refused place in red dashes. It never
* takes the pointer: the canvas box does.
*/
export default function AnnotationOverlay(props: OverlayProps) {
const { frame, selected, dragged, pending, tracing, correction } = props
const { frame, selected, pending, tracing, correction } = props
const size = frame ? Math.max(frame.w, frame.h) / 200 : 1
const shown = dragged ?? selected
const preview = usePreviewOf(props.selectedId)
const moved = props.dragged ?? preview
const shown = moved ?? selected
return (
<svg
ref={props.svgRef}
@@ -124,6 +140,20 @@ export default function AnnotationOverlay(props: OverlayProps) {
preserveAspectRatio={props.ratio}
className="pointer-events-none absolute inset-0 h-full w-full"
>
{moved && selected && isEditable(selected) && (
<g data-testid="overlay-old-place">
<Outline geometry={selected} dashed colour="var(--color-ink-muted)" />
</g>
)}
{props.refused && (
<g data-testid="overlay-refused-place">
<Outline
geometry={props.refused}
dashed
colour="var(--color-danger-strong)"
/>
</g>
)}
{shown && isEditable(shown) && (
<>
<Outline geometry={shown} dashed colour="var(--color-ink)" />
@@ -25,10 +25,16 @@ export default function EditStrip({
lead,
notice,
commands,
commandsKey,
}: {
lead: StripLead
notice: StripNotice | null
commands: ReactNode
/**
* Which set of commands shows: a new set gets a new box, so a wider one never moves an
* existing box (A14: new content is no layout shift, a box moving is).
*/
commandsKey?: string
}) {
return (
<div
@@ -43,7 +49,9 @@ export default function EditStrip({
>
{notice && <Notice notice={notice} />}
</div>
<div className="flex shrink-0 items-center gap-2 p-1">{commands}</div>
<div key={commandsKey} className="flex shrink-0 items-center gap-2 p-1">
{commands}
</div>
</div>
)
}
@@ -3,12 +3,16 @@ import Button from '@/components/ui/Button'
import type {
AnatomicalSheetDocument,
Annotation,
Geometry,
} from '@faunosteo/core-wasm/types'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import { useAnnotationRequest } from '@/editor/annotations/focusTarget'
import { keyboardPending, type NewKind } from '@/editor/annotations/creation'
import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { newPointSize } from '@/editor/annotations/pointSize'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { usePointEdit } from '@/editor/annotations/usePointEdit'
import { endMode, useAnnotationWork } from '@/editor/annotations/workStore'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { useSelectionEscape } from '@/editor/annotations/deselect'
import { usePlacement } from '@/editor/annotations/usePlacement'
@@ -37,6 +41,12 @@ import type { EditorPlaceProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import AnnotationCanvas from './AnnotationCanvas'
import { annotationName } from './AnnotationList'
import {
SelectionPointCommands,
ToolSize,
useMoveFocusReturn,
} from './PointCommands'
import CreationPanel from './CreationPanel'
import EditStrip, { type StripNotice } from './EditStrip'
import GestureMessage from './GestureMessage'
@@ -134,36 +144,70 @@ function useCommitContext(): CommitContext {
return { t, locale }
}
/** The tab's work: the commit context, the line under the drawing and the placement. */
/**
* The tab's work: the commit context, the line under the drawing, the placement and the
* point editing (handle keys, slider, move mode) on the movable selected circle.
*/
function useWork(scene: Scene) {
const context = useCommitContext()
const message = useGestureMessage()
const placement = usePlacement({ ...scene, context, message })
return { context, message, placement }
const target = circleTargetOf(scene.selected, scene.model, scene.ui.tool)
const edit = usePointEdit({
target,
frame: scene.frame,
onDrop: placement.onDrop,
})
useModeFollowsSelection(scene.ui.selectedId)
useDroppedNotice(message)
return { context, message, placement, edit, target }
}
type Work = ReturnType<typeof useWork>
/**
* The move mode belongs to the selection: another selection (a list row, a view change)
* ends it. A read-only flip keeps the body and its selection, so it suspends the mode
* instead (R-14).
*/
function useModeFollowsSelection(selectedId: string | null) {
const modeId = useAnnotationWork((s) => s.mode?.annotationId ?? null)
useEffect(() => {
if (modeId !== null && modeId !== selectedId) endMode()
}, [modeId, selectedId])
}
/** R-13: a started mode a change made elsewhere dropped is said on the line. */
function useDroppedNotice(message: GestureMessages) {
const t = useT()
const dropped = useAnnotationWork((s) => s.dropped)
const show = message.show
useEffect(() => {
if (dropped === null) return
useAnnotationWork.setState({ dropped: null })
const text = t(`editor.annotations.dropped.${dropped}`)
show(text, { undo: false, tone: 'info' })
}, [dropped, show, t])
}
export default function EditableAnnotations(props: Props) {
const scene = useScene(props)
const { context, message, placement } = useWork(scene)
const work = useWork(scene)
const { ui, selected } = scene
const visible = usePlaceVisible()
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => scene.dispatch({ type: 'select', id: null }),
visible && selected !== undefined && ui.tracing === null && !ui.pending,
visible && selected !== undefined && ui.tracing === null,
{ editable: true, creating: ui.pending !== null },
)
return (
<div className="space-y-3">
<SceneStrip scene={scene} placement={placement} message={message} />
<SceneStrip scene={scene} work={work} />
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn
scene={scene}
placement={placement}
message={message}
onDeselect={byDrawing}
/>
<CanvasColumn scene={scene} work={work} onDeselect={byDrawing} />
<aside ref={asideRef}>
<SidePanel scene={scene} context={context} />
<SidePanel scene={scene} context={work.context} />
</aside>
</div>
</div>
@@ -172,15 +216,18 @@ export default function EditableAnnotations(props: Props) {
type Placement = ReturnType<typeof usePlacement>
/** A move that drops the drawing's work asks first (R-12): the action runs once allowed. */
const guarded = (action: () => void) => () => {
if (guardDrawing(action)) action()
}
function CanvasColumn({
scene,
placement,
message,
work,
onDeselect,
}: {
scene: Scene
placement: Placement
message: GestureMessages
work: Work
onDeselect: () => void
}) {
const { doc, dispatch, model } = scene
@@ -190,37 +237,49 @@ function CanvasColumn({
<ViewSwitcher
views={doc.views}
current={scene.viewId}
onSelect={(id) => dispatch({ type: 'view', viewId: id })}
onSelect={(id) =>
guarded(() => dispatch({ type: 'view', viewId: id }))()
}
/>
<CanvasStage
scene={scene}
placement={placement}
onDeselect={onDeselect}
/>
<GestureMessage messages={message}>
<CanvasStage scene={scene} work={work} onDeselect={onDeselect} />
<GestureMessage messages={work.message}>
<KeyboardAdd
disabled={!model.measured || noCategory || scene.frame === null}
linkDisabled={model.children.length === 0}
onAdd={(kind) => addAtCentre(kind, scene)}
onAdd={(kind) => guarded(() => addAtCentre(kind, scene))()}
/>
</GestureMessage>
</div>
)
}
/** The point handle of the movable selected circle, named « Point {nom} ». */
function useHandle(target: Annotation | null, doc: AnatomicalSheetDocument) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (!target?.geometry) return null
const name = annotationName(target, doc.views, locale)
return {
annotationId: target.id,
label: t('editor.annotations.handle.point').replace('{name}', () => name),
stored: target.geometry,
}
}
function CanvasStage({
scene,
placement,
work,
onDeselect,
}: {
scene: Scene
placement: Placement
work: Work
onDeselect: () => void
}) {
const locale = useLocaleStore((s) => s.locale)
// Hidden (the editor is read-only): no drag in flight survives, none is committed.
const shown = usePlaceVisible()
const { doc, ui, dispatch, model, frame, selected } = scene
const handle = useHandle(shown ? work.target : null, doc)
const view = doc.views.find((v) => v.id === scene.viewId)
const blocked = !model.measured || doc.categories.length === 0
if (!view) return null
@@ -231,19 +290,24 @@ function CanvasStage({
tool={ui.tool}
selectedId={ui.selectedId}
moveTarget={shown ? moveTargetOf(selected, model, ui.tool) : null}
overlay={overlayOf(ui, selected, frame)}
overlay={overlayOf(ui, selected, frame, work.message.message?.place)}
handles={{
handle,
onKeyDown: work.edit.onHandleKey,
onBlur: work.edit.onHandleBlur,
}}
tools={{
tool: ui.tool,
onTool: (tool) => dispatch({ type: 'tool', tool }),
onTool: (tool) => guarded(() => dispatch({ type: 'tool', tool }))(),
drawingDisabled: blocked,
linkDisabled: model.children.length === 0,
}}
onRoot={scene.setRoot}
onSelect={(id) => dispatch({ type: 'select', id })}
onPlace={placement.onPlace}
onDrop={placement.onDrop}
onPlace={work.placement.onPlace}
onDrop={work.placement.onDrop}
onDeselect={onDeselect}
onTraceKey={placement.onTraceKey}
onTraceKey={work.placement.onTraceKey}
/>
)
}
@@ -266,6 +330,8 @@ function SidePanel({
context: CommitContext
}) {
const { doc, ui, dispatch, model, frame, selected } = scene
// During the move mode the panel offers no deselect: only the mode's own exits.
const moving = useAnnotationWork((s) => s.mode?.kind === 'move')
if (ui.pending) {
return (
<CreationPanel
@@ -304,7 +370,7 @@ function SidePanel({
context={context}
navigate={scene.navigate}
onShowAll={() => dispatch({ type: 'select', id: null })}
busy={ui.tracing !== null}
busy={ui.tracing !== null || moving}
/>
)
}
@@ -320,13 +386,26 @@ function moveTargetOf(
: null
}
/** The selected point or link circle, when it can be moved now (R-9: its handle). */
function circleTargetOf(
selected: Annotation | undefined,
model: ViewModel,
tool: ToolId,
): Annotation | null {
const movable = moveTargetOf(selected, model, tool) !== null
return movable && selected?.geometry?.type === 'circle' ? selected : null
}
function overlayOf(
ui: UiState,
selected: Annotation | undefined,
frame: Frame | null,
refused: Geometry | null | undefined,
) {
return {
frame,
selectedId: selected?.id ?? null,
refused: refused ?? null,
selected: selected?.geometry ?? null,
pending: ui.pending?.geometry ?? null,
tracing: ui.tracing?.points ?? null,
@@ -334,33 +413,65 @@ function overlayOf(
}
}
/** The strip of the edit body: the lead of the scene, its notice, the tracing commands. */
function SceneStrip({
scene,
placement,
message,
}: {
scene: Scene
placement: Placement
message: GestureMessages
}) {
/**
* The strip of the edit body: the lead of the scene (the move mode's own while it runs),
* its notice, the commands.
*/
function SceneStrip({ scene, work }: { scene: Scene; work: Work }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const notice = useStripNotice(scene, message.message)
const notice = useStripNotice(scene, work.message.message)
const moving = useAnnotationWork((s) => s.mode?.kind === 'move')
useMoveFocusReturn(moving)
const { ui, selected, doc } = scene
const lead = moving
? {
title: t('editor.annotations.move.point'),
detail: t('editor.annotations.move.hint'),
icon: 'move' as const,
}
: stripLeadOf(ui, selected, doc, { t, locale })
return (
<EditStrip
lead={stripLeadOf(ui, selected, doc, { t, locale })}
lead={lead}
notice={notice}
commands={
ui.tracing && (
<TracingCommands
count={ui.tracing.points.length}
placement={placement}
onCancel={() => scene.dispatch({ type: 'trace_cancel' })}
/>
)
}
commands={<SceneCommands scene={scene} work={work} />}
commandsKey={commandsKeyOf(ui, moving, work.target !== null)}
/>
)
}
function commandsKeyOf(ui: UiState, moving: boolean, point: boolean) {
if (ui.tracing) return 'tracing'
if (moving) return 'move'
return point ? 'point' : `tool-${ui.tool}`
}
/** A tracing's commands, a movable point's, or the Point tool's size (A5). */
function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
const { ui, doc, viewId, frame, dispatch } = scene
if (ui.tracing) {
return (
<TracingCommands
count={ui.tracing.points.length}
placement={work.placement}
onCancel={() => dispatch({ type: 'trace_cancel' })}
/>
)
}
if (work.target) {
const props = { doc, viewId, frame, edit: work.edit }
return <SelectionPointCommands annotation={work.target} {...props} />
}
if (ui.tool !== 'point' || ui.pending || !frame) return null
const size = ui.size
return (
<ToolSize
doc={doc}
viewId={viewId}
frame={frame}
size={size}
dispatch={dispatch}
/>
)
}
@@ -0,0 +1,132 @@
import {
useLayoutEffect,
useRef,
useState,
type FocusEvent,
type KeyboardEvent,
type RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import { parseFrame } from '@/editor/annotations/frame'
import { handleSizes } from '@/editor/annotations/handleSize'
import { useAnnotationWork } from '@/editor/annotations/workStore'
/** The selected point (or link circle) whose handle the layer draws. */
export interface PointHandle {
annotationId: string
/** Its accessible name: « Point {nom} ». */
label: string
stored: Geometry
}
export interface HandleLayerProps {
viewBox: string
ratio: string
/** The framing's zoom: handles keep their CSS px size under it. */
scale: number
handle: PointHandle | null
onKeyDown: (event: KeyboardEvent<SVGGElement>) => void
onBlur: (event: FocusEvent<SVGGElement>) => void
}
/** The svg's own box in CSS px before the framing's transform. */
function useBoxSize(svg: RefObject<SVGSVGElement | null>) {
const [size, setSize] = useState({ w: 0, h: 0 })
useLayoutEffect(() => {
const element = svg.current
if (!element) return
const read = () =>
// An svg without layout (tests) has no client size: one unit per px then.
setSize({ w: element.clientWidth || 0, h: element.clientHeight || 0 })
read()
if (typeof ResizeObserver === 'undefined') return
const observer = new ResizeObserver(read)
observer.observe(element)
return () => observer.disconnect()
}, [svg])
return size
}
/**
* Drawing units per CSS px: the box over the frame (`meet`), times the zoom. Unknown
* before layout (0 px), one unit per px.
* shortcut: assumes a `meet` ratio (the core's default); a `none` ratio would need one
* factor per axis. Upgrade: read both factors when a drawing ships `none`.
*/
function unitsPerPx(
viewBox: string,
size: { w: number; h: number },
scale: number,
) {
const frame = parseFrame(viewBox)
if (!frame || size.w === 0 || size.h === 0) return 1
return 1 / (Math.min(size.w / frame.w, size.h / frame.h) * scale)
}
/**
* The handle layer (docs/ANNOTATION-RENDERING.md « Editor overlay »): its own svg over the
* overlay, same `viewBox`, NOT aria-hidden. Each handle is a focusable button whose hit
* shape carries `data-handle` for the press machine. The point handle covers the point's
* circle, at least the hit radius, and follows the pending preview.
*/
export default function HandleLayer(props: HandleLayerProps) {
const svg = useRef<SVGSVGElement | null>(null)
const unit = unitsPerPx(props.viewBox, useBoxSize(svg), props.scale)
return (
<svg
ref={svg}
data-testid="handle-layer"
viewBox={props.viewBox}
preserveAspectRatio={props.ratio}
className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
>
{props.handle && (
<PointHandleShape {...props} handle={props.handle} unit={unit} />
)}
</svg>
)
}
function PointHandleShape({
handle,
unit,
onKeyDown,
onBlur,
}: HandleLayerProps & { handle: PointHandle; unit: number }) {
const preview = useAnnotationWork((s) =>
s.preview?.annotationId === handle.annotationId ? s.preview.geometry : null,
)
const shown = preview ?? handle.stored
if (shown.type !== 'circle') return null
const r = Math.max(shown.r, handleSizes().hit * unit)
return (
<g
role="button"
tabIndex={0}
aria-label={handle.label}
data-testid="point-handle"
className="group outline-none"
onKeyDown={onKeyDown}
onBlur={onBlur}
>
<circle
cx={shown.cx}
cy={shown.cy}
r={r}
data-handle={JSON.stringify({ kind: 'point' })}
fill="transparent"
className="pointer-events-auto cursor-move"
/>
<circle
cx={shown.cx}
cy={shown.cy}
r={r + 3 * unit}
fill="none"
stroke="var(--color-accent)"
strokeWidth={2}
vectorEffect="non-scaling-stroke"
className="invisible group-focus-visible:visible"
/>
</g>
)
}
@@ -0,0 +1,64 @@
import { useEffect, useRef } from 'react'
import Button from '@/components/ui/Button'
import type { Direction } from '@/editor/annotations/usePointEdit'
import { useT } from '@/i18n/useT'
const COMMAND = 'min-h-11 xl:min-h-9'
const ARROWS: { direction: Direction; glyph: string }[] = [
{ direction: 'left', glyph: '←' },
{ direction: 'up', glyph: '↑' },
{ direction: 'down', glyph: '↓' },
{ direction: 'right', glyph: '→' },
]
export interface MoveModeBarProps {
onStep: (direction: Direction) => void
onConfirm: () => void
onCancel: () => void
}
/**
* The move mode's commands in the strip (board 06 B, A11, WCAG 2.5.7): four arrows, one
* step per click, then « Valider la position » (one commit) or « Annuler » (the place
* before). The focus enters on the first arrow.
*/
export default function MoveModeBar({
onStep,
onConfirm,
onCancel,
}: MoveModeBarProps) {
const t = useT()
const first = useRef<HTMLButtonElement>(null)
useEffect(() => first.current?.focus(), [])
return (
<div data-testid="move-mode-bar" className="flex items-center gap-2">
{ARROWS.map(({ direction, glyph }, index) => (
<Button
key={direction}
ref={index === 0 ? first : undefined}
type="button"
size="sm"
variant="secondary"
className={`${COMMAND} min-w-11 xl:min-w-9`}
aria-label={t(`editor.annotations.move.${direction}`)}
onClick={() => onStep(direction)}
>
<span aria-hidden="true">{glyph}</span>
</Button>
))}
<Button type="button" size="sm" className={COMMAND} onClick={onConfirm}>
{t('editor.annotations.move.confirm')}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={onCancel}
>
{t('editor.annotations.move.cancel')}
</Button>
</div>
)
}
@@ -0,0 +1,169 @@
import { useEffect, useRef, type Dispatch } from 'react'
import { visibleElement } from '@/editor/focusRequest'
import type {
Annotation,
AnatomicalSheetDocument,
} from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import { defaultRadius, type Frame } from '@/editor/annotations/frame'
import {
newPointSize,
sizeRange,
sizeStops,
} from '@/editor/annotations/pointSize'
import type { UiAction } from '@/editor/annotations/uiState'
import type { PointEdit } from '@/editor/annotations/usePointEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from '../EditorGlyph'
import MoveModeBar from './MoveModeBar'
import SizeSlider from './SizeSlider'
const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9'
/** The core's smallest radius for the view (Task 1), null when it has none. */
function useMinimum(viewId: string): number | null {
return useEditorStore((s) => s.previewState?.min_point_radius[viewId] ?? null)
}
interface SliderScope {
doc: AnatomicalSheetDocument
viewId: string
/** The size a view without any point falls back to. */
fallback: number
}
/** The slider's stops, range and red mark on the view (R-10). */
function useSizeScale({ doc, viewId, fallback }: SliderScope) {
const minimum = useMinimum(viewId)
const stops = sizeStops(doc.annotations, viewId)
return { stops, minimum, range: sizeRange(stops, minimum, fallback) }
}
/** The selection's radius now: its pending preview, else the stored one. */
function useShownRadius(annotation: Annotation): number {
return useAnnotationWork((s) => {
const preview =
s.preview?.annotationId === annotation.id ? s.preview.geometry : null
const shown = preview ?? annotation.geometry
return shown?.type === 'circle' ? shown.r : 0
})
}
/** A size change previewed on the selection (`size`), stamped with the current text. */
function previewSize(annotation: Annotation, radius: number): void {
const { preview } = useAnnotationWork.getState()
const own = preview?.annotationId === annotation.id ? preview.geometry : null
const shown = own ?? annotation.geometry
if (shown?.type !== 'circle') return
const base = useEditorStore.getState().documentText
const geometry = { ...shown, r: radius }
useAnnotationWork.setState({
preview: { annotationId: annotation.id, geometry, base, source: 'size' },
})
}
/**
* Focus back on « Déplacer le point » when the move mode ends with the focus lost (its bar
* unmounted under it: « Valider », « Annuler », Escape). Mounted by the strip, which
* outlives the commands it swaps.
*/
export function useMoveFocusReturn(inMode: boolean) {
const was = useRef(inMode)
useEffect(() => {
const active = document.activeElement
const lost = active === null || active === document.body
if (was.current && !inMode && lost) {
visibleElement('[data-testid="edit-strip"] [data-move-entry]')?.focus()
}
was.current = inMode
}, [inMode])
}
export interface SelectionPointProps {
annotation: Annotation
doc: AnatomicalSheetDocument
viewId: string
frame: Frame | null
edit: PointEdit
}
/**
* The strip's commands for a selected point (board 03): the size slider and « Déplacer le
* point »; during the move mode, its bar (board 06 B).
*/
export function SelectionPointCommands(props: SelectionPointProps) {
const t = useT()
const { annotation, edit } = props
const inMode = useAnnotationWork(
(s) => s.mode?.kind === 'move' && s.mode.annotationId === annotation.id,
)
if (inMode) {
return (
<MoveModeBar
onStep={edit.stepMove}
onConfirm={edit.confirmMove}
onCancel={edit.cancelMove}
/>
)
}
return (
<>
{annotation.kind === 'point' && <SelectionSize {...props} />}
<Button
// R-12: the focus comes back here when the mode ends (useMoveFocusReturn).
data-move-entry=""
type="button"
size="sm"
variant="secondary"
className={COMMAND}
onClick={edit.startMove}
>
<EditorGlyph name="move" size={16} />
{t('editor.annotations.move.point')}
</Button>
</>
)
}
function SelectionSize({ annotation, doc, viewId, edit }: SelectionPointProps) {
const value = useShownRadius(annotation)
const scale = useSizeScale({ doc, viewId, fallback: value })
return (
<SizeSlider
{...scale}
value={value}
onPreview={(radius) => previewSize(annotation, radius)}
onCommit={edit.commitSize}
/>
)
}
export interface ToolSizeProps {
doc: AnatomicalSheetDocument
viewId: string
frame: Frame
/** The size chosen for the next point; null: the view's own (A5). */
size: number | null
dispatch: Dispatch<UiAction>
}
/** The Point tool's slider before the click (A5): it sets the size of the next point. */
export function ToolSize({
doc,
viewId,
frame,
size,
dispatch,
}: ToolSizeProps) {
const scale = useSizeScale({ doc, viewId, fallback: defaultRadius(frame) })
return (
<SizeSlider
{...scale}
value={newPointSize(doc.annotations, viewId, frame, size)}
onPreview={(radius) => dispatch({ type: 'size', size: radius })}
onCommit={() => undefined}
/>
)
}
@@ -0,0 +1,147 @@
import { useId, useRef, type ChangeEvent, type KeyboardEvent } from 'react'
import { round2 } from '@/editor/annotations/frame'
import { snapSize, type SizeRange } from '@/editor/annotations/pointSize'
import { useT } from '@/i18n/useT'
export interface SizeSliderProps {
value: number
/** The view's point radii (R-10): drawn as ticks, the thumb snaps to them. */
stops: readonly number[]
range: SizeRange
/** The core's smallest radius for this view: the red mark; null draws none. */
minimum: number | null
onPreview: (radius: number) => void
/** Release, Enter or blur (BDR-050): one commit of what was previewed. */
onCommit: () => void
}
/** R-10: the thumb snaps to a stop within 8 CSS px of the track. */
const SNAP_PX = 8
const THUMB_PX = 16
/** Where a value sits along the thumb's travel, as a share of it. */
function xOf(value: number, { low, high }: SizeRange): string {
const share = Math.min(Math.max((value - low) / (high - low), 0), 1)
return `${share * 100}%`
}
/** Page Up and Page Down: the next stop above or below the value. */
function nextStop(value: number, stops: readonly number[], up: boolean) {
const found = up
? stops.find((stop) => stop > value)
: [...stops].reverse().find((stop) => stop < value)
return found ?? value
}
/** The value a key gives, or null for a key the slider leaves alone. */
function keyValue(event: KeyboardEvent, props: SizeSliderProps): number | null {
const { value, range } = props
const step = (range.high - range.low) / 100
const clamp = (v: number) =>
round2(Math.min(Math.max(v, range.low), range.high))
if (event.key === 'ArrowRight' || event.key === 'ArrowUp')
return clamp(value + step)
if (event.key === 'ArrowLeft' || event.key === 'ArrowDown')
return clamp(value - step)
if (event.key === 'PageUp') return nextStop(value, props.stops, true)
if (event.key === 'PageDown') return nextStop(value, props.stops, false)
return null
}
/**
* The strip's size slider (board 03 B, R-10): no number shown, the view's sizes as ticks,
* the core's minimum as a red mark. A track click or a drag previews and commits on
* release; arrows step by 1 % of the range, Page Up and Page Down jump to the next size,
* Enter or leaving it commits (one undo step).
*/
export default function SizeSlider(props: SizeSliderProps) {
const t = useT()
const id = useId()
const input = useRef<HTMLInputElement>(null)
const { range, stops, minimum } = props
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
const width = input.current?.clientWidth ?? 0
const reach = width > 0 ? (SNAP_PX * (range.high - range.low)) / width : 0
props.onPreview(snapSize(Number(event.target.value), stops, reach))
}
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') return props.onCommit()
const next = keyValue(event, props)
if (next === null) return
event.preventDefault()
props.onPreview(next)
}
return (
<div className="flex items-center gap-2" data-testid="size-slider">
<label htmlFor={id} className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.size')}
</label>
<div className="relative w-36">
<input
ref={input}
id={id}
type="range"
min={range.low}
max={range.high}
step={0.01}
value={props.value}
onChange={onChange}
onKeyDown={onKeyDown}
onPointerUp={props.onCommit}
onBlur={props.onCommit}
className="block h-11 w-full cursor-pointer accent-[var(--color-accent)] xl:h-9"
/>
<Marks stops={stops} range={range} minimum={minimum} />
</div>
</div>
)
}
/**
* The ticks and the red mark, drawn in an svg spanning the thumb's travel: the range
* follows the view's sizes, so a commit can move them, and svg shapes moving shift no
* layout box (A14).
*/
function Marks({
stops,
range,
minimum,
}: Pick<SizeSliderProps, 'stops' | 'range' | 'minimum'>) {
return (
<svg
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 h-full overflow-visible"
style={{
left: THUMB_PX / 2,
right: THUMB_PX / 2,
width: `calc(100% - ${THUMB_PX}px)`,
}}
>
{stops.map((stop) => (
<line
key={stop}
data-testid="size-stop"
x1={xOf(stop, range)}
x2={xOf(stop, range)}
y1="78%"
y2="95%"
stroke="var(--color-ink-muted)"
strokeWidth={1}
/>
))}
{minimum !== null && (
<line
data-testid="size-minimum"
data-value={minimum}
x1={xOf(minimum, range)}
x2={xOf(minimum, range)}
y1="15%"
y2="85%"
stroke="var(--color-danger-strong)"
strokeWidth={2}
/>
)}
</svg>
)
}