dsh-artifact-studio 0.9.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
@@ -551,12 +551,12 @@ export function createTools(host) {
551
551
  };
552
552
  const exportTool = {
553
553
  name: 'artifact_export',
554
- description: 'Write an artifact to a standalone file and return its path. A page exports as html; a doc exports as md, docx, or printable html; a design exports as png, svg, or .fig; a sheet exports as csv (first sheet) or xlsx (every sheet).',
554
+ description: 'Write an artifact to a standalone file and return its path. A page exports as html; a doc exports as md, docx, or printable html; a design exports as png, svg, .fig, a self-contained view-only html viewer, or a smaller html page with an svg scene and selectable text; a sheet exports as csv (first sheet) or xlsx (every sheet).',
555
555
  parameters: {
556
556
  type: 'object',
557
557
  additionalProperties: false,
558
558
  required: ['id', 'format'],
559
- properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig', 'csv', 'xlsx'] },
559
+ properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig', 'html-svg', 'csv', 'xlsx'] },
560
560
  version: { type: 'integer', minimum: 1, description: 'Saved version to export. Omit for the current version.' },
561
561
  workspaceId: WORKSPACE_PARAM },
562
562
  },
@@ -572,6 +572,38 @@ export function createTools(host) {
572
572
  return { path: file.path, bytes: file.bytes };
573
573
  },
574
574
  };
575
+ const importTool = {
576
+ name: 'artifact_import',
577
+ description: 'Import a Figma .fig file as a new design the user calls a mockup. The file\'s first page with elements becomes the editable Design JSX source; later pages are skipped and named in warnings. Pass the absolute file path the user named. Use it when the user points at a .fig file instead of asking for a fresh mockup.',
578
+ parameters: {
579
+ type: 'object',
580
+ additionalProperties: false,
581
+ required: ['path'],
582
+ properties: {
583
+ path: { type: 'string', description: 'Absolute path of the .fig file to read.' },
584
+ title: { type: 'string', description: 'Short title, 1 to 120 characters. Defaults to the file name.' },
585
+ ...DESIGN_SELECTION,
586
+ scope: SCOPE_PARAM,
587
+ workspaceId: WORKSPACE_PARAM,
588
+ },
589
+ },
590
+ output: {
591
+ schema: { type: 'object', additionalProperties: false, required: [...WRITE_SCHEMA.required, 'warnings'], properties: { ...WRITE_SCHEMA.properties, warnings: { type: 'array', items: { type: 'string' } } } },
592
+ render: (_args, value) => [{ type: 'text', text: writeText(value, 'Imported') }],
593
+ presentationMeta: (_args, value) => cardMeta(value),
594
+ },
595
+ async execute(args, exec) {
596
+ const fields = fieldsOf(args);
597
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
598
+ const manifest = await service.importDesign(target, {
599
+ path: requiredString(fields, 'path'),
600
+ title: optionalString(fields, 'title'),
601
+ source: { origin: 'agent', action: 'create', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
602
+ });
603
+ const warnings = (await service.read(target, manifest.id)).designInfo?.warnings ?? [];
604
+ return { ...summary(manifest, target), warnings };
605
+ },
606
+ };
575
607
  const designRead = {
576
608
  name: 'design_system_read',
577
609
  description: 'Read the design tokens that pages and docs in this project inherit, and whether they come from the project, the profile library, or the built-in default.',
@@ -632,8 +664,8 @@ export function createTools(host) {
632
664
  const brief = {
633
665
  name: 'artifact_brief',
634
666
  description: [
635
- 'Get the brief for a new artifact before artifact_create: the project conventions, the user\'s preferences, the recipe sections and rules, earlier artifacts to match, the design system, and for a page the component kit. Follow it, then pass the same recipe to artifact_create.',
636
- 'Call it without recipe to list the recipes for the type, choose the one that fits the reader and purpose, and call it again with that id. Also call it before restyling an artifact that has a recipe.',
667
+ 'Get the selected type\'s authoring instructions, examples, quality checks, and saved conventions before artifact_create or a layout or styling update. Applicable briefs include recipe rules, earlier artifacts, design context, and the page kit.',
668
+ 'For page, doc, and design, omit recipe to list compatible recipes, then call again with the chosen id and pass it to artifact_create. For sheet, call once without recipe; sheets do not use recipes. Current defaults do not replace an existing artifact\'s pinned settings.',
637
669
  ].join('\n'),
638
670
  parameters: {
639
671
  type: 'object',
@@ -641,7 +673,7 @@ export function createTools(host) {
641
673
  required: ['type'],
642
674
  properties: {
643
675
  type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
644
- recipe: { type: 'string', description: 'A recipe id. Omit to list the recipes for this type.' },
676
+ recipe: { type: 'string', description: 'A recipe id for page, doc, or design. Omit to list compatible recipes. Always omit for sheet.' },
645
677
  ...DESIGN_SELECTION,
646
678
  scope: SCOPE_PARAM,
647
679
  workspaceId: WORKSPACE_PARAM,
@@ -747,5 +779,5 @@ export function createTools(host) {
747
779
  return { ...summary(manifest, target), warnings: [] };
748
780
  },
749
781
  };
750
- return [create, read, update, sheetUpdate, list, remove, exportTool, designRead, designUpdate, brief, guideUpdate, designList, rebase];
782
+ return [create, read, update, sheetUpdate, list, remove, importTool, exportTool, designRead, designUpdate, brief, guideUpdate, designList, rebase];
751
783
  }
@@ -0,0 +1,150 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import zlib from 'node:zlib';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { escapeHtml } from '../../render.js';
6
+ import { BUNDLED_FACES } from './assets.js';
7
+ import { ArtifactError } from './errors.js';
8
+ /** Where the build writes the viewer chunk, CanvasKit, and the fonts. */
9
+ const ASSET_ROOT = fileURLToPath(new URL('../../../assets/', import.meta.url));
10
+ /** The compiled viewer, imported from a blob URL by the page. */
11
+ const VIEWER_FILE = 'canvas.viewer.js';
12
+ /** CanvasKit's WebAssembly binary. */
13
+ const CANVASKIT_FILE = 'canvaskit.wasm';
14
+ /**
15
+ * What the page may do: run its own inline script and blob module, compile WebAssembly,
16
+ * decode the fonts and the scene, and reach nothing but blobs. No request leaves the file.
17
+ */
18
+ const CSP = "default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; " +
19
+ "img-src data: blob:; font-src data: blob:; connect-src blob:";
20
+ /** The page rule that the viewer module does not replace. */
21
+ const STYLE = 'html,body{margin:0;height:100%;overflow:hidden;background:#fff}#dsh-mockup{position:fixed;inset:0}';
22
+ /**
23
+ * The page's first script: decode the payload and hand it to the viewer. It holds no
24
+ * artifact text, so it is a constant. A failure shows one line instead of a blank page.
25
+ */
26
+ const BOOT = `
27
+ const node = document.getElementById('dsh-mockup-data');
28
+ const data = JSON.parse(node.textContent);
29
+ node.remove();
30
+ const fail = (error) => {
31
+ const message = document.createElement('p');
32
+ message.textContent = 'This mockup could not be opened. ' + (error && error.message ? error.message : '');
33
+ message.style.cssText = 'font:14px system-ui, sans-serif;padding:24px;color:#1f2933';
34
+ document.body.append(message);
35
+ };
36
+ const decode = async (base64) => {
37
+ const raw = atob(base64);
38
+ const bytes = new Uint8Array(raw.length);
39
+ for (let i = 0; i < raw.length; i += 1) bytes[i] = raw.charCodeAt(i);
40
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
41
+ return new Uint8Array(await new Response(stream).arrayBuffer());
42
+ };
43
+ try {
44
+ const [viewer, canvaskit, scene] = await Promise.all([
45
+ decode(data.viewer),
46
+ decode(data.canvaskit),
47
+ decode(data.scene),
48
+ ]);
49
+ const fonts = await Promise.all(data.fonts.map(async (font) => ({
50
+ family: font.family,
51
+ style: font.style,
52
+ file: font.file,
53
+ bytes: (await decode(font.data)).buffer,
54
+ })));
55
+ const module = await import(URL.createObjectURL(new Blob([viewer], { type: 'text/javascript' })));
56
+ await module.mountMockupViewer({
57
+ element: document.getElementById('dsh-mockup'),
58
+ scene: scene.buffer,
59
+ canvaskit: canvaskit.buffer,
60
+ fonts,
61
+ title: data.title,
62
+ });
63
+ } catch (error) {
64
+ fail(error);
65
+ }
66
+ `;
67
+ let packed;
68
+ /**
69
+ * Read one asset the build wrote beside the compiled host.
70
+ * @param file the asset path, relative to the assets directory.
71
+ * @returns its bytes.
72
+ */
73
+ async function readAsset(file) {
74
+ try {
75
+ return await fs.readFile(path.join(ASSET_ROOT, file));
76
+ }
77
+ catch {
78
+ throw new ArtifactError('artifact/design-unavailable', `The viewer asset ${file} is missing from the package.`, {});
79
+ }
80
+ }
81
+ /**
82
+ * Compress one asset for inlining.
83
+ * @param bytes the bytes.
84
+ * @returns the gzip bytes as base64.
85
+ */
86
+ function pack(bytes) {
87
+ return zlib.gzipSync(bytes, { level: 9 }).toString('base64');
88
+ }
89
+ /**
90
+ * Read, compress, and keep the viewer, CanvasKit, and the fonts. Every export of a
91
+ * given package shares one copy, so a second export only compresses the scene.
92
+ * @returns the packed parts.
93
+ */
94
+ function packedAssets() {
95
+ packed ??= (async () => {
96
+ const viewer = await readAsset(VIEWER_FILE);
97
+ const canvaskit = await readAsset(CANVASKIT_FILE);
98
+ const faces = await Promise.all(BUNDLED_FACES.map(async (face) => ({
99
+ family: face.family,
100
+ style: face.style,
101
+ file: face.file.replace(/^fonts\//, ''),
102
+ data: pack(await readAsset(face.file)),
103
+ })));
104
+ return { viewer: pack(viewer), canvaskit: pack(canvaskit), fonts: faces };
105
+ })();
106
+ return packed;
107
+ }
108
+ /**
109
+ * A JSON string that cannot end the script element it sits in.
110
+ * @param value the text.
111
+ * @returns its JSON form, with `<` escaped.
112
+ */
113
+ function scriptJson(value) {
114
+ return JSON.stringify(value).replace(/</g, '\\u003c');
115
+ }
116
+ /**
117
+ * Build the standalone view-only page for one saved scene: the viewer, CanvasKit,
118
+ * the fonts, and the scene inlined, so the file opens from disk with no server and
119
+ * makes no request.
120
+ * @param input the artifact title and the saved version's .fig bytes.
121
+ * @returns the HTML file.
122
+ */
123
+ export async function buildViewerHtml(input) {
124
+ const assets = await packedAssets();
125
+ const fonts = assets.fonts.map((font) => JSON.stringify(font)).join(',');
126
+ const payload = '{"title":' + scriptJson(input.title) +
127
+ ',"viewer":"' + assets.viewer +
128
+ '","canvaskit":"' + assets.canvaskit +
129
+ '","fonts":[' + fonts + '],' +
130
+ '"scene":"' + pack(Buffer.from(input.fig)) + '"}';
131
+ const html = [
132
+ '<!doctype html>',
133
+ '<html>',
134
+ '<head>',
135
+ '<meta charset="utf-8">',
136
+ '<meta http-equiv="content-security-policy" content="' + CSP + '">',
137
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
138
+ '<title>' + escapeHtml(input.title) + '</title>',
139
+ '<style>' + STYLE + '</style>',
140
+ '</head>',
141
+ '<body>',
142
+ '<div id="dsh-mockup"></div>',
143
+ '<script type="application/json" id="dsh-mockup-data">' + payload + '</script>',
144
+ '<script type="module">' + BOOT + '</script>',
145
+ '</body>',
146
+ '</html>',
147
+ '',
148
+ ].join('\n');
149
+ return Buffer.from(html, 'utf8');
150
+ }
@@ -7,7 +7,7 @@
7
7
  * the panel, while calcPr asks Excel and LibreOffice to recalculate on load.
8
8
  */
9
9
  import { zipSync, strToU8 } from 'fflate';
10
- import { columnName, evaluateWorkbook, formatNumber, usedBounds } from '../../sheet/index.js';
10
+ import { columnName, effectiveTextColor, evaluateWorkbook, formatNumber, usedBounds } from '../../sheet/index.js';
11
11
  const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
12
12
  const RELATIONSHIPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
13
13
  const PACKAGE_RELATIONSHIPS = 'http://schemas.openxmlformats.org/package/2006/relationships';
@@ -36,16 +36,17 @@ function colorHex(value) {
36
36
  function normaliseStyle(style) {
37
37
  if (style === undefined)
38
38
  return undefined;
39
+ const fill = style.background ?? null;
39
40
  const font = {
40
41
  bold: style.bold === true,
41
42
  italic: style.italic === true,
42
43
  underline: style.underline === true,
43
44
  strike: style.strike === true,
44
- color: style.color ?? null,
45
+ color: effectiveTextColor(style) ?? null,
45
46
  };
46
47
  const spec = {
47
48
  font,
48
- fill: style.background ?? null,
49
+ fill,
49
50
  align: style.align ?? null,
50
51
  numberFormat: style.numberFormat === undefined || style.numberFormat === 'general' ? null : style.numberFormat,
51
52
  };