From aecc2b468ed1e54a485b691e628f81fbd6b63b1b Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 20 Nov 2026 14:43:53 +0100 Subject: [PATCH] =?UTF-8?q?feat(editor):=20place=20the=20=C2=AB=20?= =?UTF-8?q?=E2=88=92=20=C2=BB=20bubble=20on=20the=20open=20side=20of=20its?= =?UTF-8?q?=20vertex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/editor/annotations/removeBubble.ts | 261 ++++++++++++++++ .../unit/annotations.removeBubble.test.ts | 287 ++++++++++++++++++ 2 files changed, 548 insertions(+) create mode 100644 apps/app/src/editor/annotations/removeBubble.ts create mode 100644 apps/app/tests/unit/annotations.removeBubble.test.ts diff --git a/apps/app/src/editor/annotations/removeBubble.ts b/apps/app/src/editor/annotations/removeBubble.ts new file mode 100644 index 00000000..c52bcca0 --- /dev/null +++ b/apps/app/src/editor/annotations/removeBubble.ts @@ -0,0 +1,261 @@ +import type { Point } from '@faunosteo/core-wasm/types' +import type { Frame, XY } from './frame' +import type { HandleSizes } from './handleSize' + +/** Where the bubble may lie, in drawing units, and what surrounds the chosen vertex. */ +export interface BubbleScene { + points: readonly Point[] + /** Segment i (vertex i to the next) shows its « + » (ZoneHandles.shownInserts). */ + inserts: readonly boolean[] + /** Drawing units per CSS px. */ + unit: number + sizes: HandleSizes + /** Where the bubble may lie, in drawing units: the frame ∩ the part on screen; null: no bound. */ + bounds: Frame | null + /** The whole frame: the bound used when the chosen vertex is off screen; null: none. */ + frame: Frame | null +} + +/** CSS px kept between the bubble's hit rect and its own vertex's hit circle. */ +const GAP_PX = 2 +/** Turns tried around the open direction (owner: 30° steps): 0, +30, −30, … ±150, 180. */ +const TURNS = [0, ...[1, 2, 3, 4, 5].flatMap((i) => [i, -i]), 6].map( + (i) => (i * Math.PI) / 6, +) +/** CSS px tried farther out when no turn is clear (measured: 24 px suffice on the equine sheet). */ +const FARTHER_PX = [0, 8, 16, 24, 32] +/** Float noise of the framing: a vertex on the edge of the screen is on screen (CSS px). */ +const EDGE_PX = 1e-3 + +/** What the search measures around the chosen vertex, all in CSS px relative to it. */ +interface Around { + /** Midpoints of the shown « + ». */ + insertMids: XY[] + /** The other distinct vertices. */ + vertices: XY[] +} + +interface Scored { + centre: XY + inside: boolean + insertGap: number + vertexGap: number + unambiguous: boolean +} + +/** + * Signed px gap between the bubble's hit rect centred at `centre` and a hit circle at + * `other` (both px). + */ +export function bubbleClearance( + centre: XY, + other: XY, + sizes: HandleSizes, +): number { + const dx = Math.max(Math.abs(other.x - centre.x) - sizes.bubble.w / 2, 0) + const dy = Math.max(Math.abs(other.y - centre.y) - sizes.bubble.h / 2, 0) + return Math.hypot(dx, dy) - sizes.hit +} + +/** + * The part of the frame on screen (drawing units), from the framing; null when the box + * is 0 × 0. + */ +export function visibleBounds( + frame: Frame, + box: { w: number; h: number }, + framing: { x: number; y: number; scale: number }, +): Frame | null { + if (box.w <= 0 || box.h <= 0) return null + const base = Math.min(box.w / frame.w, box.h / frame.h) + const ox = (box.w - frame.w * base) / 2 + const oy = (box.h - frame.h * base) / 2 + const toDrawing = (px: number, o: number, origin: number) => + origin + (px - o) / base + const x0 = Math.max( + frame.x, + toDrawing(-framing.x / framing.scale, ox, frame.x), + ) + const x1 = Math.min( + frame.x + frame.w, + toDrawing((box.w - framing.x) / framing.scale, ox, frame.x), + ) + const y0 = Math.max( + frame.y, + toDrawing(-framing.y / framing.scale, oy, frame.y), + ) + const y1 = Math.min( + frame.y + frame.h, + toDrawing((box.h - framing.y) / framing.scale, oy, frame.y), + ) + return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } +} + +const samePoint = (a: Point, b: Point): boolean => + a[0] === b[0] && a[1] === b[1] + +/** The first point, walking `step` (−1 or +1) from `chosen`, that differs from it. */ +function neighbour( + points: readonly Point[], + chosen: number, + step: number, +): Point | null { + const n = points.length + for (let k = 1; k < n; k++) { + const p = points[(((chosen + step * k) % n) + n) % n] + if (!samePoint(p, points[chosen])) return p + } + return null +} + +/** The angle (radians) the bubble opens towards: away from the polygon's inside corner. */ +function openDirection(points: readonly Point[], chosen: number): number { + const v = points[chosen] + const before = neighbour(points, chosen, -1) + const after = neighbour(points, chosen, 1) + if (before === null || after === null) { + const only = before ?? after + if (only === null) return -Math.PI / 2 + return Math.atan2(only[1] - v[1], only[0] - v[0]) + Math.PI + } + const ta = Math.atan2(before[1] - v[1], before[0] - v[0]) + const tb = Math.atan2(after[1] - v[1], after[0] - v[0]) + const gap = (((tb - ta) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI) + const bisector = ta + gap / 2 + return gap > Math.PI ? bisector : bisector + Math.PI +} + +function aroundVertex(scene: BubbleScene, chosen: number): Around { + const { points, inserts, unit } = scene + const v = points[chosen] + const rel = (x: number, y: number): XY => ({ + x: (x - v[0]) / unit, + y: (y - v[1]) / unit, + }) + const insertMids = points.flatMap((p, s) => { + if (!inserts[s]) return [] + const q = points[(s + 1) % points.length] + return [rel((p[0] + q[0]) / 2, (p[1] + q[1]) / 2)] + }) + const vertices = points + .filter((p) => !samePoint(p, v)) + .map((p) => rel(p[0], p[1])) + return { insertMids, vertices } +} + +/** The bound in force: `bounds`, or the whole frame when the vertex is off screen. */ +function effectiveBounds(scene: BubbleScene, vertex: Point): Frame | null { + const { bounds, frame } = scene + if (bounds === null) return null + const slack = EDGE_PX * scene.unit + const onScreen = + vertex[0] >= bounds.x - slack && + vertex[0] <= bounds.x + bounds.w + slack && + vertex[1] >= bounds.y - slack && + vertex[1] <= bounds.y + bounds.h + slack + return onScreen ? bounds : frame +} + +function rectInside( + centre: XY, + vertex: Point, + scene: BubbleScene, + bounds: Frame | null, +): boolean { + if (bounds === null) return true + const { unit, sizes } = scene + const cx = vertex[0] + centre.x * unit + const cy = vertex[1] + centre.y * unit + const hw = (sizes.bubble.w / 2) * unit + const hh = (sizes.bubble.h / 2) * unit + const slack = EDGE_PX * unit + return ( + cx - hw >= bounds.x - slack && + cx + hw <= bounds.x + bounds.w + slack && + cy - hh >= bounds.y - slack && + cy + hh <= bounds.y + bounds.h + slack + ) +} + +function isUnambiguous(centre: XY, mids: XY[], sizes: HandleSizes): boolean { + return mids.every( + (m) => + (Math.abs(m.x - centre.x) > sizes.bubble.w / 2 || + Math.abs(m.y - centre.y) > sizes.bubble.h / 2) && + Math.hypot(m.x - centre.x, m.y - centre.y) > sizes.hit, + ) +} + +function minGap(centre: XY, others: XY[], sizes: HandleSizes): number { + return Math.min( + Infinity, + ...others.map((o) => bubbleClearance(centre, o, sizes)), + ) +} + +/** The candidate centres in px, in preference order: nearer first, then each turn. */ +function candidates(open: number, sizes: HandleSizes): XY[] { + return FARTHER_PX.flatMap((extra) => + TURNS.map((turn) => { + const theta = open + turn + const d = + sizes.hit + + (sizes.bubble.w / 2) * Math.abs(Math.cos(theta)) + + (sizes.bubble.h / 2) * Math.abs(Math.sin(theta)) + + GAP_PX + + extra + return { x: d * Math.cos(theta), y: d * Math.sin(theta) } + }), + ) +} + +function score( + centre: XY, + around: Around, + inside: boolean, + sizes: HandleSizes, +): Scored { + return { + centre, + inside, + insertGap: minGap(centre, around.insertMids, sizes), + vertexGap: minGap(centre, around.vertices, sizes), + unambiguous: isUnambiguous(centre, around.insertMids, sizes), + } +} + +function largestInsertGap(list: Scored[]): Scored | undefined { + return list.reduce( + (best, c) => + best === undefined || c.insertGap > best.insertGap ? c : best, + undefined, + ) +} + +/** + * Precedence: clear of every « + » and vertex, then of every « + », then unambiguous, + * always on screen first. + */ +function choose(scored: Scored[]): Scored { + const inside = scored.filter((c) => c.inside) + return ( + inside.find((c) => c.insertGap >= 0 && c.vertexGap >= 0) ?? + inside.find((c) => c.insertGap >= 0) ?? + largestInsertGap(inside.filter((c) => c.unambiguous)) ?? + largestInsertGap(inside) ?? + scored[0] + ) +} + +/** The centre of the « − » bubble of vertex `chosen`, in drawing units. */ +export function removeBubbleCentre(scene: BubbleScene, chosen: number): Point { + const vertex = scene.points[chosen] + const open = openDirection(scene.points, chosen) + const around = aroundVertex(scene, chosen) + const bounds = effectiveBounds(scene, vertex) + const scored = candidates(open, scene.sizes).map((c) => + score(c, around, rectInside(c, vertex, scene, bounds), scene.sizes), + ) + const { centre } = choose(scored) + return [vertex[0] + centre.x * scene.unit, vertex[1] + centre.y * scene.unit] +} diff --git a/apps/app/tests/unit/annotations.removeBubble.test.ts b/apps/app/tests/unit/annotations.removeBubble.test.ts new file mode 100644 index 00000000..1cbae53d --- /dev/null +++ b/apps/app/tests/unit/annotations.removeBubble.test.ts @@ -0,0 +1,287 @@ +/** U2 trial: placement of the « − » bubble against the real hit areas (coarse sizes). */ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AnatomicalSheetDocument, Point } from '@faunosteo/core-wasm/types' +import type { Frame, XY } from '@/editor/annotations/frame' +import { deviceSizes, type HandleSizes } from '@/editor/annotations/handleSize' +import { showsInsert } from '@/editor/annotations/polygonEdit' +import { + bubbleClearance, + removeBubbleCentre, + visibleBounds, + type BubbleScene, +} from '@/editor/annotations/removeBubble' + +const SEED = resolve( + fileURLToPath(import.meta.url), + '../../../../../supabase/seed/anatomical-sheets/equine/draft', +) +const draft = JSON.parse( + readFileSync(resolve(SEED, 'document.json'), 'utf8'), +) as AnatomicalSheetDocument +const viewBox = /viewBox="([^"]+)"/.exec( + readFileSync(resolve(SEED, 'assets/horse.svg'), 'utf8'), +)![1] +const [fx, fy, fw, fh] = viewBox.split(/\s+/).map(Number) +const FRAME: Frame = { x: fx, y: fy, w: fw, h: fh } + +const polygons = draft.annotations.flatMap((a) => { + const g = a.geometry + return a.view_id === 'main' && g !== null && g.type === 'polygon' + ? [{ id: a.id, points: g.points as Point[] }] + : [] +}) + +function stubPointer(coarse: boolean) { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: coarse, + media: query, + })) +} +beforeEach(() => stubPointer(true)) +afterEach(() => vi.unstubAllGlobals()) + +const px = (p: Point, unit: number): XY => ({ x: p[0] / unit, y: p[1] / unit }) + +function insertsFor( + points: readonly Point[], + unit: number, + sizes: HandleSizes, +): boolean[] { + return points.map((p, s) => { + const q = points[(s + 1) % points.length] + return showsInsert(Math.hypot(q[0] - p[0], q[1] - p[1]) / unit, sizes.hit) + }) +} + +const mid = (a: Point, b: Point, unit: number): XY => + px([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], unit) + +function sceneOf( + points: readonly Point[], + unit: number, + sizes: HandleSizes, + bounds: Frame | null, + frame: Frame | null = bounds, +): BubbleScene { + return { + points, + inserts: insertsFor(points, unit, sizes), + unit, + sizes, + bounds, + frame, + } +} + +const shownMids = (scene: BubbleScene): XY[] => + scene.points.flatMap((p, s) => + scene.inserts[s] + ? [mid(p, scene.points[(s + 1) % scene.points.length], scene.unit)] + : [], + ) + +const insideFrame = (c: XY, sizes: HandleSizes, unit: number, b: Frame) => + c.x * unit - (sizes.bubble.w / 2) * unit >= b.x - 1e-9 && + c.x * unit + (sizes.bubble.w / 2) * unit <= b.x + b.w + 1e-9 && + c.y * unit - (sizes.bubble.h / 2) * unit >= b.y - 1e-9 && + c.y * unit + (sizes.bubble.h / 2) * unit <= b.y + b.h + 1e-9 + +describe('visibleBounds', () => { + const box = { w: 100, h: 100 } + const frame = { x: 0, y: 0, w: 100, h: 100 } + it('is the frame at fit', () => { + expect(visibleBounds(frame, box, { x: 0, y: 0, scale: 1 })).toEqual(frame) + }) + it('is the part on screen when zoomed and panned', () => { + expect(visibleBounds(frame, box, { x: -50, y: -50, scale: 2 })).toEqual({ + x: 25, + y: 25, + w: 50, + h: 50, + }) + }) + it('is null for an empty box', () => { + expect( + visibleBounds(frame, { w: 0, h: 10 }, { x: 0, y: 0, scale: 1 }), + ).toBeNull() + }) +}) + +describe('removeBubbleCentre', () => { + it('there are six equine polygons on the main view', () => { + expect(polygons.map((p) => p.id)).toHaveLength(6) + }) + + it('control: the old centre fails the criterion (thoracic, vertex 2)', () => { + const sizes = deviceSizes() + const { points } = polygons.find((p) => p.id.includes('thoracic'))! + const unit = 1 / ((679 / FRAME.w) * 2.25) + const scene = sceneOf(points, unit, sizes, FRAME) + const v = points[2] + const old: XY = px([v[0], v[1] - (9 + 6 + 18) * unit], unit) + const gaps = shownMids(scene).map((m) => bubbleClearance(old, m, sizes)) + expect(Math.min(...gaps)).toBeLessThan(0) + }) + + it('sweep: clear of every shown « + » and its own vertex, inside the frame', () => { + const sizes = deviceSizes() + let count = 0 + for (const { points } of polygons) { + for (const width of [621, 679, 694]) { + for (let k = 0; k <= 100; k++) { + const zoom = 1 + k * 0.05 + const unit = + 1 / (Math.min(width / FRAME.w, (width * 0.75) / FRAME.h) * zoom) + const scene = sceneOf(points, unit, sizes, FRAME) + const mids = shownMids(scene) + points.forEach((v, i) => { + const [bx, by] = removeBubbleCentre(scene, i) + const c = px([bx, by], unit) + count++ + for (const m of mids) { + expect(bubbleClearance(c, m, sizes)).toBeGreaterThanOrEqual(0) + expect(c).not.toEqual(m) + } + expect( + bubbleClearance(c, px(v, unit), sizes), + ).toBeGreaterThanOrEqual(0) + expect(insideFrame(c, sizes, unit, FRAME)).toBe(true) + }) + } + } + } + expect(count).toBeGreaterThan(1000) + }, 60_000) + + it('window: stays in the shown part, an off-screen vertex is not forced', () => { + const sizes = fine() + const square: Point[] = [ + [0, 0], + [100, 0], + [100, 100], + [0, 100], + ] + const window: Frame = { x: 0, y: 0, w: 60, h: 60 } + const scene = sceneOf(square, 1, sizes, window, { + x: 0, + y: 0, + w: 100, + h: 100, + }) + const [x0, y0] = removeBubbleCentre(scene, 0) + expect(insideFrame({ x: x0, y: y0 }, sizes, 1, window)).toBe(true) + const [x2, y2] = removeBubbleCentre(scene, 2) + expect(insideFrame({ x: x2, y: y2 }, sizes, 1, window)).toBe(false) + expect( + insideFrame({ x: x2, y: y2 }, sizes, 1, { x: 0, y: 0, w: 100, h: 100 }), + ).toBe(true) + }) + + it('vertex rung: keeps clear of another vertex straight ahead', () => { + const sizes = deviceSizes() + // vertex 0 opens up-left (towards -y); another vertex sits 40 px straight above it. + const points: Point[] = [ + [0, 0], + [60, 20], + [60, 80], + [0, 80], + [0, -40], + ] + const scene = sceneOf(points, 1, sizes, null) + const [bx, by] = removeBubbleCentre(scene, 0) + expect( + bubbleClearance({ x: bx, y: by }, { x: 0, y: -40 }, sizes), + ).toBeGreaterThanOrEqual(0) + expect( + bubbleClearance({ x: bx, y: by }, { x: 0, y: 0 }, sizes), + ).toBeGreaterThanOrEqual(0) + }) + + it('degenerate: repeated points give finite centres clear of the « + »', () => { + const sizes = fine() + const points: Point[] = [ + [10, 10], + [10, 10], + [60, 10], + [60, 60], + ] + const scene = sceneOf(points, 1, sizes, { x: 0, y: 0, w: 100, h: 100 }) + const mids = shownMids(scene) + points.forEach((_, i) => { + const [bx, by] = removeBubbleCentre(scene, i) + expect(Number.isFinite(bx) && Number.isFinite(by)).toBe(true) + for (const m of mids) { + expect( + bubbleClearance({ x: bx, y: by }, m, sizes), + ).toBeGreaterThanOrEqual(0) + } + }) + }) +}) + +function fine(): HandleSizes { + stubPointer(false) + const sizes = deviceSizes() + stubPointer(true) + return sizes +} + +describe('panned sweep (vertex at a chosen screen spot while zoomed)', () => { + it('stays on screen and unambiguous but for a few window corners', () => { + const sizes = deviceSizes() + const W = 679 + const H = W * 0.75 + const base = Math.min(W / FRAME.w, H / FRAME.h) + const ox = (W - FRAME.w * base) / 2 + const oy = (H - FRAME.h * base) / 2 + const xs = [0, 20, 60, W / 2, W - 60, W - 20, W] + const ys = [0, 20, 60, H / 2, H - 60, H - 20, H] + const exceptions: string[] = [] + const offscreen: string[] = [] + let clear = 0 + let total = 0 + for (const { id, points } of polygons) { + for (const zoom of [2.25, 3.375, 5.0625]) { + const unit = 1 / (base * zoom) + points.forEach((v, i) => { + for (const sx of xs) + for (const sy of ys) { + const p = { + x: ox + (v[0] - FRAME.x) * base, + y: oy + (v[1] - FRAME.y) * base, + } + const framing = { + x: sx - zoom * p.x, + y: sy - zoom * p.y, + scale: zoom, + } + const bounds = visibleBounds(FRAME, { w: W, h: H }, framing) + const scene = sceneOf(points, unit, sizes, bounds, FRAME) + const [bx, by] = removeBubbleCentre(scene, i) + const c = px([bx, by], unit) + const where = `${id} v${i} z${zoom} at (${sx}, ${sy})` + total++ + const mids = shownMids(scene) + if (!insideFrame(c, sizes, unit, bounds!)) offscreen.push(where) + const ambiguous = mids.some( + (m) => + (Math.abs(m.x - c.x) <= sizes.bubble.w / 2 && + Math.abs(m.y - c.y) <= sizes.bubble.h / 2) || + Math.hypot(m.x - c.x, m.y - c.y) <= sizes.hit, + ) + if (ambiguous) exceptions.push(where) + if (mids.every((m) => bubbleClearance(c, m, sizes) >= 0)) clear++ + } + }) + } + } + console.info(`panned: ${total} placements, ${clear} meet (a)`) + console.info(`ambiguous: ${exceptions.join(' | ')}`) + console.info(`off screen: ${offscreen.length}`) + expect(offscreen).toEqual([]) + expect(exceptions.length).toBeLessThanOrEqual(3) + }, 60_000) +})