@phun-ky/arclace 0.0.0-stage → 0.3.0

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/src/types.ts ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * A side of an element's bounding box.
3
+ */
4
+ export type ArcSideType = 'top' | 'right' | 'bottom' | 'left';
5
+
6
+ /**
7
+ * A side, or `'auto'` to let Arclace pick the side that faces the
8
+ * other element.
9
+ */
10
+ export type ArcSideOptionType = ArcSideType | 'auto';
11
+
12
+ /**
13
+ * How the line between two elements is drawn.
14
+ *
15
+ * - `bezier`: a smooth cubic curve (default)
16
+ * - `straight`: a straight line
17
+ * - `orthogonal`: horizontal and vertical segments with rounded corners
18
+ */
19
+ export type ArcPathType = 'bezier' | 'straight' | 'orthogonal';
20
+
21
+ /**
22
+ * Where to draw arrow heads.
23
+ */
24
+ export type ArcArrowType = 'none' | 'start' | 'end' | 'both';
25
+
26
+ /**
27
+ * An element, or a CSS selector that resolves to one.
28
+ */
29
+ export type ArcElementTargetType = Element | string;
30
+
31
+ export interface ArcPointInterface {
32
+ x: number;
33
+ y: number;
34
+ }
35
+
36
+ export interface ArcRectInterface {
37
+ left: number;
38
+ top: number;
39
+ right: number;
40
+ bottom: number;
41
+ width: number;
42
+ height: number;
43
+ }
44
+
45
+ /**
46
+ * Options for a single connection.
47
+ */
48
+ export type ArcConnectionOptionsType = {
49
+ /**
50
+ * A unique id for the connection. Generated when omitted.
51
+ */
52
+ id?: string;
53
+
54
+ /**
55
+ * How the line is drawn. Defaults to `'bezier'`.
56
+ */
57
+ type?: ArcPathType;
58
+
59
+ /**
60
+ * The side of the start element the line leaves from. Defaults to `'auto'`.
61
+ */
62
+ startSide?: ArcSideOptionType;
63
+
64
+ /**
65
+ * The side of the end element the line arrives at. Defaults to `'auto'`.
66
+ */
67
+ endSide?: ArcSideOptionType;
68
+
69
+ /**
70
+ * Where to draw arrow heads. Defaults to `'none'`.
71
+ */
72
+ arrow?: ArcArrowType;
73
+
74
+ /**
75
+ * Text drawn at the middle of the line.
76
+ */
77
+ label?: string;
78
+
79
+ /**
80
+ * Line color. Any CSS color. Defaults to `currentColor` of the container,
81
+ * or `--arc-color` when the stylesheet is loaded.
82
+ */
83
+ color?: string;
84
+
85
+ /**
86
+ * Line width in pixels. Defaults to `2`.
87
+ */
88
+ strokeWidth?: number;
89
+
90
+ /**
91
+ * Draw a dashed line. Defaults to `false`.
92
+ */
93
+ dashed?: boolean;
94
+
95
+ /**
96
+ * Animate the dashes from start to end. Implies `dashed`. Requires the
97
+ * stylesheet. Defaults to `false`.
98
+ */
99
+ animated?: boolean;
100
+
101
+ /**
102
+ * Draw a dot where the line touches each element. Defaults to `false`.
103
+ */
104
+ anchors?: boolean;
105
+
106
+ /**
107
+ * Extra class names added to the connection's `<g>` element.
108
+ */
109
+ className?: string;
110
+
111
+ /**
112
+ * Distance in pixels between the element's edge and the line's end.
113
+ * Defaults to `0`.
114
+ */
115
+ gap?: number;
116
+
117
+ /**
118
+ * When several connections share the same side of an element, spread their
119
+ * end points along that side instead of stacking them in the middle.
120
+ * Defaults to `true`.
121
+ */
122
+ spread?: boolean;
123
+
124
+ /**
125
+ * Preferred distance in pixels between spread end points. Shrinks to fit
126
+ * the side. Defaults to `16`.
127
+ */
128
+ spacing?: number;
129
+
130
+ /**
131
+ * `bezier` only: multiplies how far the curve bulges out from the
132
+ * elements. Defaults to `1`.
133
+ */
134
+ curvature?: number;
135
+
136
+ /**
137
+ * `orthogonal` only: corner radius in pixels. Use `0` for sharp corners.
138
+ * Defaults to `8`.
139
+ */
140
+ radius?: number;
141
+
142
+ /**
143
+ * `orthogonal` only: how far in pixels the line travels straight out of an
144
+ * element before it turns. Defaults to `20`.
145
+ */
146
+ offset?: number;
147
+ };
148
+
149
+ /**
150
+ * A connection between two elements, used with
151
+ * {@link Arclace.connectAll} and {@link createConnections}.
152
+ */
153
+ export type ArcConnectionDefinitionType = ArcConnectionOptionsType & {
154
+ startElement: ArcElementTargetType;
155
+ endElement: ArcElementTargetType;
156
+ };
157
+
158
+ /**
159
+ * Options for a {@link Arclace} instance.
160
+ */
161
+ export type ArcOptionsType = {
162
+ /**
163
+ * The element the SVG overlay is added to. All connected elements should
164
+ * be inside it. Defaults to `document.body`.
165
+ */
166
+ container?: ArcElementTargetType;
167
+
168
+ /**
169
+ * Keep lines in sync with the page.
170
+ *
171
+ * - `true`: redraw on window resize, scroll, element resize and DOM or
172
+ * style changes inside the container (default)
173
+ * - `'frame'`: redraw on every animation frame, for CSS animations and
174
+ * transitions
175
+ * - `false`: only redraw when you call `update()`
176
+ */
177
+ autoUpdate?: boolean | 'frame';
178
+
179
+ /**
180
+ * Default options for every connection made by this instance.
181
+ */
182
+ defaults?: ArcConnectionOptionsType;
183
+
184
+ /**
185
+ * Extra class names added to the SVG overlay.
186
+ */
187
+ className?: string;
188
+ };
189
+
190
+ /**
191
+ * The computed geometry of a connection after the last update.
192
+ */
193
+ export type ArcGeometryType = {
194
+ start: ArcPointInterface;
195
+ end: ArcPointInterface;
196
+ startSide: ArcSideType;
197
+ endSide: ArcSideType;
198
+ labelPoint: ArcPointInterface;
199
+ d: string;
200
+ };
@@ -0,0 +1,61 @@
1
+ import type {
2
+ ArcPointInterface,
3
+ ArcRectInterface,
4
+ ArcSideType
5
+ } from '../types';
6
+
7
+ /**
8
+ * Unit vectors pointing away from each side of a box.
9
+ */
10
+ export const NORMALS: Readonly<
11
+ Record<ArcSideType, Readonly<ArcPointInterface>>
12
+ > = Object.freeze({
13
+ top: Object.freeze({ x: 0, y: -1 }),
14
+ right: Object.freeze({ x: 1, y: 0 }),
15
+ bottom: Object.freeze({ x: 0, y: 1 }),
16
+ left: Object.freeze({ x: -1, y: 0 })
17
+ });
18
+
19
+ export const OPPOSITE: Readonly<Record<ArcSideType, ArcSideType>> =
20
+ Object.freeze({
21
+ top: 'bottom',
22
+ right: 'left',
23
+ bottom: 'top',
24
+ left: 'right'
25
+ });
26
+
27
+ export const isHorizontalSide = (side: ArcSideType): boolean =>
28
+ side === 'left' || side === 'right';
29
+
30
+ export const center = (rect: ArcRectInterface): ArcPointInterface => ({
31
+ x: rect.left + rect.width / 2,
32
+ y: rect.top + rect.height / 2
33
+ });
34
+
35
+ export const add = (
36
+ a: ArcPointInterface,
37
+ b: ArcPointInterface,
38
+ factor = 1
39
+ ): ArcPointInterface => ({ x: a.x + b.x * factor, y: a.y + b.y * factor });
40
+
41
+ /**
42
+ * Euclidean distance between two points.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * distance({ x: 0, y: 0 }, { x: 3, y: 4 }); // 5
47
+ * ```
48
+ */
49
+ export const distance = (a: ArcPointInterface, b: ArcPointInterface): number =>
50
+ Math.hypot(b.x - a.x, b.y - a.y);
51
+
52
+ /**
53
+ * Rounds to two decimals to keep path data short.
54
+ */
55
+ export const round = (value: number): number => Math.round(value * 100) / 100;
56
+
57
+ /**
58
+ * Formats a point for use in SVG path data.
59
+ */
60
+ export const fmt = (point: ArcPointInterface): string =>
61
+ `${round(point.x)} ${round(point.y)}`;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Generates a unique ID consisting of an underscore followed by a random alphanumeric string.
3
+ *
4
+ * @returns {string} - A unique ID.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * // Generate a unique ID
9
+ * const id = uniqueID();
10
+ * console.log(id); // Example output: "_abc123def"
11
+ * ```
12
+ */
13
+ export const uniqueID = (): string =>
14
+ '_' + Math.random().toString(36).substring(2, 11);
@@ -0,0 +1,64 @@
1
+ import type { ArcRectInterface } from '../types';
2
+
3
+ /**
4
+ * Where the SVG overlay is on screen, and how much it is scaled by CSS
5
+ * transforms on its ancestors.
6
+ */
7
+ export type ArcOriginType = {
8
+ left: number;
9
+ top: number;
10
+ scaleX: number;
11
+ scaleY: number;
12
+ };
13
+
14
+ /**
15
+ * Measures the overlay so screen coordinates can be converted to coordinates
16
+ * inside it. Because the overlay is measured directly, this works no matter
17
+ * how the container is positioned, scrolled or scaled.
18
+ */
19
+ export const getOrigin = (svg: SVGSVGElement): ArcOriginType => {
20
+ const rect = svg.getBoundingClientRect();
21
+ const { clientWidth, clientHeight } = svg;
22
+
23
+ return {
24
+ left: rect.left,
25
+ top: rect.top,
26
+ scaleX: clientWidth > 0 && rect.width > 0 ? rect.width / clientWidth : 1,
27
+ scaleY: clientHeight > 0 && rect.height > 0 ? rect.height / clientHeight : 1
28
+ };
29
+ };
30
+
31
+ /**
32
+ * Measures an element in the overlay's coordinate system.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const rect = getLocalRect(element, getOrigin(svg));
37
+ * ```
38
+ */
39
+ export const getLocalRect = (
40
+ el: Element,
41
+ origin: ArcOriginType
42
+ ): ArcRectInterface => {
43
+ const rect = el.getBoundingClientRect();
44
+ const left = (rect.left - origin.left) / origin.scaleX;
45
+ const top = (rect.top - origin.top) / origin.scaleY;
46
+ const width = rect.width / origin.scaleX;
47
+ const height = rect.height / origin.scaleY;
48
+
49
+ return {
50
+ left,
51
+ top,
52
+ width,
53
+ height,
54
+ right: left + width,
55
+ bottom: top + height
56
+ };
57
+ };
58
+
59
+ /**
60
+ * Whether an element is in the document and has a layout box, i.e. is not
61
+ * `display: none`.
62
+ */
63
+ export const isRendered = (el: Element): boolean =>
64
+ el.isConnected && el.getClientRects().length > 0;
@@ -0,0 +1,345 @@
1
+ import type { ArcPointInterface, ArcSideType } from '../types';
2
+
3
+ import {
4
+ add,
5
+ distance,
6
+ fmt,
7
+ isHorizontalSide,
8
+ NORMALS,
9
+ OPPOSITE
10
+ } from './geometry';
11
+ import { assertNumber, assertOneOf, assertPoint, SIDES } from './validate';
12
+
13
+ export type ArcPathResultType = {
14
+ /**
15
+ * SVG path data.
16
+ */
17
+ d: string;
18
+
19
+ /**
20
+ * The middle of the path, used to place labels.
21
+ */
22
+ labelPoint: ArcPointInterface;
23
+ };
24
+
25
+ /**
26
+ * Normalizes a distance to a range from 0 to 1, based on max distance.
27
+ *
28
+ * @param distance - The actual distance.
29
+ * @param maxDistance - The distance treated as 100% (1.0).
30
+ * @returns Normalized value between 0 and 1.
31
+ */
32
+ export const normalizeDistance = (
33
+ distance: number,
34
+ maxDistance: number = 1000
35
+ ): number => Math.min(distance / maxDistance, 1);
36
+
37
+ /**
38
+ * Maps a normalized value [0, 1] to a value between min and max.
39
+ *
40
+ * @param norm - Normalized value (0 to 1).
41
+ * @param min - Minimum output value.
42
+ * @param max - Maximum output value.
43
+ * @returns Value between min and max.
44
+ */
45
+ export const lerp = (norm: number, min: number, max: number): number =>
46
+ min + (max - min) * norm;
47
+
48
+ /**
49
+ * Calculates a curve multiplier based on distance. Short lines get a
50
+ * relatively larger bulge than long lines.
51
+ *
52
+ * @param distance - Distance between points.
53
+ * @param min - Minimum multiplier.
54
+ * @param max - Maximum multiplier.
55
+ * @param maxDistance - Distance at which max multiplier is used.
56
+ * @returns A multiplier between min and max.
57
+ */
58
+ export const curveMultiplierFromDistance = (
59
+ distance: number,
60
+ min: number = 1.1,
61
+ max: number = 3.5,
62
+ maxDistance: number = 1000
63
+ ): number => lerp(normalizeDistance(distance, maxDistance), min, max);
64
+
65
+ /**
66
+ * Checks the ends of a path, so a bad side or point fails with a clear error
67
+ * instead of path data with `NaN` in it.
68
+ */
69
+ const checkEnds = (
70
+ start: unknown,
71
+ startSide: unknown,
72
+ end: unknown,
73
+ endSide: unknown
74
+ ): void => {
75
+ assertPoint(start, 'start');
76
+ assertOneOf(startSide, SIDES, 'startSide');
77
+ assertPoint(end, 'end');
78
+ assertOneOf(endSide, SIDES, 'endSide');
79
+ };
80
+
81
+ /**
82
+ * A straight line between two points.
83
+ *
84
+ * @throws {TypeError} When a point doesn't have finite `x` and `y`.
85
+ * @example
86
+ * ```ts
87
+ * straightPath({ x: 0, y: 0 }, { x: 100, y: 0 }).d; // 'M 0 0 L 100 0'
88
+ * ```
89
+ */
90
+ export const straightPath = (
91
+ start: ArcPointInterface,
92
+ end: ArcPointInterface
93
+ ): ArcPathResultType => {
94
+ assertPoint(start, 'start');
95
+ assertPoint(end, 'end');
96
+
97
+ return {
98
+ d: `M ${fmt(start)} L ${fmt(end)}`,
99
+ labelPoint: { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 }
100
+ };
101
+ };
102
+
103
+ /**
104
+ * A cubic bezier curve that leaves `start` and arrives at `end`
105
+ * perpendicular to their sides.
106
+ *
107
+ * @throws {TypeError} When a point or `curvature` isn't finite.
108
+ * @throws {RangeError} When a side isn't `top`, `right`, `bottom` or `left`.
109
+ * @example
110
+ * ```ts
111
+ * bezierPath({ x: 0, y: 0 }, 'right', { x: 200, y: 100 }, 'left').d;
112
+ * ```
113
+ */
114
+ export const bezierPath = (
115
+ start: ArcPointInterface,
116
+ startSide: ArcSideType,
117
+ end: ArcPointInterface,
118
+ endSide: ArcSideType,
119
+ curvature = 1
120
+ ): ArcPathResultType => {
121
+ checkEnds(start, startSide, end, endSide);
122
+ assertNumber(curvature, 'curvature');
123
+
124
+ const length = distance(start, end);
125
+ const bulge = (length / curveMultiplierFromDistance(length)) * curvature;
126
+ const c1 = add(start, NORMALS[startSide], bulge);
127
+ const c2 = add(end, NORMALS[endSide], bulge);
128
+
129
+ return {
130
+ d: `M ${fmt(start)} C ${fmt(c1)}, ${fmt(c2)}, ${fmt(end)}`,
131
+ // Point on the curve at t = 0.5
132
+ labelPoint: {
133
+ x: (start.x + 3 * c1.x + 3 * c2.x + end.x) / 8,
134
+ y: (start.y + 3 * c1.y + 3 * c2.y + end.y) / 8
135
+ }
136
+ };
137
+ };
138
+
139
+ /**
140
+ * Removes repeated points and points in the middle of a straight segment.
141
+ */
142
+ export const simplifyPolyline = (
143
+ points: ArcPointInterface[]
144
+ ): ArcPointInterface[] => {
145
+ const unique = points.filter(
146
+ (point, i) => i === 0 || distance(point, points[i - 1]) > 0.01
147
+ );
148
+
149
+ return unique.filter((point, i) => {
150
+ if (i === 0 || i === unique.length - 1) return true;
151
+
152
+ const prev = unique[i - 1];
153
+ const next = unique[i + 1];
154
+ const cross =
155
+ (point.x - prev.x) * (next.y - prev.y) -
156
+ (point.y - prev.y) * (next.x - prev.x);
157
+
158
+ return Math.abs(cross) > 0.01;
159
+ });
160
+ };
161
+
162
+ /**
163
+ * Turns a polyline into path data, rounding each corner with a quadratic
164
+ * curve. The radius shrinks on short segments so corners never overlap.
165
+ */
166
+ export const roundedPolyline = (
167
+ points: ArcPointInterface[],
168
+ radius: number
169
+ ): string => {
170
+ if (points.length === 0) return '';
171
+
172
+ const towards = (
173
+ from: ArcPointInterface,
174
+ to: ArcPointInterface,
175
+ length: number
176
+ ): ArcPointInterface => {
177
+ const total = distance(from, to);
178
+
179
+ return {
180
+ x: from.x + ((to.x - from.x) / total) * length,
181
+ y: from.y + ((to.y - from.y) / total) * length
182
+ };
183
+ };
184
+ const segments = [`M ${fmt(points[0])}`];
185
+
186
+ for (let i = 1; i < points.length - 1; i++) {
187
+ const prev = points[i - 1];
188
+ const corner = points[i];
189
+ const next = points[i + 1];
190
+ const r = Math.min(
191
+ radius,
192
+ distance(prev, corner) / 2,
193
+ distance(corner, next) / 2
194
+ );
195
+
196
+ if (r <= 0) {
197
+ segments.push(`L ${fmt(corner)}`);
198
+ continue;
199
+ }
200
+
201
+ segments.push(
202
+ `L ${fmt(towards(corner, prev, r))}`,
203
+ `Q ${fmt(corner)}, ${fmt(towards(corner, next, r))}`
204
+ );
205
+ }
206
+
207
+ if (points.length > 1) segments.push(`L ${fmt(points[points.length - 1])}`);
208
+
209
+ return segments.join(' ');
210
+ };
211
+
212
+ /**
213
+ * The point halfway along a polyline.
214
+ */
215
+ export const polylineMidpoint = (
216
+ points: ArcPointInterface[]
217
+ ): ArcPointInterface => {
218
+ const lengths = points.slice(1).map((point, i) => distance(points[i], point));
219
+
220
+ let remaining = lengths.reduce((sum, length) => sum + length, 0) / 2;
221
+
222
+ for (let i = 0; i < lengths.length; i++) {
223
+ if (remaining <= lengths[i] && lengths[i] > 0) {
224
+ const t = remaining / lengths[i];
225
+
226
+ return {
227
+ x: points[i].x + (points[i + 1].x - points[i].x) * t,
228
+ y: points[i].y + (points[i + 1].y - points[i].y) * t
229
+ };
230
+ }
231
+
232
+ remaining -= lengths[i];
233
+ }
234
+
235
+ return { ...points[0] };
236
+ };
237
+
238
+ // Swapping x and y turns vertical sides into horizontal ones, so only the
239
+ // horizontal case has to be routed by hand.
240
+ const SWAPPED_SIDE: Readonly<Record<ArcSideType, ArcSideType>> = Object.freeze({
241
+ top: 'left',
242
+ bottom: 'right',
243
+ left: 'top',
244
+ right: 'bottom'
245
+ });
246
+ const swap = (point: ArcPointInterface): ArcPointInterface => ({
247
+ x: point.y,
248
+ y: point.x
249
+ });
250
+
251
+ /**
252
+ * Routes a line from `start` to `end` using only horizontal and vertical
253
+ * segments. The line leaves and arrives perpendicular to the given sides,
254
+ * travelling at least `offset` pixels straight out before turning back.
255
+ *
256
+ * @returns The corner points of the route, including `start` and `end`.
257
+ */
258
+ export const routeOrthogonal = (
259
+ start: ArcPointInterface,
260
+ startSide: ArcSideType,
261
+ end: ArcPointInterface,
262
+ endSide: ArcSideType,
263
+ offset = 20
264
+ ): ArcPointInterface[] => {
265
+ if (!isHorizontalSide(startSide)) {
266
+ return routeOrthogonal(
267
+ swap(start),
268
+ SWAPPED_SIDE[startSide],
269
+ swap(end),
270
+ SWAPPED_SIDE[endSide],
271
+ offset
272
+ ).map(swap);
273
+ }
274
+
275
+ const n1 = NORMALS[startSide];
276
+ const n2 = NORMALS[endSide];
277
+ const s1 = add(start, n1, offset);
278
+ const s2 = add(end, n2, offset);
279
+
280
+ if (isHorizontalSide(endSide)) {
281
+ if (endSide === OPPOSITE[startSide]) {
282
+ // Facing each other with room in between: turn halfway
283
+ if ((s2.x - s1.x) * n1.x >= 0) {
284
+ const midX = (start.x + end.x) / 2;
285
+
286
+ return [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
287
+ }
288
+
289
+ // Facing away from each other: step out, cross over halfway, step in
290
+ const midY = (s1.y + s2.y) / 2;
291
+
292
+ return [start, s1, { x: s1.x, y: midY }, { x: s2.x, y: midY }, s2, end];
293
+ }
294
+
295
+ // Same side: go around the outside of both
296
+ const x = n1.x > 0 ? Math.max(s1.x, s2.x) : Math.min(s1.x, s2.x);
297
+
298
+ return [start, { x, y: start.y }, { x, y: end.y }, end];
299
+ }
300
+
301
+ // One horizontal and one vertical side: a single corner if it lies in
302
+ // front of both sides, otherwise step out of both and meet
303
+ const corner = { x: end.x, y: start.y };
304
+
305
+ if ((corner.x - start.x) * n1.x > 0 && (corner.y - end.y) * n2.y > 0) {
306
+ return [start, corner, end];
307
+ }
308
+
309
+ return [start, s1, { x: s1.x, y: s2.y }, s2, end];
310
+ };
311
+
312
+ /**
313
+ * An orthogonal line with rounded corners.
314
+ *
315
+ * @throws {TypeError} When a point, `radius` or `offset` isn't finite.
316
+ * @throws {RangeError} When a side isn't `top`, `right`, `bottom` or `left`,
317
+ * or `radius` or `offset` is negative.
318
+ * @example
319
+ * ```ts
320
+ * orthogonalPath({ x: 0, y: 0 }, 'right', { x: 200, y: 100 }, 'left', {
321
+ * radius: 8,
322
+ * offset: 20
323
+ * }).d;
324
+ * ```
325
+ */
326
+ export const orthogonalPath = (
327
+ start: ArcPointInterface,
328
+ startSide: ArcSideType,
329
+ end: ArcPointInterface,
330
+ endSide: ArcSideType,
331
+ { radius = 8, offset = 20 }: { radius?: number; offset?: number } = {}
332
+ ): ArcPathResultType => {
333
+ checkEnds(start, startSide, end, endSide);
334
+ assertNumber(radius, 'radius', 0);
335
+ assertNumber(offset, 'offset', 0);
336
+
337
+ const points = simplifyPolyline(
338
+ routeOrthogonal(start, startSide, end, endSide, offset)
339
+ );
340
+
341
+ return {
342
+ d: roundedPolyline(points, radius),
343
+ labelPoint: polylineMidpoint(points)
344
+ };
345
+ };