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.
- package/README.md +72 -10
- package/THIRD_PARTY_NOTICES.md +57 -0
- package/assets/canvas.engine.js +72 -72
- package/assets/canvas.viewer.js +6415 -0
- package/client.canvas.js +1 -1
- package/client.doc.js +67 -79
- package/client.js +313 -291
- package/client.sheet.js +218 -0
- package/dist/contract.js +32 -5
- package/dist/host/lib/assets.js +12 -0
- package/dist/host/lib/brief.js +127 -0
- package/dist/host/lib/checks.js +62 -8
- package/dist/host/lib/design-catalog.js +149 -0
- package/dist/host/lib/design-render.js +37 -0
- package/dist/host/lib/design-system.js +1 -1
- package/dist/host/lib/export.js +123 -5
- package/dist/host/lib/fsutil.js +41 -0
- package/dist/host/lib/generation.js +36 -0
- package/dist/host/lib/guide.js +130 -0
- package/dist/host/lib/paths.js +2 -1
- package/dist/host/lib/recipes.js +224 -0
- package/dist/host/lib/rpc.js +20 -5
- package/dist/host/lib/service.js +253 -24
- package/dist/host/lib/skill.js +59 -18
- package/dist/host/lib/store.js +107 -25
- package/dist/host/lib/svg-model.js +85 -0
- package/dist/host/lib/svg-viewer.js +380 -0
- package/dist/host/lib/tools.js +346 -35
- package/dist/host/lib/validate.js +24 -0
- package/dist/host/lib/viewer.js +150 -0
- package/dist/host/lib/xlsx.js +314 -0
- package/dist/host/worker/design-worker.js +71 -5
- package/dist/host/worker/page-model.js +169 -0
- package/dist/html-tags.js +51 -0
- package/dist/kit.js +224 -0
- package/dist/render.js +10 -3
- package/dist/sheet/formula.js +475 -0
- package/dist/sheet/functions.js +463 -0
- package/dist/sheet/index.js +9 -0
- package/dist/sheet/model.js +695 -0
- package/dist/sheet/operations.js +384 -0
- package/dist/sheet/output.js +182 -0
- package/package.json +15 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* XLSX export for sheet artifacts. The output is a minimal but valid OOXML
|
|
3
|
+
* workbook: one worksheet per sheet, inline strings, cell styles, column
|
|
4
|
+
* widths, formulas, and cached formula results. fflate (MIT) writes the ZIP.
|
|
5
|
+
*
|
|
6
|
+
* A formula keeps a cached result so a preview tool shows the same value as
|
|
7
|
+
* the panel, while calcPr asks Excel and LibreOffice to recalculate on load.
|
|
8
|
+
*/
|
|
9
|
+
import { zipSync, strToU8 } from 'fflate';
|
|
10
|
+
import { columnName, effectiveTextColor, evaluateWorkbook, formatNumber, usedBounds } from '../../sheet/index.js';
|
|
11
|
+
const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
|
|
12
|
+
const RELATIONSHIPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
|
|
13
|
+
const PACKAGE_RELATIONSHIPS = 'http://schemas.openxmlformats.org/package/2006/relationships';
|
|
14
|
+
const BUILTIN_NUMBER_FORMATS = {
|
|
15
|
+
integer: 1,
|
|
16
|
+
number: 2,
|
|
17
|
+
percent: 10,
|
|
18
|
+
date: 14,
|
|
19
|
+
currency: 164,
|
|
20
|
+
};
|
|
21
|
+
const CUSTOM_NUMBER_FORMATS = '<numFmts count="1"><numFmt numFmtId="164" formatCode=""$"#,##0.00"/></numFmts>';
|
|
22
|
+
function xmlText(value) {
|
|
23
|
+
return value
|
|
24
|
+
.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
|
|
25
|
+
.replace(/&/g, '&')
|
|
26
|
+
.replace(/</g, '<')
|
|
27
|
+
.replace(/>/g, '>');
|
|
28
|
+
}
|
|
29
|
+
function xmlAttribute(value) {
|
|
30
|
+
return xmlText(value).replace(/"/g, '"').replace(/'/g, ''');
|
|
31
|
+
}
|
|
32
|
+
function colorHex(value) {
|
|
33
|
+
const hex = value.replace('#', '').toUpperCase();
|
|
34
|
+
return 'FF' + (hex.length === 3 ? hex.split('').map((part) => part + part).join('') : hex);
|
|
35
|
+
}
|
|
36
|
+
function normaliseStyle(style) {
|
|
37
|
+
if (style === undefined)
|
|
38
|
+
return undefined;
|
|
39
|
+
const fill = style.background ?? null;
|
|
40
|
+
const font = {
|
|
41
|
+
bold: style.bold === true,
|
|
42
|
+
italic: style.italic === true,
|
|
43
|
+
underline: style.underline === true,
|
|
44
|
+
strike: style.strike === true,
|
|
45
|
+
color: effectiveTextColor(style) ?? null,
|
|
46
|
+
};
|
|
47
|
+
const spec = {
|
|
48
|
+
font,
|
|
49
|
+
fill,
|
|
50
|
+
align: style.align ?? null,
|
|
51
|
+
numberFormat: style.numberFormat === undefined || style.numberFormat === 'general' ? null : style.numberFormat,
|
|
52
|
+
};
|
|
53
|
+
const plain = !font.bold && !font.italic && !font.underline && !font.strike && font.color === null
|
|
54
|
+
&& spec.fill === null && spec.align === null && spec.numberFormat === null;
|
|
55
|
+
return plain ? undefined : spec;
|
|
56
|
+
}
|
|
57
|
+
function fontKey(font) {
|
|
58
|
+
return (font.bold ? 'b' : '') + (font.italic ? 'i' : '') + (font.underline ? 'u' : '') + (font.strike ? 's' : '') + (font.color === null ? '' : font.color);
|
|
59
|
+
}
|
|
60
|
+
function styleKey(style) {
|
|
61
|
+
return fontKey(style.font) + '|' + (style.fill ?? '') + '|' + (style.align ?? '') + '|' + (style.numberFormat ?? '');
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Build the shared font, fill, and xf tables for one workbook.
|
|
65
|
+
* @param workbook the workbook.
|
|
66
|
+
* @returns the tables.
|
|
67
|
+
*/
|
|
68
|
+
function styleTables(workbook) {
|
|
69
|
+
const fonts = [{ bold: false, italic: false, underline: false, strike: false, color: null }];
|
|
70
|
+
const fills = [];
|
|
71
|
+
const styles = [];
|
|
72
|
+
const fontSeen = new Set(['']);
|
|
73
|
+
const fillSeen = new Set();
|
|
74
|
+
const styleSeen = new Set();
|
|
75
|
+
for (const sheet of workbook.sheets) {
|
|
76
|
+
for (const cell of Object.values(sheet.cells)) {
|
|
77
|
+
const spec = normaliseStyle(cell.style);
|
|
78
|
+
if (spec === undefined)
|
|
79
|
+
continue;
|
|
80
|
+
if (!fontSeen.has(fontKey(spec.font))) {
|
|
81
|
+
fontSeen.add(fontKey(spec.font));
|
|
82
|
+
fonts.push(spec.font);
|
|
83
|
+
}
|
|
84
|
+
if (spec.fill !== null && !fillSeen.has(spec.fill)) {
|
|
85
|
+
fillSeen.add(spec.fill);
|
|
86
|
+
fills.push(spec.fill);
|
|
87
|
+
}
|
|
88
|
+
if (!styleSeen.has(styleKey(spec))) {
|
|
89
|
+
styleSeen.add(styleKey(spec));
|
|
90
|
+
styles.push(spec);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return { fonts, fills, styles };
|
|
95
|
+
}
|
|
96
|
+
function fontIdOf(tables, spec) {
|
|
97
|
+
const index = tables.fonts.findIndex((font) => fontKey(font) === fontKey(spec.font));
|
|
98
|
+
return index < 0 ? 0 : index;
|
|
99
|
+
}
|
|
100
|
+
function fillIdOf(tables, spec) {
|
|
101
|
+
if (spec.fill === null)
|
|
102
|
+
return 0;
|
|
103
|
+
const index = tables.fills.indexOf(spec.fill);
|
|
104
|
+
return index < 0 ? 0 : index + 2;
|
|
105
|
+
}
|
|
106
|
+
function xfIdOf(tables, spec) {
|
|
107
|
+
if (spec === undefined)
|
|
108
|
+
return 0;
|
|
109
|
+
const index = tables.styles.findIndex((style) => styleKey(style) === styleKey(spec));
|
|
110
|
+
return index < 0 ? 0 : index + 1;
|
|
111
|
+
}
|
|
112
|
+
function fontXml(font) {
|
|
113
|
+
const parts = ['<font>'];
|
|
114
|
+
if (font.bold)
|
|
115
|
+
parts.push('<b/>');
|
|
116
|
+
if (font.italic)
|
|
117
|
+
parts.push('<i/>');
|
|
118
|
+
if (font.strike)
|
|
119
|
+
parts.push('<strike/>');
|
|
120
|
+
if (font.underline)
|
|
121
|
+
parts.push('<u/>');
|
|
122
|
+
parts.push('<sz val="11"/>');
|
|
123
|
+
if (font.color !== null)
|
|
124
|
+
parts.push('<color rgb="' + colorHex(font.color) + '"/>');
|
|
125
|
+
parts.push('<name val="Calibri"/><family val="2"/>');
|
|
126
|
+
parts.push('</font>');
|
|
127
|
+
return parts.join('');
|
|
128
|
+
}
|
|
129
|
+
function fillXml(color) {
|
|
130
|
+
return '<fill><patternFill patternType="solid"><fgColor rgb="' + colorHex(color) + '"/><bgColor indexed="64"/></patternFill></fill>';
|
|
131
|
+
}
|
|
132
|
+
function stylesXml(tables) {
|
|
133
|
+
const fonts = tables.fonts.map(fontXml).join('');
|
|
134
|
+
const fills = '<fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + tables.fills.map(fillXml).join('');
|
|
135
|
+
const xfs = ['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'];
|
|
136
|
+
for (const style of tables.styles) {
|
|
137
|
+
const numFmtId = style.numberFormat === null ? 0 : BUILTIN_NUMBER_FORMATS[style.numberFormat] ?? 0;
|
|
138
|
+
const attributes = [
|
|
139
|
+
'numFmtId="' + String(numFmtId) + '"',
|
|
140
|
+
'fontId="' + String(fontIdOf(tables, style)) + '"',
|
|
141
|
+
'fillId="' + String(fillIdOf(tables, style)) + '"',
|
|
142
|
+
'borderId="0"',
|
|
143
|
+
'xfId="0"',
|
|
144
|
+
];
|
|
145
|
+
if (numFmtId !== 0)
|
|
146
|
+
attributes.push('applyNumberFormat="1"');
|
|
147
|
+
if (fontIdOf(tables, style) !== 0)
|
|
148
|
+
attributes.push('applyFont="1"');
|
|
149
|
+
if (fillIdOf(tables, style) !== 0)
|
|
150
|
+
attributes.push('applyFill="1"');
|
|
151
|
+
if (style.align !== null)
|
|
152
|
+
attributes.push('applyAlignment="1"');
|
|
153
|
+
const alignment = style.align === null ? '' : '<alignment horizontal="' + style.align + '"/>';
|
|
154
|
+
xfs.push('<xf ' + attributes.join(' ') + '>' + alignment + '</xf>');
|
|
155
|
+
}
|
|
156
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
157
|
+
'<styleSheet xmlns="' + MAIN + '">' + CUSTOM_NUMBER_FORMATS +
|
|
158
|
+
'<fonts count="' + String(tables.fonts.length) + '">' + fonts + '</fonts>' +
|
|
159
|
+
'<fills count="' + String(tables.fills.length + 2) + '">' + fills + '</fills>' +
|
|
160
|
+
'<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>' +
|
|
161
|
+
'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
|
|
162
|
+
'<cellXfs count="' + String(xfs.length) + '">' + xfs.join('') + '</cellXfs>' +
|
|
163
|
+
'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
|
|
164
|
+
'</styleSheet>';
|
|
165
|
+
}
|
|
166
|
+
function numberXml(value) {
|
|
167
|
+
return Number.isFinite(value) ? String(value) : '0';
|
|
168
|
+
}
|
|
169
|
+
function cellXml(ref, cell, result, styleIndex) {
|
|
170
|
+
const styleAttribute = styleIndex === 0 ? '' : ' s="' + String(styleIndex) + '"';
|
|
171
|
+
if (cell.formula !== undefined) {
|
|
172
|
+
const formula = cell.formula.startsWith('=') ? cell.formula.slice(1) : cell.formula;
|
|
173
|
+
if (result?.error !== undefined)
|
|
174
|
+
return '<c r="' + ref + '"' + styleAttribute + ' t="e"><f>' + xmlText(formula) + '</f><v>' + xmlText(result.error) + '</v></c>';
|
|
175
|
+
if (result === undefined || result.value === null)
|
|
176
|
+
return '<c r="' + ref + '"' + styleAttribute + '><f>' + xmlText(formula) + '</f></c>';
|
|
177
|
+
if (typeof result.value === 'number')
|
|
178
|
+
return '<c r="' + ref + '"' + styleAttribute + '><f>' + xmlText(formula) + '</f><v>' + numberXml(result.value) + '</v></c>';
|
|
179
|
+
if (typeof result.value === 'boolean')
|
|
180
|
+
return '<c r="' + ref + '"' + styleAttribute + ' t="b"><f>' + xmlText(formula) + '</f><v>' + (result.value ? '1' : '0') + '</v></c>';
|
|
181
|
+
return '<c r="' + ref + '"' + styleAttribute + ' t="str"><f>' + xmlText(formula) + '</f><v>' + xmlText(result.value) + '</v></c>';
|
|
182
|
+
}
|
|
183
|
+
if (cell.value === undefined)
|
|
184
|
+
return '<c r="' + ref + '"' + styleAttribute + '/>';
|
|
185
|
+
if (typeof cell.value === 'number')
|
|
186
|
+
return '<c r="' + ref + '"' + styleAttribute + '><v>' + numberXml(cell.value) + '</v></c>';
|
|
187
|
+
if (typeof cell.value === 'boolean')
|
|
188
|
+
return '<c r="' + ref + '"' + styleAttribute + ' t="b"><v>' + (cell.value ? '1' : '0') + '</v></c>';
|
|
189
|
+
return '<c r="' + ref + '"' + styleAttribute + ' t="inlineStr"><is><t xml:space="preserve">' + xmlText(cell.value) + '</t></is></c>';
|
|
190
|
+
}
|
|
191
|
+
function columnsXml(widths) {
|
|
192
|
+
if (widths === undefined)
|
|
193
|
+
return '';
|
|
194
|
+
const columns = Object.entries(widths).map(([name, width]) => {
|
|
195
|
+
let column = 0;
|
|
196
|
+
for (const letter of name)
|
|
197
|
+
column = column * 26 + (letter.charCodeAt(0) - 64);
|
|
198
|
+
const excelWidth = Math.round((width / 7) * 100) / 100;
|
|
199
|
+
return '<col min="' + String(column) + '" max="' + String(column) + '" width="' + String(excelWidth) + '" customWidth="1"/>';
|
|
200
|
+
});
|
|
201
|
+
return columns.length === 0 ? '' : '<cols>' + columns.join('') + '</cols>';
|
|
202
|
+
}
|
|
203
|
+
function worksheetXml(sheetName, workbook, evaluated, tables) {
|
|
204
|
+
const sheet = workbook.sheets.find((item) => item.name === sheetName);
|
|
205
|
+
if (sheet === undefined)
|
|
206
|
+
return '';
|
|
207
|
+
const bounds = usedBounds(sheet);
|
|
208
|
+
const results = evaluated.results[sheet.name] ?? {};
|
|
209
|
+
const rowsXml = [];
|
|
210
|
+
for (let row = 1; row <= Math.max(1, bounds.rows); row += 1) {
|
|
211
|
+
const cells = [];
|
|
212
|
+
for (let column = 0; column < Math.max(1, bounds.columns); column += 1) {
|
|
213
|
+
const ref = columnName(column) + String(row);
|
|
214
|
+
const cell = sheet.cells[ref];
|
|
215
|
+
const result = results[ref];
|
|
216
|
+
if (cell === undefined && result === undefined)
|
|
217
|
+
continue;
|
|
218
|
+
const styleIndex = xfIdOf(tables, cell === undefined ? undefined : normaliseStyle(cell.style));
|
|
219
|
+
cells.push(cellXml(ref, cell ?? {}, result, styleIndex));
|
|
220
|
+
}
|
|
221
|
+
if (cells.length > 0)
|
|
222
|
+
rowsXml.push('<row r="' + String(row) + '">' + cells.join('') + '</row>');
|
|
223
|
+
}
|
|
224
|
+
const dimension = bounds.rows === 0 || bounds.columns === 0
|
|
225
|
+
? 'A1'
|
|
226
|
+
: 'A1:' + columnName(Math.max(0, bounds.columns - 1)) + String(Math.max(1, bounds.rows));
|
|
227
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
228
|
+
'<worksheet xmlns="' + MAIN + '" xmlns:r="' + RELATIONSHIPS + '">' +
|
|
229
|
+
'<dimension ref="' + dimension + '"/>' +
|
|
230
|
+
'<sheetViews><sheetView workbookViewId="0"/></sheetViews>' +
|
|
231
|
+
'<sheetFormatPr defaultRowHeight="15"/>' +
|
|
232
|
+
columnsXml(sheet.columnWidths) +
|
|
233
|
+
'<sheetData>' + rowsXml.join('') + '</sheetData>' +
|
|
234
|
+
'<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>' +
|
|
235
|
+
'</worksheet>';
|
|
236
|
+
}
|
|
237
|
+
function workbookXml(workbook) {
|
|
238
|
+
const sheets = workbook.sheets
|
|
239
|
+
.map((sheet, index) => '<sheet name="' + xmlAttribute(sheet.name) + '" sheetId="' + String(index + 1) + '" r:id="rId' + String(index + 1) + '"/>')
|
|
240
|
+
.join('');
|
|
241
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
242
|
+
'<workbook xmlns="' + MAIN + '" xmlns:r="' + RELATIONSHIPS + '">' +
|
|
243
|
+
'<sheets>' + sheets + '</sheets>' +
|
|
244
|
+
'<calcPr calcId="171027" fullCalcOnLoad="1"/>' +
|
|
245
|
+
'</workbook>';
|
|
246
|
+
}
|
|
247
|
+
function workbookRels(workbook) {
|
|
248
|
+
const sheets = workbook.sheets
|
|
249
|
+
.map((_sheet, index) => '<Relationship Id="rId' + String(index + 1) + '" Type="' + RELATIONSHIPS + '/worksheet" Target="worksheets/sheet' + String(index + 1) + '.xml"/>')
|
|
250
|
+
.join('');
|
|
251
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
252
|
+
'<Relationships xmlns="' + PACKAGE_RELATIONSHIPS + '">' + sheets +
|
|
253
|
+
'<Relationship Id="rId' + String(workbook.sheets.length + 1) + '" Type="' + RELATIONSHIPS + '/styles" Target="styles.xml"/>' +
|
|
254
|
+
'</Relationships>';
|
|
255
|
+
}
|
|
256
|
+
function contentTypes(workbook) {
|
|
257
|
+
const sheets = workbook.sheets
|
|
258
|
+
.map((_sheet, index) => '<Override PartName="/xl/worksheets/sheet' + String(index + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>')
|
|
259
|
+
.join('');
|
|
260
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
261
|
+
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
|
|
262
|
+
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
|
263
|
+
'<Default Extension="xml" ContentType="application/xml"/>' +
|
|
264
|
+
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
|
|
265
|
+
'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
|
|
266
|
+
sheets +
|
|
267
|
+
'</Types>';
|
|
268
|
+
}
|
|
269
|
+
function packageRels() {
|
|
270
|
+
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
271
|
+
'<Relationships xmlns="' + PACKAGE_RELATIONSHIPS + '">' +
|
|
272
|
+
'<Relationship Id="rId1" Type="' + RELATIONSHIPS + '/officeDocument" Target="xl/workbook.xml"/>' +
|
|
273
|
+
'</Relationships>';
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Write a workbook as an XLSX package.
|
|
277
|
+
* @param workbook the validated workbook.
|
|
278
|
+
* @returns the file bytes.
|
|
279
|
+
*/
|
|
280
|
+
export function workbookToXlsx(workbook) {
|
|
281
|
+
const evaluated = evaluateWorkbook(workbook);
|
|
282
|
+
const tables = styleTables(workbook);
|
|
283
|
+
const files = {
|
|
284
|
+
'[Content_Types].xml': strToU8(contentTypes(workbook)),
|
|
285
|
+
'_rels/.rels': strToU8(packageRels()),
|
|
286
|
+
'xl/workbook.xml': strToU8(workbookXml(workbook)),
|
|
287
|
+
'xl/_rels/workbook.xml.rels': strToU8(workbookRels(workbook)),
|
|
288
|
+
'xl/styles.xml': strToU8(stylesXml(tables)),
|
|
289
|
+
};
|
|
290
|
+
workbook.sheets.forEach((sheet, index) => {
|
|
291
|
+
files['xl/worksheets/sheet' + String(index + 1) + '.xml'] = strToU8(worksheetXml(sheet.name, workbook, evaluated, tables));
|
|
292
|
+
});
|
|
293
|
+
return Buffer.from(zipSync(files, { level: 6 }));
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* The display text for one evaluated value, used by CSV and print copies.
|
|
297
|
+
* @param result the evaluated result.
|
|
298
|
+
* @param style the cell style.
|
|
299
|
+
* @returns the text.
|
|
300
|
+
*/
|
|
301
|
+
export function resultText(result, style) {
|
|
302
|
+
if (result === undefined)
|
|
303
|
+
return '';
|
|
304
|
+
if (result.error !== undefined)
|
|
305
|
+
return result.error;
|
|
306
|
+
const value = result.value;
|
|
307
|
+
if (value === null)
|
|
308
|
+
return '';
|
|
309
|
+
if (typeof value === 'number')
|
|
310
|
+
return formatNumber(value, style?.numberFormat);
|
|
311
|
+
if (typeof value === 'boolean')
|
|
312
|
+
return value ? 'TRUE' : 'FALSE';
|
|
313
|
+
return value;
|
|
314
|
+
}
|
|
@@ -3,10 +3,13 @@ import fs from 'node:fs/promises';
|
|
|
3
3
|
import { SceneGraph } from '@open-pencil/scene-graph';
|
|
4
4
|
import { designJSXRenderer } from '@open-pencil/core/design-jsx';
|
|
5
5
|
import { fontManager } from '@open-pencil/core/text';
|
|
6
|
+
import { createLinter } from '@open-pencil/core/lint';
|
|
6
7
|
import { computeContentBounds, headlessRenderNodes } from '@open-pencil/core/io/formats/raster';
|
|
7
8
|
import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg';
|
|
8
|
-
import { exportFigFile } from '@open-pencil/core/io/formats/fig';
|
|
9
|
+
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig';
|
|
10
|
+
import { selectionToJSX } from '@open-pencil/design-jsx';
|
|
9
11
|
import { bundledIconProvider } from '../../icon-set.js';
|
|
12
|
+
import { buildPageModel } from './page-model.js';
|
|
10
13
|
/** Fonts that ship with the package; any other family is substituted. */
|
|
11
14
|
const BUNDLED_FONTS = new Set(['Inter', 'Noto Naskh Arabic', 'Roboto']);
|
|
12
15
|
/** The Roboto faces the package ships, by style. */
|
|
@@ -70,6 +73,26 @@ function descendants(graph, page) {
|
|
|
70
73
|
visit(id);
|
|
71
74
|
return out;
|
|
72
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* The highest design-lint severities, as the summary's warnings.
|
|
78
|
+
* Info rules stay out: token adoption and structure hygiene are suggestions.
|
|
79
|
+
* A lint failure must never block saving, so any throw returns nothing.
|
|
80
|
+
* @param graph the compiled graph.
|
|
81
|
+
* @returns the warnings.
|
|
82
|
+
*/
|
|
83
|
+
function lintWarnings(graph) {
|
|
84
|
+
const LIMIT = 12;
|
|
85
|
+
try {
|
|
86
|
+
const result = createLinter({ preset: 'recommended' }).lintGraph(graph);
|
|
87
|
+
const relevant = result.messages.filter((message) => message.severity === 'error' || message.severity === 'warning');
|
|
88
|
+
const lines = relevant.slice(0, LIMIT).map((message) => `Design issue, ${message.nodePath.join(' / ')}: ${message.message}`);
|
|
89
|
+
const rest = relevant.length - lines.length;
|
|
90
|
+
return rest > 0 ? [...lines, `And ${rest} more design issues.`] : lines;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
}
|
|
73
96
|
/**
|
|
74
97
|
* Count the design's nodes, record its types and fonts, and warn about
|
|
75
98
|
* families the engine cannot load.
|
|
@@ -91,7 +114,43 @@ function summarize(graph, page) {
|
|
|
91
114
|
const warnings = sorted
|
|
92
115
|
.filter((family) => !BUNDLED_FONTS.has(family))
|
|
93
116
|
.map((family) => `Font "${family}" is not bundled. The preview substitutes a default face.`);
|
|
94
|
-
return { pages: graph.getPages().length, nodes: nodes.length, types, fonts: sorted, warnings };
|
|
117
|
+
return { pages: graph.getPages().length, nodes: nodes.length, types, fonts: sorted, warnings: [...warnings, ...lintWarnings(graph)] };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Convert a .fig file into stored Design JSX: the first page that holds elements,
|
|
121
|
+
* serialized like the panel's own save path. Non-empty pages after it are named
|
|
122
|
+
* in warnings, because the stored mockup keeps one page.
|
|
123
|
+
* @param bytes64 the base64 file bytes the host read.
|
|
124
|
+
* @returns the response.
|
|
125
|
+
*/
|
|
126
|
+
async function handleImport(bytes64) {
|
|
127
|
+
const bytes = Buffer.from(bytes64, 'base64');
|
|
128
|
+
if (bytes.byteLength === 0) {
|
|
129
|
+
return { ok: false, code: 'artifact/bad-request', message: 'The import received no .fig bytes.' };
|
|
130
|
+
}
|
|
131
|
+
const view = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
132
|
+
let graph;
|
|
133
|
+
try {
|
|
134
|
+
graph = await parseFigFile(view, { populate: 'all' });
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
return { ok: false, code: 'artifact/bad-request', message: 'The file is not a readable .fig document: ' + messageOf(error) };
|
|
138
|
+
}
|
|
139
|
+
const pages = graph.getPages();
|
|
140
|
+
const page = pages.find((candidate) => candidate.childIds.length > 0);
|
|
141
|
+
if (page === undefined) {
|
|
142
|
+
return { ok: false, code: 'artifact/bad-request', message: 'The file has no page with elements. Draw the mockup in Figma before exporting it.' };
|
|
143
|
+
}
|
|
144
|
+
const source = selectionToJSX(page.childIds, graph);
|
|
145
|
+
if (source === null) {
|
|
146
|
+
return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no source.' };
|
|
147
|
+
}
|
|
148
|
+
const info = summarize(graph, page);
|
|
149
|
+
const skipped = pages.filter((candidate) => candidate !== page && candidate.childIds.length > 0).length;
|
|
150
|
+
if (skipped > 0) {
|
|
151
|
+
info.warnings.push(`The file holds ${skipped} more page${skipped === 1 ? '' : 's'}; only "${page.name}" was imported.`);
|
|
152
|
+
}
|
|
153
|
+
return { ok: true, info, source };
|
|
95
154
|
}
|
|
96
155
|
/**
|
|
97
156
|
* Read a PNG's pixel size from its IHDR chunk.
|
|
@@ -124,11 +183,13 @@ async function renderPng(compiled, maxSide) {
|
|
|
124
183
|
}
|
|
125
184
|
/**
|
|
126
185
|
* Answer one request.
|
|
127
|
-
* @param source the Design JSX source.
|
|
186
|
+
* @param source the Design JSX source, or the empty string on an import.
|
|
128
187
|
* @param request the request.
|
|
129
188
|
* @returns the response.
|
|
130
189
|
*/
|
|
131
190
|
async function handle(source, request) {
|
|
191
|
+
if (request.action === 'import-fig')
|
|
192
|
+
return handleImport(request.bytes ?? '');
|
|
132
193
|
let compiled;
|
|
133
194
|
try {
|
|
134
195
|
compiled = await compile(source);
|
|
@@ -172,6 +233,10 @@ async function handle(source, request) {
|
|
|
172
233
|
return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no SVG.' };
|
|
173
234
|
return { ok: true, info, mediaType: 'image/svg+xml', data: Buffer.from(svg, 'utf8').toString('base64') };
|
|
174
235
|
}
|
|
236
|
+
if (request.format === 'html-svg') {
|
|
237
|
+
const model = await buildPageModel(compiled.graph, compiled.page);
|
|
238
|
+
return { ok: true, info, mediaType: 'application/json', data: Buffer.from(JSON.stringify(model), 'utf8').toString('base64') };
|
|
239
|
+
}
|
|
175
240
|
const png = await renderPng(compiled, 0);
|
|
176
241
|
if (png === null)
|
|
177
242
|
return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no image.' };
|
|
@@ -198,7 +263,7 @@ async function readRequest() {
|
|
|
198
263
|
throw new Error('The design request has no nonce.');
|
|
199
264
|
if (typeof fields.source !== 'string')
|
|
200
265
|
throw new Error('The design request has no source.');
|
|
201
|
-
if (fields.action !== 'inspect' && fields.action !== 'preview' && fields.action !== 'export') {
|
|
266
|
+
if (fields.action !== 'inspect' && fields.action !== 'preview' && fields.action !== 'export' && fields.action !== 'import-fig') {
|
|
202
267
|
throw new Error('The design request has an unknown action.');
|
|
203
268
|
}
|
|
204
269
|
return {
|
|
@@ -206,7 +271,8 @@ async function readRequest() {
|
|
|
206
271
|
action: fields.action,
|
|
207
272
|
source: fields.source,
|
|
208
273
|
...(typeof fields.maxSide === 'number' ? { maxSide: fields.maxSide } : {}),
|
|
209
|
-
...(fields.format === 'png' || fields.format === 'svg' || fields.format === 'fig' ? { format: fields.format } : {}),
|
|
274
|
+
...(fields.format === 'png' || fields.format === 'svg' || fields.format === 'fig' || fields.format === 'html-svg' ? { format: fields.format } : {}),
|
|
275
|
+
...(typeof fields.bytes === 'string' ? { bytes: fields.bytes } : {}),
|
|
210
276
|
};
|
|
211
277
|
}
|
|
212
278
|
await loadExtraFonts();
|