@adecore/drawing 0.0.1 → 0.17.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,110 @@
1
+ # Functional Source License, Version 1.1, MIT Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 - present Bas Milius
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
100
+
101
+ The above copyright notice and this permission notice shall be included in all
102
+ copies or substantial portions of the Software.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
105
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
106
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
107
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
108
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
109
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
110
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @adecore/drawing
2
+
3
+ [![npm](https://img.shields.io/npm/v/@adecore/drawing)](https://www.npmjs.com/package/@adecore/drawing)
4
+ [![Docs](https://img.shields.io/badge/docs-adecore.dev-blue)](https://adecore.dev/drawing/)
5
+
6
+ Hand-drawn shapes, arrows, freehand strokes, text and sticky notes as plain JSON, with hit tests and resizing for an editor, paths for a painter, an SVG export and a reading of a drawing as lines of text. It needs no DOM, so a backend exports a stored drawing the same way a page draws it.
7
+
8
+ **[Documentation with live demos](https://adecore.dev/drawing/)**
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ bun add @adecore/drawing
14
+ ```
15
+
16
+ ## Use
17
+
18
+ ```ts
19
+ import { DEFAULT_PALETTE, readingOrder, toSvg } from '@adecore/drawing';
20
+ import { duplicateElementIdIn, migrateDrawing } from '@adecore/drawing/protocol';
21
+
22
+ const drawing = migrateDrawing(JSON.parse(file));
23
+ if (drawing === null || duplicateElementIdIn(drawing.elements) !== null) {
24
+ throw new Error('Not a drawing');
25
+ }
26
+
27
+ const svg = toSvg(drawing.elements, { palette: DEFAULT_PALETTE });
28
+ const lines = readingOrder(drawing.elements);
29
+ ```
30
+
31
+ ## Entry points
32
+
33
+ | Import | What it holds |
34
+ |---|---|
35
+ | `@adecore/drawing` | Geometry, paths, SVG export, text and reading order |
36
+ | `@adecore/drawing/protocol` | The Zod schemas and types of a drawing; loads nothing else |
37
+
38
+ ## Documentation
39
+
40
+ | Page | What it covers |
41
+ |---|---|
42
+ | [Documents](https://adecore.dev/drawing/documents) | The document, the seven element kinds and reading a file |
43
+ | [Geometry](https://adecore.dev/drawing/geometry) | Bounds, hit tests, selection and resizing |
44
+ | [Paths and SVG](https://adecore.dev/drawing/rendering) | `toSvg` and the paths of one element for a painter of your own |
45
+ | [Text and reading order](https://adecore.dev/drawing/text) | Wrapping, measuring and `readingOrder` |
46
+
47
+ ## License
48
+
49
+ FSL-1.1-MIT, see [LICENSE](./LICENSE). Rough.js and perfect-freehand keep their own licenses.
@@ -0,0 +1,32 @@
1
+ import type { DrawingElement } from './protocol.ts';
2
+ export interface Point {
3
+ x: number;
4
+ y: number;
5
+ }
6
+ export interface Rect {
7
+ x: number;
8
+ y: number;
9
+ w: number;
10
+ h: number;
11
+ }
12
+ export declare const RESIZE_HANDLES: readonly ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
13
+ export type ResizeHandle = (typeof RESIZE_HANDLES)[number];
14
+ export declare function boundsOf(element: Pick<DrawingElement, 'x' | 'y' | 'w' | 'h'>): Rect;
15
+ export declare function centerOf(rect: Rect): Point;
16
+ export declare function roundPoint(point: Point): Point;
17
+ export declare function rotatePoint(point: Point, around: Point, angle: number): Point;
18
+ export declare function toLocal(element: DrawingElement, point: Point): Point;
19
+ export declare function unionOf(rects: readonly Rect[]): Rect | null;
20
+ export declare function boundsOfElements(elements: readonly DrawingElement[]): Rect | null;
21
+ export declare function intersects(a: Rect, b: Rect): boolean;
22
+ export declare function rectFromPoints(from: Point, to: Point): Rect;
23
+ export declare function distanceToSegment(point: Point, a: Point, b: Point): number;
24
+ export declare function absolutePoints(element: DrawingElement): Point[];
25
+ export declare function hitsElement(element: DrawingElement, point: Point, tolerance: number): boolean;
26
+ export declare function elementAt(elements: readonly DrawingElement[], point: Point, tolerance: number): DrawingElement | undefined;
27
+ export declare function elementsIn(elements: readonly DrawingElement[], rect: Rect): DrawingElement[];
28
+ export declare function handlePoint(rect: Rect, handle: ResizeHandle): Point;
29
+ export declare function resizeRect(rect: Rect, handle: ResizeHandle, point: Point, aspect?: boolean): Rect;
30
+ export declare function scaleElement(element: DrawingElement, from: Rect, to: Rect): DrawingElement;
31
+ export declare function arrowHead(tip: Point, from: Point, size: number): [Point, Point][];
32
+ export declare function arrowHeadSize(strokeWidth: number): number;
@@ -0,0 +1,233 @@
1
+ export const RESIZE_HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
2
+ export function boundsOf(element) {
3
+ return { x: element.x, y: element.y, w: element.w, h: element.h };
4
+ }
5
+ export function centerOf(rect) {
6
+ return { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 };
7
+ }
8
+ /* A point on the whole pixel, for a layout that lines its boxes and its lines up on a pixel grid. */
9
+ export function roundPoint(point) {
10
+ return { x: Math.round(point.x), y: Math.round(point.y) };
11
+ }
12
+ export function rotatePoint(point, around, angle) {
13
+ if (angle === 0) {
14
+ return point;
15
+ }
16
+ const cos = Math.cos(angle);
17
+ const sin = Math.sin(angle);
18
+ const dx = point.x - around.x;
19
+ const dy = point.y - around.y;
20
+ return { x: around.x + dx * cos - dy * sin, y: around.y + dx * sin + dy * cos };
21
+ }
22
+ /* A point in the element's own frame, so every hit test can pretend nothing is turned. */
23
+ export function toLocal(element, point) {
24
+ return rotatePoint(point, centerOf(boundsOf(element)), -(element.angle ?? 0));
25
+ }
26
+ export function unionOf(rects) {
27
+ if (rects.length === 0) {
28
+ return null;
29
+ }
30
+ let left = Infinity;
31
+ let top = Infinity;
32
+ let right = -Infinity;
33
+ let bottom = -Infinity;
34
+ for (const rect of rects) {
35
+ left = Math.min(left, rect.x, rect.x + rect.w);
36
+ top = Math.min(top, rect.y, rect.y + rect.h);
37
+ right = Math.max(right, rect.x, rect.x + rect.w);
38
+ bottom = Math.max(bottom, rect.y, rect.y + rect.h);
39
+ }
40
+ return { x: left, y: top, w: right - left, h: bottom - top };
41
+ }
42
+ export function boundsOfElements(elements) {
43
+ return unionOf(elements.map(boundsOf));
44
+ }
45
+ export function intersects(a, b) {
46
+ return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
47
+ }
48
+ export function rectFromPoints(from, to) {
49
+ return {
50
+ x: Math.min(from.x, to.x),
51
+ y: Math.min(from.y, to.y),
52
+ w: Math.abs(to.x - from.x),
53
+ h: Math.abs(to.y - from.y)
54
+ };
55
+ }
56
+ export function distanceToSegment(point, a, b) {
57
+ const dx = b.x - a.x;
58
+ const dy = b.y - a.y;
59
+ const length = dx * dx + dy * dy;
60
+ if (length === 0) {
61
+ return Math.hypot(point.x - a.x, point.y - a.y);
62
+ }
63
+ const t = Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / length));
64
+ return Math.hypot(point.x - (a.x + t * dx), point.y - (a.y + t * dy));
65
+ }
66
+ export function absolutePoints(element) {
67
+ if (element.kind !== 'line' && element.kind !== 'freehand') {
68
+ return [];
69
+ }
70
+ return element.points.map(([x, y]) => ({ x: element.x + x, y: element.y + y }));
71
+ }
72
+ function isFilled(element) {
73
+ return element.fill !== undefined && element.fill !== 'none';
74
+ }
75
+ function cornersOfDiamond(rect) {
76
+ return [
77
+ { x: rect.x + rect.w / 2, y: rect.y },
78
+ { x: rect.x + rect.w, y: rect.y + rect.h / 2 },
79
+ { x: rect.x + rect.w / 2, y: rect.y + rect.h },
80
+ { x: rect.x, y: rect.y + rect.h / 2 }
81
+ ];
82
+ }
83
+ function insidePolygon(point, polygon) {
84
+ let inside = false;
85
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
86
+ const a = polygon[i];
87
+ const b = polygon[j];
88
+ if (a.y > point.y !== b.y > point.y && point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x) {
89
+ inside = !inside;
90
+ }
91
+ }
92
+ return inside;
93
+ }
94
+ function nearPolygon(point, polygon, tolerance) {
95
+ return polygon.some((corner, index) => distanceToSegment(point, corner, polygon[(index + 1) % polygon.length]) <= tolerance);
96
+ }
97
+ function nearPolyline(point, points, tolerance) {
98
+ if (points.length === 1) {
99
+ return Math.hypot(point.x - points[0].x, point.y - points[0].y) <= tolerance;
100
+ }
101
+ return points.slice(0, -1).some((from, index) => distanceToSegment(point, from, points[index + 1]) <= tolerance);
102
+ }
103
+ function insideRect(point, rect) {
104
+ return point.x >= rect.x && point.x <= rect.x + rect.w && point.y >= rect.y && point.y <= rect.y + rect.h;
105
+ }
106
+ /*
107
+ * Whether a point lands on an element. A shape with a fill is hit anywhere inside it, one without
108
+ * only near its outline, which is what makes an empty rectangle easy to draw inside of.
109
+ */
110
+ export function hitsElement(element, point, tolerance) {
111
+ const local = toLocal(element, point);
112
+ const rect = boundsOf(element);
113
+ const reach = Math.max(tolerance, element.strokeWidth);
114
+ switch (element.kind) {
115
+ // Both are their own sheet: anywhere on it is on them.
116
+ case 'text':
117
+ case 'note':
118
+ return insideRect(local, rect);
119
+ case 'rect': {
120
+ const corners = [
121
+ { x: rect.x, y: rect.y },
122
+ { x: rect.x + rect.w, y: rect.y },
123
+ { x: rect.x + rect.w, y: rect.y + rect.h },
124
+ { x: rect.x, y: rect.y + rect.h }
125
+ ];
126
+ return isFilled(element) ? insideRect(local, rect) : nearPolygon(local, corners, reach);
127
+ }
128
+ case 'diamond': {
129
+ const corners = cornersOfDiamond(rect);
130
+ return isFilled(element) ? insidePolygon(local, corners) : nearPolygon(local, corners, reach);
131
+ }
132
+ case 'ellipse': {
133
+ const center = centerOf(rect);
134
+ const rx = Math.max(rect.w / 2, 0.01);
135
+ const ry = Math.max(rect.h / 2, 0.01);
136
+ const distance = Math.hypot((local.x - center.x) / rx, (local.y - center.y) / ry);
137
+ if (isFilled(element)) {
138
+ return distance <= 1;
139
+ }
140
+ return Math.abs(distance - 1) <= reach / Math.min(rx, ry);
141
+ }
142
+ case 'line':
143
+ case 'freehand':
144
+ return nearPolyline(local, absolutePoints(element), reach);
145
+ }
146
+ }
147
+ export function elementAt(elements, point, tolerance) {
148
+ for (let i = elements.length - 1; i >= 0; i--) {
149
+ const element = elements[i];
150
+ if (!element.locked && hitsElement(element, point, tolerance)) {
151
+ return element;
152
+ }
153
+ }
154
+ return undefined;
155
+ }
156
+ export function elementsIn(elements, rect) {
157
+ return elements.filter((element) => !element.locked && intersects(boundsOf(element), rect));
158
+ }
159
+ export function handlePoint(rect, handle) {
160
+ const x = handle.includes('w') ? rect.x : handle.includes('e') ? rect.x + rect.w : rect.x + rect.w / 2;
161
+ const y = handle.startsWith('n') ? rect.y : handle.startsWith('s') ? rect.y + rect.h : rect.y + rect.h / 2;
162
+ return { x, y };
163
+ }
164
+ /*
165
+ * The box a resize drag makes: the handle follows the pointer and the side across from it stays
166
+ * put. `aspect` keeps the proportions, which is what Shift asks for.
167
+ */
168
+ export function resizeRect(rect, handle, point, aspect = false) {
169
+ let { x, y, w, h } = rect;
170
+ if (handle.includes('w')) {
171
+ w = rect.x + rect.w - point.x;
172
+ x = point.x;
173
+ }
174
+ if (handle.includes('e')) {
175
+ w = point.x - rect.x;
176
+ }
177
+ if (handle.startsWith('n')) {
178
+ h = rect.y + rect.h - point.y;
179
+ y = point.y;
180
+ }
181
+ if (handle.startsWith('s')) {
182
+ h = point.y - rect.y;
183
+ }
184
+ if (aspect && rect.w > 0 && rect.h > 0) {
185
+ const ratio = rect.h / rect.w;
186
+ // A side handle moves one dimension, which sets the other; a corner follows the smaller pull.
187
+ const width = handle === 'e' || handle === 'w' ? w : handle === 'n' || handle === 's' ? h / ratio : Math.abs(w) < Math.abs(h / ratio) ? w : h / ratio;
188
+ const height = width * ratio;
189
+ if (handle.includes('w')) {
190
+ x = rect.x + rect.w - width;
191
+ }
192
+ if (handle.startsWith('n')) {
193
+ y = rect.y + rect.h - height;
194
+ }
195
+ w = width;
196
+ h = height;
197
+ }
198
+ return { x, y, w, h };
199
+ }
200
+ export function scaleElement(element, from, to) {
201
+ const scaleX = from.w === 0 ? 1 : to.w / from.w;
202
+ const scaleY = from.h === 0 ? 1 : to.h / from.h;
203
+ const placed = {
204
+ ...element,
205
+ x: to.x + (element.x - from.x) * scaleX,
206
+ y: to.y + (element.y - from.y) * scaleY,
207
+ w: element.w * scaleX,
208
+ h: element.h * scaleY
209
+ };
210
+ if (placed.kind === 'line') {
211
+ return { ...placed, points: placed.points.map(([x, y]) => [x * scaleX, y * scaleY]) };
212
+ }
213
+ if (placed.kind === 'freehand') {
214
+ return { ...placed, points: placed.points.map(([x, y, pressure]) => [x * scaleX, y * scaleY, pressure]) };
215
+ }
216
+ if (placed.kind === 'text') {
217
+ // From here on the box is the person's, so typing no longer refits it.
218
+ return { ...placed, sized: true };
219
+ }
220
+ return placed;
221
+ }
222
+ export function arrowHead(tip, from, size) {
223
+ const angle = Math.atan2(tip.y - from.y, tip.x - from.x);
224
+ const spread = Math.PI / 7;
225
+ return [
226
+ [tip, { x: tip.x - size * Math.cos(angle - spread), y: tip.y - size * Math.sin(angle - spread) }],
227
+ [tip, { x: tip.x - size * Math.cos(angle + spread), y: tip.y - size * Math.sin(angle + spread) }]
228
+ ];
229
+ }
230
+ /* How long an arrow head is for a given stroke: heavier lines carry a bigger head. */
231
+ export function arrowHeadSize(strokeWidth) {
232
+ return 12 + strokeWidth * 4;
233
+ }
@@ -0,0 +1,5 @@
1
+ export { type Point, type Rect, RESIZE_HANDLES, type ResizeHandle, boundsOf, centerOf, roundPoint, rotatePoint, toLocal, unionOf, boundsOfElements, intersects, rectFromPoints, distanceToSegment, absolutePoints, hitsElement, elementAt, elementsIn, handlePoint, resizeRect, scaleElement, arrowHead, arrowHeadSize } from './geometry.ts';
2
+ export { type ElementPath, outlineToPath, freehandOutline, pathsOfElement } from './paths.ts';
3
+ export { readingOrder } from './reading-order.ts';
4
+ export { type SvgOptions, DEFAULT_SVG_MARGIN, DEFAULT_PALETTE, DEFAULT_PAPER, DEFAULT_EDGE, toSvg } from './svg.ts';
5
+ export { LINE_HEIGHT, DEFAULT_FONT_STACKS, type WrittenElement, NOTE_PADDING, NOTE_RADIUS, writingFrameOf, textLines, type MeasureLine, approximateMeasure, wrapLines, linesOf, fontOf } from './text.ts';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { RESIZE_HANDLES, boundsOf, centerOf, roundPoint, rotatePoint, toLocal, unionOf, boundsOfElements, intersects, rectFromPoints, distanceToSegment, absolutePoints, hitsElement, elementAt, elementsIn, handlePoint, resizeRect, scaleElement, arrowHead, arrowHeadSize } from './geometry.js';
2
+ export { outlineToPath, freehandOutline, pathsOfElement } from './paths.js';
3
+ export { readingOrder } from './reading-order.js';
4
+ export { DEFAULT_SVG_MARGIN, DEFAULT_PALETTE, DEFAULT_PAPER, DEFAULT_EDGE, toSvg } from './svg.js';
5
+ export { LINE_HEIGHT, DEFAULT_FONT_STACKS, NOTE_PADDING, NOTE_RADIUS, writingFrameOf, textLines, approximateMeasure, wrapLines, linesOf, fontOf } from './text.js';
@@ -0,0 +1,12 @@
1
+ import type { DrawingElement } from './protocol.ts';
2
+ export interface ElementPath {
3
+ d: string;
4
+ role: 'stroke' | 'fill' | 'ink';
5
+ strokeWidth: number;
6
+ dash: number[] | null;
7
+ }
8
+ export declare function outlineToPath(outline: readonly (readonly number[])[]): string;
9
+ export declare function freehandOutline(element: DrawingElement & {
10
+ kind: 'freehand';
11
+ }): string;
12
+ export declare function pathsOfElement(element: DrawingElement): ElementPath[];
package/dist/paths.js ADDED
@@ -0,0 +1,129 @@
1
+ import { getStroke } from 'perfect-freehand';
2
+ // Rough's unbundled modules use extensionless imports; its package entry also runs in Node.
3
+ import rough from 'roughjs';
4
+ import { arrowHead, arrowHeadSize } from './geometry.js';
5
+ import { NOTE_RADIUS } from './text.js';
6
+ // Sentinels, not colors: rough hands them back on every path, which is how a path says what it is.
7
+ const STROKE = '#000001';
8
+ const FILL = '#000002';
9
+ let generator;
10
+ function drawingGenerator() {
11
+ return (generator ??= rough.generator());
12
+ }
13
+ function dashOf(element) {
14
+ if (element.strokeStyle === 'dashed') {
15
+ return [element.strokeWidth * 4, element.strokeWidth * 4];
16
+ }
17
+ if (element.strokeStyle === 'dotted') {
18
+ return [element.strokeWidth, element.strokeWidth * 3];
19
+ }
20
+ return null;
21
+ }
22
+ /* Architect, Artist, Cartoonist. Absent reads as Artist, which is what a hand-written file gets. */
23
+ function roughnessOf(element) {
24
+ switch (element.roughness ?? 1) {
25
+ case 0:
26
+ return { roughness: 0, bowing: 0, disableMultiStroke: true };
27
+ case 2:
28
+ return { roughness: 2.5, bowing: 2 };
29
+ default:
30
+ return { roughness: 1, bowing: 1 };
31
+ }
32
+ }
33
+ function optionsOf(element) {
34
+ return {
35
+ seed: element.seed + 1,
36
+ stroke: STROKE,
37
+ strokeWidth: element.strokeWidth,
38
+ ...roughnessOf(element),
39
+ ...(element.fill && element.fill !== 'none'
40
+ ? { fill: FILL, fillStyle: element.fill === 'solid' ? 'solid' : 'hachure', fillWeight: element.strokeWidth / 2, hachureGap: 8 }
41
+ : {})
42
+ };
43
+ }
44
+ // Rough has no rounded-rectangle primitive.
45
+ function roundedRectPath(w, h, radius) {
46
+ const r = Math.min(radius, w / 2, h / 2);
47
+ return `M ${r} 0 L ${w - r} 0 Q ${w} 0 ${w} ${r} L ${w} ${h - r} Q ${w} ${h} ${w - r} ${h} L ${r} ${h} Q 0 ${h} 0 ${h - r} L 0 ${r} Q 0 0 ${r} 0 Z`;
48
+ }
49
+ export function outlineToPath(outline) {
50
+ if (outline.length === 0) {
51
+ return '';
52
+ }
53
+ const [first, ...rest] = outline;
54
+ return `M ${first[0]} ${first[1]} ${rest.map((point) => `L ${point[0]} ${point[1]}`).join(' ')} Z`;
55
+ }
56
+ export function freehandOutline(element) {
57
+ const points = element.points.map(([x, y, pressure]) => [x, y, pressure ?? 0.5]);
58
+ const outline = getStroke(points, {
59
+ size: element.strokeWidth * 4 + 2,
60
+ thinning: 0.6,
61
+ smoothing: 0.5,
62
+ streamline: 0.5,
63
+ // A pressure of exactly 0.5 on every point is a mouse; the stroke gets its taper from speed.
64
+ simulatePressure: element.points.every((point) => point[2] === undefined)
65
+ });
66
+ return outlineToPath(outline);
67
+ }
68
+ function linesToPath(segments) {
69
+ return segments.map(([from, to]) => `M ${from.x} ${from.y} L ${to.x} ${to.y}`).join(' ');
70
+ }
71
+ /*
72
+ * One element as paths in its own frame: the origin is the element's own (x, y), so the painter
73
+ * translates and turns, and a path can be cached until the element's shape itself changes.
74
+ */
75
+ export function pathsOfElement(element) {
76
+ if (element.kind === 'text') {
77
+ return [];
78
+ }
79
+ // A note is a sheet of paper, not a drawn shape: no wobble, and an edge of its own paper color.
80
+ if (element.kind === 'note') {
81
+ const d = roundedRectPath(element.w, element.h, NOTE_RADIUS);
82
+ return [
83
+ { d, role: 'fill', strokeWidth: 0, dash: null },
84
+ { d, role: 'stroke', strokeWidth: element.strokeWidth, dash: null }
85
+ ];
86
+ }
87
+ const options = optionsOf(element);
88
+ const dash = dashOf(element);
89
+ if (element.kind === 'freehand') {
90
+ return [{ d: freehandOutline(element), role: 'ink', strokeWidth: 0, dash: null }];
91
+ }
92
+ const generator = drawingGenerator();
93
+ const drawable = (() => {
94
+ switch (element.kind) {
95
+ case 'rect':
96
+ return element.radius
97
+ ? generator.path(roundedRectPath(element.w, element.h, element.radius), options)
98
+ : generator.rectangle(0, 0, element.w, element.h, options);
99
+ case 'diamond':
100
+ return generator.polygon([
101
+ [element.w / 2, 0],
102
+ [element.w, element.h / 2],
103
+ [element.w / 2, element.h],
104
+ [0, element.h / 2]
105
+ ], options);
106
+ case 'ellipse':
107
+ return generator.ellipse(element.w / 2, element.h / 2, element.w, element.h, options);
108
+ case 'line':
109
+ return generator.linearPath(element.points.map(([x, y]) => [x, y]), options);
110
+ }
111
+ })();
112
+ const paths = generator.toPaths(drawable).map((path) => ({
113
+ d: path.d,
114
+ role: path.fill === FILL ? 'fill' : path.stroke === FILL ? 'fill' : 'stroke',
115
+ strokeWidth: path.strokeWidth,
116
+ dash: path.stroke === STROKE ? dash : null
117
+ }));
118
+ if (element.kind !== 'line') {
119
+ return paths;
120
+ }
121
+ const points = element.points.map(([x, y]) => ({ x, y }));
122
+ const size = arrowHeadSize(element.strokeWidth);
123
+ const heads = [
124
+ ...(element.arrowEnd ? arrowHead(points.at(-1), points.at(-2), size) : []),
125
+ ...(element.arrowStart ? arrowHead(points[0], points[1], size) : [])
126
+ ];
127
+ // The head is always solid: a dashed arrow still points at something.
128
+ return heads.length === 0 ? paths : [...paths, { d: linesToPath(heads), role: 'stroke', strokeWidth: element.strokeWidth, dash: null }];
129
+ }