Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

annotationStroke.ts

72 lines2.5 KB

1import type { PreviewAnnotationPoint, PreviewAnnotationRect } from "@t3tools/contracts";
2​
3// Same geometry as apps/desktop/src/preview/AnnotationStroke.ts: the preview preload bundle
4// must stay self-contained, so the browser Draw tool keeps its own copy.
5​
6// Setting a path's `d` makes Chromium parse the whole string again, so a long
7// stroke is drawn as a run of paths and only the last one is rewritten per move.
8const STROKE_SEGMENTS_PER_PATH = 100;
9​
10export interface StrokeGeometry {
11 readonly points: PreviewAnnotationPoint[];
12 minX: number;
13 minY: number;
14 maxX: number;
15 maxY: number;
16 // The curve through the newest point is still open: where it ends depends on
17 // the point after it. This holds only the settled segments of the last path.
18 openPath: string;
19 openSegments: number;
21​
22export function startStroke(point: PreviewAnnotationPoint): StrokeGeometry {
23 return {
24 points: [point],
25 minX: point.x,
26 minY: point.y,
27 maxX: point.x,
28 maxY: point.y,
29 openPath: `M ${point.x} ${point.y}`,
30 openSegments: 0,
31 };
33​
34// Returns the final `d` of the path this point filled, if it filled one.
35export function addStrokePoint(
36 geometry: StrokeGeometry,
37 point: PreviewAnnotationPoint,
38): string | null {
39 const previous = geometry.points[geometry.points.length - 1]!;
40 let closedPath: string | null = null;
41 if (geometry.points.length > 1) {
42 const midX = (previous.x + point.x) / 2;
43 const midY = (previous.y + point.y) / 2;
44 geometry.openPath += ` Q ${previous.x} ${previous.y} ${midX} ${midY}`;
45 geometry.openSegments += 1;
46 if (geometry.openSegments === STROKE_SEGMENTS_PER_PATH) {
47 closedPath = geometry.openPath;
48 geometry.openPath = `M ${midX} ${midY}`;
49 geometry.openSegments = 0;
50 }
51 }
52 geometry.points.push(point);
53 geometry.minX = Math.min(geometry.minX, point.x);
54 geometry.minY = Math.min(geometry.minY, point.y);
55 geometry.maxX = Math.max(geometry.maxX, point.x);
56 geometry.maxY = Math.max(geometry.maxY, point.y);
57 return closedPath;
59​
60export function openStrokePath(geometry: StrokeGeometry): string {
61 const last = geometry.points[geometry.points.length - 1]!;
62 return `${geometry.openPath} L ${last.x} ${last.y}`;
64​
65export function strokeBounds(geometry: StrokeGeometry, width: number): PreviewAnnotationRect {
66 const padding = width + 3;
67 const left = geometry.minX - padding;
68 const top = geometry.minY - padding;
69 const right = geometry.maxX + padding;
70 const bottom = geometry.maxY + padding;
71 return { x: left, y: top, width: right - left, height: bottom - top };