@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.
@@ -0,0 +1,455 @@
1
+ import type { Arclace } from './Arclace';
2
+ import { ArclaceError } from './errors';
3
+ import type {
4
+ ArcConnectionOptionsType,
5
+ ArcGeometryType,
6
+ ArcPointInterface,
7
+ ArcSideType
8
+ } from './types';
9
+ import { add, distance, NORMALS } from './utils/geometry';
10
+ import { uniqueID } from './utils/id';
11
+ import {
12
+ bezierPath,
13
+ type ArcPathResultType,
14
+ orthogonalPath,
15
+ straightPath
16
+ } from './utils/paths';
17
+ import { createSVGElement, setAttributes } from './utils/svg';
18
+ import { validateConnectionOptions } from './utils/validate';
19
+
20
+ /**
21
+ * Connection options with every default filled in. `label`, `color` and
22
+ * `className` have no default.
23
+ */
24
+ export type ArcResolvedConnectionOptionsType = Required<
25
+ Omit<ArcConnectionOptionsType, 'id' | 'label' | 'color' | 'className'>
26
+ > &
27
+ Pick<ArcConnectionOptionsType, 'label' | 'color' | 'className'> & {
28
+ id: string;
29
+ };
30
+
31
+ /**
32
+ * Options every connection falls back to. Frozen: set your own defaults with
33
+ * the `defaults` option of {@link Arclace} instead.
34
+ */
35
+ export const DEFAULT_CONNECTION_OPTIONS: Readonly<
36
+ Required<
37
+ Omit<ArcConnectionOptionsType, 'id' | 'label' | 'color' | 'className'>
38
+ >
39
+ > = Object.freeze({
40
+ type: 'bezier',
41
+ startSide: 'auto',
42
+ endSide: 'auto',
43
+ arrow: 'none',
44
+ strokeWidth: 2,
45
+ dashed: false,
46
+ animated: false,
47
+ anchors: false,
48
+ gap: 0,
49
+ spread: true,
50
+ spacing: 16,
51
+ curvature: 1,
52
+ radius: 8,
53
+ offset: 20
54
+ });
55
+
56
+ /**
57
+ * Drops options set to `undefined`, so they fall back to the defaults instead
58
+ * of replacing them.
59
+ */
60
+ const definedOnly = (
61
+ options: ArcConnectionOptionsType
62
+ ): ArcConnectionOptionsType =>
63
+ Object.fromEntries(
64
+ Object.entries(options).filter(([, value]) => value !== undefined)
65
+ );
66
+ // Arrow length in multiples of the stroke width
67
+ const ARROW_SIZE = 4;
68
+
69
+ type ArcConnectionParamsType = {
70
+ id: string;
71
+ startElement: Element;
72
+ endElement: Element;
73
+ options: ArcConnectionOptionsType;
74
+ defaults?: ArcConnectionOptionsType;
75
+ owner: Arclace;
76
+ };
77
+
78
+ /**
79
+ * A line between two elements. Created with {@link Arclace.connect} or
80
+ * {@link Arclace.connectAll}, not with `new`.
81
+ *
82
+ * Each connection renders as:
83
+ *
84
+ * ```html
85
+ * <g class="arc-connection arc-bezier">
86
+ * <marker class="arc-marker">…</marker> <!-- when `arrow` is set -->
87
+ * <path class="arc-path" />
88
+ * <text class="arc-label">…</text> <!-- when `label` is set -->
89
+ * <circle class="arc-anchor arc-anchor-start" /> <!-- when `anchors` is set -->
90
+ * <circle class="arc-anchor arc-anchor-end" />
91
+ * </g>
92
+ * ```
93
+ *
94
+ * The line, arrows and anchors use `currentColor`, so setting `color` on
95
+ * `.arc-connection` colors all of them.
96
+ */
97
+ export class Connection {
98
+ readonly id: string;
99
+ readonly startElement: Element;
100
+ readonly endElement: Element;
101
+
102
+ /**
103
+ * The `<g>` element holding everything this connection draws.
104
+ */
105
+ readonly element: SVGGElement;
106
+
107
+ /**
108
+ * The `<path>` element of the line.
109
+ */
110
+ readonly path: SVGPathElement;
111
+
112
+ #geometry: ArcGeometryType | null = null;
113
+ #removed = false;
114
+ #owner: Arclace;
115
+ #options: ArcConnectionOptionsType;
116
+ #defaults: ArcConnectionOptionsType;
117
+ #marker: SVGMarkerElement | null = null;
118
+ #label: SVGTextElement | null = null;
119
+ #anchors: [SVGCircleElement, SVGCircleElement] | null = null;
120
+
121
+ private constructor(params: ArcConnectionParamsType) {
122
+ const {
123
+ id,
124
+ startElement,
125
+ endElement,
126
+ options,
127
+ defaults = {},
128
+ owner
129
+ } = params;
130
+
131
+ this.id = id;
132
+ this.startElement = startElement;
133
+ this.endElement = endElement;
134
+ this.#owner = owner;
135
+ this.#options = { ...options };
136
+ this.#defaults = defaults;
137
+ this.element = createSVGElement('g', { 'data-arc-id': id });
138
+ this.path = createSVGElement('path', {
139
+ class: 'arc-path',
140
+ fill: 'none',
141
+ stroke: 'currentColor'
142
+ });
143
+ this.element.appendChild(this.path);
144
+ this.#applyOptions();
145
+ }
146
+
147
+ /**
148
+ * Creates a connection for its owner. Options must already be validated.
149
+ *
150
+ * @internal
151
+ */
152
+ static _create(params: ArcConnectionParamsType): Connection {
153
+ return new Connection(params);
154
+ }
155
+
156
+ /**
157
+ * The geometry from the last update, or `null` when the connection is
158
+ * hidden because one of its elements is not rendered.
159
+ */
160
+ get geometry(): Readonly<ArcGeometryType> | null {
161
+ return this.#geometry;
162
+ }
163
+
164
+ /**
165
+ * The connection's options merged with the instance defaults.
166
+ */
167
+ get options(): Readonly<ArcResolvedConnectionOptionsType> {
168
+ return {
169
+ ...DEFAULT_CONNECTION_OPTIONS,
170
+ ...definedOnly(this.#defaults),
171
+ ...definedOnly(this.#options),
172
+ id: this.id
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Changes options and redraws.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * connection.setOptions({ type: 'orthogonal', arrow: 'end' });
182
+ * ```
183
+ * @throws {TypeError} When an option has the wrong type, or `id` is set.
184
+ * @throws {RangeError} When an option is out of range.
185
+ * @throws {ArclaceError} When the connection has been removed.
186
+ */
187
+ setOptions(options: Omit<ArcConnectionOptionsType, 'id'>): this {
188
+ if (this.#removed) {
189
+ throw new ArclaceError(`connection "${this.id}" has been removed`);
190
+ }
191
+
192
+ validateConnectionOptions(options);
193
+
194
+ if ((options as ArcConnectionOptionsType).id !== undefined) {
195
+ throw new TypeError('arclace: setOptions() cannot change the id');
196
+ }
197
+
198
+ this.#options = { ...this.#options, ...options };
199
+ this.#applyOptions();
200
+ this.#owner.update();
201
+
202
+ return this;
203
+ }
204
+
205
+ /**
206
+ * Redraws every connection of the owning instance.
207
+ */
208
+ update(): void {
209
+ this.#owner.update();
210
+ }
211
+
212
+ /**
213
+ * Removes this connection.
214
+ */
215
+ remove(): void {
216
+ this.#owner.disconnect(this);
217
+ }
218
+
219
+ /**
220
+ * Draws the connection between two attachment points.
221
+ *
222
+ * @internal
223
+ */
224
+ _draw(
225
+ start: ArcPointInterface,
226
+ startSide: ArcSideType,
227
+ end: ArcPointInterface,
228
+ endSide: ArcSideType
229
+ ): void {
230
+ const { arrow, strokeWidth } = this.options;
231
+ const arrowLength = ARROW_SIZE * strokeWidth;
232
+ // Shorten the line so arrow tips, not the line's end caps, touch the
233
+ // elements
234
+ const pathStart =
235
+ arrow === 'start' || arrow === 'both'
236
+ ? this.#pullBack(start, startSide, end, arrowLength)
237
+ : start;
238
+ const pathEnd =
239
+ arrow === 'end' || arrow === 'both'
240
+ ? this.#pullBack(end, endSide, start, arrowLength)
241
+ : end;
242
+ const { d, labelPoint } = this.#buildPath(
243
+ pathStart,
244
+ startSide,
245
+ pathEnd,
246
+ endSide
247
+ );
248
+
249
+ this.#geometry = Object.freeze({
250
+ start,
251
+ end,
252
+ startSide,
253
+ endSide,
254
+ labelPoint,
255
+ d
256
+ });
257
+
258
+ this.element.removeAttribute('display');
259
+ setAttributes(this.element, {
260
+ 'data-start-side': startSide,
261
+ 'data-end-side': endSide
262
+ });
263
+ this.path.setAttribute('d', d);
264
+
265
+ if (this.#label) setAttributes(this.#label, { ...labelPoint });
266
+
267
+ if (this.#anchors) {
268
+ setAttributes(this.#anchors[0], { cx: start.x, cy: start.y });
269
+ setAttributes(this.#anchors[1], { cx: end.x, cy: end.y });
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Hides the connection.
275
+ *
276
+ * @internal
277
+ */
278
+ _hide(): void {
279
+ this.#geometry = null;
280
+ this.element.setAttribute('display', 'none');
281
+ }
282
+
283
+ /**
284
+ * Removes the connection's elements from the overlay.
285
+ *
286
+ * @internal
287
+ */
288
+ _dispose(): void {
289
+ this.#removed = true;
290
+ this.element.remove();
291
+ }
292
+
293
+ #buildPath(
294
+ start: ArcPointInterface,
295
+ startSide: ArcSideType,
296
+ end: ArcPointInterface,
297
+ endSide: ArcSideType
298
+ ): ArcPathResultType {
299
+ const { type, curvature, radius, offset } = this.options;
300
+
301
+ if (type === 'straight') return straightPath(start, end);
302
+
303
+ if (type === 'orthogonal') {
304
+ return orthogonalPath(start, startSide, end, endSide, {
305
+ radius,
306
+ offset
307
+ });
308
+ }
309
+
310
+ return bezierPath(start, startSide, end, endSide, curvature);
311
+ }
312
+
313
+ #pullBack(
314
+ point: ArcPointInterface,
315
+ side: ArcSideType,
316
+ other: ArcPointInterface,
317
+ length: number
318
+ ): ArcPointInterface {
319
+ const total = distance(point, other);
320
+ const amount = Math.min(length, total / 3);
321
+
322
+ if (this.options.type !== 'straight') {
323
+ return add(point, NORMALS[side], amount);
324
+ }
325
+
326
+ if (total === 0) return point;
327
+
328
+ return {
329
+ x: point.x + ((other.x - point.x) / total) * amount,
330
+ y: point.y + ((other.y - point.y) / total) * amount
331
+ };
332
+ }
333
+
334
+ #applyOptions(): void {
335
+ const {
336
+ type,
337
+ arrow,
338
+ label,
339
+ color,
340
+ strokeWidth,
341
+ dashed,
342
+ animated,
343
+ anchors,
344
+ className
345
+ } = this.options;
346
+ const classes = ['arc-connection', `arc-${type}`];
347
+
348
+ if (dashed || animated) classes.push('arc-dashed');
349
+
350
+ if (animated) classes.push('arc-animated');
351
+
352
+ if (className) classes.push(...className.split(/\s+/).filter(Boolean));
353
+
354
+ setAttributes(this.element, {
355
+ class: classes.join(' '),
356
+ 'data-type': type
357
+ });
358
+ // Inline so it wins over the stylesheet's --arc-color
359
+ this.element.style.color = color ?? '';
360
+
361
+ setAttributes(this.path, {
362
+ 'stroke-width': strokeWidth,
363
+ 'stroke-dasharray': dashed || animated ? '6 6' : null
364
+ });
365
+
366
+ this.#applyArrow(arrow);
367
+ this.#applyLabel(label);
368
+ this.#applyAnchors(anchors, strokeWidth);
369
+ }
370
+
371
+ #applyArrow(arrow: ArcResolvedConnectionOptionsType['arrow']): void {
372
+ if (arrow === 'none') {
373
+ this.#marker?.remove();
374
+ this.#marker = null;
375
+ setAttributes(this.path, { 'marker-start': null, 'marker-end': null });
376
+
377
+ return;
378
+ }
379
+
380
+ if (!this.#marker) {
381
+ // The marker lives inside the connection's group so it inherits the
382
+ // group's color
383
+ this.#marker = createSVGElement('marker', {
384
+ id: `arc-arrow-${uniqueID()}`,
385
+ class: 'arc-marker',
386
+ viewBox: '0 0 10 10',
387
+ refX: 0,
388
+ refY: 5,
389
+ markerWidth: ARROW_SIZE,
390
+ markerHeight: ARROW_SIZE,
391
+ markerUnits: 'strokeWidth',
392
+ orient: 'auto-start-reverse'
393
+ });
394
+ this.#marker.appendChild(
395
+ createSVGElement('path', {
396
+ d: 'M 0 0 L 10 5 L 0 10 z',
397
+ fill: 'currentColor'
398
+ })
399
+ );
400
+ this.element.insertBefore(this.#marker, this.path);
401
+ }
402
+
403
+ const url = `url(#${this.#marker.id})`;
404
+
405
+ setAttributes(this.path, {
406
+ 'marker-start': arrow === 'start' || arrow === 'both' ? url : null,
407
+ 'marker-end': arrow === 'end' || arrow === 'both' ? url : null
408
+ });
409
+ }
410
+
411
+ #applyLabel(label: string | undefined): void {
412
+ if (!label) {
413
+ this.#label?.remove();
414
+ this.#label = null;
415
+
416
+ return;
417
+ }
418
+
419
+ if (!this.#label) {
420
+ this.#label = createSVGElement('text', {
421
+ class: 'arc-label',
422
+ fill: 'currentColor',
423
+ 'text-anchor': 'middle',
424
+ 'dominant-baseline': 'central'
425
+ });
426
+ this.path.after(this.#label);
427
+
428
+ if (this.#geometry)
429
+ setAttributes(this.#label, { ...this.#geometry.labelPoint });
430
+ }
431
+
432
+ this.#label.textContent = label;
433
+ }
434
+
435
+ #applyAnchors(anchors: boolean, strokeWidth: number): void {
436
+ if (!anchors) {
437
+ this.#anchors?.forEach((anchor) => anchor.remove());
438
+ this.#anchors = null;
439
+
440
+ return;
441
+ }
442
+
443
+ if (!this.#anchors) {
444
+ this.#anchors = [
445
+ createSVGElement('circle', { class: 'arc-anchor arc-anchor-start' }),
446
+ createSVGElement('circle', { class: 'arc-anchor arc-anchor-end' })
447
+ ];
448
+ this.element.append(...this.#anchors);
449
+ }
450
+
451
+ this.#anchors.forEach((anchor) =>
452
+ setAttributes(anchor, { r: strokeWidth + 2, fill: 'currentColor' })
453
+ );
454
+ }
455
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Thrown when Arclace can't do what was asked, for example when a selector
3
+ * matches nothing, an id is taken, or the instance has been destroyed.
4
+ *
5
+ * Arguments of the wrong type throw a `TypeError`, and values out of range a
6
+ * `RangeError`, instead. When another error is behind the failure, such as
7
+ * an invalid selector, it is the `cause`.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * try {
12
+ * arclace.connect('#a', '#b', { id: 'a-to-b' });
13
+ * arclace.connect('#b', '#c', { id: 'a-to-b' }); // the id is taken
14
+ * } catch (error) {
15
+ * if (error instanceof ArclaceError) console.warn(error.message);
16
+ * }
17
+ * ```
18
+ */
19
+ export class ArclaceError extends Error {
20
+ override name = 'ArclaceError';
21
+
22
+ constructor(message: string, options?: ErrorOptions) {
23
+ super(`arclace: ${message}`, options);
24
+ }
25
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ export { Arclace, createConnections } from './Arclace';
2
+
3
+ export {
4
+ Connection,
5
+ DEFAULT_CONNECTION_OPTIONS,
6
+ type ArcResolvedConnectionOptionsType
7
+ } from './Connection';
8
+
9
+ export { ArclaceError } from './errors';
10
+
11
+ export type {
12
+ ArcArrowType,
13
+ ArcConnectionDefinitionType,
14
+ ArcConnectionOptionsType,
15
+ ArcElementTargetType,
16
+ ArcGeometryType,
17
+ ArcOptionsType,
18
+ ArcPathType,
19
+ ArcPointInterface,
20
+ ArcRectInterface,
21
+ ArcSideOptionType,
22
+ ArcSideType
23
+ } from './types';
24
+
25
+ export {
26
+ bezierPath,
27
+ orthogonalPath,
28
+ straightPath,
29
+ type ArcPathResultType
30
+ } from './utils/paths';
package/src/style.css ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Optional styles for @phun-ky/arclace.
3
+ *
4
+ * Lines work without this file. It adds the label halo, hollow anchors and
5
+ * the dash animation, and exposes custom properties for theming:
6
+ *
7
+ * --arc-color line, arrow and anchor color
8
+ * --arc-label-color label text color
9
+ * --arc-label-halo outline drawn behind labels so they stay readable
10
+ * --arc-label-size label font size
11
+ * --arc-anchor-fill inside of anchor dots
12
+ */
13
+
14
+ .arc-connection {
15
+ color: var(--arc-color, currentColor);
16
+ }
17
+
18
+ .arc-path {
19
+ stroke-linecap: round;
20
+ stroke-linejoin: round;
21
+ }
22
+
23
+ .arc-label {
24
+ fill: var(--arc-label-color, currentColor);
25
+ font-size: var(--arc-label-size, 12px);
26
+ paint-order: stroke;
27
+ stroke: var(--arc-label-halo, #fff);
28
+ stroke-width: 4px;
29
+ stroke-linejoin: round;
30
+ }
31
+
32
+ .arc-anchor {
33
+ fill: var(--arc-anchor-fill, #fff);
34
+ stroke: currentColor;
35
+ stroke-width: 2px;
36
+ }
37
+
38
+ .arc-animated .arc-path {
39
+ animation: arc-dash 0.6s linear infinite;
40
+ }
41
+
42
+ @keyframes arc-dash {
43
+ to {
44
+ stroke-dashoffset: -12;
45
+ }
46
+ }
47
+
48
+ @media (prefers-reduced-motion: reduce) {
49
+ .arc-animated .arc-path {
50
+ animation: none;
51
+ }
52
+ }