dsh-artifact-studio 0.8.0 → 0.13.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.
Files changed (43) hide show
  1. package/README.md +72 -10
  2. package/THIRD_PARTY_NOTICES.md +57 -0
  3. package/assets/canvas.engine.js +72 -72
  4. package/assets/canvas.viewer.js +6415 -0
  5. package/client.canvas.js +1 -1
  6. package/client.doc.js +67 -79
  7. package/client.js +313 -291
  8. package/client.sheet.js +218 -0
  9. package/dist/contract.js +32 -5
  10. package/dist/host/lib/assets.js +12 -0
  11. package/dist/host/lib/brief.js +127 -0
  12. package/dist/host/lib/checks.js +62 -8
  13. package/dist/host/lib/design-catalog.js +149 -0
  14. package/dist/host/lib/design-render.js +37 -0
  15. package/dist/host/lib/design-system.js +1 -1
  16. package/dist/host/lib/export.js +123 -5
  17. package/dist/host/lib/fsutil.js +41 -0
  18. package/dist/host/lib/generation.js +36 -0
  19. package/dist/host/lib/guide.js +130 -0
  20. package/dist/host/lib/paths.js +2 -1
  21. package/dist/host/lib/recipes.js +224 -0
  22. package/dist/host/lib/rpc.js +20 -5
  23. package/dist/host/lib/service.js +253 -24
  24. package/dist/host/lib/skill.js +59 -18
  25. package/dist/host/lib/store.js +107 -25
  26. package/dist/host/lib/svg-model.js +85 -0
  27. package/dist/host/lib/svg-viewer.js +380 -0
  28. package/dist/host/lib/tools.js +346 -35
  29. package/dist/host/lib/validate.js +24 -0
  30. package/dist/host/lib/viewer.js +150 -0
  31. package/dist/host/lib/xlsx.js +314 -0
  32. package/dist/host/worker/design-worker.js +71 -5
  33. package/dist/host/worker/page-model.js +169 -0
  34. package/dist/html-tags.js +51 -0
  35. package/dist/kit.js +224 -0
  36. package/dist/render.js +10 -3
  37. package/dist/sheet/formula.js +475 -0
  38. package/dist/sheet/functions.js +463 -0
  39. package/dist/sheet/index.js +9 -0
  40. package/dist/sheet/model.js +695 -0
  41. package/dist/sheet/operations.js +384 -0
  42. package/dist/sheet/output.js +182 -0
  43. package/package.json +15 -3
@@ -0,0 +1,380 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { escapeHtml } from '../../render.js';
5
+ import { BUNDLED_FACES } from './assets.js';
6
+ /** Where the build writes the bundled faces. */
7
+ const ASSET_ROOT = fileURLToPath(new URL('../../../assets/', import.meta.url));
8
+ /**
9
+ * What the page may do: lay itself out with inline styles, load the faces it carries, and
10
+ * run its own fit and pan script. Nothing is fetched, and nothing may be framed.
11
+ */
12
+ const CSP = "default-src 'none'; style-src 'unsafe-inline'; font-src data:; img-src data:; script-src 'unsafe-inline'";
13
+ /** The weight each bundled style name stands for. */
14
+ const WEIGHTS = {
15
+ Regular: 400,
16
+ Medium: 500,
17
+ SemiBold: 600,
18
+ Bold: 700,
19
+ ExtraBold: 800,
20
+ };
21
+ let faces;
22
+ /**
23
+ * Read every bundled face the page could need. Each file is read once per process.
24
+ * @returns the packed faces.
25
+ */
26
+ function packedFaces() {
27
+ faces ??= Promise.all(BUNDLED_FACES.map(async (face) => {
28
+ const bytes = await fs.readFile(path.join(ASSET_ROOT, face.file));
29
+ const woff2 = face.file.endsWith('.woff2');
30
+ return {
31
+ family: face.family,
32
+ weight: WEIGHTS[face.style] ?? 400,
33
+ format: woff2 ? 'woff2' : 'truetype',
34
+ mime: woff2 ? 'font/woff2' : 'font/ttf',
35
+ data: bytes.toString('base64'),
36
+ };
37
+ }));
38
+ return faces;
39
+ }
40
+ /**
41
+ * The face rules for the families a design uses.
42
+ * @param packed the packed faces.
43
+ * @param families the families the design uses.
44
+ * @returns the CSS.
45
+ */
46
+ function faceCss(packed, families) {
47
+ return packed
48
+ .filter((face) => families.includes(face.family))
49
+ .map((face) => '@font-face{font-family:' + quote(face.family) + ';font-style:normal;font-weight:' + face.weight +
50
+ ";src:url(data:" + face.mime + ';base64,' + face.data + ") format('" + face.format + "')}")
51
+ .join('');
52
+ }
53
+ /**
54
+ * A CSS string literal that cannot end the attribute it sits in.
55
+ * @param value the text.
56
+ * @returns the quoted value, with single quotes removed.
57
+ */
58
+ function quote(value) {
59
+ return "'" + value.replace(/'/g, '') + "'";
60
+ }
61
+ /**
62
+ * A colour as CSS, with a separate alpha.
63
+ * @param color the hex colour.
64
+ * @param alpha the alpha, 0 to 1.
65
+ * @returns the CSS colour.
66
+ */
67
+ function paint(color, alpha) {
68
+ if (alpha >= 0.999)
69
+ return color;
70
+ const value = Number.parseInt(color.slice(1), 16);
71
+ const red = (value >> 16) & 0xff;
72
+ const green = (value >> 8) & 0xff;
73
+ const blue = value & 0xff;
74
+ return 'rgba(' + red + ',' + green + ',' + blue + ',' + alpha.toFixed(3) + ')';
75
+ }
76
+ /**
77
+ * The CSS transform for a text case.
78
+ * @param textCase the node's case.
79
+ * @returns the CSS value, or undefined when the text keeps its case.
80
+ */
81
+ function textTransform(textCase) {
82
+ if (textCase === 'UPPER')
83
+ return 'uppercase';
84
+ if (textCase === 'LOWER')
85
+ return 'lowercase';
86
+ if (textCase === 'TITLE')
87
+ return 'capitalize';
88
+ return undefined;
89
+ }
90
+ /**
91
+ * The CSS text alignment for a node's alignment.
92
+ * @param align the alignment.
93
+ * @returns the CSS value.
94
+ */
95
+ function textAlign(align) {
96
+ if (align === 'CENTER')
97
+ return 'center';
98
+ if (align === 'RIGHT')
99
+ return 'right';
100
+ if (align === 'JUSTIFIED')
101
+ return 'justify';
102
+ return 'left';
103
+ }
104
+ /**
105
+ * The inline style of one text box.
106
+ * @param box the box.
107
+ * @param offsetX the clipping wrapper's left edge, subtracted from the transform.
108
+ * @param offsetY the clipping wrapper's top edge, subtracted from the transform.
109
+ * @returns the style text.
110
+ */
111
+ function boxStyle(box, offsetX, offsetY) {
112
+ const matrix = box.matrix;
113
+ const transform = [matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - offsetX, matrix.f - offsetY].join(',');
114
+ const parts = [
115
+ 'position:absolute',
116
+ 'left:0',
117
+ 'top:0',
118
+ 'width:' + box.width + 'px',
119
+ 'height:' + box.height + 'px',
120
+ 'transform-origin:0 0',
121
+ 'transform:matrix(' + transform + ')',
122
+ 'font-family:' + quote(box.family) + ',Inter,sans-serif',
123
+ 'font-size:' + box.size + 'px',
124
+ 'font-weight:' + box.weight,
125
+ 'font-style:' + (box.italic ? 'italic' : 'normal'),
126
+ 'line-height:' + (box.lineHeight === null ? 'normal' : box.lineHeight + 'px'),
127
+ 'letter-spacing:' + box.letterSpacing + 'px',
128
+ 'color:' + paint(box.color, box.alpha),
129
+ 'text-align:' + textAlign(box.align),
130
+ 'white-space:' + (box.wrap ? 'pre-wrap' : 'pre'),
131
+ 'overflow:visible',
132
+ ];
133
+ const textCaseCss = textTransform(box.textCase);
134
+ if (textCaseCss !== undefined)
135
+ parts.push('text-transform:' + textCaseCss);
136
+ if (box.verticalAlign === 'CENTER')
137
+ parts.push('display:flex', 'align-items:center');
138
+ else if (box.verticalAlign === 'BOTTOM')
139
+ parts.push('display:flex', 'align-items:flex-end');
140
+ return parts.join(';');
141
+ }
142
+ /**
143
+ * One style run as a span.
144
+ * @param run the run.
145
+ * @returns the markup.
146
+ */
147
+ function runHtml(run) {
148
+ const style = [
149
+ 'font-size:' + run.size + 'px',
150
+ 'font-weight:' + run.weight,
151
+ 'font-style:' + (run.italic ? 'italic' : 'normal'),
152
+ 'letter-spacing:' + run.letterSpacing + 'px',
153
+ 'color:' + paint(run.color, run.alpha),
154
+ ].join(';');
155
+ return '<span style="' + escapeHtml(style) + '">' + escapeHtml(run.text) + '</span>';
156
+ }
157
+ /**
158
+ * One text box as markup, inside its clipping ancestor when it has one.
159
+ * @param box the box.
160
+ * @returns the markup.
161
+ */
162
+ function boxHtml(box) {
163
+ const inner = box.runs.length === 0
164
+ ? escapeHtml(box.text)
165
+ : box.runs.map(runHtml).join('');
166
+ const clip = box.clip;
167
+ if (clip === null)
168
+ return '<div class="t" style="' + escapeHtml(boxStyle(box, 0, 0)) + '">' + inner + '</div>';
169
+ const wrapper = [
170
+ 'position:absolute',
171
+ 'left:' + clip.x + 'px',
172
+ 'top:' + clip.y + 'px',
173
+ 'width:' + clip.width + 'px',
174
+ 'height:' + clip.height + 'px',
175
+ 'overflow:hidden',
176
+ ].join(';');
177
+ return '<div style="' + escapeHtml(wrapper) + '"><div class="t" style="' + escapeHtml(boxStyle(box, clip.x, clip.y)) + '">' + inner + '</div></div>';
178
+ }
179
+ /**
180
+ * The page script: fit the stage to the window, pan with a drag or a plain wheel, and
181
+ * zoom about the pointer with Ctrl or Cmd wheel. A left drag that starts on a text box
182
+ * selects text instead of panning, because the page exists to be read and copied.
183
+ * @param width the stage width.
184
+ * @param height the stage height.
185
+ * @returns the script body.
186
+ */
187
+ function pageScript(width, height) {
188
+ return `
189
+ const host = document.getElementById('dsh-mockup');
190
+ const pan = document.getElementById('dsh-pan');
191
+ const stage = document.getElementById('dsh-stage');
192
+ const W = ${width};
193
+ const H = ${height};
194
+ let zoom = 1, panX = 0, panY = 0, touched = false, space = false;
195
+ // The stage is fitted with CSS zoom, not a scaled transform: Chromium's drag
196
+ // selection misfires on transform-scaled text at some fit scales, and the page
197
+ // exists to be read and copied. Panning is a translate on the wrapper outside it.
198
+ const apply = () => { pan.style.transform = 'translate(' + panX + 'px,' + panY + 'px)'; stage.style.zoom = String(zoom); };
199
+ const fit = () => {
200
+ zoom = Math.min(window.innerWidth / W, window.innerHeight / H);
201
+ panX = (window.innerWidth - W * zoom) / 2;
202
+ panY = (window.innerHeight - H * zoom) / 2;
203
+ apply();
204
+ };
205
+ fit();
206
+ window.addEventListener('resize', () => { if (!touched) fit(); });
207
+ // A text box is a hit target across its whole node box, which is wider and taller
208
+ // than the painted lines. Only a press on a painted line belongs to text selection;
209
+ // a press on the empty part of the box still pans.
210
+ const onText = (event) => {
211
+ const target = event.target;
212
+ if (!(target instanceof Element)) return false;
213
+ const box = target.closest('.t');
214
+ if (box === null) return false;
215
+ const range = document.createRange();
216
+ range.selectNodeContents(box);
217
+ const x = event.clientX, y = event.clientY;
218
+ return [...range.getClientRects()].some((rect) => x >= rect.left - 1 && x <= rect.right + 1 && y >= rect.top - 1 && y <= rect.bottom + 1);
219
+ };
220
+ // The page fits scaled text, where Chromium's own drag sometimes moves a caret
221
+ // instead of extending a selection. Drive the selection from the caret position
222
+ // instead, so a drag over glyphs always selects them.
223
+ const caretAt = (x, y) => {
224
+ if (document.caretRangeFromPoint) return document.caretRangeFromPoint(x, y);
225
+ const position = document.caretPositionFromPoint ? document.caretPositionFromPoint(x, y) : null;
226
+ if (position === null) return null;
227
+ const range = document.createRange();
228
+ range.setStart(position.offsetNode, position.offset);
229
+ range.collapse(true);
230
+ return range;
231
+ };
232
+ const inText = (range) => range !== null && range.startContainer.parentElement !== null && range.startContainer.parentElement.closest('.t') !== null;
233
+ let selecting = null;
234
+ const extendSelection = (event) => {
235
+ const focus = caretAt(event.clientX, event.clientY);
236
+ if (!inText(focus)) return;
237
+ window.getSelection().setBaseAndExtent(selecting.node, selecting.offset, focus.startContainer, focus.startOffset);
238
+ };
239
+ const selectWord = (caret) => {
240
+ const text = caret.startContainer.textContent === null ? '' : caret.startContainer.textContent;
241
+ let start = caret.startOffset;
242
+ let end = caret.startOffset;
243
+ while (start > 0 && text[start - 1].trim() !== '') start -= 1;
244
+ while (end < text.length && text[end].trim() !== '') end += 1;
245
+ window.getSelection().setBaseAndExtent(caret.startContainer, start, caret.startContainer, end);
246
+ };
247
+ const selectBox = (box) => {
248
+ const range = document.createRange();
249
+ range.selectNodeContents(box);
250
+ const selection = window.getSelection();
251
+ selection.removeAllRanges();
252
+ selection.addRange(range);
253
+ };
254
+ // The browser's click counter is lost once a press is cancelled, so count the
255
+ // presses here: two select a word, three select the whole text box.
256
+ let lastPress = { time: 0, x: 0, y: 0, count: 0 };
257
+ const pressCount = (event) => {
258
+ const near = Math.abs(event.clientX - lastPress.x) <= 4 && Math.abs(event.clientY - lastPress.y) <= 4;
259
+ const quick = event.timeStamp - lastPress.time <= 400;
260
+ lastPress = { time: event.timeStamp, x: event.clientX, y: event.clientY, count: near && quick ? lastPress.count + 1 : 1 };
261
+ return lastPress.count;
262
+ };
263
+ let drag = null;
264
+ host.addEventListener('pointerdown', (event) => {
265
+ if (event.button !== 0 && event.button !== 1) return;
266
+ if (event.button === 0 && !space && onText(event)) {
267
+ if (event.altKey) return;
268
+ const caret = caretAt(event.clientX, event.clientY);
269
+ if (!inText(caret)) return;
270
+ // A Shift click extends the current selection from its fixed end.
271
+ if (event.shiftKey) {
272
+ const selection = window.getSelection();
273
+ if (selection === null || selection.rangeCount === 0 || selection.anchorNode === null) return;
274
+ event.preventDefault();
275
+ selection.setBaseAndExtent(selection.anchorNode, selection.anchorOffset, caret.startContainer, caret.startOffset);
276
+ return;
277
+ }
278
+ event.preventDefault();
279
+ const count = pressCount(event);
280
+ if (count >= 3) {
281
+ const box = event.target.closest('.t');
282
+ if (box !== null) selectBox(box);
283
+ return;
284
+ }
285
+ if (count === 2) {
286
+ selectWord(caret);
287
+ return;
288
+ }
289
+ selecting = { node: caret.startContainer, offset: caret.startOffset };
290
+ window.getSelection().setBaseAndExtent(selecting.node, selecting.offset, selecting.node, selecting.offset);
291
+ host.setPointerCapture(event.pointerId);
292
+ return;
293
+ }
294
+ event.preventDefault();
295
+ const selection = window.getSelection();
296
+ if (selection !== null) selection.removeAllRanges();
297
+ touched = true;
298
+ drag = { x: event.clientX - panX, y: event.clientY - panY };
299
+ host.setPointerCapture(event.pointerId);
300
+ host.style.cursor = 'grabbing';
301
+ });
302
+ host.addEventListener('pointermove', (event) => {
303
+ if (selecting !== null) {
304
+ extendSelection(event);
305
+ return;
306
+ }
307
+ if (drag === null) return;
308
+ panX = event.clientX - drag.x;
309
+ panY = event.clientY - drag.y;
310
+ apply();
311
+ });
312
+ const end = (event) => { drag = null; selecting = null; host.style.cursor = space ? 'grabbing' : 'grab'; if (host.hasPointerCapture(event.pointerId)) host.releasePointerCapture(event.pointerId); };
313
+ host.addEventListener('pointerup', end);
314
+ host.addEventListener('pointercancel', end);
315
+ window.addEventListener('keydown', (event) => {
316
+ if (event.code !== 'Space' || space) return;
317
+ space = true;
318
+ host.style.cursor = 'grabbing';
319
+ });
320
+ window.addEventListener('keyup', (event) => {
321
+ if (event.code !== 'Space') return;
322
+ space = false;
323
+ host.style.cursor = drag === null ? 'grab' : 'grabbing';
324
+ });
325
+ window.addEventListener('blur', () => { space = false; host.style.cursor = drag === null ? 'grab' : 'grabbing'; });
326
+ host.addEventListener('wheel', (event) => {
327
+ event.preventDefault();
328
+ touched = true;
329
+ if (event.ctrlKey || event.metaKey) {
330
+ const rect = host.getBoundingClientRect();
331
+ const next = Math.min(8, Math.max(0.02, zoom * (event.deltaY < 0 ? 1.1 : 1 / 1.1)));
332
+ const mx = event.clientX - rect.left;
333
+ const my = event.clientY - rect.top;
334
+ panX = mx - (mx - panX) * (next / zoom);
335
+ panY = my - (my - panY) * (next / zoom);
336
+ zoom = next;
337
+ } else {
338
+ panX -= event.deltaX;
339
+ panY -= event.deltaY;
340
+ }
341
+ apply();
342
+ }, { passive: false });
343
+ `;
344
+ }
345
+ /**
346
+ * Build the offline page for one saved scene: the engine's shapes, the text as real
347
+ * HTML, and only the faces the design uses.
348
+ * @param input the artifact title and the page model.
349
+ * @returns the HTML file.
350
+ */
351
+ export async function buildSvgViewerHtml(input) {
352
+ const model = input.model;
353
+ const faces = faceCss(await packedFaces(), model.families);
354
+ const base = [
355
+ 'html,body{margin:0;height:100%;overflow:hidden;background:#fff}',
356
+ '#dsh-mockup{position:fixed;inset:0;overflow:hidden;background:#fff;cursor:grab;touch-action:none}',
357
+ '#dsh-pan{position:absolute;left:0;top:0;transform-origin:0 0}',
358
+ '#dsh-stage{position:absolute;left:0;top:0;transform-origin:0 0;width:' + model.width + 'px;height:' + model.height + 'px}',
359
+ '#dsh-stage svg{display:block}',
360
+ '.t{margin:0;cursor:text;user-select:text;-webkit-user-select:text}',
361
+ ].join('');
362
+ const html = [
363
+ '<!doctype html>',
364
+ '<html>',
365
+ '<head>',
366
+ '<meta charset="utf-8">',
367
+ '<meta http-equiv="content-security-policy" content="' + CSP + '">',
368
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
369
+ '<title>' + escapeHtml(input.title) + '</title>',
370
+ '<style>' + faces + base + '</style>',
371
+ '</head>',
372
+ '<body>',
373
+ '<div id="dsh-mockup"><div id="dsh-pan"><div id="dsh-stage">' + model.svg + model.texts.map(boxHtml).join('') + '</div></div></div>',
374
+ '<script>' + pageScript(model.width, model.height) + '</script>',
375
+ '</body>',
376
+ '</html>',
377
+ '',
378
+ ].join('\n');
379
+ return Buffer.from(html, 'utf8');
380
+ }