@luutuankiet/clipboard2markdown 0.1.0 → 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/README.md +121 -91
- package/bin/cli.js +32 -8
- package/bin/diagrams.js +142 -0
- package/bin/excalidraw.js +167 -0
- package/package.json +3 -2
- package/src/diagrams/browser.js +4 -0
- package/src/diagrams/edit.js +523 -0
- package/src/diagrams/index.js +8 -0
- package/src/diagrams/markdown.js +152 -0
- package/src/diagrams/scene-model.js +453 -0
- package/src/diagrams/scene-to-mermaid.js +168 -0
- package/src/diagrams/share-link.js +179 -0
- package/src/diagrams/skeleton.js +321 -0
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
// Patch an existing canvas in place with a small set of operations, so the
|
|
2
|
+
// human's layout, colours and annotations survive an agent's change.
|
|
3
|
+
//
|
|
4
|
+
// Ops reference the Mermaid ids printed by sceneToMermaid; they are resolved with
|
|
5
|
+
// the same analyzeScene, re-run after every op. applyEdits works on a deep copy
|
|
6
|
+
// and throws on the first bad op, so a typo never yields a half-edited canvas.
|
|
7
|
+
|
|
8
|
+
import { analyzeScene, bounds, center, isReadableId } from './scene-model.js';
|
|
9
|
+
import { sceneToMermaid, flowDirection } from './scene-to-mermaid.js';
|
|
10
|
+
import { loadScene, saveScene, parseShareLink, normalizeScene } from './share-link.js';
|
|
11
|
+
|
|
12
|
+
// Text size estimate for Excalidraw's default hand-drawn font. Errs wide so new
|
|
13
|
+
// or renamed labels do not clip.
|
|
14
|
+
export const TEXT_METRICS = { charWidth: 0.68, lineHeight: 1.25, padding: 10 };
|
|
15
|
+
// Room between boxes for a labelled arrow to stay visible.
|
|
16
|
+
const DEFAULT_GAP = 120;
|
|
17
|
+
const GROUP_PADDING = 24;
|
|
18
|
+
|
|
19
|
+
const OP_FIELDS = {
|
|
20
|
+
rename: ['node', 'label'],
|
|
21
|
+
add: ['id', 'label', 'near'],
|
|
22
|
+
connect: ['from', 'to'],
|
|
23
|
+
disconnect: ['from', 'to'],
|
|
24
|
+
'relabel-edge': ['from', 'to', 'label'],
|
|
25
|
+
remove: ['node'],
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function randomInt() { return Math.floor(Math.random() * 2 ** 31); }
|
|
29
|
+
|
|
30
|
+
function randomId() {
|
|
31
|
+
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
32
|
+
var bytes = globalThis.crypto.getRandomValues(new Uint8Array(20));
|
|
33
|
+
return Array.from(bytes, function (b) { return alphabet[b % alphabet.length]; }).join('');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function touch(el) {
|
|
37
|
+
el.version = (el.version || 1) + 1;
|
|
38
|
+
el.versionNonce = randomInt();
|
|
39
|
+
el.updated = Date.now();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function measureText(text, fontSize) {
|
|
43
|
+
var lines = String(text).split('\n');
|
|
44
|
+
var longest = Math.max.apply(null, lines.map(function (l) { return l.length; }));
|
|
45
|
+
return {
|
|
46
|
+
width: Math.ceil(Math.max(1, longest) * TEXT_METRICS.charWidth * fontSize),
|
|
47
|
+
height: Math.ceil(lines.length * TEXT_METRICS.lineHeight * fontSize),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// How much bigger than its text a container must be, by shape.
|
|
52
|
+
export function containerFactor(type) {
|
|
53
|
+
if (type === 'ellipse') return Math.SQRT2;
|
|
54
|
+
if (type === 'diamond') return 2;
|
|
55
|
+
return 1;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Word-wrap to the container's width, as Excalidraw does for bound text: the
|
|
59
|
+
// box keeps its width (so arrow ends at its sides stay outside it) and grows in
|
|
60
|
+
// height. A single word longer than a line still widens the box.
|
|
61
|
+
export function wrapLabel(label, fontSize, containerWidth, type) {
|
|
62
|
+
var avail = containerWidth / containerFactor(type) - 2 * TEXT_METRICS.padding;
|
|
63
|
+
var maxChars = Math.max(1, Math.floor(avail / (TEXT_METRICS.charWidth * fontSize)));
|
|
64
|
+
return String(label).split('\n').map(function (para) {
|
|
65
|
+
var lines = [];
|
|
66
|
+
var line = '';
|
|
67
|
+
para.split(/\s+/).filter(Boolean).forEach(function (word) {
|
|
68
|
+
if (!line) line = word;
|
|
69
|
+
else if ((line + ' ' + word).length <= maxChars) line += ' ' + word;
|
|
70
|
+
else { lines.push(line); line = word; }
|
|
71
|
+
});
|
|
72
|
+
lines.push(line);
|
|
73
|
+
return lines.join('\n');
|
|
74
|
+
}).join('\n');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Size the text element to its content and centre it in its container,
|
|
78
|
+
// growing the container (around its centre) when the text would not fit.
|
|
79
|
+
// `originalText` keeps the unwrapped label; that is what the reader prints.
|
|
80
|
+
function fitBoundText(textEl, container) {
|
|
81
|
+
if (container && container.type !== 'arrow') {
|
|
82
|
+
textEl.text = wrapLabel(textEl.originalText != null ? textEl.originalText : textEl.text, textEl.fontSize || 20, container.width, container.type);
|
|
83
|
+
}
|
|
84
|
+
var size = measureText(textEl.text, textEl.fontSize || 20);
|
|
85
|
+
textEl.width = size.width;
|
|
86
|
+
textEl.height = size.height;
|
|
87
|
+
if (container) {
|
|
88
|
+
var f = containerFactor(container.type);
|
|
89
|
+
var needW = Math.ceil((size.width + 2 * TEXT_METRICS.padding) * f);
|
|
90
|
+
var needH = Math.ceil((size.height + 2 * TEXT_METRICS.padding) * f);
|
|
91
|
+
if (container.type !== 'arrow' && (container.width < needW || container.height < needH)) {
|
|
92
|
+
var c = center(container);
|
|
93
|
+
container.width = Math.max(container.width, needW);
|
|
94
|
+
container.height = Math.max(container.height, needH);
|
|
95
|
+
container.x = c[0] - container.width / 2;
|
|
96
|
+
container.y = c[1] - container.height / 2;
|
|
97
|
+
touch(container);
|
|
98
|
+
}
|
|
99
|
+
var cc = container.type === 'arrow' ? arrowMidpoint(container) : center(container);
|
|
100
|
+
textEl.x = cc[0] - size.width / 2;
|
|
101
|
+
textEl.y = cc[1] - size.height / 2;
|
|
102
|
+
}
|
|
103
|
+
touch(textEl);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function arrowMidpoint(arrow) {
|
|
107
|
+
var pts = arrow.points || [[0, 0]];
|
|
108
|
+
var a = pts[Math.floor((pts.length - 1) / 2)], b = pts[Math.ceil((pts.length - 1) / 2)];
|
|
109
|
+
if (pts.length % 2 === 1) return [arrow.x + a[0], arrow.y + a[1]];
|
|
110
|
+
return [arrow.x + (a[0] + b[0]) / 2, arrow.y + (a[1] + b[1]) / 2];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function setText(textEl, label) {
|
|
114
|
+
textEl.text = label;
|
|
115
|
+
textEl.originalText = label;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function newText(template, overrides) {
|
|
119
|
+
return Object.assign({
|
|
120
|
+
type: 'text', id: randomId(), x: 0, y: 0, width: 0, height: 0, angle: 0,
|
|
121
|
+
strokeColor: '#1e1e1e', backgroundColor: 'transparent', fillStyle: 'solid', strokeWidth: 2,
|
|
122
|
+
strokeStyle: 'solid', roughness: 1, opacity: 100, groupIds: [], frameId: null, roundness: null,
|
|
123
|
+
seed: randomInt(), version: 1, versionNonce: randomInt(), isDeleted: false, boundElements: null,
|
|
124
|
+
updated: Date.now(), link: null, locked: false, text: '', fontSize: 20, fontFamily: 5,
|
|
125
|
+
textAlign: 'center', verticalAlign: 'middle', containerId: null, originalText: '',
|
|
126
|
+
autoResize: true, lineHeight: 1.25,
|
|
127
|
+
}, template ? {
|
|
128
|
+
strokeColor: template.strokeColor, fontSize: template.fontSize, fontFamily: template.fontFamily,
|
|
129
|
+
lineHeight: template.lineHeight || 1.25, opacity: template.opacity,
|
|
130
|
+
} : {}, overrides);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function addBound(el, ref) {
|
|
134
|
+
el.boundElements = (el.boundElements || []).filter(function (b) { return b.id !== ref.id; }).concat([ref]);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function dropBound(el, id) {
|
|
138
|
+
if (!el.boundElements) return;
|
|
139
|
+
var next = el.boundElements.filter(function (b) { return b.id !== id; });
|
|
140
|
+
if (next.length !== el.boundElements.length) { el.boundElements = next; touch(el); }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ------------------------------------------------------------------ errors ---
|
|
144
|
+
|
|
145
|
+
function validIds(model) {
|
|
146
|
+
return Array.from(model.byMermaidId.keys()).sort().join(', ') || '(none)';
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function resolve(model, id, field, allowGroups) {
|
|
150
|
+
var item = model.byMermaidId.get(id);
|
|
151
|
+
if (!item || (!allowGroups && item.kind !== 'node')) {
|
|
152
|
+
throw new Error('unknown ' + (allowGroups ? 'node or subgraph' : 'node') + ' "' + id + '" in ' + field + '; valid ids: ' + validIds(model));
|
|
153
|
+
}
|
|
154
|
+
return item;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function findEdges(model, from, to) {
|
|
158
|
+
var a = resolve(model, from, 'from', true).el.id;
|
|
159
|
+
var b = resolve(model, to, 'to', true).el.id;
|
|
160
|
+
var hits = model.edges.filter(function (e) { return e.from === a && e.to === b; });
|
|
161
|
+
if (!hits.length) {
|
|
162
|
+
hits = model.edges.filter(function (e) { return e.kind !== 'arrow' && e.from === b && e.to === a; });
|
|
163
|
+
}
|
|
164
|
+
if (!hits.length) {
|
|
165
|
+
var known = model.edges.map(function (e) { return model.mermaidId(e.from) + '->' + model.mermaidId(e.to); }).join(', ');
|
|
166
|
+
throw new Error('no edge from "' + from + '" to "' + to + '"; edges: ' + (known || '(none)'));
|
|
167
|
+
}
|
|
168
|
+
return hits;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// --------------------------------------------------------------------- ops ---
|
|
172
|
+
|
|
173
|
+
function removeElements(scene, ids) {
|
|
174
|
+
var gone = new Set(ids);
|
|
175
|
+
scene.elements = scene.elements.filter(function (el) { return !gone.has(el.id); });
|
|
176
|
+
scene.elements.forEach(function (el) {
|
|
177
|
+
if (el.boundElements && el.boundElements.some(function (b) { return gone.has(b.id); })) {
|
|
178
|
+
el.boundElements = el.boundElements.filter(function (b) { return !gone.has(b.id); });
|
|
179
|
+
touch(el);
|
|
180
|
+
}
|
|
181
|
+
['startBinding', 'endBinding'].forEach(function (k) {
|
|
182
|
+
if (el[k] && gone.has(el[k].elementId)) { el[k] = null; touch(el); }
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function opRename(scene, model, op) {
|
|
188
|
+
var item = resolve(model, op.node, 'node', true);
|
|
189
|
+
var label = item.label;
|
|
190
|
+
if (label.frameName) { item.el.name = op.label; touch(item.el); return; }
|
|
191
|
+
if (!label.els.length) {
|
|
192
|
+
var t = newText(null, { containerId: item.el.id, frameId: item.el.frameId || null });
|
|
193
|
+
setText(t, op.label);
|
|
194
|
+
addBound(item.el, { type: 'text', id: t.id });
|
|
195
|
+
scene.elements.push(t);
|
|
196
|
+
fitBoundText(t, item.el);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
var first = label.els[0];
|
|
200
|
+
setText(first, op.label);
|
|
201
|
+
if (label.bound) {
|
|
202
|
+
fitBoundText(first, item.el);
|
|
203
|
+
} else {
|
|
204
|
+
var c = center(first);
|
|
205
|
+
fitBoundText(first, null);
|
|
206
|
+
first.x = c[0] - first.width / 2;
|
|
207
|
+
first.y = c[1] - first.height / 2;
|
|
208
|
+
if (item.kind === 'node') growToFit(item.el, first);
|
|
209
|
+
}
|
|
210
|
+
// A label spread over several free texts collapses into the first one.
|
|
211
|
+
if (label.els.length > 1) removeElements(scene, label.els.slice(1).map(function (e) { return e.id; }));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function growToFit(shape, textEl) {
|
|
215
|
+
var f = containerFactor(shape.type);
|
|
216
|
+
var needW = Math.ceil((textEl.width + 2 * TEXT_METRICS.padding) * f);
|
|
217
|
+
var needH = Math.ceil((textEl.height + 2 * TEXT_METRICS.padding) * f);
|
|
218
|
+
if (shape.width >= needW && shape.height >= needH) return;
|
|
219
|
+
var c = center(shape);
|
|
220
|
+
shape.width = Math.max(shape.width, needW);
|
|
221
|
+
shape.height = Math.max(shape.height, needH);
|
|
222
|
+
shape.x = c[0] - shape.width / 2;
|
|
223
|
+
shape.y = c[1] - shape.height / 2;
|
|
224
|
+
touch(shape);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function overlaps(a, b, margin) {
|
|
228
|
+
return a.x < b.x + b.w + margin && b.x < a.x + a.w + margin && a.y < b.y + b.h + margin && b.y < a.y + a.h + margin;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function ancestors(model, item) {
|
|
232
|
+
var out = [];
|
|
233
|
+
var p = item.parent;
|
|
234
|
+
while (p && model.groups.has(p)) { out.push(model.groups.get(p)); p = model.groups.get(p).parent; }
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function opAdd(scene, model, op) {
|
|
239
|
+
if (!isReadableId(op.id)) {
|
|
240
|
+
throw new Error('add: id "' + op.id + '" must match ^[A-Za-z][A-Za-z0-9_]{0,23}$ and not be a Mermaid keyword');
|
|
241
|
+
}
|
|
242
|
+
if (model.byMermaidId.has(op.id) || model.byId.has(op.id)) {
|
|
243
|
+
throw new Error('add: id "' + op.id + '" already exists; valid ids: ' + validIds(model));
|
|
244
|
+
}
|
|
245
|
+
var anchor = resolve(model, op.near, 'near', false);
|
|
246
|
+
var side = op.side || (flowDirection(model) === 'LR' ? 'right' : 'below');
|
|
247
|
+
if (['right', 'left', 'below', 'above'].indexOf(side) < 0) throw new Error('add: side must be right, left, below or above');
|
|
248
|
+
|
|
249
|
+
var a = anchor.el;
|
|
250
|
+
var anchorText = anchor.label.els[0];
|
|
251
|
+
var fontSize = (anchorText && anchorText.fontSize) || 20;
|
|
252
|
+
var size = measureText(wrapLabel(op.label, fontSize, a.width, a.type), fontSize);
|
|
253
|
+
var f = containerFactor(a.type);
|
|
254
|
+
var w = Math.max(a.width, Math.ceil((size.width + 2 * TEXT_METRICS.padding) * f));
|
|
255
|
+
var h = Math.max(a.height, Math.ceil((size.height + 2 * TEXT_METRICS.padding) * f));
|
|
256
|
+
|
|
257
|
+
var start = function (sd, ab) {
|
|
258
|
+
return {
|
|
259
|
+
right: [ab.x + ab.w + DEFAULT_GAP, ab.y + ab.h / 2 - h / 2],
|
|
260
|
+
left: [ab.x - DEFAULT_GAP - w, ab.y + ab.h / 2 - h / 2],
|
|
261
|
+
below: [ab.x + ab.w / 2 - w / 2, ab.y + ab.h + DEFAULT_GAP],
|
|
262
|
+
above: [ab.x + ab.w / 2 - w / 2, ab.y - DEFAULT_GAP - h],
|
|
263
|
+
}[sd];
|
|
264
|
+
};
|
|
265
|
+
var stepFor = function (sd) { return sd === 'right' || sd === 'left' ? [0, h + DEFAULT_GAP / 2] : [w + DEFAULT_GAP / 2, 0]; };
|
|
266
|
+
|
|
267
|
+
var groupChain = ancestors(model, anchor);
|
|
268
|
+
var ancestorIds = new Set(groupChain.map(function (g) { return g.el.id; }));
|
|
269
|
+
var obstaclesFor = function (skip) {
|
|
270
|
+
return scene.elements.filter(function (el) {
|
|
271
|
+
return !el.isDeleted && el.type !== 'arrow' && !(el.type === 'line') && !el.containerId && !skip.has(el.id);
|
|
272
|
+
}).map(bounds);
|
|
273
|
+
};
|
|
274
|
+
// Growing an enclosing group must not swallow a box that is not in it.
|
|
275
|
+
var outsiders = groupChain.map(function (g) {
|
|
276
|
+
return Array.from(model.nodes.values()).concat(Array.from(model.groups.values())).filter(function (o) {
|
|
277
|
+
return o !== g && groupChain.indexOf(o) < 0 && !isInside(model, o, g);
|
|
278
|
+
}).map(function (o) { return bounds(o.el); });
|
|
279
|
+
});
|
|
280
|
+
var blockedBy = function (obstacles, chain) {
|
|
281
|
+
return function (b) {
|
|
282
|
+
if (obstacles.some(function (o) { return overlaps(b, o, 16); })) return true;
|
|
283
|
+
return chain.some(function (g, i) {
|
|
284
|
+
var grown = grownBounds(bounds(g.el), b);
|
|
285
|
+
return outsiders[i].some(function (o) { return overlaps(grown, o, 0) && !overlaps(bounds(g.el), o, 0); });
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
};
|
|
289
|
+
// Requested side first; if every slot there is blocked, the other sides.
|
|
290
|
+
var search = function (ab, blocked) {
|
|
291
|
+
var sides = [side].concat(['right', 'below', 'left', 'above'].filter(function (sd) { return sd !== side; }));
|
|
292
|
+
for (var si = 0; si < sides.length; si++) {
|
|
293
|
+
var p = start(sides[si], ab), st = stepFor(sides[si]);
|
|
294
|
+
var b = { x: p[0], y: p[1], w: w, h: h };
|
|
295
|
+
for (var tries = 0; tries < 12; tries++) {
|
|
296
|
+
if (!blocked(b)) return { box: b, side: sides[si] };
|
|
297
|
+
b = { x: b.x + st[0], y: b.y + st[1], w: w, h: h };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return null;
|
|
301
|
+
};
|
|
302
|
+
var found = search(bounds(a), blockedBy(obstaclesFor(ancestorIds), groupChain));
|
|
303
|
+
var note = null;
|
|
304
|
+
if (found && found.side !== side) note = side + ' of ' + op.near + ' was blocked; placed ' + found.side + ' instead';
|
|
305
|
+
// A group hemmed in on every side cannot grow: place the node just outside
|
|
306
|
+
// the outermost group rather than on top of whatever surrounds it.
|
|
307
|
+
if (!found && groupChain.length) {
|
|
308
|
+
var outer = groupChain[groupChain.length - 1];
|
|
309
|
+
found = search(bounds(outer.el), blockedBy(obstaclesFor(new Set()), []));
|
|
310
|
+
if (found) {
|
|
311
|
+
note = 'no room inside ' + outer.id + ' for ' + op.id + '; placed ' + found.side + ' of ' + outer.id + ', outside it';
|
|
312
|
+
groupChain = [];
|
|
313
|
+
outside = true;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
var box, outside = false;
|
|
317
|
+
if (found) {
|
|
318
|
+
box = found.box;
|
|
319
|
+
} else {
|
|
320
|
+
var p0 = start(side, bounds(a));
|
|
321
|
+
box = { x: p0[0], y: p0[1], w: w, h: h };
|
|
322
|
+
note = 'no free spot next to ' + op.near + '; placed ' + side + ' anyway, it may overlap';
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
var shape = Object.assign({}, a, {
|
|
326
|
+
id: op.id, x: box.x, y: box.y, width: w, height: h, groupIds: [], boundElements: [], frameId: outside ? null : a.frameId || null,
|
|
327
|
+
seed: randomInt(), version: 1, versionNonce: randomInt(), updated: Date.now(), isDeleted: false, link: null, locked: false,
|
|
328
|
+
});
|
|
329
|
+
delete shape.index;
|
|
330
|
+
var text = newText(anchorText, { containerId: op.id, frameId: outside ? null : a.frameId || null });
|
|
331
|
+
setText(text, op.label);
|
|
332
|
+
shape.boundElements = [{ type: 'text', id: text.id }];
|
|
333
|
+
scene.elements.push(shape, text);
|
|
334
|
+
fitBoundText(text, shape);
|
|
335
|
+
|
|
336
|
+
// Grow every enclosing group box, innermost first, so the new node stays inside.
|
|
337
|
+
var inner = bounds(shape);
|
|
338
|
+
groupChain.forEach(function (g) {
|
|
339
|
+
var gb = bounds(g.el);
|
|
340
|
+
var grown = grownBounds(gb, inner);
|
|
341
|
+
if (grown.x !== gb.x || grown.y !== gb.y || grown.w !== gb.w || grown.h !== gb.h) {
|
|
342
|
+
g.el.x = grown.x; g.el.y = grown.y; g.el.width = grown.w; g.el.height = grown.h;
|
|
343
|
+
touch(g.el);
|
|
344
|
+
}
|
|
345
|
+
inner = grown;
|
|
346
|
+
});
|
|
347
|
+
return note;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function grownBounds(gb, nb) {
|
|
351
|
+
var x1 = Math.min(gb.x, nb.x - GROUP_PADDING), y1 = Math.min(gb.y, nb.y - GROUP_PADDING);
|
|
352
|
+
var x2 = Math.max(gb.x + gb.w, nb.x + nb.w + GROUP_PADDING), y2 = Math.max(gb.y + gb.h, nb.y + nb.h + GROUP_PADDING);
|
|
353
|
+
return { x: x1, y: y1, w: x2 - x1, h: y2 - y1 };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function isInside(model, item, group) {
|
|
357
|
+
var p = item.parent;
|
|
358
|
+
while (p) {
|
|
359
|
+
if (p === group.el.id) return true;
|
|
360
|
+
p = model.groups.has(p) ? model.groups.get(p).parent : null;
|
|
361
|
+
}
|
|
362
|
+
return false;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Point where the ray from a box centre towards `toward` leaves the box.
|
|
366
|
+
function borderPoint(el, toward) {
|
|
367
|
+
var b = bounds(el), c = [b.x + b.w / 2, b.y + b.h / 2];
|
|
368
|
+
var dx = toward[0] - c[0], dy = toward[1] - c[1];
|
|
369
|
+
if (!dx && !dy) return c;
|
|
370
|
+
var sx = dx ? (b.w / 2) / Math.abs(dx) : Infinity;
|
|
371
|
+
var sy = dy ? (b.h / 2) / Math.abs(dy) : Infinity;
|
|
372
|
+
var s = Math.min(sx, sy);
|
|
373
|
+
if (el.type === 'ellipse' || el.type === 'diamond') {
|
|
374
|
+
// Ellipse: exact; diamond: |x|/a + |y|/b = 1.
|
|
375
|
+
var a = b.w / 2, bb = b.h / 2;
|
|
376
|
+
s = el.type === 'ellipse'
|
|
377
|
+
? 1 / Math.sqrt((dx * dx) / (a * a) + (dy * dy) / (bb * bb))
|
|
378
|
+
: 1 / (Math.abs(dx) / a + Math.abs(dy) / bb);
|
|
379
|
+
}
|
|
380
|
+
return [c[0] + dx * s, c[1] + dy * s];
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function opConnect(scene, model, op) {
|
|
384
|
+
var from = resolve(model, op.from, 'from', true).el;
|
|
385
|
+
var to = resolve(model, op.to, 'to', true).el;
|
|
386
|
+
if (from === to) throw new Error('connect: from and to are the same element');
|
|
387
|
+
var gap = 6;
|
|
388
|
+
var p1 = borderPoint(from, center(to)), p2 = borderPoint(to, center(from));
|
|
389
|
+
var len = Math.hypot(p2[0] - p1[0], p2[1] - p1[1]) || 1;
|
|
390
|
+
var ux = (p2[0] - p1[0]) / len, uy = (p2[1] - p1[1]) / len;
|
|
391
|
+
p1 = [p1[0] + ux * gap, p1[1] + uy * gap];
|
|
392
|
+
p2 = [p2[0] - ux * gap, p2[1] - uy * gap];
|
|
393
|
+
|
|
394
|
+
var template = scene.elements.find(function (el) { return !el.isDeleted && el.type === 'arrow'; }) || {};
|
|
395
|
+
var arrow = {
|
|
396
|
+
type: 'arrow', id: randomId(), x: p1[0], y: p1[1], width: Math.abs(p2[0] - p1[0]), height: Math.abs(p2[1] - p1[1]),
|
|
397
|
+
angle: 0, strokeColor: template.strokeColor || '#1e1e1e', backgroundColor: 'transparent', fillStyle: 'solid',
|
|
398
|
+
strokeWidth: template.strokeWidth || 2, strokeStyle: op.dashed ? 'dashed' : 'solid',
|
|
399
|
+
roughness: template.roughness != null ? template.roughness : 1, opacity: 100, groupIds: [],
|
|
400
|
+
frameId: from.frameId && from.frameId === to.frameId ? from.frameId : null,
|
|
401
|
+
roundness: template.roundness !== undefined ? template.roundness : { type: 2 },
|
|
402
|
+
seed: randomInt(), version: 1, versionNonce: randomInt(), isDeleted: false, boundElements: [],
|
|
403
|
+
updated: Date.now(), link: null, locked: false,
|
|
404
|
+
points: [[0, 0], [p2[0] - p1[0], p2[1] - p1[1]]], lastCommittedPoint: null,
|
|
405
|
+
startBinding: { elementId: from.id, focus: 0, gap: gap }, endBinding: { elementId: to.id, focus: 0, gap: gap },
|
|
406
|
+
startArrowhead: null, endArrowhead: 'arrow', elbowed: false,
|
|
407
|
+
};
|
|
408
|
+
scene.elements.push(arrow);
|
|
409
|
+
addBound(from, { type: 'arrow', id: arrow.id }); touch(from);
|
|
410
|
+
addBound(to, { type: 'arrow', id: arrow.id }); touch(to);
|
|
411
|
+
if (op.label) attachEdgeLabel(scene, arrow, op.label);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function attachEdgeLabel(scene, arrow, label) {
|
|
415
|
+
var template = scene.elements.find(function (el) { return !el.isDeleted && el.type === 'text'; });
|
|
416
|
+
var t = newText(template, { containerId: arrow.id, frameId: arrow.frameId || null, fontSize: template && template.fontSize ? Math.min(template.fontSize, 16) : 16 });
|
|
417
|
+
setText(t, label);
|
|
418
|
+
addBound(arrow, { type: 'text', id: t.id });
|
|
419
|
+
scene.elements.push(t);
|
|
420
|
+
fitBoundText(t, arrow);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function edgeElementIds(e) {
|
|
424
|
+
var ids = [e.el.id];
|
|
425
|
+
if (e.label) e.label.els.forEach(function (t) { ids.push(t.id); });
|
|
426
|
+
return ids;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function opDisconnect(scene, model, op) {
|
|
430
|
+
var hits = findEdges(model, op.from, op.to);
|
|
431
|
+
removeElements(scene, hits.reduce(function (acc, e) { return acc.concat(edgeElementIds(e)); }, []));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function opRelabelEdge(scene, model, op) {
|
|
435
|
+
findEdges(model, op.from, op.to).forEach(function (e) {
|
|
436
|
+
var arrow = scene.elements.find(function (el) { return el.id === e.el.id; });
|
|
437
|
+
if (!op.label) {
|
|
438
|
+
if (e.label) removeElements(scene, e.label.els.map(function (t) { return t.id; }));
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
if (!e.label) { attachEdgeLabel(scene, arrow, op.label); return; }
|
|
442
|
+
var t = e.label.els[0];
|
|
443
|
+
setText(t, op.label);
|
|
444
|
+
if (e.label.bound) {
|
|
445
|
+
fitBoundText(t, arrow);
|
|
446
|
+
} else {
|
|
447
|
+
var c = center(t);
|
|
448
|
+
fitBoundText(t, null);
|
|
449
|
+
t.x = c[0] - t.width / 2;
|
|
450
|
+
t.y = c[1] - t.height / 2;
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function opRemove(scene, model, op) {
|
|
456
|
+
var item = resolve(model, op.node, 'node', true);
|
|
457
|
+
var ids = [item.el.id].concat(item.label.els.map(function (t) { return t.id; }));
|
|
458
|
+
model.edges.concat(model.unresolved).forEach(function (e) {
|
|
459
|
+
if (e.from === item.el.id || e.to === item.el.id) ids = ids.concat(edgeElementIds(e));
|
|
460
|
+
});
|
|
461
|
+
// Arrows bound to it that the reader could not resolve still go.
|
|
462
|
+
scene.elements.forEach(function (el) {
|
|
463
|
+
if ((el.startBinding && el.startBinding.elementId === item.el.id) || (el.endBinding && el.endBinding.elementId === item.el.id)) {
|
|
464
|
+
ids.push(el.id);
|
|
465
|
+
scene.elements.forEach(function (t) { if (t.containerId === el.id) ids.push(t.id); });
|
|
466
|
+
}
|
|
467
|
+
if (el.containerId === item.el.id) ids.push(el.id);
|
|
468
|
+
});
|
|
469
|
+
removeElements(scene, ids);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const OPS = { rename: opRename, add: opAdd, connect: opConnect, disconnect: opDisconnect, 'relabel-edge': opRelabelEdge, remove: opRemove };
|
|
473
|
+
|
|
474
|
+
function checkShape(op, index) {
|
|
475
|
+
if (!op || typeof op !== 'object') throw new Error('op ' + index + ' is not an object');
|
|
476
|
+
var fields = OP_FIELDS[op.op];
|
|
477
|
+
if (!fields) throw new Error('op ' + index + ': unknown op "' + op.op + '"; valid ops: ' + Object.keys(OP_FIELDS).join(', '));
|
|
478
|
+
fields.forEach(function (f) {
|
|
479
|
+
if (typeof op[f] !== 'string' || (f !== 'label' && !op[f])) {
|
|
480
|
+
throw new Error('op ' + index + ' (' + op.op + '): field "' + f + '" must be a string');
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// Pure: returns a new scene. Throws before returning anything if any op is bad.
|
|
486
|
+
export function applyEdits(scene, ops) {
|
|
487
|
+
if (!Array.isArray(ops)) throw new Error('ops must be a JSON array');
|
|
488
|
+
ops.forEach(checkShape);
|
|
489
|
+
var working = normalizeScene(JSON.parse(JSON.stringify(scene)));
|
|
490
|
+
var report = [];
|
|
491
|
+
ops.forEach(function (op, i) {
|
|
492
|
+
var model = analyzeScene(working);
|
|
493
|
+
var note;
|
|
494
|
+
try {
|
|
495
|
+
note = OPS[op.op](working, model, op);
|
|
496
|
+
} catch (err) {
|
|
497
|
+
throw new Error('op ' + i + ' (' + op.op + '): ' + err.message);
|
|
498
|
+
}
|
|
499
|
+
report.push('op ' + i + ' (' + op.op + ') ok' + (note ? ': ' + note : ''));
|
|
500
|
+
});
|
|
501
|
+
return { scene: working, report: report };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// Link (or scene object) in, one new link out. Validation happens before upload.
|
|
505
|
+
export async function editLink(urlOrScene, ops, options) {
|
|
506
|
+
options = options || {};
|
|
507
|
+
var scene, backendBase;
|
|
508
|
+
if (typeof urlOrScene === 'string') {
|
|
509
|
+
var link = parseShareLink(urlOrScene);
|
|
510
|
+
if (!link) throw new Error('not an excalidraw.com share link');
|
|
511
|
+
backendBase = link.backendBase;
|
|
512
|
+
scene = await loadScene(urlOrScene, { fetch: options.fetch });
|
|
513
|
+
} else {
|
|
514
|
+
scene = urlOrScene;
|
|
515
|
+
}
|
|
516
|
+
var result = applyEdits(scene, ops);
|
|
517
|
+
var url = null;
|
|
518
|
+
if (options.upload !== false) {
|
|
519
|
+
url = await saveScene(result.scene, { fetch: options.fetch, backendBase: backendBase });
|
|
520
|
+
}
|
|
521
|
+
var mermaid = sceneToMermaid(result.scene, { sourceUrl: url || undefined });
|
|
522
|
+
return { url: url, scene: result.scene, mermaid: mermaid.text, report: result.report };
|
|
523
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Diagram round trip: excalidraw.com share links <-> Mermaid reading copies.
|
|
2
|
+
// Shared by the page (MD -> MD diagrams mode) and bin/diagrams.js.
|
|
3
|
+
export { parseShareLink, loadScene, saveScene, normalizeScene, DEFAULT_BACKEND_BASE } from './share-link.js';
|
|
4
|
+
export { sceneToMermaid } from './scene-to-mermaid.js';
|
|
5
|
+
export { expandDiagramLinks, stripDiagramBlocks, findDiagramLinks } from './markdown.js';
|
|
6
|
+
export { applyEdits, editLink } from './edit.js';
|
|
7
|
+
export { analyzeScene, TUNING } from './scene-model.js';
|
|
8
|
+
export { buildSkeleton } from './skeleton.js';
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// Markdown <-> generated Mermaid blocks.
|
|
2
|
+
//
|
|
3
|
+
// expandDiagramLinks inserts, after the paragraph / list item / table holding
|
|
4
|
+
// each excalidraw.com share link, a block of the form
|
|
5
|
+
//
|
|
6
|
+
// <!-- excalidraw-mermaid:begin <id> -->
|
|
7
|
+
// ```mermaid
|
|
8
|
+
// %% generated from <url>; reading copy, ...
|
|
9
|
+
// ...
|
|
10
|
+
// ```
|
|
11
|
+
// <!-- excalidraw-mermaid:end <id> -->
|
|
12
|
+
//
|
|
13
|
+
// Everything else is left byte-for-byte. Each block is inserted as
|
|
14
|
+
// "\n\n" + block right before the newline that ends the host block, so
|
|
15
|
+
// stripDiagramBlocks can remove exactly what was added and expand -> strip
|
|
16
|
+
// returns the original.
|
|
17
|
+
|
|
18
|
+
import { parseShareLink, SHARE_LINK_PATTERN } from './share-link.js';
|
|
19
|
+
import { sceneToMermaid, headerLine } from './scene-to-mermaid.js';
|
|
20
|
+
|
|
21
|
+
const BLOCK_PATTERN = /(?:\r?\n){0,2}[ \t]*<!-- excalidraw-mermaid:begin ([A-Za-z0-9_-]+) -->[\s\S]*?<!-- excalidraw-mermaid:end \1 -->/g;
|
|
22
|
+
const LIST_MARKER = /^(\s*)([-*+]|\d+[.)])(\s+)/;
|
|
23
|
+
const FENCE = /^\s*(```|~~~)/;
|
|
24
|
+
const HEADING = /^\s{0,3}#{1,6}\s/;
|
|
25
|
+
|
|
26
|
+
export function stripDiagramBlocks(markdown) {
|
|
27
|
+
return String(markdown).replace(BLOCK_PATTERN, '');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Line table with offsets so insertion works on the original string untouched.
|
|
31
|
+
function lineTable(text) {
|
|
32
|
+
var lines = [];
|
|
33
|
+
var start = 0;
|
|
34
|
+
while (start <= text.length) {
|
|
35
|
+
var nl = text.indexOf('\n', start);
|
|
36
|
+
var end = nl < 0 ? text.length : nl;
|
|
37
|
+
var contentEnd = end > start && text[end - 1] === '\r' ? end - 1 : end;
|
|
38
|
+
lines.push({ start: start, end: contentEnd, text: text.slice(start, contentEnd) });
|
|
39
|
+
if (nl < 0) break;
|
|
40
|
+
start = nl + 1;
|
|
41
|
+
}
|
|
42
|
+
return lines;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function fencedLines(lines) {
|
|
46
|
+
var inside = new Array(lines.length).fill(false);
|
|
47
|
+
var open = null;
|
|
48
|
+
lines.forEach(function (l, i) {
|
|
49
|
+
var m = FENCE.exec(l.text);
|
|
50
|
+
if (open) {
|
|
51
|
+
inside[i] = true;
|
|
52
|
+
if (m && m[1] === open) open = null;
|
|
53
|
+
} else if (m) {
|
|
54
|
+
inside[i] = true;
|
|
55
|
+
open = m[1];
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
return inside;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
var isBlank = function (s) { return /^\s*$/.test(s); };
|
|
62
|
+
|
|
63
|
+
// Where to insert, and how far to indent, for a link on line `i`.
|
|
64
|
+
function hostBlock(lines, i) {
|
|
65
|
+
// List item: nearest marker line above within the same run of non-blank lines.
|
|
66
|
+
var markerLine = -1;
|
|
67
|
+
for (var j = i; j >= 0 && !isBlank(lines[j].text); j--) {
|
|
68
|
+
if (LIST_MARKER.test(lines[j].text)) { markerLine = j; break; }
|
|
69
|
+
}
|
|
70
|
+
if (markerLine >= 0) {
|
|
71
|
+
var m = LIST_MARKER.exec(lines[markerLine].text);
|
|
72
|
+
var indent = ' '.repeat(m[1].length + m[2].length + m[3].length);
|
|
73
|
+
var end = i;
|
|
74
|
+
while (end + 1 < lines.length && !isBlank(lines[end + 1].text) && !LIST_MARKER.test(lines[end + 1].text)) end++;
|
|
75
|
+
return { line: end, indent: indent };
|
|
76
|
+
}
|
|
77
|
+
if (HEADING.test(lines[i].text)) return { line: i, indent: '' };
|
|
78
|
+
var last = i;
|
|
79
|
+
while (last + 1 < lines.length) {
|
|
80
|
+
var next = lines[last + 1].text;
|
|
81
|
+
if (isBlank(next) || HEADING.test(next) || FENCE.test(next) || LIST_MARKER.test(next)) break;
|
|
82
|
+
last++;
|
|
83
|
+
}
|
|
84
|
+
return { line: last, indent: '' };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function renderBlock(id, mermaidText, indent) {
|
|
88
|
+
var body = ['<!-- excalidraw-mermaid:begin ' + id + ' -->', '```mermaid']
|
|
89
|
+
.concat(mermaidText.split('\n'))
|
|
90
|
+
.concat(['```', '<!-- excalidraw-mermaid:end ' + id + ' -->']);
|
|
91
|
+
return body.map(function (l) { return l ? indent + l : l; }).join('\n');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Every share link in the text, first occurrence per scene id, outside code fences.
|
|
95
|
+
export function findDiagramLinks(markdown) {
|
|
96
|
+
var text = String(markdown);
|
|
97
|
+
var lines = lineTable(text);
|
|
98
|
+
var fenced = fencedLines(lines);
|
|
99
|
+
var seen = new Set();
|
|
100
|
+
var found = [];
|
|
101
|
+
var re = new RegExp(SHARE_LINK_PATTERN.source, 'g');
|
|
102
|
+
var m;
|
|
103
|
+
var lineIdx = 0;
|
|
104
|
+
while ((m = re.exec(text))) {
|
|
105
|
+
var link = parseShareLink(m[0]);
|
|
106
|
+
if (!link || seen.has(link.id)) continue;
|
|
107
|
+
while (lineIdx + 1 < lines.length && lines[lineIdx + 1].start <= m.index) lineIdx++;
|
|
108
|
+
if (fenced[lineIdx]) continue;
|
|
109
|
+
seen.add(link.id);
|
|
110
|
+
var host = hostBlock(lines, lineIdx);
|
|
111
|
+
found.push({ link: link, offset: lines[host.line].end, indent: host.indent });
|
|
112
|
+
}
|
|
113
|
+
return found;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Replaces any existing generated blocks, then inserts fresh ones. One failing
|
|
117
|
+
// link produces a visible error block and never stops the others.
|
|
118
|
+
export async function expandDiagramLinks(markdown, options) {
|
|
119
|
+
var loadScene = options && options.loadScene;
|
|
120
|
+
if (typeof loadScene !== 'function') throw new Error('expandDiagramLinks needs options.loadScene');
|
|
121
|
+
var onProgress = (options && options.onProgress) || function () {};
|
|
122
|
+
var text = stripDiagramBlocks(markdown);
|
|
123
|
+
var links = findDiagramLinks(text);
|
|
124
|
+
var stats = { total: links.length, done: 0, failed: 0, outline: 0 };
|
|
125
|
+
onProgress(Object.assign({}, stats));
|
|
126
|
+
|
|
127
|
+
var blocks = [];
|
|
128
|
+
for (var i = 0; i < links.length; i++) {
|
|
129
|
+
var item = links[i];
|
|
130
|
+
var mermaid;
|
|
131
|
+
try {
|
|
132
|
+
var scene = await loadScene(item.link.url);
|
|
133
|
+
var result = sceneToMermaid(scene, { sourceUrl: item.link.url });
|
|
134
|
+
if (result.kind === 'outline') stats.outline++;
|
|
135
|
+
mermaid = result.text;
|
|
136
|
+
} catch (err) {
|
|
137
|
+
stats.failed++;
|
|
138
|
+
mermaid = headerLine(item.link.url) + '\n%% could not load: ' + String(err && err.message ? err.message : err).replace(/\s+/g, ' ');
|
|
139
|
+
}
|
|
140
|
+
blocks.push({ offset: item.offset, text: '\n\n' + renderBlock(item.link.id, mermaid, item.indent) });
|
|
141
|
+
stats.done++;
|
|
142
|
+
onProgress(Object.assign({}, stats));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Insert back to front so earlier offsets stay valid; same-offset blocks keep order.
|
|
146
|
+
var out = text;
|
|
147
|
+
for (var k = blocks.length - 1; k >= 0; k--) {
|
|
148
|
+
out = out.slice(0, blocks[k].offset) + blocks[k].text + out.slice(blocks[k].offset);
|
|
149
|
+
}
|
|
150
|
+
if (options && options.report) Object.assign(options.report, stats);
|
|
151
|
+
return out;
|
|
152
|
+
}
|