@open-artifact/dc 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +53 -4
- package/src/check.d.ts +30 -0
- package/src/check.js +337 -0
- package/src/document.d.ts +63 -0
- package/src/document.js +126 -0
- package/src/edit.d.ts +72 -0
- package/src/edit.js +249 -0
- package/src/holes.d.ts +46 -0
- package/src/holes.js +91 -0
- package/src/html.d.ts +113 -0
- package/src/html.js +335 -0
- package/src/index.d.ts +16 -0
- package/src/index.js +15 -0
- package/src/props.d.ts +51 -0
- package/src/props.js +57 -0
- package/src/protocol.d.ts +266 -0
- package/src/protocol.js +16 -0
- package/src/render.d.ts +34 -0
- package/src/render.js +256 -0
- package/src/rich-text.d.ts +106 -0
- package/src/rich-text.js +515 -0
- package/src/runtime/board.d.ts +6 -0
- package/src/runtime/board.js +509 -0
- package/src/runtime/focus-guard.d.ts +18 -0
- package/src/runtime/focus-guard.js +40 -0
- package/src/runtime/index.d.ts +16 -0
- package/src/runtime/index.js +15 -0
- package/src/runtime/logic.d.ts +31 -0
- package/src/runtime/logic.js +47 -0
- package/src/runtime/text-edit.d.ts +121 -0
- package/src/runtime/text-edit.js +1251 -0
- package/src/style.d.ts +30 -0
- package/src/style.js +108 -0
- package/src/template.d.ts +80 -0
- package/src/template.js +186 -0
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* The board runtime: renders one artboard inside its iframe and exposes
|
|
4
|
+
* `window.__dc` to the editor. Bundled as the classic script `support.js`.
|
|
5
|
+
*/
|
|
6
|
+
import * as React from 'react';
|
|
7
|
+
import { Component as ReactComponent } from 'react';
|
|
8
|
+
import { createRoot } from 'react-dom/client';
|
|
9
|
+
import { parseDcDocument } from "../document.js";
|
|
10
|
+
import { defaultProps } from "../props.js";
|
|
11
|
+
import { TID_ATTRIBUTE, renderTemplate } from "../render.js";
|
|
12
|
+
import { parseTemplate } from "../template.js";
|
|
13
|
+
import { TextEditor } from "./text-edit.js";
|
|
14
|
+
import { guardFocus } from "./focus-guard.js";
|
|
15
|
+
import { createLogicBase, evaluateLogic } from "./logic.js";
|
|
16
|
+
/** Deepest chain of nested `<dc-import>`s. */
|
|
17
|
+
const MAX_IMPORT_DEPTH = 8;
|
|
18
|
+
/** How long the size report waits for an animation frame before it is taken anyway (see `scheduleSize`). */
|
|
19
|
+
const SIZE_FALLBACK_MS = 100;
|
|
20
|
+
/** Computed properties the inspector reports. */
|
|
21
|
+
const INSPECTED = [
|
|
22
|
+
'display', 'position', 'flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'align-self', 'gap',
|
|
23
|
+
'row-gap', 'column-gap', 'grid-template-columns', 'grid-template-rows', 'flex-grow', 'flex-shrink', 'flex-basis',
|
|
24
|
+
'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height', 'padding-top', 'padding-right',
|
|
25
|
+
'padding-bottom', 'padding-left', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'color',
|
|
26
|
+
'background-color', 'background-image', 'border-top-width', 'border-top-style', 'border-top-color',
|
|
27
|
+
'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius',
|
|
28
|
+
'box-shadow', 'opacity', 'font-family', 'font-size', 'font-weight', 'font-style', 'line-height', 'letter-spacing',
|
|
29
|
+
'text-align', 'text-transform', 'text-decoration-line', 'white-space', 'overflow', 'object-fit', 'top', 'left',
|
|
30
|
+
'right', 'bottom', 'z-index', 'transform', 'rotate', 'scale', 'translate', 'transform-origin', 'border-right-width',
|
|
31
|
+
'border-bottom-width', 'border-left-width',
|
|
32
|
+
];
|
|
33
|
+
/** Catches render errors so one broken artboard (or child) never blanks the frame. */
|
|
34
|
+
class ErrorBoundary extends ReactComponent {
|
|
35
|
+
state = { failed: false, key: this.props.resetKey };
|
|
36
|
+
static getDerivedStateFromProps(props, state) {
|
|
37
|
+
return props.resetKey !== state.key ? { failed: false, key: props.resetKey } : null;
|
|
38
|
+
}
|
|
39
|
+
static getDerivedStateFromError() {
|
|
40
|
+
return { failed: true };
|
|
41
|
+
}
|
|
42
|
+
componentDidCatch(error, _info) {
|
|
43
|
+
this.props.onError(error);
|
|
44
|
+
}
|
|
45
|
+
render() {
|
|
46
|
+
return this.state.failed ? null : this.props.children;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** The small error panel shown over a broken board. */
|
|
50
|
+
function ErrorPanel({ errors }) {
|
|
51
|
+
if (!errors.length)
|
|
52
|
+
return null;
|
|
53
|
+
return (_jsx("div", { "data-dc-errors": "", style: {
|
|
54
|
+
position: 'fixed', left: 8, right: 8, bottom: 8, zIndex: 2147483647, padding: '8px 10px',
|
|
55
|
+
font: '12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace', color: '#7f1d1d', background: '#fef2f2',
|
|
56
|
+
border: '1px solid #fca5a5', borderRadius: 6, whiteSpace: 'pre-wrap', maxHeight: '40%', overflow: 'auto',
|
|
57
|
+
}, children: errors.map((error, index) => (_jsxs("div", { children: [_jsx("strong", { children: error.source }), ": ", error.message] }, index))) }));
|
|
58
|
+
}
|
|
59
|
+
/** Directory part of a path (`sub/A.dc.html` → `sub/`). */
|
|
60
|
+
function dirOf(path) {
|
|
61
|
+
return path.slice(0, path.lastIndexOf('/') + 1);
|
|
62
|
+
}
|
|
63
|
+
/** Normalizes `a/./b/../c` and strips a leading `/`. */
|
|
64
|
+
function normalizePath(path) {
|
|
65
|
+
const out = [];
|
|
66
|
+
for (const part of path.split('/')) {
|
|
67
|
+
if (!part || part === '.')
|
|
68
|
+
continue;
|
|
69
|
+
if (part === '..')
|
|
70
|
+
out.pop();
|
|
71
|
+
else
|
|
72
|
+
out.push(part);
|
|
73
|
+
}
|
|
74
|
+
return out.join('/');
|
|
75
|
+
}
|
|
76
|
+
/* -------------------------------------------------------------------------- */
|
|
77
|
+
/* Board */
|
|
78
|
+
/* -------------------------------------------------------------------------- */
|
|
79
|
+
class Board {
|
|
80
|
+
boot;
|
|
81
|
+
unit = null;
|
|
82
|
+
overrides;
|
|
83
|
+
mode;
|
|
84
|
+
root;
|
|
85
|
+
renderErrors = [];
|
|
86
|
+
renderVersion = 0;
|
|
87
|
+
children = new Map();
|
|
88
|
+
lastSize = { width: 0, height: 0 };
|
|
89
|
+
booted = false;
|
|
90
|
+
text = new TextEditor((event) => this.report(event));
|
|
91
|
+
previews = new Map();
|
|
92
|
+
constructor(boot) {
|
|
93
|
+
this.boot = boot;
|
|
94
|
+
this.overrides = { ...(boot.props ?? {}) };
|
|
95
|
+
this.mode = boot.mode;
|
|
96
|
+
const container = document.createElement('div');
|
|
97
|
+
container.setAttribute('data-dc-root', '');
|
|
98
|
+
container.style.display = 'contents';
|
|
99
|
+
document.body.appendChild(container);
|
|
100
|
+
this.root = createRoot(container, {
|
|
101
|
+
onUncaughtError: (error) => this.addRenderError('render', error),
|
|
102
|
+
});
|
|
103
|
+
this.installEvents();
|
|
104
|
+
this.setSource(boot.source);
|
|
105
|
+
}
|
|
106
|
+
/* ---------------------------- units ---------------------------- */
|
|
107
|
+
/** Parses a source into a unit, reusing the previous logic class when the script is unchanged. */
|
|
108
|
+
buildUnit(path, source, previous, depth) {
|
|
109
|
+
const doc = parseDcDocument(source);
|
|
110
|
+
const errors = [];
|
|
111
|
+
if (!doc.template)
|
|
112
|
+
errors.push({ source: 'template', message: 'No <x-dc> template found.' });
|
|
113
|
+
if (doc.propsError)
|
|
114
|
+
errors.push({ source: 'props', message: doc.propsError });
|
|
115
|
+
const scriptChanged = !previous || previous.doc.script?.body.text !== doc.script?.body.text;
|
|
116
|
+
// The logic class reads its renderer through this holder, so a template-only
|
|
117
|
+
// change swaps the renderer under the same class (and keeps state).
|
|
118
|
+
const rendererRef = scriptChanged ? { current: (() => null) } : previous.rendererRef;
|
|
119
|
+
const unit = {
|
|
120
|
+
path,
|
|
121
|
+
doc,
|
|
122
|
+
model: parseTemplate(doc.template?.text ?? ''),
|
|
123
|
+
Logic: previous?.Logic,
|
|
124
|
+
logicVersion: previous?.logicVersion ?? 0,
|
|
125
|
+
rendererRef,
|
|
126
|
+
defaults: defaultProps(doc.props),
|
|
127
|
+
errors,
|
|
128
|
+
};
|
|
129
|
+
rendererRef.current = (values) => renderTemplate(unit.model, values, this.host(unit, depth));
|
|
130
|
+
if (scriptChanged) {
|
|
131
|
+
const Base = createLogicBase(() => rendererRef.current);
|
|
132
|
+
try {
|
|
133
|
+
unit.Logic = doc.script ? evaluateLogic(doc.script.body.text, Base, React, path) : Base;
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
errors.push({ source: 'script', message: error instanceof Error ? error.message : String(error) });
|
|
137
|
+
unit.Logic = Base;
|
|
138
|
+
}
|
|
139
|
+
unit.logicVersion = (previous?.logicVersion ?? 0) + 1;
|
|
140
|
+
}
|
|
141
|
+
return unit;
|
|
142
|
+
}
|
|
143
|
+
/** The render host of a unit (the board stamps tids; children do not). */
|
|
144
|
+
host(unit, depth) {
|
|
145
|
+
return {
|
|
146
|
+
head: document.head,
|
|
147
|
+
stamp: depth === 0,
|
|
148
|
+
streaming: false,
|
|
149
|
+
importComponent: (name) => this.importComponent(unit, name, depth),
|
|
150
|
+
globalComponent: (path) => {
|
|
151
|
+
let value = window;
|
|
152
|
+
for (const key of path.split('.'))
|
|
153
|
+
value = value == null ? undefined : value[key];
|
|
154
|
+
return typeof value === 'function' || (value && typeof value === 'object') ? value : null;
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/** Resolves `<dc-import name>` to a component, loading the sibling file on first use. */
|
|
159
|
+
importComponent(parent, name, depth) {
|
|
160
|
+
if (!/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(name)) {
|
|
161
|
+
this.noteChildError(`dc-import name "${name}" is not a file name.`);
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
const path = normalizePath(`${dirOf(parent.path)}${name}.dc.html`);
|
|
165
|
+
if (depth + 1 > MAX_IMPORT_DEPTH || path === this.unit?.path) {
|
|
166
|
+
this.noteChildError(`dc-import "${name}" nests too deep (or imports itself).`);
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const entry = this.children.get(path);
|
|
170
|
+
if (entry?.status === 'ready')
|
|
171
|
+
return entry.Component;
|
|
172
|
+
if (entry?.status === 'error')
|
|
173
|
+
return null;
|
|
174
|
+
if (!entry) {
|
|
175
|
+
this.children.set(path, { status: 'loading' });
|
|
176
|
+
this.boot
|
|
177
|
+
.load(path)
|
|
178
|
+
.then((source) => {
|
|
179
|
+
const unit = this.buildUnit(path, source, null, depth + 1);
|
|
180
|
+
const Component = (props) => (_jsx(ErrorBoundary, { resetKey: unit.logicVersion, onError: (error) => this.addRenderError('import', error, name), children: React.createElement(unit.Logic, { ...unit.defaults, ...props }) }));
|
|
181
|
+
Component.displayName = `Import(${name})`;
|
|
182
|
+
this.children.set(path, { status: 'ready', unit, Component });
|
|
183
|
+
for (const error of unit.errors)
|
|
184
|
+
this.addError({ source: 'import', message: `${name}: ${error.message}` });
|
|
185
|
+
})
|
|
186
|
+
.catch((error) => {
|
|
187
|
+
this.children.set(path, { status: 'error', message: String(error) });
|
|
188
|
+
this.addError({ source: 'import', message: `${name}: could not load ${path}` });
|
|
189
|
+
})
|
|
190
|
+
.finally(() => this.render());
|
|
191
|
+
}
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
noteChildError(message) {
|
|
195
|
+
queueMicrotask(() => this.addError({ source: 'import', message }));
|
|
196
|
+
}
|
|
197
|
+
/* --------------------------- rendering -------------------------- */
|
|
198
|
+
render() {
|
|
199
|
+
const unit = this.unit;
|
|
200
|
+
if (!unit)
|
|
201
|
+
return;
|
|
202
|
+
const errors = [...unit.errors, ...this.renderErrors];
|
|
203
|
+
this.root.render(_jsxs(_Fragment, { children: [_jsx(ErrorBoundary, { resetKey: this.renderVersion, onError: (error) => this.addRenderError('render', error), children: React.createElement(unit.Logic, { key: unit.logicVersion, ...unit.defaults, ...this.overrides }) }), _jsx(ErrorPanel, { errors: errors })] }));
|
|
204
|
+
}
|
|
205
|
+
addRenderError(source, error, prefix) {
|
|
206
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
207
|
+
this.addError({ source, message: prefix ? `${prefix}: ${message}` : message });
|
|
208
|
+
}
|
|
209
|
+
addError(error) {
|
|
210
|
+
if (this.renderErrors.some((e) => e.source === error.source && e.message === error.message))
|
|
211
|
+
return;
|
|
212
|
+
this.renderErrors = [...this.renderErrors, error];
|
|
213
|
+
this.report({ type: 'errors', errors: this.errors() });
|
|
214
|
+
this.render();
|
|
215
|
+
}
|
|
216
|
+
report(event) {
|
|
217
|
+
try {
|
|
218
|
+
this.boot.report(event);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
/* The editor went away; nothing to do. */
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/* ------------------------------ api ------------------------------ */
|
|
225
|
+
setSource(source) {
|
|
226
|
+
this.endTextEdit(false);
|
|
227
|
+
this.unit = this.buildUnit(this.boot.path, source, this.unit, 0);
|
|
228
|
+
this.renderErrors = [];
|
|
229
|
+
this.renderVersion++;
|
|
230
|
+
this.render();
|
|
231
|
+
this.report({ type: 'errors', errors: this.errors() });
|
|
232
|
+
this.scheduleSize();
|
|
233
|
+
}
|
|
234
|
+
invalidate(paths) {
|
|
235
|
+
let changed = false;
|
|
236
|
+
for (const path of paths)
|
|
237
|
+
changed = this.children.delete(normalizePath(path)) || changed;
|
|
238
|
+
if (changed) {
|
|
239
|
+
this.renderErrors = this.renderErrors.filter((error) => error.source !== 'import');
|
|
240
|
+
this.render();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
setProps(props) {
|
|
244
|
+
this.overrides = { ...props };
|
|
245
|
+
this.render();
|
|
246
|
+
}
|
|
247
|
+
setMode(mode) {
|
|
248
|
+
this.mode = mode;
|
|
249
|
+
if (mode !== 'edit')
|
|
250
|
+
this.endTextEdit(true);
|
|
251
|
+
}
|
|
252
|
+
errors() {
|
|
253
|
+
return [...(this.unit?.errors ?? []), ...this.renderErrors];
|
|
254
|
+
}
|
|
255
|
+
size() {
|
|
256
|
+
const doc = document.documentElement;
|
|
257
|
+
return { width: Math.ceil(doc.scrollWidth), height: Math.ceil(doc.scrollHeight) };
|
|
258
|
+
}
|
|
259
|
+
/** Instances of a template node in document order. */
|
|
260
|
+
instances(tid) {
|
|
261
|
+
return Array.from(document.querySelectorAll(`[${TID_ATTRIBUTE}="${tid}"]`));
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The stamped element owning a DOM node: the nearest one up. What a
|
|
265
|
+
* component draws itself carries no tid, so it resolves to the import's
|
|
266
|
+
* boundary; markup written between an `<x-import>`'s tags is this board's
|
|
267
|
+
* template and stays selectable on its own (a provider wrapping the whole
|
|
268
|
+
* artboard must not swallow it). A `<dc-import>`'s board is rendered
|
|
269
|
+
* unstamped, so it resolves to the import as a whole.
|
|
270
|
+
*/
|
|
271
|
+
owner(node) {
|
|
272
|
+
return node?.closest(`[${TID_ATTRIBUTE}]`) ?? null;
|
|
273
|
+
}
|
|
274
|
+
rectOf(element) {
|
|
275
|
+
if (getComputedStyle(element).display === 'contents') {
|
|
276
|
+
const rects = Array.from(element.children).map((child) => this.rectOf(child)).filter((r) => r.width || r.height);
|
|
277
|
+
if (!rects.length)
|
|
278
|
+
return { x: 0, y: 0, width: 0, height: 0 };
|
|
279
|
+
const left = Math.min(...rects.map((r) => r.x));
|
|
280
|
+
const top = Math.min(...rects.map((r) => r.y));
|
|
281
|
+
const right = Math.max(...rects.map((r) => r.x + r.width));
|
|
282
|
+
const bottom = Math.max(...rects.map((r) => r.y + r.height));
|
|
283
|
+
return { x: left, y: top, width: right - left, height: bottom - top };
|
|
284
|
+
}
|
|
285
|
+
const rect = element.getBoundingClientRect();
|
|
286
|
+
return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
|
|
287
|
+
}
|
|
288
|
+
toPick(element) {
|
|
289
|
+
const tid = Number(element.getAttribute(TID_ATTRIBUTE));
|
|
290
|
+
return { tid, rect: this.rectOf(element), instance: Math.max(0, this.instances(tid).indexOf(element)) };
|
|
291
|
+
}
|
|
292
|
+
pick(x, y) {
|
|
293
|
+
const element = this.owner(document.elementFromPoint(x, y));
|
|
294
|
+
return element ? this.toPick(element) : null;
|
|
295
|
+
}
|
|
296
|
+
pickAll(x, y) {
|
|
297
|
+
const out = [];
|
|
298
|
+
for (let element = this.owner(document.elementFromPoint(x, y)); element; element = this.owner(element.parentElement)) {
|
|
299
|
+
out.push(this.toPick(element));
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
rects(tids) {
|
|
304
|
+
const out = {};
|
|
305
|
+
for (const tid of tids)
|
|
306
|
+
out[tid] = this.instances(tid).map((element) => this.rectOf(element));
|
|
307
|
+
return out;
|
|
308
|
+
}
|
|
309
|
+
importValues(name, props) {
|
|
310
|
+
const parent = this.unit;
|
|
311
|
+
if (!parent)
|
|
312
|
+
return null;
|
|
313
|
+
const entry = this.children.get(normalizePath(`${dirOf(parent.path)}${name}.dc.html`));
|
|
314
|
+
if (entry?.status !== 'ready')
|
|
315
|
+
return null;
|
|
316
|
+
try {
|
|
317
|
+
const instance = new entry.unit.Logic({ ...entry.unit.defaults, ...props });
|
|
318
|
+
const values = instance.renderVals();
|
|
319
|
+
return values && typeof values === 'object' ? { ...values } : null;
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
inspect(tid) {
|
|
326
|
+
const element = this.instances(tid)[0];
|
|
327
|
+
if (!element)
|
|
328
|
+
return null;
|
|
329
|
+
const style = getComputedStyle(element);
|
|
330
|
+
const computed = {};
|
|
331
|
+
for (const name of INSPECTED)
|
|
332
|
+
computed[name] = style.getPropertyValue(name);
|
|
333
|
+
return {
|
|
334
|
+
tid,
|
|
335
|
+
tag: element.tagName.toLowerCase(),
|
|
336
|
+
rect: this.rectOf(element),
|
|
337
|
+
computed,
|
|
338
|
+
parentDisplay: element.parentElement ? getComputedStyle(element.parentElement).display : 'block',
|
|
339
|
+
text: (element.innerText ?? '').slice(0, 200),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
editText(tid, instance = 0, options) {
|
|
343
|
+
this.text.end(true);
|
|
344
|
+
const element = this.instances(tid)[instance];
|
|
345
|
+
return element ? this.text.start(element, tid, options) : false;
|
|
346
|
+
}
|
|
347
|
+
editImportText(tid, instance, x, y, targets) {
|
|
348
|
+
this.text.end(true);
|
|
349
|
+
// A component's words are editable only when it is placed once.
|
|
350
|
+
const mounts = this.instances(tid);
|
|
351
|
+
const mount = mounts[instance];
|
|
352
|
+
return mounts.length === 1 && mount ? this.text.startImport(mount, tid, x, y, targets) : false;
|
|
353
|
+
}
|
|
354
|
+
endTextEdit(commit) {
|
|
355
|
+
this.text.end(commit);
|
|
356
|
+
}
|
|
357
|
+
formatText(format) {
|
|
358
|
+
this.text.format(format);
|
|
359
|
+
}
|
|
360
|
+
applyLink(href) {
|
|
361
|
+
this.text.applyLink(href);
|
|
362
|
+
}
|
|
363
|
+
cancelLinkEdit() {
|
|
364
|
+
this.text.cancelLinkEdit();
|
|
365
|
+
}
|
|
366
|
+
preview(tid, style) {
|
|
367
|
+
const previous = this.previews.get(tid);
|
|
368
|
+
if (previous) {
|
|
369
|
+
for (const { element, style: original } of previous) {
|
|
370
|
+
if (original === null)
|
|
371
|
+
element.removeAttribute('style');
|
|
372
|
+
else
|
|
373
|
+
element.setAttribute('style', original);
|
|
374
|
+
}
|
|
375
|
+
this.previews.delete(tid);
|
|
376
|
+
}
|
|
377
|
+
if (!style)
|
|
378
|
+
return;
|
|
379
|
+
const elements = this.instances(tid);
|
|
380
|
+
this.previews.set(tid, elements.map((element) => ({ element, style: element.getAttribute('style') })));
|
|
381
|
+
for (const element of elements)
|
|
382
|
+
for (const [name, value] of Object.entries(style))
|
|
383
|
+
element.style.setProperty(name, value);
|
|
384
|
+
}
|
|
385
|
+
/* ----------------------------- events ----------------------------- */
|
|
386
|
+
scheduled = false;
|
|
387
|
+
/**
|
|
388
|
+
* Measures on the next animation frame, or after `SIZE_FALLBACK_MS` when
|
|
389
|
+
* none comes: a frame the browser does not render gets no animation
|
|
390
|
+
* frames (Chrome pauses hidden iframes that are cross-origin to the top
|
|
391
|
+
* page, and the editor keeps a canvas frame hidden until it reports
|
|
392
|
+
* 'booted'), and the report must not wait for it to be shown.
|
|
393
|
+
*/
|
|
394
|
+
scheduleSize() {
|
|
395
|
+
if (this.scheduled)
|
|
396
|
+
return;
|
|
397
|
+
this.scheduled = true;
|
|
398
|
+
const run = () => {
|
|
399
|
+
if (!this.scheduled)
|
|
400
|
+
return;
|
|
401
|
+
this.scheduled = false;
|
|
402
|
+
cancelAnimationFrame(frame);
|
|
403
|
+
clearTimeout(timer);
|
|
404
|
+
const size = this.size();
|
|
405
|
+
if (!this.booted) {
|
|
406
|
+
this.booted = true;
|
|
407
|
+
this.lastSize = size;
|
|
408
|
+
this.report({ type: 'booted', size });
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (size.width !== this.lastSize.width || size.height !== this.lastSize.height) {
|
|
412
|
+
this.lastSize = size;
|
|
413
|
+
this.report({ type: 'resized', size });
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
const frame = requestAnimationFrame(run);
|
|
417
|
+
const timer = setTimeout(run, SIZE_FALLBACK_MS);
|
|
418
|
+
}
|
|
419
|
+
installEvents() {
|
|
420
|
+
new ResizeObserver(() => this.scheduleSize()).observe(document.documentElement);
|
|
421
|
+
window.addEventListener('error', (event) => this.addError({ source: 'runtime', message: event.message }));
|
|
422
|
+
window.addEventListener('unhandledrejection', (event) => this.addError({ source: 'runtime', message: String(event.reason) }));
|
|
423
|
+
document.addEventListener('click', (event) => {
|
|
424
|
+
const anchor = event.target?.closest?.('a[href]');
|
|
425
|
+
if (!anchor || this.text.active)
|
|
426
|
+
return;
|
|
427
|
+
const href = anchor.getAttribute('href') ?? '';
|
|
428
|
+
if (this.mode !== 'play') {
|
|
429
|
+
event.preventDefault();
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (href.startsWith('#')) {
|
|
433
|
+
event.preventDefault();
|
|
434
|
+
document.getElementById(decodeURIComponent(href.slice(1)))?.scrollIntoView({ behavior: 'smooth' });
|
|
435
|
+
}
|
|
436
|
+
else if (/^https?:\/\//i.test(href)) {
|
|
437
|
+
event.preventDefault();
|
|
438
|
+
window.open(href, '_blank', 'noopener,noreferrer');
|
|
439
|
+
}
|
|
440
|
+
else if (/\.dc\.html(#.*)?$/i.test(href)) {
|
|
441
|
+
event.preventDefault();
|
|
442
|
+
const target = href.replace(/#.*$/, '');
|
|
443
|
+
const path = target.startsWith('/') ? normalizePath(target) : normalizePath(dirOf(this.boot.path) + target);
|
|
444
|
+
this.report({ type: 'navigate', path });
|
|
445
|
+
}
|
|
446
|
+
else {
|
|
447
|
+
event.preventDefault();
|
|
448
|
+
}
|
|
449
|
+
}, true);
|
|
450
|
+
document.addEventListener('keydown', (event) => {
|
|
451
|
+
if (this.text.active) {
|
|
452
|
+
if (this.text.keydown(event))
|
|
453
|
+
event.stopPropagation();
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
if (this.mode !== 'edit')
|
|
457
|
+
return;
|
|
458
|
+
const target = event.target;
|
|
459
|
+
if (target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)))
|
|
460
|
+
return;
|
|
461
|
+
event.preventDefault();
|
|
462
|
+
this.report({ type: 'key', key: event.key, code: event.code, meta: event.metaKey || event.ctrlKey, shift: event.shiftKey, alt: event.altKey });
|
|
463
|
+
}, true);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
/* -------------------------------------------------------------------------- */
|
|
467
|
+
/* Boot */
|
|
468
|
+
/* -------------------------------------------------------------------------- */
|
|
469
|
+
/** Boot config when the page runs on its own: fetch our own source, siblings by URL. */
|
|
470
|
+
async function standaloneBoot() {
|
|
471
|
+
const source = await fetch(location.href).then((response) => response.text());
|
|
472
|
+
const path = decodeURIComponent(location.pathname.split('/').pop() ?? 'index.dc.html');
|
|
473
|
+
const base = location.href.replace(/[^/]*$/, '');
|
|
474
|
+
return {
|
|
475
|
+
path,
|
|
476
|
+
source,
|
|
477
|
+
mode: 'play',
|
|
478
|
+
// The page's own path is its base name, so children resolve next to it.
|
|
479
|
+
load: (target) => fetch(new URL(target, base)).then((r) => (r.ok ? r.text() : Promise.reject(new Error(`HTTP ${r.status}`)))),
|
|
480
|
+
report: (event) => window.parent !== window && window.parent.postMessage({ __dc: event }, '*'),
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
/** Starts the runtime: hides the raw template, waits for the DOM, then renders. */
|
|
484
|
+
export function startBoardRuntime() {
|
|
485
|
+
if (window.__dc)
|
|
486
|
+
return;
|
|
487
|
+
guardFocus();
|
|
488
|
+
const hide = document.createElement('style');
|
|
489
|
+
hide.textContent = 'x-dc{display:none!important}';
|
|
490
|
+
(document.head ?? document.documentElement).appendChild(hide);
|
|
491
|
+
const run = async () => {
|
|
492
|
+
let boot;
|
|
493
|
+
try {
|
|
494
|
+
boot = window.frameElement?.__dcBoot;
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
boot = undefined;
|
|
498
|
+
}
|
|
499
|
+
boot ??= await standaloneBoot();
|
|
500
|
+
// The browser parsed the template as DOM; it is not the board.
|
|
501
|
+
document.querySelectorAll('x-dc, script[data-dc-script]').forEach((node) => node.remove());
|
|
502
|
+
const board = new Board(boot);
|
|
503
|
+
Object.defineProperty(window, '__dc', { value: board, configurable: false, writable: false });
|
|
504
|
+
};
|
|
505
|
+
if (document.readyState === 'loading')
|
|
506
|
+
document.addEventListener('DOMContentLoaded', () => void run(), { once: true });
|
|
507
|
+
else
|
|
508
|
+
void run();
|
|
509
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps a board from taking focus it was not given.
|
|
3
|
+
*
|
|
4
|
+
* Every artboard is its own frame, and a component in one (an open modal
|
|
5
|
+
* dialog, say, whose focus scope pulls focus back when it leaves) can call
|
|
6
|
+
* `focus()` while the person is working elsewhere: on the canvas, or in a
|
|
7
|
+
* text edit on another board. That would end the edit. While this frame's
|
|
8
|
+
* document does not have focus, a component's `focus()` does nothing; the
|
|
9
|
+
* runtime's own calls (a text edit's field, made with `ownFocus`) still go
|
|
10
|
+
* through. Once the person clicks into the board (interacting with it),
|
|
11
|
+
* the document has focus and components focus as usual.
|
|
12
|
+
*/
|
|
13
|
+
/** Runs `run` with the runtime's own focus calls let through. */
|
|
14
|
+
export declare function ownFocus<T>(run: () => T): T;
|
|
15
|
+
/** Focuses an element for the runtime itself. */
|
|
16
|
+
export declare function focusElement(element: HTMLElement | SVGElement, options?: FocusOptions): void;
|
|
17
|
+
/** Installs the guard; only inside a frame. */
|
|
18
|
+
export declare function guardFocus(): void;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps a board from taking focus it was not given.
|
|
3
|
+
*
|
|
4
|
+
* Every artboard is its own frame, and a component in one (an open modal
|
|
5
|
+
* dialog, say, whose focus scope pulls focus back when it leaves) can call
|
|
6
|
+
* `focus()` while the person is working elsewhere: on the canvas, or in a
|
|
7
|
+
* text edit on another board. That would end the edit. While this frame's
|
|
8
|
+
* document does not have focus, a component's `focus()` does nothing; the
|
|
9
|
+
* runtime's own calls (a text edit's field, made with `ownFocus`) still go
|
|
10
|
+
* through. Once the person clicks into the board (interacting with it),
|
|
11
|
+
* the document has focus and components focus as usual.
|
|
12
|
+
*/
|
|
13
|
+
let own = 0;
|
|
14
|
+
/** Runs `run` with the runtime's own focus calls let through. */
|
|
15
|
+
export function ownFocus(run) {
|
|
16
|
+
own += 1;
|
|
17
|
+
try {
|
|
18
|
+
return run();
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
own -= 1;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Focuses an element for the runtime itself. */
|
|
25
|
+
export function focusElement(element, options) {
|
|
26
|
+
ownFocus(() => element.focus(options));
|
|
27
|
+
}
|
|
28
|
+
/** Installs the guard; only inside a frame. */
|
|
29
|
+
export function guardFocus() {
|
|
30
|
+
if (window.parent === window)
|
|
31
|
+
return;
|
|
32
|
+
for (const proto of [HTMLElement.prototype, SVGElement.prototype]) {
|
|
33
|
+
const focus = proto.focus;
|
|
34
|
+
proto.focus = function guardedFocus(options) {
|
|
35
|
+
if (own === 0 && !document.hasFocus())
|
|
36
|
+
return;
|
|
37
|
+
focus.call(this, options);
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry of `support.js`, the board runtime loaded by every artboard.
|
|
3
|
+
*
|
|
4
|
+
* Besides starting the board, it shares its React as `window.React` and
|
|
5
|
+
* `window.ReactDOM`. A design-system bundle loaded after `support.js`
|
|
6
|
+
* (`<script src="./ds/<folder>/components/bundle.js">`) builds its components
|
|
7
|
+
* with that same React, so `<x-import>` can render them: two copies of React
|
|
8
|
+
* in one tree break hooks.
|
|
9
|
+
*/
|
|
10
|
+
declare global {
|
|
11
|
+
interface Window {
|
|
12
|
+
React?: unknown;
|
|
13
|
+
ReactDOM?: unknown;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry of `support.js`, the board runtime loaded by every artboard.
|
|
3
|
+
*
|
|
4
|
+
* Besides starting the board, it shares its React as `window.React` and
|
|
5
|
+
* `window.ReactDOM`. A design-system bundle loaded after `support.js`
|
|
6
|
+
* (`<script src="./ds/<folder>/components/bundle.js">`) builds its components
|
|
7
|
+
* with that same React, so `<x-import>` can render them: two copies of React
|
|
8
|
+
* in one tree break hooks.
|
|
9
|
+
*/
|
|
10
|
+
import * as React from 'react';
|
|
11
|
+
import * as ReactDOM from 'react-dom';
|
|
12
|
+
import { startBoardRuntime } from "./board.js";
|
|
13
|
+
window.React ??= React;
|
|
14
|
+
window.ReactDOM ??= ReactDOM;
|
|
15
|
+
startBoardRuntime();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `DCLogic` base class and loading of an artboard's logic script.
|
|
3
|
+
*
|
|
4
|
+
* Authors write `class Component extends DCLogic { renderVals() { … } }` as
|
|
5
|
+
* plain classic JavaScript. They get a React class component minus
|
|
6
|
+
* `render()`: `this.props`, `state` / `setState` / `forceUpdate`, the
|
|
7
|
+
* lifecycle methods. The runtime supplies `render()`, which calls
|
|
8
|
+
* `renderVals()` and renders the template with the result.
|
|
9
|
+
*/
|
|
10
|
+
import { Component as ReactComponent, type ReactNode } from 'react';
|
|
11
|
+
/** Renders the template with the values a logic instance returned. */
|
|
12
|
+
export type TemplateRenderer = (values: Record<string, unknown>) => ReactNode;
|
|
13
|
+
/** Instance shape of a logic class. */
|
|
14
|
+
export interface DCLogicInstance extends ReactComponent<Record<string, unknown>, Record<string, unknown>> {
|
|
15
|
+
renderVals(): Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
/** Constructor of a logic class. */
|
|
18
|
+
export type DCLogicClass = new (props: Record<string, unknown>) => DCLogicInstance;
|
|
19
|
+
/**
|
|
20
|
+
* Creates the `DCLogic` base for one artboard. The renderer is read on every
|
|
21
|
+
* render, so a template change shows without remounting (state survives).
|
|
22
|
+
*/
|
|
23
|
+
export declare function createLogicBase(getRenderer: () => TemplateRenderer): DCLogicClass;
|
|
24
|
+
/**
|
|
25
|
+
* Evaluates a logic script and returns its `Component` class.
|
|
26
|
+
*
|
|
27
|
+
* The script is classic JavaScript with no imports; it sees `DCLogic` and
|
|
28
|
+
* `React` as globals. Throws with a readable message when the script fails
|
|
29
|
+
* or does not define `class Component extends DCLogic`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function evaluateLogic(body: string, base: DCLogicClass, react: unknown, label: string): DCLogicClass;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `DCLogic` base class and loading of an artboard's logic script.
|
|
3
|
+
*
|
|
4
|
+
* Authors write `class Component extends DCLogic { renderVals() { … } }` as
|
|
5
|
+
* plain classic JavaScript. They get a React class component minus
|
|
6
|
+
* `render()`: `this.props`, `state` / `setState` / `forceUpdate`, the
|
|
7
|
+
* lifecycle methods. The runtime supplies `render()`, which calls
|
|
8
|
+
* `renderVals()` and renders the template with the result.
|
|
9
|
+
*/
|
|
10
|
+
import { Component as ReactComponent, createRef } from 'react';
|
|
11
|
+
/**
|
|
12
|
+
* Creates the `DCLogic` base for one artboard. The renderer is read on every
|
|
13
|
+
* render, so a template change shows without remounting (state survives).
|
|
14
|
+
*/
|
|
15
|
+
export function createLogicBase(getRenderer) {
|
|
16
|
+
class DCLogic extends ReactComponent {
|
|
17
|
+
state = {};
|
|
18
|
+
/** Returns the template's inputs. Override in the artboard's class. */
|
|
19
|
+
renderVals() {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
/** Convenience for refs returned from `renderVals()`. */
|
|
23
|
+
createRef = createRef;
|
|
24
|
+
render() {
|
|
25
|
+
const values = this.renderVals();
|
|
26
|
+
return getRenderer()(values && typeof values === 'object' ? values : {});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return DCLogic;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Evaluates a logic script and returns its `Component` class.
|
|
33
|
+
*
|
|
34
|
+
* The script is classic JavaScript with no imports; it sees `DCLogic` and
|
|
35
|
+
* `React` as globals. Throws with a readable message when the script fails
|
|
36
|
+
* or does not define `class Component extends DCLogic`.
|
|
37
|
+
*/
|
|
38
|
+
export function evaluateLogic(body, base, react, label) {
|
|
39
|
+
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
40
|
+
const factory = new Function('DCLogic', 'React', `"use strict";\n${body}\n;return typeof Component === "function" ? Component : null;\n//# sourceURL=${label.replace(/[^\w./-]/g, '_')}`);
|
|
41
|
+
const Component = factory(base, react);
|
|
42
|
+
if (!Component)
|
|
43
|
+
throw new Error('The logic script must define `class Component extends DCLogic`.');
|
|
44
|
+
if (!(Component.prototype instanceof base))
|
|
45
|
+
throw new Error('`Component` must extend DCLogic.');
|
|
46
|
+
return Component;
|
|
47
|
+
}
|