@phun-ky/arclace 0.0.0-stage → 0.2.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,407 @@
1
+ import type { Arclace } from './Arclace';
2
+ import type {
3
+ ArcConnectionOptionsType,
4
+ ArcGeometryType,
5
+ ArcPointInterface,
6
+ ArcSideType
7
+ } from './types';
8
+ import { add, distance, NORMALS } from './utils/geometry';
9
+ import { uniqueID } from './utils/id';
10
+ import {
11
+ bezierPath,
12
+ type ArcPathResultType,
13
+ orthogonalPath,
14
+ straightPath
15
+ } from './utils/paths';
16
+ import { createSVGElement, setAttributes } from './utils/svg';
17
+
18
+ /**
19
+ * Connection options that have no default.
20
+ */
21
+ export type ArcOptionalKeysType = 'id' | 'label' | 'color' | 'className';
22
+
23
+ /**
24
+ * Connection options with every default filled in.
25
+ */
26
+ export type ArcResolvedConnectionOptionsType = Required<
27
+ Omit<ArcConnectionOptionsType, ArcOptionalKeysType>
28
+ > &
29
+ Pick<ArcConnectionOptionsType, ArcOptionalKeysType> & { id: string };
30
+
31
+ /**
32
+ * Options every connection falls back to.
33
+ */
34
+ export const DEFAULT_CONNECTION_OPTIONS: Required<
35
+ Omit<ArcConnectionOptionsType, ArcOptionalKeysType>
36
+ > = {
37
+ type: 'bezier',
38
+ startSide: 'auto',
39
+ stopSide: 'auto',
40
+ arrow: 'none',
41
+ strokeWidth: 2,
42
+ dashed: false,
43
+ animated: false,
44
+ anchors: false,
45
+ gap: 0,
46
+ spread: true,
47
+ spacing: 16,
48
+ curvature: 1,
49
+ radius: 8,
50
+ offset: 20
51
+ };
52
+
53
+ // Arrow length in multiples of the stroke width
54
+ const ARROW_SIZE = 4;
55
+
56
+ export type ArcConnectionParamsType = {
57
+ id: string;
58
+ startElement: Element;
59
+ stopElement: Element;
60
+ options: ArcConnectionOptionsType;
61
+ defaults?: ArcConnectionOptionsType;
62
+ owner: Arclace;
63
+ };
64
+
65
+ /**
66
+ * A line between two elements. Created with {@link Arclace.connect}.
67
+ *
68
+ * Each connection renders as:
69
+ *
70
+ * ```html
71
+ * <g class="arc-connection arc-bezier">
72
+ * <marker class="arc-marker">…</marker> <!-- when `arrow` is set -->
73
+ * <path class="arc-path" />
74
+ * <text class="arc-label">…</text> <!-- when `label` is set -->
75
+ * <circle class="arc-anchor arc-anchor-start" /> <!-- when `anchors` is set -->
76
+ * <circle class="arc-anchor arc-anchor-stop" />
77
+ * </g>
78
+ * ```
79
+ *
80
+ * The line, arrows and anchors use `currentColor`, so setting `color` on
81
+ * `.arc-connection` colors all of them.
82
+ */
83
+ export class Connection {
84
+ readonly id: string;
85
+ readonly startElement: Element;
86
+ readonly stopElement: Element;
87
+
88
+ /**
89
+ * The `<g>` element holding everything this connection draws.
90
+ */
91
+ readonly element: SVGGElement;
92
+
93
+ /**
94
+ * The `<path>` element of the line.
95
+ */
96
+ readonly path: SVGPathElement;
97
+
98
+ /**
99
+ * The geometry from the last update, or `null` when the connection is
100
+ * hidden because one of its elements is not rendered.
101
+ */
102
+ geometry: ArcGeometryType | null = null;
103
+
104
+ #owner: Arclace;
105
+ #options: ArcConnectionOptionsType;
106
+ #defaults: ArcConnectionOptionsType;
107
+ #marker: SVGMarkerElement | null = null;
108
+ #label: SVGTextElement | null = null;
109
+ #anchors: [SVGCircleElement, SVGCircleElement] | null = null;
110
+
111
+ constructor(params: ArcConnectionParamsType) {
112
+ const {
113
+ id,
114
+ startElement,
115
+ stopElement,
116
+ options,
117
+ defaults = {},
118
+ owner
119
+ } = params;
120
+
121
+ this.id = id;
122
+ this.startElement = startElement;
123
+ this.stopElement = stopElement;
124
+ this.#owner = owner;
125
+ this.#options = { ...options };
126
+ this.#defaults = defaults;
127
+ this.element = createSVGElement('g', { 'data-arc-id': id });
128
+ this.path = createSVGElement('path', {
129
+ class: 'arc-path',
130
+ fill: 'none',
131
+ stroke: 'currentColor'
132
+ });
133
+ this.element.appendChild(this.path);
134
+ this.#applyOptions();
135
+ }
136
+
137
+ /**
138
+ * The connection's options merged with the instance defaults.
139
+ */
140
+ get options(): Readonly<ArcResolvedConnectionOptionsType> {
141
+ return {
142
+ ...DEFAULT_CONNECTION_OPTIONS,
143
+ ...this.#defaults,
144
+ ...this.#options,
145
+ id: this.id
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Changes options and redraws.
151
+ *
152
+ * @example
153
+ * ```ts
154
+ * connection.setOptions({ type: 'orthogonal', arrow: 'end' });
155
+ * ```
156
+ */
157
+ setOptions(options: Omit<ArcConnectionOptionsType, 'id'>): this {
158
+ this.#options = { ...this.#options, ...options };
159
+ this.#applyOptions();
160
+ this.#owner.update();
161
+
162
+ return this;
163
+ }
164
+
165
+ /**
166
+ * Redraws every connection of the owning instance.
167
+ */
168
+ update(): void {
169
+ this.#owner.update();
170
+ }
171
+
172
+ /**
173
+ * Removes this connection.
174
+ */
175
+ remove(): void {
176
+ this.#owner.disconnect(this);
177
+ }
178
+
179
+ /**
180
+ * Draws the connection between two attachment points.
181
+ *
182
+ * @internal
183
+ */
184
+ _draw(
185
+ start: ArcPointInterface,
186
+ startSide: ArcSideType,
187
+ stop: ArcPointInterface,
188
+ stopSide: ArcSideType
189
+ ): void {
190
+ const { arrow, strokeWidth } = this.options;
191
+ const arrowLength = ARROW_SIZE * strokeWidth;
192
+ // Shorten the line so arrow tips, not the line's end caps, touch the
193
+ // elements
194
+ const pathStart =
195
+ arrow === 'start' || arrow === 'both'
196
+ ? this.#pullBack(start, startSide, stop, arrowLength)
197
+ : start;
198
+ const pathStop =
199
+ arrow === 'end' || arrow === 'both'
200
+ ? this.#pullBack(stop, stopSide, start, arrowLength)
201
+ : stop;
202
+ const { d, labelPoint } = this.#buildPath(
203
+ pathStart,
204
+ startSide,
205
+ pathStop,
206
+ stopSide
207
+ );
208
+
209
+ this.geometry = { start, stop, startSide, stopSide, labelPoint, d };
210
+
211
+ this.element.removeAttribute('display');
212
+ setAttributes(this.element, {
213
+ 'data-start-side': startSide,
214
+ 'data-stop-side': stopSide
215
+ });
216
+ this.path.setAttribute('d', d);
217
+
218
+ if (this.#label) setAttributes(this.#label, { ...labelPoint });
219
+
220
+ if (this.#anchors) {
221
+ setAttributes(this.#anchors[0], { cx: start.x, cy: start.y });
222
+ setAttributes(this.#anchors[1], { cx: stop.x, cy: stop.y });
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Hides the connection.
228
+ *
229
+ * @internal
230
+ */
231
+ _hide(): void {
232
+ this.geometry = null;
233
+ this.element.setAttribute('display', 'none');
234
+ }
235
+
236
+ /**
237
+ * Removes the connection's elements from the overlay.
238
+ *
239
+ * @internal
240
+ */
241
+ _dispose(): void {
242
+ this.element.remove();
243
+ }
244
+
245
+ #buildPath(
246
+ start: ArcPointInterface,
247
+ startSide: ArcSideType,
248
+ stop: ArcPointInterface,
249
+ stopSide: ArcSideType
250
+ ): ArcPathResultType {
251
+ const { type, curvature, radius, offset } = this.options;
252
+
253
+ if (type === 'straight') return straightPath(start, stop);
254
+
255
+ if (type === 'orthogonal') {
256
+ return orthogonalPath(start, startSide, stop, stopSide, {
257
+ radius,
258
+ offset
259
+ });
260
+ }
261
+
262
+ return bezierPath(start, startSide, stop, stopSide, curvature);
263
+ }
264
+
265
+ #pullBack(
266
+ point: ArcPointInterface,
267
+ side: ArcSideType,
268
+ other: ArcPointInterface,
269
+ length: number
270
+ ): ArcPointInterface {
271
+ const total = distance(point, other);
272
+ const amount = Math.min(length, total / 3);
273
+
274
+ if (this.options.type !== 'straight') {
275
+ return add(point, NORMALS[side], amount);
276
+ }
277
+
278
+ if (total === 0) return point;
279
+
280
+ return {
281
+ x: point.x + ((other.x - point.x) / total) * amount,
282
+ y: point.y + ((other.y - point.y) / total) * amount
283
+ };
284
+ }
285
+
286
+ #applyOptions(): void {
287
+ const {
288
+ type,
289
+ arrow,
290
+ label,
291
+ color,
292
+ strokeWidth,
293
+ dashed,
294
+ animated,
295
+ anchors,
296
+ className
297
+ } = this.options;
298
+ const classes = ['arc-connection', `arc-${type}`];
299
+
300
+ if (dashed || animated) classes.push('arc-dashed');
301
+
302
+ if (animated) classes.push('arc-animated');
303
+
304
+ if (className) classes.push(...className.split(/\s+/).filter(Boolean));
305
+
306
+ setAttributes(this.element, {
307
+ class: classes.join(' '),
308
+ 'data-type': type
309
+ });
310
+ // Inline so it wins over the stylesheet's --arc-color
311
+ this.element.style.color = color ?? '';
312
+
313
+ setAttributes(this.path, {
314
+ 'stroke-width': strokeWidth,
315
+ 'stroke-dasharray': dashed || animated ? '6 6' : null
316
+ });
317
+
318
+ this.#applyArrow(arrow);
319
+ this.#applyLabel(label);
320
+ this.#applyAnchors(anchors, strokeWidth);
321
+ }
322
+
323
+ #applyArrow(arrow: ArcResolvedConnectionOptionsType['arrow']): void {
324
+ if (arrow === 'none') {
325
+ this.#marker?.remove();
326
+ this.#marker = null;
327
+ setAttributes(this.path, { 'marker-start': null, 'marker-end': null });
328
+
329
+ return;
330
+ }
331
+
332
+ if (!this.#marker) {
333
+ // The marker lives inside the connection's group so it inherits the
334
+ // group's color
335
+ this.#marker = createSVGElement('marker', {
336
+ id: `arc-arrow-${uniqueID()}`,
337
+ class: 'arc-marker',
338
+ viewBox: '0 0 10 10',
339
+ refX: 0,
340
+ refY: 5,
341
+ markerWidth: ARROW_SIZE,
342
+ markerHeight: ARROW_SIZE,
343
+ markerUnits: 'strokeWidth',
344
+ orient: 'auto-start-reverse'
345
+ });
346
+ this.#marker.appendChild(
347
+ createSVGElement('path', {
348
+ d: 'M 0 0 L 10 5 L 0 10 z',
349
+ fill: 'currentColor'
350
+ })
351
+ );
352
+ this.element.insertBefore(this.#marker, this.path);
353
+ }
354
+
355
+ const url = `url(#${this.#marker.id})`;
356
+
357
+ setAttributes(this.path, {
358
+ 'marker-start': arrow === 'start' || arrow === 'both' ? url : null,
359
+ 'marker-end': arrow === 'end' || arrow === 'both' ? url : null
360
+ });
361
+ }
362
+
363
+ #applyLabel(label: string | undefined): void {
364
+ if (!label) {
365
+ this.#label?.remove();
366
+ this.#label = null;
367
+
368
+ return;
369
+ }
370
+
371
+ if (!this.#label) {
372
+ this.#label = createSVGElement('text', {
373
+ class: 'arc-label',
374
+ fill: 'currentColor',
375
+ 'text-anchor': 'middle',
376
+ 'dominant-baseline': 'central'
377
+ });
378
+ this.path.after(this.#label);
379
+
380
+ if (this.geometry)
381
+ setAttributes(this.#label, { ...this.geometry.labelPoint });
382
+ }
383
+
384
+ this.#label.textContent = label;
385
+ }
386
+
387
+ #applyAnchors(anchors: boolean, strokeWidth: number): void {
388
+ if (!anchors) {
389
+ this.#anchors?.forEach((anchor) => anchor.remove());
390
+ this.#anchors = null;
391
+
392
+ return;
393
+ }
394
+
395
+ if (!this.#anchors) {
396
+ this.#anchors = [
397
+ createSVGElement('circle', { class: 'arc-anchor arc-anchor-start' }),
398
+ createSVGElement('circle', { class: 'arc-anchor arc-anchor-stop' })
399
+ ];
400
+ this.element.append(...this.#anchors);
401
+ }
402
+
403
+ this.#anchors.forEach((anchor) =>
404
+ setAttributes(anchor, { r: strokeWidth + 2, fill: 'currentColor' })
405
+ );
406
+ }
407
+ }
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 ArcConnectionParamsType,
7
+ type ArcOptionalKeysType,
8
+ type ArcResolvedConnectionOptionsType
9
+ } from './Connection';
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
+ }
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 stop element the line arrives at. Defaults to `'auto'`.
66
+ */
67
+ stopSide?: 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 stop. 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
+ stopElement: 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
+ stop: ArcPointInterface;
196
+ startSide: ArcSideType;
197
+ stopSide: ArcSideType;
198
+ labelPoint: ArcPointInterface;
199
+ d: string;
200
+ };