@rasamjs/connectors 0.0.0-stage → 0.1.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/API.md +114 -0
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +44 -2
- package/RELEASING.md +25 -0
- package/dist/connectors.d.ts +26 -0
- package/dist/connectors.d.ts.map +1 -0
- package/dist/connectors.js +231 -0
- package/dist/connectors.js.map +1 -0
- package/dist/editor.d.ts +42 -0
- package/dist/editor.d.ts.map +1 -0
- package/dist/editor.js +55 -0
- package/dist/editor.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/metadata.d.ts +8 -0
- package/dist/metadata.d.ts.map +1 -0
- package/dist/metadata.js +47 -0
- package/dist/metadata.js.map +1 -0
- package/dist/routing.d.ts +11 -0
- package/dist/routing.d.ts.map +1 -0
- package/dist/routing.js +110 -0
- package/dist/routing.js.map +1 -0
- package/dist/tool-surface.d.ts +21 -0
- package/dist/tool-surface.d.ts.map +1 -0
- package/dist/tool-surface.js +98 -0
- package/dist/tool-surface.js.map +1 -0
- package/dist/tool.d.ts +44 -0
- package/dist/tool.d.ts.map +1 -0
- package/dist/tool.js +305 -0
- package/dist/tool.js.map +1 -0
- package/dist/types.d.ts +36 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +61 -4
- package/src/connectors.ts +248 -0
- package/src/editor.ts +82 -0
- package/src/index.ts +14 -0
- package/src/metadata.ts +63 -0
- package/src/routing.ts +127 -0
- package/src/tool-surface.ts +96 -0
- package/src/tool.ts +344 -0
- package/src/types.ts +33 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { Path } from '@rasamjs/core';
|
|
2
|
+
import type { Svg, AnyNode } from '@rasamjs/core';
|
|
3
|
+
import { Guards } from '@rasamjs/core/advanced';
|
|
4
|
+
import { beginChangeGroup, deriveChanges } from '@rasamjs/core/changes';
|
|
5
|
+
import { isConnector, readConnector, writeConnector } from './metadata.js';
|
|
6
|
+
import {
|
|
7
|
+
connectorPort,
|
|
8
|
+
endpointCenter,
|
|
9
|
+
pathData,
|
|
10
|
+
routeConnector,
|
|
11
|
+
validateAnchor,
|
|
12
|
+
validatePoint,
|
|
13
|
+
} from './routing.js';
|
|
14
|
+
import type { ConnectorEndpoint, ConnectorOptions, ConnectorState } from './types.js';
|
|
15
|
+
|
|
16
|
+
const owners = new WeakMap<Svg, Connectors>();
|
|
17
|
+
const drawableTags = new Set([
|
|
18
|
+
'rect',
|
|
19
|
+
'circle',
|
|
20
|
+
'ellipse',
|
|
21
|
+
'line',
|
|
22
|
+
'polyline',
|
|
23
|
+
'polygon',
|
|
24
|
+
'path',
|
|
25
|
+
'text',
|
|
26
|
+
'image',
|
|
27
|
+
'foreignObject',
|
|
28
|
+
'use',
|
|
29
|
+
'g',
|
|
30
|
+
'svg',
|
|
31
|
+
]);
|
|
32
|
+
export class Connectors {
|
|
33
|
+
private disposed = false;
|
|
34
|
+
private readonly cleanups: (() => void)[] = [];
|
|
35
|
+
private readonly disposals = new Set<() => void>();
|
|
36
|
+
constructor(readonly drawing: Svg) {
|
|
37
|
+
if (
|
|
38
|
+
!Guards.isTransformable(drawing) ||
|
|
39
|
+
drawing.isDestroyed ||
|
|
40
|
+
drawing !== drawing.context.root ||
|
|
41
|
+
drawing.el.localName !== 'svg'
|
|
42
|
+
)
|
|
43
|
+
throw new TypeError('Connectors needs a live SVG drawing root');
|
|
44
|
+
if (owners.has(drawing)) throw new Error('Connectors is already attached to this drawing');
|
|
45
|
+
// Validate saved attachments without changing stored routing during attachment or replay.
|
|
46
|
+
this.nodes.forEach(readConnector);
|
|
47
|
+
owners.set(drawing, this);
|
|
48
|
+
this.cleanups.push(
|
|
49
|
+
deriveChanges(drawing, (event) => {
|
|
50
|
+
if (event.source === 'viewport') return;
|
|
51
|
+
for (const path of this.nodes) {
|
|
52
|
+
const state = readConnector(path);
|
|
53
|
+
if (event.nodes.some((changed) => changed === path || this.affects(changed, state)))
|
|
54
|
+
this.route(state);
|
|
55
|
+
}
|
|
56
|
+
}),
|
|
57
|
+
drawing.onDispose(() => this.destroy()),
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
get isDestroyed(): boolean {
|
|
61
|
+
return this.disposed;
|
|
62
|
+
}
|
|
63
|
+
onDispose(listener: () => void): () => void {
|
|
64
|
+
this.assertLive();
|
|
65
|
+
if (typeof listener !== 'function') throw new TypeError('Disposal listener must be a function');
|
|
66
|
+
this.disposals.add(listener);
|
|
67
|
+
return () => {
|
|
68
|
+
this.disposals.delete(listener);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
get nodes(): readonly Path[] {
|
|
72
|
+
this.assertLive();
|
|
73
|
+
return Object.freeze(this.drawing.descendants().filter(isConnector));
|
|
74
|
+
}
|
|
75
|
+
read(path: Path): ConnectorState {
|
|
76
|
+
this.assertPath(path);
|
|
77
|
+
return readConnector(path);
|
|
78
|
+
}
|
|
79
|
+
create(options: ConnectorOptions): Path {
|
|
80
|
+
this.assertLive();
|
|
81
|
+
this.validate(options);
|
|
82
|
+
return this.edit('Create connector', () => {
|
|
83
|
+
const path = this.drawing.path({
|
|
84
|
+
d: '',
|
|
85
|
+
fill: 'none',
|
|
86
|
+
stroke: options.stroke ?? '#334155',
|
|
87
|
+
'stroke-width': options.strokeWidth ?? 2,
|
|
88
|
+
});
|
|
89
|
+
writeConnector(path, {
|
|
90
|
+
start: options.start,
|
|
91
|
+
end: options.end,
|
|
92
|
+
routing: options.routing ?? 'straight',
|
|
93
|
+
});
|
|
94
|
+
if ((options.arrows ?? 'end') !== 'none') {
|
|
95
|
+
const marker = this.drawing.createMarker({
|
|
96
|
+
viewBox: '0 0 10 10',
|
|
97
|
+
markerWidth: 6,
|
|
98
|
+
markerHeight: 6,
|
|
99
|
+
refX: 9,
|
|
100
|
+
refY: 5,
|
|
101
|
+
orient: 'auto-start-reverse',
|
|
102
|
+
});
|
|
103
|
+
marker.path({ d: 'M0 0 L10 5 L0 10 Z', fill: 'context-stroke', stroke: 'none' });
|
|
104
|
+
path.marker('end', marker);
|
|
105
|
+
if (options.arrows === 'both') path.marker('start', marker);
|
|
106
|
+
}
|
|
107
|
+
if (!this.route(readConnector(path)))
|
|
108
|
+
throw new Error('Connector needs available bounds and invertible transforms');
|
|
109
|
+
return path;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
update(path: Path, patch: Partial<Pick<ConnectorOptions, 'start' | 'end' | 'routing'>>): void {
|
|
113
|
+
this.assertPath(path);
|
|
114
|
+
const state = { ...readConnector(path), ...patch };
|
|
115
|
+
this.validate(state);
|
|
116
|
+
this.edit('Edit connector', () => {
|
|
117
|
+
writeConnector(path, state);
|
|
118
|
+
if (!this.route(state))
|
|
119
|
+
throw new Error('Connector needs available bounds and invertible transforms');
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
remove(path: Path): void {
|
|
123
|
+
this.assertPath(path);
|
|
124
|
+
this.edit('Delete connector', () => path.remove());
|
|
125
|
+
}
|
|
126
|
+
destroy(): void {
|
|
127
|
+
if (this.disposed) return;
|
|
128
|
+
this.disposed = true;
|
|
129
|
+
owners.delete(this.drawing);
|
|
130
|
+
const failures: unknown[] = [];
|
|
131
|
+
for (const stop of [...this.cleanups.splice(0).reverse(), ...this.disposals]) {
|
|
132
|
+
try {
|
|
133
|
+
stop();
|
|
134
|
+
} catch (error) {
|
|
135
|
+
failures.push(error);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
this.disposals.clear();
|
|
139
|
+
if (failures.length) throw new AggregateError(failures, 'Connector cleanup failed');
|
|
140
|
+
}
|
|
141
|
+
private assertLive(): void {
|
|
142
|
+
if (this.disposed) throw new Error('Connectors is destroyed');
|
|
143
|
+
}
|
|
144
|
+
private assertPath(path: Path): void {
|
|
145
|
+
this.assertLive();
|
|
146
|
+
if (
|
|
147
|
+
!isConnector(path) ||
|
|
148
|
+
path.isDestroyed ||
|
|
149
|
+
path.context !== this.drawing.context ||
|
|
150
|
+
!this.drawing.descendants().includes(path)
|
|
151
|
+
)
|
|
152
|
+
throw new TypeError('Expected a connector in this drawing');
|
|
153
|
+
}
|
|
154
|
+
private validate(options: ConnectorOptions): void {
|
|
155
|
+
if (!options || typeof options !== 'object')
|
|
156
|
+
throw new TypeError('Connector options must be an object');
|
|
157
|
+
for (const endpoint of [options.start, options.end]) this.validateEndpoint(endpoint);
|
|
158
|
+
if (options.routing !== undefined && !['straight', 'elbow'].includes(options.routing))
|
|
159
|
+
throw new TypeError('Unknown connector routing');
|
|
160
|
+
if (options.arrows !== undefined && !['none', 'end', 'both'].includes(options.arrows))
|
|
161
|
+
throw new TypeError('Unknown connector arrows');
|
|
162
|
+
if (
|
|
163
|
+
options.stroke !== undefined &&
|
|
164
|
+
(typeof options.stroke !== 'string' || !options.stroke.trim())
|
|
165
|
+
)
|
|
166
|
+
throw new TypeError('Connector stroke must be nonempty');
|
|
167
|
+
if (
|
|
168
|
+
options.strokeWidth !== undefined &&
|
|
169
|
+
(!Number.isFinite(options.strokeWidth) || options.strokeWidth < 0)
|
|
170
|
+
)
|
|
171
|
+
throw new TypeError('Connector stroke width must be nonnegative');
|
|
172
|
+
}
|
|
173
|
+
private validateEndpoint(endpoint: ConnectorEndpoint): void {
|
|
174
|
+
if (!endpoint || typeof endpoint !== 'object' || 'target' in endpoint === 'point' in endpoint)
|
|
175
|
+
throw new TypeError('Endpoint needs either a target or a point');
|
|
176
|
+
if ('point' in endpoint) {
|
|
177
|
+
validatePoint(endpoint.point);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const target = endpoint.target;
|
|
181
|
+
if (
|
|
182
|
+
!Guards.isTransformable(target) ||
|
|
183
|
+
target.isDestroyed ||
|
|
184
|
+
target === this.drawing ||
|
|
185
|
+
target.context !== this.drawing.context ||
|
|
186
|
+
!this.drawing.descendants().includes(target) ||
|
|
187
|
+
target.descendants().some(isConnector)
|
|
188
|
+
)
|
|
189
|
+
throw new TypeError(
|
|
190
|
+
'Endpoint target must be a drawable shape without connectors in this drawing',
|
|
191
|
+
);
|
|
192
|
+
for (let node: AnyNode | null = target; node && node !== this.drawing; node = node.parent)
|
|
193
|
+
if (!drawableTags.has(node.el.localName))
|
|
194
|
+
throw new TypeError('Connector targets cannot be inside definitions');
|
|
195
|
+
validateAnchor(endpoint.anchor ?? 'auto');
|
|
196
|
+
}
|
|
197
|
+
private affects(changed: AnyNode, { path, start, end }: ConnectorState): boolean {
|
|
198
|
+
// Parents can move, resize, reparent or change a group's local bounds through a descendant.
|
|
199
|
+
return [
|
|
200
|
+
path,
|
|
201
|
+
...[start, end].flatMap((endpoint) => ('target' in endpoint ? [endpoint.target] : [])),
|
|
202
|
+
].some(
|
|
203
|
+
(node) =>
|
|
204
|
+
node === changed ||
|
|
205
|
+
node.descendants().includes(changed) ||
|
|
206
|
+
changed.descendants().includes(node),
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
private route(state: ConnectorState): boolean {
|
|
210
|
+
const { path, start, end } = state;
|
|
211
|
+
for (const endpoint of [start, end])
|
|
212
|
+
if ('target' in endpoint) {
|
|
213
|
+
if (endpoint.target.isDestroyed || !this.drawing.descendants().includes(endpoint.target))
|
|
214
|
+
return false;
|
|
215
|
+
if (endpoint.target.descendants().includes(path))
|
|
216
|
+
throw new TypeError('A connector cannot be inside its endpoint target');
|
|
217
|
+
}
|
|
218
|
+
const a = endpointCenter(start),
|
|
219
|
+
b = endpointCenter(end);
|
|
220
|
+
const from = a && b ? connectorPort(start, b) : null;
|
|
221
|
+
const to = a && b ? connectorPort(end, a) : null;
|
|
222
|
+
const inverse = path.worldMatrix().inverse();
|
|
223
|
+
if (!from || !to || !inverse) return false;
|
|
224
|
+
const d = pathData(
|
|
225
|
+
routeConnector({ start: from, end: to, routing: state.routing }).map((point) =>
|
|
226
|
+
inverse.apply(point),
|
|
227
|
+
),
|
|
228
|
+
);
|
|
229
|
+
if (path.getAttributeValue('d') !== d) path.attrs({ d });
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
private edit<Result>(label: string, run: () => Result): Result {
|
|
233
|
+
const group = beginChangeGroup(this.drawing, { source: 'connectors', label });
|
|
234
|
+
let result: Result;
|
|
235
|
+
try {
|
|
236
|
+
result = group.run(run);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
try {
|
|
239
|
+
group.cancel();
|
|
240
|
+
} catch (cleanup) {
|
|
241
|
+
throw new AggregateError([error, cleanup], 'Connector edit and rollback failed');
|
|
242
|
+
}
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
group.end();
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
248
|
+
}
|
package/src/editor.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { AnyNode, Svg } from '@rasamjs/core';
|
|
2
|
+
import { Connectors } from './connectors.js';
|
|
3
|
+
import { ConnectorTool } from './tool.js';
|
|
4
|
+
|
|
5
|
+
export interface ConnectorScope {
|
|
6
|
+
readonly drawing: Svg;
|
|
7
|
+
readonly editor: {
|
|
8
|
+
readonly paint: { readonly stroke: string; readonly strokeWidth: number };
|
|
9
|
+
readonly selection: { canSelect(node: AnyNode): boolean };
|
|
10
|
+
readonly layers: { isSelectable(node: AnyNode): boolean };
|
|
11
|
+
fail(action: string, error: unknown): void;
|
|
12
|
+
};
|
|
13
|
+
use<Value extends { destroy(): void }>(value: Value): Value;
|
|
14
|
+
registerTool(definition: {
|
|
15
|
+
id: string;
|
|
16
|
+
label: string;
|
|
17
|
+
key: string;
|
|
18
|
+
hint: string;
|
|
19
|
+
commandId: string;
|
|
20
|
+
activate(scope: ConnectorScope): { destroy(): void; key?(event: KeyboardEvent): boolean };
|
|
21
|
+
}): () => void;
|
|
22
|
+
cleanup(callback: () => void): void;
|
|
23
|
+
on(type: 'camera' | 'paint', callback: () => void): void;
|
|
24
|
+
gesture(): () => void;
|
|
25
|
+
created(node: AnyNode): void;
|
|
26
|
+
exit(): void;
|
|
27
|
+
}
|
|
28
|
+
export function connectorEditing() {
|
|
29
|
+
return {
|
|
30
|
+
id: 'connectors',
|
|
31
|
+
create(scope: ConnectorScope) {
|
|
32
|
+
const service = scope.use(new Connectors(scope.drawing));
|
|
33
|
+
for (const routing of ['straight', 'elbow'] as const)
|
|
34
|
+
scope.registerTool({
|
|
35
|
+
id: `connector-${routing}`,
|
|
36
|
+
commandId: `connector-${routing}`,
|
|
37
|
+
label: routing === 'straight' ? 'Connector' : 'Elbow connector',
|
|
38
|
+
key: routing === 'straight' ? 'C' : 'Shift+C',
|
|
39
|
+
hint: 'Drag between shapes to connect; hover to choose an anchor; Escape cancels.',
|
|
40
|
+
activate(current) {
|
|
41
|
+
const editor = current.editor;
|
|
42
|
+
let release = () => {},
|
|
43
|
+
dragging = false;
|
|
44
|
+
current.cleanup(() => release());
|
|
45
|
+
const tool = current.use(
|
|
46
|
+
new ConnectorTool(service, {
|
|
47
|
+
routing,
|
|
48
|
+
...editor.paint,
|
|
49
|
+
selectable: (node) =>
|
|
50
|
+
editor.selection.canSelect(node) && editor.layers.isSelectable(node),
|
|
51
|
+
onGesture(active) {
|
|
52
|
+
dragging = active;
|
|
53
|
+
release();
|
|
54
|
+
release = active ? current.gesture() : () => {};
|
|
55
|
+
},
|
|
56
|
+
onCreate: (path) => current.created(path),
|
|
57
|
+
onError: (error) => {
|
|
58
|
+
editor.fail('Draw connector', error);
|
|
59
|
+
current.exit();
|
|
60
|
+
},
|
|
61
|
+
onExit: () => current.exit(),
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
current.on('camera', () => tool.update());
|
|
65
|
+
current.on('paint', () => {
|
|
66
|
+
tool.paint = editor.paint;
|
|
67
|
+
});
|
|
68
|
+
tool.enabled = true;
|
|
69
|
+
return {
|
|
70
|
+
destroy() {},
|
|
71
|
+
key(event: KeyboardEvent) {
|
|
72
|
+
if (event.type !== 'keydown' || event.key !== 'Escape' || !dragging) return false;
|
|
73
|
+
tool.cancel();
|
|
74
|
+
return true;
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
return service;
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export { Connectors } from './connectors.js';
|
|
2
|
+
export { isConnector } from './metadata.js';
|
|
3
|
+
export { connectorPort, routeConnector } from './routing.js';
|
|
4
|
+
export type {
|
|
5
|
+
ConnectorTarget,
|
|
6
|
+
ConnectorAnchor,
|
|
7
|
+
ConnectorSide,
|
|
8
|
+
ConnectorEndpoint,
|
|
9
|
+
ConnectorRouting,
|
|
10
|
+
ConnectorOptions,
|
|
11
|
+
ConnectorState,
|
|
12
|
+
ConnectorPort,
|
|
13
|
+
ConnectorRoute,
|
|
14
|
+
} from './types.js';
|
package/src/metadata.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Path } from '@rasamjs/core';
|
|
2
|
+
import type { AnyNode } from '@rasamjs/core';
|
|
3
|
+
import { data } from '@rasamjs/core/data';
|
|
4
|
+
import type {
|
|
5
|
+
ConnectorAnchor,
|
|
6
|
+
ConnectorEndpoint,
|
|
7
|
+
ConnectorRouting,
|
|
8
|
+
ConnectorState,
|
|
9
|
+
} from './types.js';
|
|
10
|
+
import { validateAnchor, validatePoint } from './routing.js';
|
|
11
|
+
export const endpointAttribute = (end: 'start' | 'end') => `data-rasam-connector-${end}`;
|
|
12
|
+
const metadataKey = 'rasam-connector';
|
|
13
|
+
interface SavedEndpoint {
|
|
14
|
+
anchor?: ConnectorAnchor;
|
|
15
|
+
point?: import('@rasamjs/core').Point;
|
|
16
|
+
}
|
|
17
|
+
interface SavedConnector {
|
|
18
|
+
version: 1;
|
|
19
|
+
routing: ConnectorRouting;
|
|
20
|
+
start: SavedEndpoint;
|
|
21
|
+
end: SavedEndpoint;
|
|
22
|
+
}
|
|
23
|
+
export function isConnector(node: AnyNode): node is Path {
|
|
24
|
+
return node instanceof Path && node.getAttributeValue('data-rasam-connector') !== undefined;
|
|
25
|
+
}
|
|
26
|
+
export function readConnector(path: Path): ConnectorState {
|
|
27
|
+
const saved = data(path, metadataKey) as SavedConnector;
|
|
28
|
+
if (!saved || saved.version !== 1 || !['straight', 'elbow'].includes(saved.routing))
|
|
29
|
+
throw new TypeError('Invalid connector metadata');
|
|
30
|
+
const endpoint = (end: 'start' | 'end'): ConnectorEndpoint => {
|
|
31
|
+
const value = saved[end];
|
|
32
|
+
if (!value || typeof value !== 'object')
|
|
33
|
+
throw new TypeError('Invalid connector endpoint metadata');
|
|
34
|
+
if (value.point) {
|
|
35
|
+
validatePoint(value.point);
|
|
36
|
+
return { point: { ...value.point } };
|
|
37
|
+
}
|
|
38
|
+
const target = path.references.get(endpointAttribute(end));
|
|
39
|
+
if (!target || !('toRoot' in target))
|
|
40
|
+
throw new TypeError('Connector endpoint has no bound target');
|
|
41
|
+
validateAnchor(value.anchor ?? 'auto');
|
|
42
|
+
return {
|
|
43
|
+
target: target as import('./types.js').ConnectorTarget,
|
|
44
|
+
anchor: typeof value.anchor === 'object' ? { ...value.anchor } : (value.anchor ?? 'auto'),
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
return { path, start: endpoint('start'), end: endpoint('end'), routing: saved.routing };
|
|
48
|
+
}
|
|
49
|
+
export function writeConnector(path: Path, state: Omit<ConnectorState, 'path'>): void {
|
|
50
|
+
const save = (end: 'start' | 'end'): SavedEndpoint => {
|
|
51
|
+
const endpoint = state[end];
|
|
52
|
+
path.reference(endpointAttribute(end), 'target' in endpoint ? endpoint.target : null, 'href');
|
|
53
|
+
return 'point' in endpoint
|
|
54
|
+
? { point: { ...endpoint.point } }
|
|
55
|
+
: { anchor: endpoint.anchor ?? 'auto' };
|
|
56
|
+
};
|
|
57
|
+
data(path, metadataKey, {
|
|
58
|
+
version: 1,
|
|
59
|
+
routing: state.routing,
|
|
60
|
+
start: save('start'),
|
|
61
|
+
end: save('end'),
|
|
62
|
+
} satisfies SavedConnector);
|
|
63
|
+
}
|
package/src/routing.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { Point } from '@rasamjs/core';
|
|
2
|
+
import type {
|
|
3
|
+
ConnectorAnchor,
|
|
4
|
+
ConnectorEndpoint,
|
|
5
|
+
ConnectorPort,
|
|
6
|
+
ConnectorRoute,
|
|
7
|
+
ConnectorSide,
|
|
8
|
+
} from './types.js';
|
|
9
|
+
|
|
10
|
+
export function validatePoint(point: Point, normalized = false): void {
|
|
11
|
+
if (
|
|
12
|
+
!point ||
|
|
13
|
+
!Number.isFinite(point.x) ||
|
|
14
|
+
!Number.isFinite(point.y) ||
|
|
15
|
+
(normalized && (point.x < 0 || point.x > 1 || point.y < 0 || point.y > 1))
|
|
16
|
+
)
|
|
17
|
+
throw new TypeError(
|
|
18
|
+
normalized ? 'Anchor point must lie between 0 and 1' : 'Connector point must be finite',
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
export function validateAnchor(anchor: ConnectorAnchor): void {
|
|
22
|
+
if (typeof anchor === 'string') {
|
|
23
|
+
if (!['auto', 'top', 'right', 'bottom', 'left'].includes(anchor))
|
|
24
|
+
throw new TypeError('Unknown connector anchor');
|
|
25
|
+
} else validatePoint(anchor, true);
|
|
26
|
+
}
|
|
27
|
+
export function endpointCenter(endpoint: ConnectorEndpoint): Point | null {
|
|
28
|
+
if ('point' in endpoint) return endpoint.point;
|
|
29
|
+
const bounds = endpoint.target.bounds();
|
|
30
|
+
if (!('box' in bounds)) return null;
|
|
31
|
+
const { x, y, width, height } = bounds.box;
|
|
32
|
+
return endpoint.target.toRoot({ x: x + width / 2, y: y + height / 2 });
|
|
33
|
+
}
|
|
34
|
+
/** Resolve on the local box, then map into drawing units, retaining rotated anchors. */
|
|
35
|
+
export function connectorPort(endpoint: ConnectorEndpoint, toward: Point): ConnectorPort | null {
|
|
36
|
+
if ('point' in endpoint) return { point: endpoint.point, direction: { x: 0, y: 0 } };
|
|
37
|
+
const { target, anchor = 'auto' } = endpoint;
|
|
38
|
+
const bounds = target.bounds();
|
|
39
|
+
if (!('box' in bounds)) return null;
|
|
40
|
+
const { x, y, width, height } = bounds.box;
|
|
41
|
+
const center = { x: x + width / 2, y: y + height / 2 };
|
|
42
|
+
let side: ConnectorSide = 'right';
|
|
43
|
+
let point: Point;
|
|
44
|
+
if (typeof anchor === 'object') point = { x: x + anchor.x * width, y: y + anchor.y * height };
|
|
45
|
+
else if (anchor !== 'auto') {
|
|
46
|
+
side = anchor;
|
|
47
|
+
point = {
|
|
48
|
+
x: side === 'left' ? x : side === 'right' ? x + width : center.x,
|
|
49
|
+
y: side === 'top' ? y : side === 'bottom' ? y + height : center.y,
|
|
50
|
+
};
|
|
51
|
+
} else {
|
|
52
|
+
const local = target.fromRoot(toward);
|
|
53
|
+
if (!local) return null;
|
|
54
|
+
const dx = local.x - center.x,
|
|
55
|
+
dy = local.y - center.y;
|
|
56
|
+
const ratio = Math.max(
|
|
57
|
+
width ? Math.abs(dx) / (width / 2) : Infinity,
|
|
58
|
+
height ? Math.abs(dy) / (height / 2) : Infinity,
|
|
59
|
+
);
|
|
60
|
+
point =
|
|
61
|
+
ratio > 0 && Number.isFinite(ratio)
|
|
62
|
+
? { x: center.x + dx / ratio, y: center.y + dy / ratio }
|
|
63
|
+
: { x: x + width, y: center.y };
|
|
64
|
+
side =
|
|
65
|
+
Math.abs(point.x - center.x) / (width || 1) >= Math.abs(point.y - center.y) / (height || 1)
|
|
66
|
+
? dx < 0
|
|
67
|
+
? 'left'
|
|
68
|
+
: 'right'
|
|
69
|
+
: dy < 0
|
|
70
|
+
? 'top'
|
|
71
|
+
: 'bottom';
|
|
72
|
+
}
|
|
73
|
+
const root = target.toRoot(point);
|
|
74
|
+
const localDirection =
|
|
75
|
+
typeof anchor === 'object'
|
|
76
|
+
? { x: point.x - center.x, y: point.y - center.y }
|
|
77
|
+
: {
|
|
78
|
+
x: side === 'left' ? -1 : side === 'right' ? 1 : 0,
|
|
79
|
+
y: side === 'top' ? -1 : side === 'bottom' ? 1 : 0,
|
|
80
|
+
};
|
|
81
|
+
const offset = target.toRoot({ x: point.x + localDirection.x, y: point.y + localDirection.y });
|
|
82
|
+
const dx = offset.x - root.x,
|
|
83
|
+
dy = offset.y - root.y;
|
|
84
|
+
return {
|
|
85
|
+
point: root,
|
|
86
|
+
direction:
|
|
87
|
+
Math.abs(dx) >= Math.abs(dy) ? { x: Math.sign(dx), y: 0 } : { x: 0, y: Math.sign(dy) },
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Manhattan routing with short outward leads. It does not avoid other shapes. */
|
|
91
|
+
export function routeConnector({ start, end, routing }: ConnectorRoute): readonly Point[] {
|
|
92
|
+
if (routing === 'straight') return [start.point, end.point];
|
|
93
|
+
if (routing !== 'elbow') throw new TypeError('Unknown connector routing');
|
|
94
|
+
const lead = (port: ConnectorPort) => ({
|
|
95
|
+
x: port.point.x + port.direction.x * 16,
|
|
96
|
+
y: port.point.y + port.direction.y * 16,
|
|
97
|
+
});
|
|
98
|
+
const a = lead(start),
|
|
99
|
+
b = lead(end);
|
|
100
|
+
const horizontal =
|
|
101
|
+
start.direction.x !== 0 || (!start.direction.y && Math.abs(b.x - a.x) >= Math.abs(b.y - a.y));
|
|
102
|
+
const endHorizontal = end.direction.x !== 0 || (!end.direction.y && horizontal);
|
|
103
|
+
const bends =
|
|
104
|
+
horizontal !== endHorizontal
|
|
105
|
+
? [horizontal ? { x: b.x, y: a.y } : { x: a.x, y: b.y }]
|
|
106
|
+
: horizontal
|
|
107
|
+
? [
|
|
108
|
+
{ x: (a.x + b.x) / 2, y: a.y },
|
|
109
|
+
{ x: (a.x + b.x) / 2, y: b.y },
|
|
110
|
+
]
|
|
111
|
+
: [
|
|
112
|
+
{ x: a.x, y: (a.y + b.y) / 2 },
|
|
113
|
+
{ x: b.x, y: (a.y + b.y) / 2 },
|
|
114
|
+
];
|
|
115
|
+
return [start.point, a, ...bends, b, end.point].filter(
|
|
116
|
+
(point, index, points) =>
|
|
117
|
+
index === 0 || point.x !== points[index - 1].x || point.y !== points[index - 1].y,
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
export function pathData(points: readonly Point[]): string {
|
|
121
|
+
return points
|
|
122
|
+
.map(
|
|
123
|
+
(point, index) =>
|
|
124
|
+
`${index ? 'L' : 'M'}${Number(point.x.toFixed(6))} ${Number(point.y.toFixed(6))}`,
|
|
125
|
+
)
|
|
126
|
+
.join(' ');
|
|
127
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { Matrix } from '@rasamjs/core';
|
|
2
|
+
import type { Point, Svg } from '@rasamjs/core';
|
|
3
|
+
const namespace = 'http://www.w3.org/2000/svg';
|
|
4
|
+
export function svg<Tag extends keyof SVGElementTagNameMap>(
|
|
5
|
+
document: Document,
|
|
6
|
+
tag: Tag,
|
|
7
|
+
attributes: Record<string, string | number> = {},
|
|
8
|
+
): SVGElementTagNameMap[Tag] {
|
|
9
|
+
const element = document.createElementNS(namespace, tag);
|
|
10
|
+
for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value));
|
|
11
|
+
return element;
|
|
12
|
+
}
|
|
13
|
+
/** Connector UI lives outside the managed SVG; none of it can enter export/history. */
|
|
14
|
+
export class ToolSurface {
|
|
15
|
+
readonly element: SVGSVGElement;
|
|
16
|
+
readonly view: Window & typeof globalThis;
|
|
17
|
+
private readonly cleanups: (() => void)[] = [];
|
|
18
|
+
private pending: number | null = null;
|
|
19
|
+
private disposed = false;
|
|
20
|
+
constructor(
|
|
21
|
+
readonly drawing: Svg,
|
|
22
|
+
private readonly render: () => void,
|
|
23
|
+
) {
|
|
24
|
+
if (drawing.isDestroyed || !drawing.el.isConnected || !drawing.el.parentElement)
|
|
25
|
+
throw new TypeError('Connector tool needs a mounted drawing');
|
|
26
|
+
this.view = drawing.el.ownerDocument.defaultView!;
|
|
27
|
+
this.element = svg(drawing.el.ownerDocument, 'svg', {
|
|
28
|
+
class: 'rasam-connector-tool',
|
|
29
|
+
width: '100%',
|
|
30
|
+
height: '100%',
|
|
31
|
+
'aria-label': 'Connector tool',
|
|
32
|
+
});
|
|
33
|
+
Object.assign(this.element.style, {
|
|
34
|
+
position: 'absolute',
|
|
35
|
+
inset: '0',
|
|
36
|
+
overflow: 'visible',
|
|
37
|
+
pointerEvents: 'none',
|
|
38
|
+
touchAction: 'none',
|
|
39
|
+
zIndex: '25',
|
|
40
|
+
});
|
|
41
|
+
drawing.el.parentElement.append(this.element);
|
|
42
|
+
this.listen(this.view, 'resize', this.schedule);
|
|
43
|
+
this.listen(this.view, 'scroll', this.schedule, true);
|
|
44
|
+
const mutation = new this.view.MutationObserver(this.schedule);
|
|
45
|
+
mutation.observe(drawing.el, { attributes: true });
|
|
46
|
+
const resize = new this.view.ResizeObserver(this.schedule);
|
|
47
|
+
resize.observe(drawing.el);
|
|
48
|
+
this.cleanup(() => {
|
|
49
|
+
mutation.disconnect();
|
|
50
|
+
resize.disconnect();
|
|
51
|
+
});
|
|
52
|
+
this.cleanup(drawing.onDispose(() => this.destroy()));
|
|
53
|
+
}
|
|
54
|
+
get isDestroyed(): boolean {
|
|
55
|
+
return this.disposed;
|
|
56
|
+
}
|
|
57
|
+
cleanup(stop: () => void): void {
|
|
58
|
+
this.cleanups.push(stop);
|
|
59
|
+
}
|
|
60
|
+
listen(target: EventTarget, type: string, listener: EventListener, capture = false): void {
|
|
61
|
+
target.addEventListener(type, listener, capture);
|
|
62
|
+
this.cleanup(() => target.removeEventListener(type, listener, capture));
|
|
63
|
+
}
|
|
64
|
+
fromRoot(point: Point): Point | null {
|
|
65
|
+
const client = this.drawing.toClient(point),
|
|
66
|
+
m = this.element.getScreenCTM?.();
|
|
67
|
+
return client && m
|
|
68
|
+
? (new Matrix(m.a, m.b, m.c, m.d, m.e, m.f).inverse()?.apply(client) ?? null)
|
|
69
|
+
: null;
|
|
70
|
+
}
|
|
71
|
+
readonly schedule = (): void => {
|
|
72
|
+
if (!this.disposed && this.pending === null)
|
|
73
|
+
this.pending = this.view.requestAnimationFrame(() => {
|
|
74
|
+
this.pending = null;
|
|
75
|
+
this.render();
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
update(): void {
|
|
79
|
+
if (!this.disposed) this.render();
|
|
80
|
+
}
|
|
81
|
+
destroy(): void {
|
|
82
|
+
if (this.disposed) return;
|
|
83
|
+
this.disposed = true;
|
|
84
|
+
if (this.pending !== null) this.view.cancelAnimationFrame(this.pending);
|
|
85
|
+
const failures: unknown[] = [];
|
|
86
|
+
for (const stop of this.cleanups.splice(0).reverse()) {
|
|
87
|
+
try {
|
|
88
|
+
stop();
|
|
89
|
+
} catch (error) {
|
|
90
|
+
failures.push(error);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
this.element.remove();
|
|
94
|
+
if (failures.length) throw new AggregateError(failures, 'Connector tool cleanup failed');
|
|
95
|
+
}
|
|
96
|
+
}
|