@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.
package/src/Arclace.ts ADDED
@@ -0,0 +1,488 @@
1
+ import { Connection } from './Connection';
2
+ import type {
3
+ ArcConnectionDefinitionType,
4
+ ArcConnectionOptionsType,
5
+ ArcElementTargetType,
6
+ ArcOptionsType,
7
+ ArcRectInterface,
8
+ ArcSideType
9
+ } from './types';
10
+ import { center, isHorizontalSide } from './utils/geometry';
11
+ import { uniqueID } from './utils/id';
12
+ import { getLocalRect, getOrigin, isRendered } from './utils/measure';
13
+ import { resolveElement } from './utils/resolve-element';
14
+ import { getAnchorPoint, resolveSides } from './utils/sides';
15
+ import { createSVGElement } from './utils/svg';
16
+
17
+ type ArcLayoutItemType = {
18
+ connection: Connection;
19
+ startRect: ArcRectInterface;
20
+ stopRect: ArcRectInterface;
21
+ startSide: ArcSideType;
22
+ stopSide: ArcSideType;
23
+ startSlot: { index: number; count: number };
24
+ stopSlot: { index: number; count: number };
25
+ };
26
+
27
+ type ArcSlotEntryType = {
28
+ slot: { index: number; count: number };
29
+ // Position of the other end along the side, used to avoid crossing lines
30
+ key: number;
31
+ };
32
+
33
+ const nextFrame = (callback: () => void): number =>
34
+ typeof requestAnimationFrame === 'function'
35
+ ? requestAnimationFrame(callback)
36
+ : (setTimeout(callback, 16) as unknown as number);
37
+ const cancelFrame = (handle: number): void => {
38
+ if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(handle);
39
+ else clearTimeout(handle);
40
+ };
41
+
42
+ /**
43
+ * Draws and maintains SVG lines between DOM elements.
44
+ *
45
+ * An instance adds one `<svg class="arc-svg">` overlay to its container and
46
+ * draws every connection into it.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * import { Arclace } from '@phun-ky/arclace';
51
+ *
52
+ * const arclace = new Arclace({ container: '#diagram' });
53
+ *
54
+ * arclace.connect('#a', '#b', { arrow: 'end', label: 'depends on' });
55
+ * ```
56
+ */
57
+ export class Arclace {
58
+ /**
59
+ * The element the overlay was added to.
60
+ */
61
+ readonly container: HTMLElement;
62
+
63
+ /**
64
+ * The SVG overlay all lines are drawn in.
65
+ */
66
+ readonly svg: SVGSVGElement;
67
+
68
+ #options: ArcOptionsType;
69
+ #connections = new Map<string, Connection>();
70
+ #frame = 0;
71
+ #loop = 0;
72
+ #destroyed = false;
73
+ #resizeObserver: ResizeObserver | null = null;
74
+ #mutationObserver: MutationObserver | null = null;
75
+ #originalPosition: string | null = null;
76
+
77
+ constructor(options: ArcOptionsType = {}) {
78
+ if (typeof document === 'undefined') {
79
+ throw Error('arclace: a DOM is required');
80
+ }
81
+
82
+ this.#options = options;
83
+ this.container = (
84
+ options.container
85
+ ? resolveElement(options.container, 'container')
86
+ : document.body
87
+ ) as HTMLElement;
88
+
89
+ // The overlay is positioned absolutely, so the container has to be its
90
+ // containing block for it to scroll and clip with the container
91
+ if (
92
+ this.container !== document.body &&
93
+ getComputedStyle(this.container).position === 'static'
94
+ ) {
95
+ this.#originalPosition = this.container.style.position;
96
+ this.container.style.position = 'relative';
97
+ }
98
+
99
+ this.svg = createSVGElement('svg', {
100
+ class: ['arc-svg', options.className].filter(Boolean).join(' '),
101
+ 'aria-hidden': 'true'
102
+ });
103
+ Object.assign(this.svg.style, {
104
+ position: 'absolute',
105
+ top: '0',
106
+ left: '0',
107
+ width: '100%',
108
+ height: '100%',
109
+ overflow: 'visible',
110
+ pointerEvents: 'none'
111
+ });
112
+ this.container.prepend(this.svg);
113
+ this.#startAutoUpdate();
114
+ }
115
+
116
+ /**
117
+ * All current connections, in the order they were made.
118
+ */
119
+ get connections(): Connection[] {
120
+ return [...this.#connections.values()];
121
+ }
122
+
123
+ /**
124
+ * Connects two elements and draws the line right away.
125
+ *
126
+ * @param startElement - The element (or selector) the line starts at.
127
+ * @param stopElement - The element (or selector) the line stops at.
128
+ * @param options - Options for this connection, merged over the instance defaults.
129
+ * @throws {Error} When an element can't be found or the id is taken.
130
+ * @example
131
+ * ```ts
132
+ * const connection = arclace.connect(a, b, { type: 'orthogonal', arrow: 'end' });
133
+ * ```
134
+ */
135
+ connect(
136
+ startElement: ArcElementTargetType,
137
+ stopElement: ArcElementTargetType,
138
+ options: ArcConnectionOptionsType = {}
139
+ ): Connection {
140
+ const connection = this.#add(startElement, stopElement, options);
141
+
142
+ this.update();
143
+
144
+ return connection;
145
+ }
146
+
147
+ /**
148
+ * Connects many pairs of elements and draws them in one go.
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * arclace.connectAll([
153
+ * { startElement: '#a', stopElement: '#b' },
154
+ * { startElement: '#a', stopElement: '#c', dashed: true }
155
+ * ]);
156
+ * ```
157
+ */
158
+ connectAll(definitions: ArcConnectionDefinitionType[]): Connection[] {
159
+ const connections = definitions.map(
160
+ ({ startElement, stopElement, ...options }) =>
161
+ this.#add(startElement, stopElement, options)
162
+ );
163
+
164
+ this.update();
165
+
166
+ return connections;
167
+ }
168
+
169
+ /**
170
+ * Returns the connection with the given id.
171
+ */
172
+ get(id: string): Connection | undefined {
173
+ return this.#connections.get(id);
174
+ }
175
+
176
+ /**
177
+ * Returns every connection that starts or stops at an element.
178
+ */
179
+ find(target: ArcElementTargetType): Connection[] {
180
+ const el = resolveElement(target);
181
+
182
+ return this.connections.filter(
183
+ (connection) =>
184
+ connection.startElement === el || connection.stopElement === el
185
+ );
186
+ }
187
+
188
+ /**
189
+ * Removes connections.
190
+ *
191
+ * @param target - A connection, a connection id, or an element (or
192
+ * selector) whose connections should all be removed. Targets that match
193
+ * nothing are ignored.
194
+ * @example
195
+ * ```ts
196
+ * arclace.disconnect(connection);
197
+ * arclace.disconnect('my-connection-id');
198
+ * arclace.disconnect(document.querySelector('#a'));
199
+ * ```
200
+ */
201
+ disconnect(target: Connection | string | Element): void {
202
+ let removed: Connection[] = [];
203
+
204
+ if (target instanceof Connection) {
205
+ removed = [target];
206
+ } else if (typeof target === 'string' && this.#connections.has(target)) {
207
+ removed = [this.#connections.get(target)!];
208
+ } else if (target instanceof Element) {
209
+ removed = this.find(target);
210
+ } else {
211
+ const el = document.querySelector(target);
212
+
213
+ if (el) removed = this.find(el);
214
+ }
215
+
216
+ for (const connection of removed) {
217
+ if (this.#connections.get(connection.id) !== connection) continue;
218
+
219
+ this.#connections.delete(connection.id);
220
+ connection._dispose();
221
+ this.#unobserve(connection.startElement);
222
+ this.#unobserve(connection.stopElement);
223
+ }
224
+
225
+ if (removed.length > 0) this.update();
226
+ }
227
+
228
+ /**
229
+ * Removes every connection.
230
+ */
231
+ clear(): void {
232
+ for (const connection of this.#connections.values()) {
233
+ connection._dispose();
234
+ }
235
+
236
+ this.#connections.clear();
237
+ this.#resizeObserver?.disconnect();
238
+
239
+ if (this.#resizeObserver) this.#resizeObserver.observe(this.container);
240
+ }
241
+
242
+ /**
243
+ * Remeasures every element and redraws every connection. Called
244
+ * automatically when `autoUpdate` is on; call it yourself after moving
245
+ * elements in ways the page can't observe.
246
+ */
247
+ update(): void {
248
+ if (this.#destroyed) return;
249
+
250
+ if (this.#frame) {
251
+ cancelFrame(this.#frame);
252
+ this.#frame = 0;
253
+ }
254
+
255
+ // Measure everything first, then write, so the browser only lays out once
256
+ const origin = getOrigin(this.svg);
257
+ const items: ArcLayoutItemType[] = [];
258
+ const slots = new Map<Element, Record<ArcSideType, ArcSlotEntryType[]>>();
259
+ const addToSlot = (
260
+ el: Element,
261
+ side: ArcSideType,
262
+ otherRect: ArcRectInterface
263
+ ): { index: number; count: number } => {
264
+ const slot = { index: 0, count: 1 };
265
+ const other = center(otherRect);
266
+
267
+ if (!slots.has(el)) {
268
+ slots.set(el, { top: [], right: [], bottom: [], left: [] });
269
+ }
270
+
271
+ slots.get(el)![side].push({
272
+ slot,
273
+ key: isHorizontalSide(side) ? other.y : other.x
274
+ });
275
+
276
+ return slot;
277
+ };
278
+
279
+ for (const connection of this.#connections.values()) {
280
+ const { startElement, stopElement } = connection;
281
+
282
+ if (!isRendered(startElement) || !isRendered(stopElement)) {
283
+ connection._hide();
284
+ continue;
285
+ }
286
+
287
+ const { spread, startSide, stopSide } = connection.options;
288
+ const startRect = getLocalRect(startElement, origin);
289
+ const stopRect = getLocalRect(stopElement, origin);
290
+ const sides = resolveSides(startRect, stopRect, startSide, stopSide);
291
+ const solo = { index: 0, count: 1 };
292
+
293
+ items.push({
294
+ connection,
295
+ startRect,
296
+ stopRect,
297
+ ...sides,
298
+ startSlot: spread
299
+ ? addToSlot(startElement, sides.startSide, stopRect)
300
+ : solo,
301
+ stopSlot: spread
302
+ ? addToSlot(stopElement, sides.stopSide, startRect)
303
+ : { ...solo }
304
+ });
305
+ }
306
+
307
+ for (const sides of slots.values()) {
308
+ for (const entries of Object.values(sides)) {
309
+ entries
310
+ .sort((a, b) => a.key - b.key)
311
+ .forEach((entry, index) => {
312
+ entry.slot.index = index;
313
+ entry.slot.count = entries.length;
314
+ });
315
+ }
316
+ }
317
+
318
+ for (const item of items) {
319
+ const { connection, startRect, stopRect, startSide, stopSide } = item;
320
+ const { spacing, gap } = connection.options;
321
+
322
+ connection._draw(
323
+ getAnchorPoint(startRect, startSide, {
324
+ ...item.startSlot,
325
+ spacing,
326
+ gap
327
+ }),
328
+ startSide,
329
+ getAnchorPoint(stopRect, stopSide, { ...item.stopSlot, spacing, gap }),
330
+ stopSide
331
+ );
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Removes every connection and the overlay, and stops listening for
337
+ * changes. The instance can't be used afterwards.
338
+ */
339
+ destroy(): void {
340
+ if (this.#destroyed) return;
341
+
342
+ this.clear();
343
+ this.#destroyed = true;
344
+
345
+ if (this.#frame) cancelFrame(this.#frame);
346
+
347
+ if (this.#loop) cancelFrame(this.#loop);
348
+
349
+ window.removeEventListener('resize', this.#scheduleUpdate);
350
+ document.removeEventListener('scroll', this.#scheduleUpdate, {
351
+ capture: true
352
+ });
353
+ this.#resizeObserver?.disconnect();
354
+ this.#mutationObserver?.disconnect();
355
+ this.svg.remove();
356
+
357
+ if (this.#originalPosition !== null) {
358
+ this.container.style.position = this.#originalPosition;
359
+ }
360
+ }
361
+
362
+ #add(
363
+ startTarget: ArcElementTargetType,
364
+ stopTarget: ArcElementTargetType,
365
+ options: ArcConnectionOptionsType
366
+ ): Connection {
367
+ if (this.#destroyed) {
368
+ throw Error('arclace: this instance has been destroyed');
369
+ }
370
+
371
+ const startElement = resolveElement(startTarget, 'startElement');
372
+ const stopElement = resolveElement(stopTarget, 'stopElement');
373
+ const id = options.id ?? `arc-${uniqueID()}`;
374
+
375
+ if (this.#connections.has(id)) {
376
+ throw Error(`arclace: a connection with id "${id}" exists`);
377
+ }
378
+
379
+ const connection = new Connection({
380
+ id,
381
+ startElement,
382
+ stopElement,
383
+ options,
384
+ defaults: this.#options.defaults,
385
+ owner: this
386
+ });
387
+
388
+ this.#connections.set(id, connection);
389
+ this.svg.appendChild(connection.element);
390
+ this.#resizeObserver?.observe(startElement);
391
+ this.#resizeObserver?.observe(stopElement);
392
+
393
+ return connection;
394
+ }
395
+
396
+ #unobserve(el: Element): void {
397
+ if (!this.#resizeObserver || el === this.container) return;
398
+
399
+ const inUse = this.connections.some(
400
+ (connection) =>
401
+ connection.startElement === el || connection.stopElement === el
402
+ );
403
+
404
+ if (!inUse) this.#resizeObserver.unobserve(el);
405
+ }
406
+
407
+ #scheduleUpdate = (): void => {
408
+ if (this.#frame || this.#destroyed) return;
409
+
410
+ this.#frame = nextFrame(() => {
411
+ this.#frame = 0;
412
+ this.update();
413
+ });
414
+ };
415
+
416
+ #startAutoUpdate(): void {
417
+ const { autoUpdate = true } = this.#options;
418
+
419
+ if (autoUpdate === false) return;
420
+
421
+ if (autoUpdate === 'frame') {
422
+ const loop = (): void => {
423
+ this.update();
424
+ this.#loop = nextFrame(loop);
425
+ };
426
+
427
+ this.#loop = nextFrame(loop);
428
+
429
+ return;
430
+ }
431
+
432
+ window.addEventListener('resize', this.#scheduleUpdate);
433
+ // Capture scroll events from any scrolling element, not just the page
434
+ document.addEventListener('scroll', this.#scheduleUpdate, {
435
+ capture: true,
436
+ passive: true
437
+ });
438
+
439
+ if (typeof ResizeObserver !== 'undefined') {
440
+ this.#resizeObserver = new ResizeObserver(this.#scheduleUpdate);
441
+ this.#resizeObserver.observe(this.container);
442
+ }
443
+
444
+ if (typeof MutationObserver !== 'undefined') {
445
+ this.#mutationObserver = new MutationObserver((records) => {
446
+ // Ignore the changes we make to the overlay ourselves
447
+ if (records.some((record) => !this.svg.contains(record.target))) {
448
+ this.#scheduleUpdate();
449
+ }
450
+ });
451
+ this.#mutationObserver.observe(this.container, {
452
+ subtree: true,
453
+ childList: true,
454
+ attributes: true,
455
+ attributeFilter: ['style', 'class', 'hidden']
456
+ });
457
+ }
458
+
459
+ document.fonts?.ready.then(this.#scheduleUpdate);
460
+ }
461
+ }
462
+
463
+ /**
464
+ * Creates a {@link Arclace} instance and connects the given pairs.
465
+ *
466
+ * @example
467
+ * ```ts
468
+ * import { createConnections } from '@phun-ky/arclace';
469
+ *
470
+ * const arclace = createConnections(
471
+ * [
472
+ * { startElement: '#a', stopElement: '#b' },
473
+ * { startElement: '#b', stopElement: '#c', arrow: 'end' }
474
+ * ],
475
+ * { defaults: { type: 'orthogonal' } }
476
+ * );
477
+ * ```
478
+ */
479
+ export const createConnections = (
480
+ definitions: ArcConnectionDefinitionType[],
481
+ options?: ArcOptionsType
482
+ ): Arclace => {
483
+ const arclace = new Arclace(options);
484
+
485
+ arclace.connectAll(definitions);
486
+
487
+ return arclace;
488
+ };