@open-artifact/dc 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The contract between the editor and the board runtime (`support.js`)
3
+ * running inside each artboard iframe.
4
+ *
5
+ * The editor creates the iframe (`sandbox="allow-scripts allow-same-origin"`,
6
+ * `srcdoc` = the artboard source with `./support.js` pointing at the runtime)
7
+ * and, before setting `srcdoc`, attaches a {@link BoardBoot} to the iframe
8
+ * element as `iframe.__dcBoot`. The runtime reads it through
9
+ * `window.frameElement`, reports through its callback, and exposes a
10
+ * {@link BoardApi} as `window.__dc` for the editor to call directly.
11
+ *
12
+ * Opened on its own (an exported file, or the server serving a `.dc.html`
13
+ * page), there is no boot object: the runtime fetches its own source and
14
+ * runs as a plain page.
15
+ */
16
+ /** How the board behaves. */
17
+ export type BoardMode =
18
+ /** On the canvas: links do nothing, the editor owns the pointer. */
19
+ 'edit'
20
+ /** Clicking through: handlers and links work. */
21
+ | 'play'
22
+ /** Rendered for export or thumbnail: no interaction. */
23
+ | 'static';
24
+ /** Everything the runtime needs from the editor. */
25
+ export interface BoardBoot {
26
+ /** Project-relative path of this artboard (`sub/Main.dc.html`). */
27
+ path: string;
28
+ /** The full `.dc.html` source. */
29
+ source: string;
30
+ mode: BoardMode;
31
+ /** Tweak overrides on top of the `data-props` defaults. */
32
+ props?: Record<string, unknown>;
33
+ /** Loads another artboard's source, for `<dc-import>`. */
34
+ load(path: string): Promise<string>;
35
+ /** Receives runtime events. */
36
+ report(event: BoardEvent): void;
37
+ }
38
+ /** A problem the board shows instead of (or over) its content. */
39
+ export interface BoardError {
40
+ /** Where it came from. */
41
+ source: 'script' | 'render' | 'import' | 'template' | 'props' | 'runtime';
42
+ message: string;
43
+ }
44
+ /** Events the runtime reports. */
45
+ export type BoardEvent =
46
+ /** First render finished. */
47
+ {
48
+ type: 'booted';
49
+ size: BoardSize;
50
+ }
51
+ /** The content size changed (throttled). */
52
+ | {
53
+ type: 'resized';
54
+ size: BoardSize;
55
+ }
56
+ /** The set of current errors changed. */
57
+ | {
58
+ type: 'errors';
59
+ errors: BoardError[];
60
+ }
61
+ /** A link to another artboard was followed in Play. */
62
+ | {
63
+ type: 'navigate';
64
+ path: string;
65
+ }
66
+ /**
67
+ * In-place text editing finished with a change: the edited element's
68
+ * `html` (unsanitized) and its `text`. A `target` says where text a
69
+ * hole showed is written instead of the template. `link`: a link was just
70
+ * set, the how-manyth `<a>` of `html` it is (the editor selects it).
71
+ */
72
+ | {
73
+ type: 'text-commit';
74
+ tid: number;
75
+ html: string;
76
+ text: string;
77
+ target?: TextEditTarget;
78
+ link?: number;
79
+ }
80
+ /** In-place text editing finished without a change. */
81
+ | {
82
+ type: 'text-cancel';
83
+ tid: number;
84
+ }
85
+ /** The formatting at the caret while editing text (`active` false when editing stopped). */
86
+ | {
87
+ type: 'text-state';
88
+ active: false;
89
+ } | {
90
+ type: 'text-state';
91
+ active: true;
92
+ tid: number;
93
+ plain: boolean;
94
+ formats: TextFormats;
95
+ }
96
+ /** The text being edited lost focus (the editor decides whether that ends the edit). */
97
+ | {
98
+ type: 'text-blur';
99
+ }
100
+ /**
101
+ * The link at the selection is to be set: its current `href` (`''` for
102
+ * none), whether the selection is empty, and where it is (board px).
103
+ * Answer with {@link BoardApi.applyLink} or {@link BoardApi.cancelLinkEdit}.
104
+ * `host`: the edited element is itself the link; its `href` attribute is
105
+ * the editor's to set.
106
+ */
107
+ | {
108
+ type: 'link-edit';
109
+ href: string;
110
+ collapsed: boolean;
111
+ rect: BoardRect;
112
+ host?: boolean;
113
+ }
114
+ /** A key the editor handles (undo, delete…) was pressed inside the frame. */
115
+ | {
116
+ type: 'key';
117
+ key: string;
118
+ code?: string;
119
+ meta: boolean;
120
+ shift: boolean;
121
+ alt: boolean;
122
+ };
123
+ /** Formatting toggles in-place text editing applies to the selection. */
124
+ export type TextFormat = 'bold' | 'italic' | 'underline' | 'ul' | 'ol' | 'link';
125
+ /** Which formats the selection has. */
126
+ export type TextFormats = Record<TextFormat, boolean>;
127
+ /** Text a hole shows, written where the value comes from. */
128
+ export type TextEditTarget =
129
+ /** A text prop: its value. */
130
+ {
131
+ kind: 'prop';
132
+ prop: string;
133
+ value: string;
134
+ }
135
+ /** A string literal of the logic script (offsets into the script body). */
136
+ | {
137
+ kind: 'script';
138
+ start: number;
139
+ end: number;
140
+ quote: string;
141
+ value: string;
142
+ }
143
+ /** Words of a component instance: between its tags (`__text`) or an attribute (`@name`). */
144
+ | {
145
+ kind: 'import';
146
+ key: string;
147
+ words: string;
148
+ };
149
+ /** How {@link BoardApi.editText} starts. */
150
+ export interface TextEditOptions {
151
+ /**
152
+ * The element's content as written in the template, when it has holes:
153
+ * edited as written unless a prop or a script literal supplies the text.
154
+ */
155
+ seed?: string;
156
+ /** Current values of the text props (a seed of one whole `{{prop}}` edits the prop). */
157
+ props?: Record<string, string>;
158
+ /** The logic script's string literals (a hole showing exactly one of them edits it). */
159
+ literals?: {
160
+ start: number;
161
+ end: number;
162
+ quote: string;
163
+ value: string;
164
+ }[];
165
+ /**
166
+ * `all` selects every word (default); `end` puts the caret after the last
167
+ * one; a point (board px) puts it at the words there.
168
+ */
169
+ caret?: 'all' | 'end' | {
170
+ x: number;
171
+ y: number;
172
+ };
173
+ }
174
+ /** Words of a component instance the editor allows retyping (see `importTextTargets`). */
175
+ export interface ImportTextTargetSpec {
176
+ words: string;
177
+ key: string;
178
+ number?: boolean;
179
+ }
180
+ /** Size of the rendered content in CSS pixels. */
181
+ export interface BoardSize {
182
+ width: number;
183
+ height: number;
184
+ }
185
+ /** A rectangle in the board's coordinate space (CSS pixels from its top-left). */
186
+ export interface BoardRect {
187
+ x: number;
188
+ y: number;
189
+ width: number;
190
+ height: number;
191
+ }
192
+ /** What a pick at a point found. */
193
+ export interface PickResult {
194
+ tid: number;
195
+ /** Rect of the rendered instance that was hit. */
196
+ rect: BoardRect;
197
+ /** Index of that instance among the template node's rendered instances. */
198
+ instance: number;
199
+ }
200
+ /** Computed values the properties panel shows for an element. */
201
+ export interface ElementInspection {
202
+ tid: number;
203
+ tag: string;
204
+ rect: BoardRect;
205
+ /** Selected computed style properties (kebab case). */
206
+ computed: Record<string, string>;
207
+ /** The parent's display (to offer flex/grid child controls). */
208
+ parentDisplay: string;
209
+ /** Text of the first instance (for the layers list and labels). */
210
+ text: string;
211
+ }
212
+ /** What the runtime exposes as `window.__dc`. */
213
+ export interface BoardApi {
214
+ /** Replace the source (template, script and props are re-read). */
215
+ setSource(source: string): void;
216
+ /** Other artboards changed: imported children with these paths reload. */
217
+ invalidate(paths: readonly string[]): void;
218
+ /** Replace the tweak overrides. */
219
+ setProps(props: Record<string, unknown>): void;
220
+ setMode(mode: BoardMode): void;
221
+ /** The template node under a point, honoring import boundaries; `null` on empty space. */
222
+ pick(x: number, y: number): PickResult | null;
223
+ /** Every element under a point, innermost first (for deep select). */
224
+ pickAll(x: number, y: number): PickResult[];
225
+ /** Rects of every rendered instance of each template node. */
226
+ rects(tids: readonly number[]): Record<number, BoardRect[]>;
227
+ inspect(tid: number): ElementInspection | null;
228
+ /**
229
+ * The render values a loaded `<dc-import name>` component computes for
230
+ * these props (its logic's `renderVals()`); `null` when it is not loaded
231
+ * or its logic throws.
232
+ */
233
+ importValues(name: string, props: Record<string, unknown>): Record<string, unknown> | null;
234
+ /** Content size. */
235
+ size(): BoardSize;
236
+ /** Current errors. */
237
+ errors(): BoardError[];
238
+ /** Starts in-place (rich) text editing of an instance; false when it cannot. */
239
+ editText(tid: number, instance?: number, options?: TextEditOptions): boolean;
240
+ /**
241
+ * Edits words a component instance (`<x-import>` node `tid`) draws at
242
+ * `x, y` (board px) in place, when they are one of `targets`; false
243
+ * when there are none there. The edit reports a `text-commit` with an
244
+ * `import` target.
245
+ */
246
+ editImportText(tid: number, instance: number, x: number, y: number, targets: ImportTextTargetSpec[]): boolean;
247
+ /** Ends in-place text editing (`commit` false cancels). */
248
+ endTextEdit(commit: boolean): void;
249
+ /** Toggles a format on the selection of the text being edited (`link` asks for an address: `link-edit`). */
250
+ formatText(format: TextFormat): void;
251
+ /** Answers `link-edit`: links the saved selection to `href` (`''` or `null` unlinks). */
252
+ applyLink(href: string | null): void;
253
+ /** Answers `link-edit` without a change. */
254
+ cancelLinkEdit(): void;
255
+ /** Temporarily applies inline styles to a node's instances (drag previews); `null` restores. */
256
+ preview(tid: number, style: Record<string, string> | null): void;
257
+ }
258
+ /** Window globals the runtime and editor share. */
259
+ declare global {
260
+ interface Window {
261
+ __dc?: BoardApi;
262
+ }
263
+ interface HTMLIFrameElement {
264
+ __dcBoot?: BoardBoot;
265
+ }
266
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The contract between the editor and the board runtime (`support.js`)
3
+ * running inside each artboard iframe.
4
+ *
5
+ * The editor creates the iframe (`sandbox="allow-scripts allow-same-origin"`,
6
+ * `srcdoc` = the artboard source with `./support.js` pointing at the runtime)
7
+ * and, before setting `srcdoc`, attaches a {@link BoardBoot} to the iframe
8
+ * element as `iframe.__dcBoot`. The runtime reads it through
9
+ * `window.frameElement`, reports through its callback, and exposes a
10
+ * {@link BoardApi} as `window.__dc` for the editor to call directly.
11
+ *
12
+ * Opened on its own (an exported file, or the server serving a `.dc.html`
13
+ * page), there is no boot object: the runtime fetches its own source and
14
+ * runs as a plain page.
15
+ */
16
+ export {};
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Renders a template tree with React.
3
+ *
4
+ * The template is walked as written; nothing is compiled to code, so a
5
+ * template can never run anything the logic class did not return. Each DOM
6
+ * element gets `data-dc-tpl="<tid>"` so the editor can map what the viewer
7
+ * clicks back to the template node.
8
+ */
9
+ import { type ComponentType, type ReactNode } from 'react';
10
+ import type { TemplateModel } from './template.ts';
11
+ /** Attribute naming the template node a DOM element came from. */
12
+ export declare const TID_ATTRIBUTE = "data-dc-tpl";
13
+ /** Attribute marking a `<dc-import>` / `<x-import>` boundary: clicks inside select the import. */
14
+ export declare const BOUNDARY_ATTRIBUTE = "data-dc-boundary";
15
+ /** What the renderer needs from its host. */
16
+ export interface RenderHost {
17
+ /**
18
+ * The component for `<dc-import name>`; `undefined` while it loads,
19
+ * `null` when it failed (the error is reported by the host).
20
+ */
21
+ importComponent(name: string): ComponentType<Record<string, unknown>> | null | undefined;
22
+ /** Resolves `<x-import component-from-global-scope="Ns.Comp">`. */
23
+ globalComponent(path: string): ComponentType<Record<string, unknown>> | null;
24
+ /** Where `<helmet>` content goes; `null` drops it. */
25
+ head: Element | null;
26
+ /** Stamp {@link TID_ATTRIBUTE} on elements (off inside imported children). */
27
+ stamp: boolean;
28
+ /** Values are still arriving: unresolved loops and branches use their `hint-*` placeholders. */
29
+ streaming: boolean;
30
+ }
31
+ /** React prop name of an attribute. */
32
+ export declare function reactAttributeName(name: string): string;
33
+ /** Renders a template against render values. */
34
+ export declare function renderTemplate(model: TemplateModel, values: Record<string, unknown>, host: RenderHost): ReactNode;
package/src/render.js ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Renders a template tree with React.
3
+ *
4
+ * The template is walked as written; nothing is compiled to code, so a
5
+ * template can never run anything the logic class did not return. Each DOM
6
+ * element gets `data-dc-tpl="<tid>"` so the editor can map what the viewer
7
+ * clicks back to the template node.
8
+ */
9
+ import { Fragment, createElement, } from 'react';
10
+ import { createPortal } from 'react-dom';
11
+ import { VOID_ELEMENTS, attributeValue } from "./html.js";
12
+ import { evaluateHole, interpolate, wholeHole } from "./holes.js";
13
+ import { toReactStyle } from "./style.js";
14
+ /** Attribute naming the template node a DOM element came from. */
15
+ export const TID_ATTRIBUTE = 'data-dc-tpl';
16
+ /** Attribute marking a `<dc-import>` / `<x-import>` boundary: clicks inside select the import. */
17
+ export const BOUNDARY_ATTRIBUTE = 'data-dc-boundary';
18
+ /** HTML attribute names React spells differently. */
19
+ const ATTRIBUTE_NAMES = {
20
+ class: 'className',
21
+ for: 'htmlFor',
22
+ tabindex: 'tabIndex',
23
+ readonly: 'readOnly',
24
+ maxlength: 'maxLength',
25
+ minlength: 'minLength',
26
+ colspan: 'colSpan',
27
+ rowspan: 'rowSpan',
28
+ contenteditable: 'contentEditable',
29
+ crossorigin: 'crossOrigin',
30
+ srcset: 'srcSet',
31
+ autoplay: 'autoPlay',
32
+ autofocus: 'autoFocus',
33
+ autocomplete: 'autoComplete',
34
+ novalidate: 'noValidate',
35
+ spellcheck: 'spellCheck',
36
+ enterkeyhint: 'enterKeyHint',
37
+ inputmode: 'inputMode',
38
+ playsinline: 'playsInline',
39
+ referrerpolicy: 'referrerPolicy',
40
+ datetime: 'dateTime',
41
+ usemap: 'useMap',
42
+ frameborder: 'frameBorder',
43
+ 'accept-charset': 'acceptCharset',
44
+ 'http-equiv': 'httpEquiv',
45
+ 'xlink:href': 'xlinkHref',
46
+ 'xml:space': 'xmlSpace',
47
+ };
48
+ /** SVG tags whose camel case matters. */
49
+ const SVG_CAMEL_TAGS = new Map([
50
+ 'clipPath', 'foreignObject', 'linearGradient', 'radialGradient', 'textPath', 'feBlend', 'feColorMatrix',
51
+ 'feComposite', 'feDropShadow', 'feFlood', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feOffset',
52
+ 'feTurbulence', 'feDisplacementMap', 'animateTransform', 'animateMotion',
53
+ ].map((name) => [name.toLowerCase(), name]));
54
+ /** Parents in which whitespace text is not allowed. */
55
+ const NO_TEXT_PARENTS = new Set(['table', 'thead', 'tbody', 'tfoot', 'tr', 'colgroup', 'select', 'helmet', 'svg', 'g', 'defs']);
56
+ /** Template-only attributes that never reach the DOM. */
57
+ const CONTROL_ATTRIBUTES = new Set(['hint-placeholder-count', 'hint-placeholder-val', 'hint-size']);
58
+ /** React prop name of an attribute. */
59
+ export function reactAttributeName(name) {
60
+ const lower = name.toLowerCase();
61
+ if (ATTRIBUTE_NAMES[lower])
62
+ return ATTRIBUTE_NAMES[lower];
63
+ if (lower.startsWith('data-') || lower.startsWith('aria-'))
64
+ return lower;
65
+ if (name.includes('-'))
66
+ return name.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
67
+ return name;
68
+ }
69
+ /** The value of an attribute for React: literal string, raw hole value, or interpolated string. */
70
+ function attributeProp(attr, scopes) {
71
+ if (attr.value === null)
72
+ return true;
73
+ const hole = wholeHole(attr.value);
74
+ if (hole)
75
+ return evaluateHole(hole, scopes);
76
+ return interpolate(attr.value, scopes);
77
+ }
78
+ /** Builds the React props of a plain element. */
79
+ function elementProps(element, tid, scopes, host) {
80
+ const props = {};
81
+ const hasChange = element.attrs.some((attr) => /^on(change|input)$/i.test(attr.name));
82
+ for (const attr of element.attrs) {
83
+ if (CONTROL_ATTRIBUTES.has(attr.name.toLowerCase()))
84
+ continue;
85
+ const name = reactAttributeName(attr.name);
86
+ let value = attributeProp(attr, scopes);
87
+ // Event handlers must be functions; inline handler strings never run.
88
+ if (/^on[A-Za-z]/.test(name)) {
89
+ if (typeof value !== 'function')
90
+ continue;
91
+ props[name.length > 2 ? `on${name[2].toUpperCase()}${name.slice(3)}` : name] = value;
92
+ continue;
93
+ }
94
+ if (name === 'style') {
95
+ if (typeof value === 'string')
96
+ value = toReactStyle(value);
97
+ else if (!value || typeof value !== 'object')
98
+ continue;
99
+ }
100
+ // Uncontrolled form fields unless the logic class handles changes.
101
+ if ((name === 'value' || name === 'checked') && !hasChange && ['input', 'textarea', 'select'].includes(element.tag)) {
102
+ props[name === 'value' ? 'defaultValue' : 'defaultChecked'] = value;
103
+ continue;
104
+ }
105
+ if (value === undefined || value === null || value === false) {
106
+ if (value === false && (name.startsWith('aria-') || name.startsWith('data-')))
107
+ props[name] = 'false';
108
+ continue;
109
+ }
110
+ props[name] = value;
111
+ }
112
+ if (host.stamp)
113
+ props[TID_ATTRIBUTE] = String(tid);
114
+ return props;
115
+ }
116
+ /** Converts a `hint-size="W,H"` to a placeholder style. */
117
+ function hintSizeStyle(hint) {
118
+ const [width, height] = (hint ?? '').split(',').map((part) => part.trim());
119
+ return { width: width || '100%', height: height || '80px' };
120
+ }
121
+ /** Props passed to an imported component: every attribute but `name` and hints, kebab → camel. */
122
+ function importProps(element, scopes, skip) {
123
+ const props = {};
124
+ for (const attr of element.attrs) {
125
+ const lower = attr.name.toLowerCase();
126
+ if (skip.includes(lower) || CONTROL_ATTRIBUTES.has(lower))
127
+ continue;
128
+ const key = attr.name.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
129
+ props[key] = attributeProp(attr, scopes);
130
+ }
131
+ return props;
132
+ }
133
+ /** Renders a template against render values. */
134
+ export function renderTemplate(model, values, host) {
135
+ const helmet = [];
136
+ const body = renderNodes(model, model.nodes, null, [values], host, helmet);
137
+ const head = host.head && helmet.length ? createPortal(createElement(Fragment, null, ...helmet), host.head) : null;
138
+ return createElement(Fragment, null, head, ...body);
139
+ }
140
+ /** Renders a list of sibling nodes. */
141
+ function renderNodes(model, nodes, parent, scopes, host, helmet) {
142
+ const out = [];
143
+ nodes.forEach((node, index) => {
144
+ if (node.type === 'comment')
145
+ return;
146
+ if (node.type === 'text') {
147
+ if (parent && (parent.tag === 'style' || parent.tag === 'script')) {
148
+ out.push(node.value);
149
+ return;
150
+ }
151
+ if (!/\S/.test(node.value)) {
152
+ // Formatting whitespace: one space between inline siblings, nothing at the edges.
153
+ const atEdge = index === 0 || index === nodes.length - 1;
154
+ if (!atEdge && !(parent && NO_TEXT_PARENTS.has(parent.tag)) && node.value.length > 0)
155
+ out.push(' ');
156
+ return;
157
+ }
158
+ out.push(interpolate(node.value, scopes));
159
+ return;
160
+ }
161
+ out.push(renderElement(model, node, scopes, host, helmet, index));
162
+ });
163
+ return out;
164
+ }
165
+ /** Renders one element (or structure tag). */
166
+ function renderElement(model, element, scopes, host, helmet, key) {
167
+ const tid = model.tidOf.get(element) ?? -1;
168
+ switch (element.tag) {
169
+ case 'helmet': {
170
+ helmet.push(...renderNodes(model, element.children, element, scopes, host, helmet).map((child, i) => withKey(child, `h${tid}-${i}`)));
171
+ return null;
172
+ }
173
+ case 'script':
174
+ // Scripts in the template never run; logic lives in the data-dc-script block.
175
+ return null;
176
+ case 'sc-for': {
177
+ const list = evaluateList(element, scopes);
178
+ const as = attributeValue(element, 'as') || 'item';
179
+ let items = Array.isArray(list) ? list : null;
180
+ if (!items && (host.streaming || list === undefined)) {
181
+ const count = Number(attributeValue(element, 'hint-placeholder-count') ?? 0);
182
+ items = Number.isFinite(count) && count > 0 ? Array.from({ length: Math.min(count, 50) }, () => undefined) : [];
183
+ }
184
+ return createElement(Fragment, { key }, ...(items ?? []).map((item, $index) => createElement(Fragment, { key: $index }, ...renderNodes(model, element.children, element, [{ [as]: item, $index }, ...scopes], host, helmet))));
185
+ }
186
+ case 'sc-if': {
187
+ const attr = element.attrs.find((a) => a.name.toLowerCase() === 'value');
188
+ let value = attr ? attributeProp(attr, scopes) : undefined;
189
+ if (value === undefined && host.streaming) {
190
+ const hint = element.attrs.find((a) => a.name.toLowerCase() === 'hint-placeholder-val');
191
+ value = hint ? attributeProp(hint, scopes) : false;
192
+ }
193
+ if (!value)
194
+ return null;
195
+ return createElement(Fragment, { key }, ...renderNodes(model, element.children, element, scopes, host, helmet));
196
+ }
197
+ case 'dc-import': {
198
+ const name = attributeValue(element, 'name') ?? '';
199
+ const Component = host.importComponent(name);
200
+ const boundary = { key, style: { display: 'contents' }, [BOUNDARY_ATTRIBUTE]: 'dc-import', ...(host.stamp ? { [TID_ATTRIBUTE]: String(tid) } : {}) };
201
+ if (!Component) {
202
+ const placeholder = createElement('div', {
203
+ style: { ...hintSizeStyle(attributeValue(element, 'hint-size')), background: 'rgba(127,127,127,0.08)', borderRadius: 4 },
204
+ 'data-dc-placeholder': name,
205
+ });
206
+ return createElement('div', boundary, placeholder);
207
+ }
208
+ return createElement('div', boundary, createElement(Component, importProps(element, scopes, ['name'])));
209
+ }
210
+ case 'x-import': {
211
+ const path = attributeValue(element, 'component-from-global-scope') ?? '';
212
+ const Component = host.globalComponent(path);
213
+ const boundary = { key, style: { display: 'contents' }, [BOUNDARY_ATTRIBUTE]: 'x-import', ...(host.stamp ? { [TID_ATTRIBUTE]: String(tid) } : {}) };
214
+ if (!Component)
215
+ return createElement('div', boundary);
216
+ // Content between the tags is the component's children (`<x-import …>Save</x-import>`).
217
+ const children = renderNodes(model, element.children, element, scopes, host, helmet);
218
+ return createElement('div', boundary, createElement(Component, importProps(element, scopes, ['component-from-global-scope']), ...children));
219
+ }
220
+ default:
221
+ break;
222
+ }
223
+ const props = elementProps(element, tid, scopes, host);
224
+ props.key = key;
225
+ const type = SVG_CAMEL_TAGS.get(element.tag) ?? (element.rawTag.includes('-') ? element.rawTag : element.tag);
226
+ if (VOID_ELEMENTS.has(element.tag))
227
+ return createElement(type, props);
228
+ if (element.tag === 'textarea') {
229
+ const text = element.children.map((child) => (child.type === 'text' ? interpolate(child.value, scopes) : '')).join('');
230
+ if (!('value' in props) && !('defaultValue' in props))
231
+ props.defaultValue = text;
232
+ return createElement(type, props);
233
+ }
234
+ if (element.tag === 'style') {
235
+ // One string child so React does not split the stylesheet.
236
+ const css = element.children.map((child) => (child.type === 'text' ? child.value : '')).join('');
237
+ return createElement(type, props, css);
238
+ }
239
+ return createElement(type, props, ...renderNodes(model, element.children, element, scopes, host, helmet));
240
+ }
241
+ /** Evaluates `<sc-for list>`. */
242
+ function evaluateList(element, scopes) {
243
+ const raw = attributeValue(element, 'list');
244
+ if (raw === undefined)
245
+ return undefined;
246
+ const hole = wholeHole(raw);
247
+ // A list must be one whole hole; anything else renders nothing (check reports it).
248
+ return hole ? evaluateHole(hole, scopes) : undefined;
249
+ }
250
+ /** Gives a rendered child a key (helmet children are collected across the tree). */
251
+ function withKey(node, key) {
252
+ if (node && typeof node === 'object' && 'type' in node) {
253
+ return createElement(Fragment, { key }, node);
254
+ }
255
+ return node;
256
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Rich text in templates in-place text editing:
3
+ *
4
+ * - which elements are edited in place ({@link isRichTextElement}): their
5
+ * content is words and inline formatting (`<b>`, `<i>`, `<a>`, `<br>`…);
6
+ * - cleaning the HTML an edit produced before it is written back
7
+ * ({@link sanitizeTextHtml});
8
+ * - the string literals of a logic script ({@link scriptLiterals}), so text
9
+ * a script supplies can be edited where it is written.
10
+ */
11
+ import { type HtmlElement } from './html.ts';
12
+ /** Inline formatting an editable text may hold. */
13
+ export declare const INLINE_TEXT_TAGS: ReadonlySet<string>;
14
+ /**
15
+ * True when the element's content is edited in place as rich text: words
16
+ * and inline formatting only, written in the template (holes allowed: they
17
+ * are edited as written).
18
+ */
19
+ export declare function isRichTextElement(element: HtmlElement): boolean;
20
+ /** True for an SVG text element holding words and nothing else: edited as plain text. */
21
+ export declare function isSvgText(element: HtmlElement): boolean;
22
+ /** True when text inside the element has `{{ … }}` holes. */
23
+ export declare function hasTextHoles(element: HtmlElement): boolean;
24
+ /**
25
+ * Cleans HTML an in-place edit produced (`innerHTML` of the edited
26
+ * element) for writing into the template: comments, scripts, frames, form
27
+ * controls, event handlers, code-running addresses and the editor's own
28
+ * attributes go; the words and their formatting stay. A trailing `<br>`
29
+ * the browser keeps for the caret goes too.
30
+ */
31
+ export declare function sanitizeTextHtml(html: string): string;
32
+ /** Block content in an edit's HTML (a list, a paragraph): a `<p>` holding it must become a `<div>`. */
33
+ export declare function hasBlockContent(html: string): boolean;
34
+ /** A string literal in a script: `[start, end)` covers the quotes. */
35
+ export interface ScriptLiteral {
36
+ start: number;
37
+ end: number;
38
+ /** The quote character: `'`, `"` or `` ` `` (a template without `${}`). */
39
+ quote: string;
40
+ /** The decoded value. */
41
+ value: string;
42
+ }
43
+ /**
44
+ * The string literals of a script, in order. Comments and regular
45
+ * expressions are skipped (a `/` after a value is division); template
46
+ * literals with `${}` are not literals.
47
+ */
48
+ export declare function scriptLiterals(js: string): ScriptLiteral[];
49
+ /** Writes text as a JS string literal with the given quote. */
50
+ export declare function quoteScriptString(text: string, quote: string): string;
51
+ /** A source range to wrap: `[start, end)` of the template text. */
52
+ export interface TextRun {
53
+ start: number;
54
+ end: number;
55
+ }
56
+ /**
57
+ * The runs of loose words in an element that mixes words with other layout
58
+ * each run of text — with the inline formatting
59
+ * around it unless the element lays its children out as items (`inline`
60
+ * false) — trimmed of the spaces at its ends. `<sc-if>` / `<sc-for>`
61
+ * children are looked into. `text` is the template text.
62
+ */
63
+ export declare function looseTextRuns(element: HtmlElement, text: string, inline: boolean): TextRun[];
64
+ /** Words of an `<x-import>` that can be retyped where the component draws them. */
65
+ export interface ImportTextTarget {
66
+ /** The words as drawn (spaces squashed). */
67
+ words: string;
68
+ /** Where they are written: `__text` (between its tags) or `@name` (an attribute). */
69
+ key: string;
70
+ /** The attribute holds a number (`{{ 3 }}`): the retyped words must be one. */
71
+ number?: boolean;
72
+ }
73
+ /** Spaces squashed and trimmed, as text is drawn. */
74
+ export declare const squashSpaces: (text: string) => string;
75
+ /** Longest words taken as an instance's own. */
76
+ export declare const MAX_IMPORT_WORDS = 2000;
77
+ /**
78
+ * The words of an `<x-import>` instance that are written on it — between
79
+ * its tags or in an attribute — and appear as-is where the component draws
80
+ * them. Words written twice, or that a hole
81
+ * could also be supplying (`known`: the script's strings and the props'
82
+ * values), are left out; so is everything when an attribute mixes words
83
+ * with holes.
84
+ */
85
+ export declare function importTextTargets(element: HtmlElement, known: ReadonlySet<string> | null): ImportTextTarget[];
86
+ /** Normalizes retyped words. */
87
+ export declare const retypedWords: (text: string) => string;
88
+ /** What retyping an instance's words comes to. */
89
+ export type ImportTextOutcome = {
90
+ kind: 'commit';
91
+ key: string;
92
+ text: string;
93
+ } | {
94
+ kind: 'noop';
95
+ } | {
96
+ kind: 'refuse';
97
+ } | {
98
+ kind: 'toolong';
99
+ } | {
100
+ kind: 'notnumber';
101
+ };
102
+ /** Checks retyped words against the instance's targets now. */
103
+ export declare function importTextOutcome(target: {
104
+ key: string;
105
+ words: string;
106
+ }, text: string, targets: readonly ImportTextTarget[]): ImportTextOutcome;