@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,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `.dc.html` file as a whole: where the template, the logic script and
|
|
3
|
+
* its `data-props` live in the source, and how to replace one of them while
|
|
4
|
+
* every other byte of the file stays as written.
|
|
5
|
+
*/
|
|
6
|
+
import { type PropsSpec } from './props.ts';
|
|
7
|
+
/** The line every artboard's `<head>` must carry; the editor swaps it for the runtime. */
|
|
8
|
+
export declare const SUPPORT_SCRIPT_TAG = "<script src=\"./support.js\"></script>";
|
|
9
|
+
/** A range of the source. */
|
|
10
|
+
export interface SourceRange {
|
|
11
|
+
start: number;
|
|
12
|
+
end: number;
|
|
13
|
+
}
|
|
14
|
+
/** A parsed `.dc.html` source. All offsets index into `source`. */
|
|
15
|
+
export interface DcDocument {
|
|
16
|
+
source: string;
|
|
17
|
+
/** The text strictly between `<x-dc …>` and the LAST `</x-dc>`; `null` when missing. */
|
|
18
|
+
template: (SourceRange & {
|
|
19
|
+
text: string;
|
|
20
|
+
}) | null;
|
|
21
|
+
/** The `<script type="text/x-dc" data-dc-script>` element, if any. */
|
|
22
|
+
script: (SourceRange & {
|
|
23
|
+
/** The script body (classic JS). */
|
|
24
|
+
body: SourceRange & {
|
|
25
|
+
text: string;
|
|
26
|
+
};
|
|
27
|
+
/** The `data-props` attribute's full `data-props='…'` text, if present. */
|
|
28
|
+
propsAttr: (SourceRange & {
|
|
29
|
+
raw: string;
|
|
30
|
+
}) | null;
|
|
31
|
+
}) | null;
|
|
32
|
+
/** Parsed `data-props`, or `null` when absent. */
|
|
33
|
+
props: PropsSpec | null;
|
|
34
|
+
/** Why `data-props` could not be parsed. */
|
|
35
|
+
propsError: string | null;
|
|
36
|
+
/** `<title>` text, decoded. */
|
|
37
|
+
title: string | null;
|
|
38
|
+
/** `<html lang>` value. */
|
|
39
|
+
lang: string | null;
|
|
40
|
+
/** The head carries {@link SUPPORT_SCRIPT_TAG} exactly. */
|
|
41
|
+
hasSupportScript: boolean;
|
|
42
|
+
/** The `<head>` inner text (between `<head>` and `</head>`), for importers and exports. */
|
|
43
|
+
head: (SourceRange & {
|
|
44
|
+
text: string;
|
|
45
|
+
}) | null;
|
|
46
|
+
}
|
|
47
|
+
/** Parses a `.dc.html` source. Never throws; problems surface as `null` fields. */
|
|
48
|
+
export declare function parseDcDocument(source: string): DcDocument;
|
|
49
|
+
/** Replaces the template text; everything outside `<x-dc>` stays byte-identical. */
|
|
50
|
+
export declare function replaceTemplate(doc: DcDocument, template: string): string;
|
|
51
|
+
/** Replaces the logic script's body. */
|
|
52
|
+
export declare function replaceScriptBody(doc: DcDocument, body: string): string;
|
|
53
|
+
/**
|
|
54
|
+
* Encodes JSON for a single-quoted `data-props` attribute: `&` → `&`,
|
|
55
|
+
* `'` → `'`. Raw UTF-8 and double quotes stay as they are.
|
|
56
|
+
*/
|
|
57
|
+
export declare function encodePropsAttribute(json: string): string;
|
|
58
|
+
/** Writes (or adds) the `data-props` attribute with a new spec. */
|
|
59
|
+
export declare function replaceProps(doc: DcDocument, props: PropsSpec): string;
|
|
60
|
+
/** Base name of a path: `sub/Main.dc.html` → `Main.dc.html`. */
|
|
61
|
+
export declare function baseName(path: string): string;
|
|
62
|
+
/** The stem of an artboard file: `sub/Main.dc.html` → `Main`. */
|
|
63
|
+
export declare function boardStem(path: string): string;
|
package/src/document.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `.dc.html` file as a whole: where the template, the logic script and
|
|
3
|
+
* its `data-props` live in the source, and how to replace one of them while
|
|
4
|
+
* every other byte of the file stays as written.
|
|
5
|
+
*/
|
|
6
|
+
import { decodeEntities } from "./html.js";
|
|
7
|
+
import { parseProps } from "./props.js";
|
|
8
|
+
/** The line every artboard's `<head>` must carry; the editor swaps it for the runtime. */
|
|
9
|
+
export const SUPPORT_SCRIPT_TAG = '<script src="./support.js"></script>';
|
|
10
|
+
/** Finds the `<x-dc>` open tag and the last `</x-dc>`. */
|
|
11
|
+
function findTemplate(source) {
|
|
12
|
+
const open = /<x-dc(\s[^>]*)?>/i.exec(source);
|
|
13
|
+
if (!open)
|
|
14
|
+
return null;
|
|
15
|
+
const start = open.index + open[0].length;
|
|
16
|
+
const end = source.toLowerCase().lastIndexOf('</x-dc>');
|
|
17
|
+
if (end < start)
|
|
18
|
+
return null;
|
|
19
|
+
return { start, end, text: source.slice(start, end) };
|
|
20
|
+
}
|
|
21
|
+
/** Finds the logic script after the template. */
|
|
22
|
+
function findScript(source, after) {
|
|
23
|
+
const re = /<script\b([^>]*)>/gi;
|
|
24
|
+
re.lastIndex = after;
|
|
25
|
+
for (let match = re.exec(source); match; match = re.exec(source)) {
|
|
26
|
+
const attrs = match[1] ?? '';
|
|
27
|
+
if (!/\bdata-dc-script\b/i.test(attrs) && !/type\s*=\s*["']text\/x-dc["']/i.test(attrs))
|
|
28
|
+
continue;
|
|
29
|
+
const bodyStart = match.index + match[0].length;
|
|
30
|
+
const close = source.toLowerCase().indexOf('</script>', bodyStart);
|
|
31
|
+
const bodyEnd = close === -1 ? source.length : close;
|
|
32
|
+
const end = close === -1 ? source.length : close + '</script>'.length;
|
|
33
|
+
let propsAttr = null;
|
|
34
|
+
const propsMatch = /\sdata-props\s*=\s*('[^']*'|"[^"]*")/i.exec(attrs);
|
|
35
|
+
if (propsMatch) {
|
|
36
|
+
// Offsets of `data-props='…'` inside the start tag (skip the leading space).
|
|
37
|
+
const attrOffset = match.index + '<script'.length + propsMatch.index + 1;
|
|
38
|
+
const raw = propsMatch[0].slice(1);
|
|
39
|
+
propsAttr = { start: attrOffset, end: attrOffset + raw.length, raw };
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
start: match.index,
|
|
43
|
+
end,
|
|
44
|
+
body: { start: bodyStart, end: bodyEnd, text: source.slice(bodyStart, bodyEnd) },
|
|
45
|
+
propsAttr,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
/** Parses a `.dc.html` source. Never throws; problems surface as `null` fields. */
|
|
51
|
+
export function parseDcDocument(source) {
|
|
52
|
+
const template = findTemplate(source);
|
|
53
|
+
const script = findScript(source, template ? template.end : 0);
|
|
54
|
+
let props = null;
|
|
55
|
+
let propsError = null;
|
|
56
|
+
if (script?.propsAttr) {
|
|
57
|
+
const quoted = script.propsAttr.raw.slice(script.propsAttr.raw.indexOf('=') + 1).trim();
|
|
58
|
+
const json = decodeEntities(quoted.slice(1, -1));
|
|
59
|
+
const parsed = parseProps(json);
|
|
60
|
+
if (parsed.ok)
|
|
61
|
+
props = parsed.props;
|
|
62
|
+
else
|
|
63
|
+
propsError = parsed.error;
|
|
64
|
+
}
|
|
65
|
+
const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(template ? source.slice(0, template.start) : source);
|
|
66
|
+
const langMatch = /<html\b[^>]*\blang\s*=\s*["']([^"']*)["']/i.exec(source);
|
|
67
|
+
const headOpen = /<head(\s[^>]*)?>/i.exec(source);
|
|
68
|
+
const headClose = source.toLowerCase().indexOf('</head>');
|
|
69
|
+
const head = headOpen && headClose > headOpen.index
|
|
70
|
+
? {
|
|
71
|
+
start: headOpen.index + headOpen[0].length,
|
|
72
|
+
end: headClose,
|
|
73
|
+
text: source.slice(headOpen.index + headOpen[0].length, headClose),
|
|
74
|
+
}
|
|
75
|
+
: null;
|
|
76
|
+
return {
|
|
77
|
+
source,
|
|
78
|
+
template,
|
|
79
|
+
script,
|
|
80
|
+
props,
|
|
81
|
+
propsError,
|
|
82
|
+
title: titleMatch ? decodeEntities(titleMatch[1].trim()) : null,
|
|
83
|
+
lang: langMatch ? langMatch[1] : null,
|
|
84
|
+
hasSupportScript: source.includes(SUPPORT_SCRIPT_TAG),
|
|
85
|
+
head,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Replaces the template text; everything outside `<x-dc>` stays byte-identical. */
|
|
89
|
+
export function replaceTemplate(doc, template) {
|
|
90
|
+
if (!doc.template)
|
|
91
|
+
throw new Error('The file has no <x-dc> template to replace.');
|
|
92
|
+
return doc.source.slice(0, doc.template.start) + template + doc.source.slice(doc.template.end);
|
|
93
|
+
}
|
|
94
|
+
/** Replaces the logic script's body. */
|
|
95
|
+
export function replaceScriptBody(doc, body) {
|
|
96
|
+
if (!doc.script)
|
|
97
|
+
throw new Error('The file has no data-dc-script block.');
|
|
98
|
+
return doc.source.slice(0, doc.script.body.start) + body + doc.source.slice(doc.script.body.end);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Encodes JSON for a single-quoted `data-props` attribute: `&` → `&`,
|
|
102
|
+
* `'` → `'`. Raw UTF-8 and double quotes stay as they are.
|
|
103
|
+
*/
|
|
104
|
+
export function encodePropsAttribute(json) {
|
|
105
|
+
return `data-props='${json.replace(/&/g, '&').replace(/'/g, ''')}'`;
|
|
106
|
+
}
|
|
107
|
+
/** Writes (or adds) the `data-props` attribute with a new spec. */
|
|
108
|
+
export function replaceProps(doc, props) {
|
|
109
|
+
if (!doc.script)
|
|
110
|
+
throw new Error('The file has no data-dc-script block.');
|
|
111
|
+
const attribute = encodePropsAttribute(JSON.stringify(props));
|
|
112
|
+
if (doc.script.propsAttr) {
|
|
113
|
+
return doc.source.slice(0, doc.script.propsAttr.start) + attribute + doc.source.slice(doc.script.propsAttr.end);
|
|
114
|
+
}
|
|
115
|
+
// Insert right before the start tag's closing `>`.
|
|
116
|
+
const close = doc.source.indexOf('>', doc.script.start);
|
|
117
|
+
return `${doc.source.slice(0, close)} ${attribute}${doc.source.slice(close)}`;
|
|
118
|
+
}
|
|
119
|
+
/** Base name of a path: `sub/Main.dc.html` → `Main.dc.html`. */
|
|
120
|
+
export function baseName(path) {
|
|
121
|
+
return path.slice(path.lastIndexOf('/') + 1);
|
|
122
|
+
}
|
|
123
|
+
/** The stem of an artboard file: `sub/Main.dc.html` → `Main`. */
|
|
124
|
+
export function boardStem(path) {
|
|
125
|
+
return baseName(path).replace(/\.dc\.html$/i, '');
|
|
126
|
+
}
|
package/src/edit.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edits to a template, expressed as text splices.
|
|
3
|
+
*
|
|
4
|
+
* Every edit names elements of a {@link TemplateModel} and returns the new
|
|
5
|
+
* template text. Only the bytes an edit touches change: an attribute edit
|
|
6
|
+
* rewrites that attribute, a text edit rewrites the element's content, a
|
|
7
|
+
* removal cuts the element and the whitespace that introduced it. Several
|
|
8
|
+
* edits can be combined with {@link applyEdits} as long as their ranges do
|
|
9
|
+
* not overlap.
|
|
10
|
+
*/
|
|
11
|
+
import { type HtmlElement, type HtmlNode } from './html.ts';
|
|
12
|
+
import { type StylePatch } from './style.ts';
|
|
13
|
+
import type { TemplateModel } from './template.ts';
|
|
14
|
+
/** Replace `[start, end)` of the template text with `text`. */
|
|
15
|
+
export interface Splice {
|
|
16
|
+
start: number;
|
|
17
|
+
end: number;
|
|
18
|
+
text: string;
|
|
19
|
+
}
|
|
20
|
+
/** Thrown when an edit cannot be expressed on this element. */
|
|
21
|
+
export declare class EditError extends Error {
|
|
22
|
+
name: string;
|
|
23
|
+
}
|
|
24
|
+
/** Applies splices (in any order) to a text. Overlapping splices throw. */
|
|
25
|
+
export declare function applySplices(text: string, splices: readonly Splice[]): string;
|
|
26
|
+
/** Applies the splices of several edits to the model's text. */
|
|
27
|
+
export declare function applyEdits(model: TemplateModel, edits: readonly (readonly Splice[])[]): string;
|
|
28
|
+
/** Writes `name="value"`, single-quoting values that contain `"` but no `'`. */
|
|
29
|
+
export declare function formatAttribute(name: string, value: string | null): string;
|
|
30
|
+
/** Sets (or, with `null`, removes) an attribute. `undefined` value = bare attribute. */
|
|
31
|
+
export declare function setAttribute(model: TemplateModel, element: HtmlElement, name: string, value: string | null | {
|
|
32
|
+
bare: true;
|
|
33
|
+
}): Splice[];
|
|
34
|
+
/** True when the element's style is a whole-value hole (`style="{{s}}"`), which the panel must not rewrite. */
|
|
35
|
+
export declare function hasDynamicStyle(element: HtmlElement): boolean;
|
|
36
|
+
/** Patches the inline style. */
|
|
37
|
+
export declare function setStyle(model: TemplateModel, element: HtmlElement, patch: StylePatch): Splice[];
|
|
38
|
+
/**
|
|
39
|
+
* True when the element's words are edited in place: words and inline
|
|
40
|
+
* formatting, as written in the template (see {@link isRichTextElement}).
|
|
41
|
+
*/
|
|
42
|
+
export declare function isTextEditable(element: HtmlElement): boolean;
|
|
43
|
+
/** True when the element holds plain text only (words and `<br>`, no holes). */
|
|
44
|
+
export declare function holdsPlainText(element: HtmlElement): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Replaces the element's content with text. Newlines become `<br>`, matching
|
|
47
|
+
* how a content-editable element reports line breaks.
|
|
48
|
+
*/
|
|
49
|
+
export declare function setText(element: HtmlElement, text: string): Splice[];
|
|
50
|
+
/** Replaces the element's content with raw HTML (already sanitized by the caller). */
|
|
51
|
+
export declare function setInnerHtml(element: HtmlElement, html: string): Splice[];
|
|
52
|
+
/** Removes elements together with the line break and indent that introduced each. */
|
|
53
|
+
export declare function removeElements(model: TemplateModel, elements: readonly HtmlElement[]): Splice[];
|
|
54
|
+
/** True when `outer` contains `inner` (or is it). */
|
|
55
|
+
export declare function contains(outer: HtmlElement, inner: HtmlNode): boolean;
|
|
56
|
+
/** The element's source text. */
|
|
57
|
+
export declare function elementSource(model: TemplateModel, element: HtmlElement): string;
|
|
58
|
+
/** Inserts a copy of each element right after it. */
|
|
59
|
+
export declare function duplicateElements(model: TemplateModel, elements: readonly HtmlElement[]): Splice[];
|
|
60
|
+
/** Where to insert relative to a reference element. */
|
|
61
|
+
export type InsertPosition = 'before' | 'after' | 'first-child' | 'last-child';
|
|
62
|
+
/** Inserts HTML relative to an element (or, with `null`, at the end of the template). */
|
|
63
|
+
export declare function insertHtml(model: TemplateModel, target: HtmlElement | null, position: InsertPosition, html: string): Splice[];
|
|
64
|
+
/**
|
|
65
|
+
* Moves elements next to (or into) a target, keeping their order. The moved
|
|
66
|
+
* source text is carried verbatim.
|
|
67
|
+
*/
|
|
68
|
+
export declare function moveElements(model: TemplateModel, elements: readonly HtmlElement[], target: HtmlElement, position: InsertPosition): Splice[];
|
|
69
|
+
/** Wraps elements (siblings, in source order) in a new container. */
|
|
70
|
+
export declare function wrapElements(model: TemplateModel, elements: readonly HtmlElement[], openTag: string, closeTag: string): Splice[];
|
|
71
|
+
/** Replaces an element with its children. */
|
|
72
|
+
export declare function unwrapElement(model: TemplateModel, element: HtmlElement): Splice[];
|
package/src/edit.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edits to a template, expressed as text splices.
|
|
3
|
+
*
|
|
4
|
+
* Every edit names elements of a {@link TemplateModel} and returns the new
|
|
5
|
+
* template text. Only the bytes an edit touches change: an attribute edit
|
|
6
|
+
* rewrites that attribute, a text edit rewrites the element's content, a
|
|
7
|
+
* removal cuts the element and the whitespace that introduced it. Several
|
|
8
|
+
* edits can be combined with {@link applyEdits} as long as their ranges do
|
|
9
|
+
* not overlap.
|
|
10
|
+
*/
|
|
11
|
+
import { VOID_ELEMENTS, elementChildren, escapeAttribute, escapeText, getAttribute, } from "./html.js";
|
|
12
|
+
import { hasHoles } from "./holes.js";
|
|
13
|
+
import { isRichTextElement } from "./rich-text.js";
|
|
14
|
+
import { patchStyle } from "./style.js";
|
|
15
|
+
/** Thrown when an edit cannot be expressed on this element. */
|
|
16
|
+
export class EditError extends Error {
|
|
17
|
+
name = 'EditError';
|
|
18
|
+
}
|
|
19
|
+
/** Applies splices (in any order) to a text. Overlapping splices throw. */
|
|
20
|
+
export function applySplices(text, splices) {
|
|
21
|
+
const sorted = [...splices].sort((a, b) => b.start - a.start || b.end - a.end);
|
|
22
|
+
let out = text;
|
|
23
|
+
let floor = Infinity;
|
|
24
|
+
for (const splice of sorted) {
|
|
25
|
+
if (splice.end > floor)
|
|
26
|
+
throw new EditError('Edits overlap.');
|
|
27
|
+
out = out.slice(0, splice.start) + splice.text + out.slice(splice.end);
|
|
28
|
+
floor = splice.start;
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/** Applies the splices of several edits to the model's text. */
|
|
33
|
+
export function applyEdits(model, edits) {
|
|
34
|
+
return applySplices(model.text, edits.flat());
|
|
35
|
+
}
|
|
36
|
+
/* -------------------------------------------------------------------------- */
|
|
37
|
+
/* Attributes */
|
|
38
|
+
/* -------------------------------------------------------------------------- */
|
|
39
|
+
/** Writes `name="value"`, single-quoting values that contain `"` but no `'`. */
|
|
40
|
+
export function formatAttribute(name, value) {
|
|
41
|
+
if (value === null)
|
|
42
|
+
return name;
|
|
43
|
+
if (value.includes('"') && !value.includes("'"))
|
|
44
|
+
return `${name}='${value.replace(/&/g, '&')}'`;
|
|
45
|
+
return `${name}="${escapeAttribute(value)}"`;
|
|
46
|
+
}
|
|
47
|
+
/** Where a new attribute goes: right before `>` or `/>`. */
|
|
48
|
+
function attributeInsertPoint(model, element) {
|
|
49
|
+
let at = element.openEnd - 1;
|
|
50
|
+
if (element.selfClosing && model.text[at - 1] === '/')
|
|
51
|
+
at--;
|
|
52
|
+
while (at > element.start && /\s/.test(model.text[at - 1]))
|
|
53
|
+
at--;
|
|
54
|
+
return at;
|
|
55
|
+
}
|
|
56
|
+
/** Sets (or, with `null`, removes) an attribute. `undefined` value = bare attribute. */
|
|
57
|
+
export function setAttribute(model, element, name, value) {
|
|
58
|
+
const attr = getAttribute(element, name);
|
|
59
|
+
if (value === null) {
|
|
60
|
+
if (!attr)
|
|
61
|
+
return [];
|
|
62
|
+
let start = attr.start;
|
|
63
|
+
while (start > element.start && /\s/.test(model.text[start - 1]))
|
|
64
|
+
start--;
|
|
65
|
+
return [{ start, end: attr.end, text: '' }];
|
|
66
|
+
}
|
|
67
|
+
const written = typeof value === 'string' ? formatAttribute(attr?.name ?? name, value) : (attr?.name ?? name);
|
|
68
|
+
if (attr)
|
|
69
|
+
return [{ start: attr.start, end: attr.end, text: written }];
|
|
70
|
+
const at = attributeInsertPoint(model, element);
|
|
71
|
+
return [{ start: at, end: at, text: ` ${written}` }];
|
|
72
|
+
}
|
|
73
|
+
/** True when the element's style is a whole-value hole (`style="{{s}}"`), which the panel must not rewrite. */
|
|
74
|
+
export function hasDynamicStyle(element) {
|
|
75
|
+
const value = getAttribute(element, 'style')?.value ?? '';
|
|
76
|
+
return /^\s*\{\{[^}]*\}\}\s*$/.test(value);
|
|
77
|
+
}
|
|
78
|
+
/** Patches the inline style. */
|
|
79
|
+
export function setStyle(model, element, patch) {
|
|
80
|
+
if (hasDynamicStyle(element))
|
|
81
|
+
throw new EditError('This element takes its whole style from the logic class.');
|
|
82
|
+
const current = getAttribute(element, 'style')?.value ?? '';
|
|
83
|
+
const next = patchStyle(current, patch);
|
|
84
|
+
return setAttribute(model, element, 'style', next === '' ? null : next);
|
|
85
|
+
}
|
|
86
|
+
/* -------------------------------------------------------------------------- */
|
|
87
|
+
/* Text */
|
|
88
|
+
/* -------------------------------------------------------------------------- */
|
|
89
|
+
/**
|
|
90
|
+
* True when the element's words are edited in place: words and inline
|
|
91
|
+
* formatting, as written in the template (see {@link isRichTextElement}).
|
|
92
|
+
*/
|
|
93
|
+
export function isTextEditable(element) {
|
|
94
|
+
return isRichTextElement(element);
|
|
95
|
+
}
|
|
96
|
+
/** True when the element holds plain text only (words and `<br>`, no holes). */
|
|
97
|
+
export function holdsPlainText(element) {
|
|
98
|
+
if (VOID_ELEMENTS.has(element.tag) || element.closeStart < 0)
|
|
99
|
+
return false;
|
|
100
|
+
if (['script', 'style', 'helmet', 'sc-for', 'sc-if', 'dc-import', 'x-import', 'svg'].includes(element.tag))
|
|
101
|
+
return false;
|
|
102
|
+
for (const child of element.children) {
|
|
103
|
+
if (child.type === 'element' && child.tag !== 'br')
|
|
104
|
+
return false;
|
|
105
|
+
if (child.type === 'text' && hasHoles(child.value))
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Replaces the element's content with text. Newlines become `<br>`, matching
|
|
112
|
+
* how a content-editable element reports line breaks.
|
|
113
|
+
*/
|
|
114
|
+
export function setText(element, text) {
|
|
115
|
+
if (!holdsPlainText(element))
|
|
116
|
+
throw new EditError('This element does not hold plain text.');
|
|
117
|
+
const html = text.split('\n').map(escapeText).join('<br>');
|
|
118
|
+
return [{ start: element.openEnd, end: element.closeStart, text: html }];
|
|
119
|
+
}
|
|
120
|
+
/** Replaces the element's content with raw HTML (already sanitized by the caller). */
|
|
121
|
+
export function setInnerHtml(element, html) {
|
|
122
|
+
if (VOID_ELEMENTS.has(element.tag) || element.closeStart < 0)
|
|
123
|
+
throw new EditError('This element has no content.');
|
|
124
|
+
return [{ start: element.openEnd, end: element.closeStart, text: html }];
|
|
125
|
+
}
|
|
126
|
+
/* -------------------------------------------------------------------------- */
|
|
127
|
+
/* Structure */
|
|
128
|
+
/* -------------------------------------------------------------------------- */
|
|
129
|
+
/** The whitespace text right before a node among its siblings (`''` when none). */
|
|
130
|
+
function leadingWhitespace(model, node) {
|
|
131
|
+
let start = node.start;
|
|
132
|
+
while (start > 0 && /[ \t]/.test(model.text[start - 1]))
|
|
133
|
+
start--;
|
|
134
|
+
if (start > 0 && model.text[start - 1] === '\n')
|
|
135
|
+
start--;
|
|
136
|
+
if (start > 0 && model.text[start - 1] === '\r')
|
|
137
|
+
start--;
|
|
138
|
+
return { start, text: model.text.slice(start, node.start) };
|
|
139
|
+
}
|
|
140
|
+
/** Removes elements together with the line break and indent that introduced each. */
|
|
141
|
+
export function removeElements(model, elements) {
|
|
142
|
+
const outermost = elements.filter((element) => !elements.some((other) => other !== element && contains(other, element)));
|
|
143
|
+
return outermost.map((element) => ({ start: leadingWhitespace(model, element).start, end: element.end, text: '' }));
|
|
144
|
+
}
|
|
145
|
+
/** True when `outer` contains `inner` (or is it). */
|
|
146
|
+
export function contains(outer, inner) {
|
|
147
|
+
for (let node = inner; node; node = node.parent)
|
|
148
|
+
if (node === outer)
|
|
149
|
+
return true;
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
/** The element's source text. */
|
|
153
|
+
export function elementSource(model, element) {
|
|
154
|
+
return model.text.slice(element.start, element.end);
|
|
155
|
+
}
|
|
156
|
+
/** The line-break-plus-indent to put before a new sibling of `element`. */
|
|
157
|
+
function siblingSeparator(model, element) {
|
|
158
|
+
const lead = leadingWhitespace(model, element).text;
|
|
159
|
+
return lead.includes('\n') ? lead : '';
|
|
160
|
+
}
|
|
161
|
+
/** Inserts a copy of each element right after it. */
|
|
162
|
+
export function duplicateElements(model, elements) {
|
|
163
|
+
const outermost = elements.filter((element) => !elements.some((other) => other !== element && contains(other, element)));
|
|
164
|
+
return outermost.map((element) => ({
|
|
165
|
+
start: element.end,
|
|
166
|
+
end: element.end,
|
|
167
|
+
text: siblingSeparator(model, element) + elementSource(model, element),
|
|
168
|
+
}));
|
|
169
|
+
}
|
|
170
|
+
/** Inserts HTML relative to an element (or, with `null`, at the end of the template). */
|
|
171
|
+
export function insertHtml(model, target, position, html) {
|
|
172
|
+
if (!target) {
|
|
173
|
+
const tops = elementChildren(model.nodes);
|
|
174
|
+
const last = tops[tops.length - 1];
|
|
175
|
+
if (!last)
|
|
176
|
+
return [{ start: model.text.length, end: model.text.length, text: `\n${html}\n` }];
|
|
177
|
+
return [{ start: last.end, end: last.end, text: (siblingSeparator(model, last) || '\n') + html }];
|
|
178
|
+
}
|
|
179
|
+
if (position === 'before') {
|
|
180
|
+
const separator = siblingSeparator(model, target);
|
|
181
|
+
return [{ start: leadingWhitespace(model, target).start, end: leadingWhitespace(model, target).start, text: separator + html }];
|
|
182
|
+
}
|
|
183
|
+
if (position === 'after') {
|
|
184
|
+
return [{ start: target.end, end: target.end, text: siblingSeparator(model, target) + html }];
|
|
185
|
+
}
|
|
186
|
+
if (VOID_ELEMENTS.has(target.tag) || target.closeStart < 0)
|
|
187
|
+
throw new EditError('This element cannot hold children.');
|
|
188
|
+
const kids = elementChildren(target);
|
|
189
|
+
if (position === 'first-child') {
|
|
190
|
+
const first = kids[0];
|
|
191
|
+
if (first)
|
|
192
|
+
return insertHtml(model, first, 'before', html);
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
const last = kids[kids.length - 1];
|
|
196
|
+
if (last)
|
|
197
|
+
return insertHtml(model, last, 'after', html);
|
|
198
|
+
}
|
|
199
|
+
// Empty element: indent one step deeper than the element itself.
|
|
200
|
+
const indent = siblingSeparator(model, target);
|
|
201
|
+
const inner = indent ? `${indent} ` : '';
|
|
202
|
+
const content = model.text.slice(target.openEnd, target.closeStart);
|
|
203
|
+
const tail = content.trim() === '' ? indent : '';
|
|
204
|
+
return [{ start: target.openEnd, end: target.closeStart, text: `${content.trim() === '' ? '' : content}${inner}${html}${tail}` }];
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Moves elements next to (or into) a target, keeping their order. The moved
|
|
208
|
+
* source text is carried verbatim.
|
|
209
|
+
*/
|
|
210
|
+
export function moveElements(model, elements, target, position) {
|
|
211
|
+
const moving = elements
|
|
212
|
+
.filter((element) => !elements.some((other) => other !== element && contains(other, element)))
|
|
213
|
+
.sort((a, b) => a.start - b.start);
|
|
214
|
+
if (moving.some((element) => contains(element, target)))
|
|
215
|
+
throw new EditError('Cannot move an element into itself.');
|
|
216
|
+
const separator = siblingSeparator(model, target) || '\n';
|
|
217
|
+
const html = moving.map((element) => elementSource(model, element)).join(separator);
|
|
218
|
+
return [...removeElements(model, moving), ...insertHtml(model, target, position, html)];
|
|
219
|
+
}
|
|
220
|
+
/** Wraps elements (siblings, in source order) in a new container. */
|
|
221
|
+
export function wrapElements(model, elements, openTag, closeTag) {
|
|
222
|
+
const sorted = [...elements].sort((a, b) => a.start - b.start);
|
|
223
|
+
const first = sorted[0];
|
|
224
|
+
const last = sorted[sorted.length - 1];
|
|
225
|
+
if (!first || !last)
|
|
226
|
+
return [];
|
|
227
|
+
if (sorted.some((element) => element.parent !== first.parent))
|
|
228
|
+
throw new EditError('Only siblings can be wrapped together.');
|
|
229
|
+
const indent = siblingSeparator(model, first);
|
|
230
|
+
const inner = model.text
|
|
231
|
+
.slice(first.start, last.end)
|
|
232
|
+
.split('\n')
|
|
233
|
+
.map((line, index) => (index === 0 || line.trim() === '' ? line : ` ${line}`))
|
|
234
|
+
.join('\n');
|
|
235
|
+
const innerIndent = indent ? `${indent} ` : '';
|
|
236
|
+
return [{ start: first.start, end: last.end, text: `${openTag}${innerIndent}${inner}${indent}${closeTag}` }];
|
|
237
|
+
}
|
|
238
|
+
/** Replaces an element with its children. */
|
|
239
|
+
export function unwrapElement(model, element) {
|
|
240
|
+
if (element.closeStart < 0)
|
|
241
|
+
throw new EditError('This element has no children to keep.');
|
|
242
|
+
const content = model.text.slice(element.openEnd, element.closeStart).replace(/^\s*\n/, '').replace(/\n\s*$/, '');
|
|
243
|
+
const dedented = content
|
|
244
|
+
.split('\n')
|
|
245
|
+
.map((line) => line.replace(/^ {2}/, ''))
|
|
246
|
+
.join('\n')
|
|
247
|
+
.trimStart();
|
|
248
|
+
return [{ start: element.start, end: element.end, text: dedented }];
|
|
249
|
+
}
|
package/src/holes.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Template holes: `{{ path }}`.
|
|
3
|
+
*
|
|
4
|
+
* A hole is a dotted lookup or a literal, never an expression. Anything else
|
|
5
|
+
* renders as an empty value (and `check` reports it), so a broken hole fails
|
|
6
|
+
* visibly in checks but never throws while rendering.
|
|
7
|
+
*/
|
|
8
|
+
/** A literal hole value. */
|
|
9
|
+
export type HoleLiteral = string | number | boolean | null | undefined;
|
|
10
|
+
/** A parsed hole. */
|
|
11
|
+
export type Hole = {
|
|
12
|
+
kind: 'path';
|
|
13
|
+
segments: string[];
|
|
14
|
+
raw: string;
|
|
15
|
+
} | {
|
|
16
|
+
kind: 'literal';
|
|
17
|
+
value: HoleLiteral;
|
|
18
|
+
raw: string;
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'invalid';
|
|
21
|
+
raw: string;
|
|
22
|
+
};
|
|
23
|
+
/** A piece of interpolated text: literal text or a hole. */
|
|
24
|
+
export type Part = {
|
|
25
|
+
kind: 'text';
|
|
26
|
+
text: string;
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'hole';
|
|
29
|
+
hole: Hole;
|
|
30
|
+
};
|
|
31
|
+
/** Parses the inside of one `{{ … }}`. */
|
|
32
|
+
export declare function parseHole(inner: string): Hole;
|
|
33
|
+
/** Splits text into literal parts and holes. */
|
|
34
|
+
export declare function splitHoles(text: string): Part[];
|
|
35
|
+
/** True when the text contains at least one hole. */
|
|
36
|
+
export declare function hasHoles(text: string): boolean;
|
|
37
|
+
/** When the whole text is exactly one hole (ignoring surrounding spaces), returns it. */
|
|
38
|
+
export declare function wholeHole(text: string): Hole | null;
|
|
39
|
+
/** A lookup scope: loop variables shadow the render values. */
|
|
40
|
+
export type Scope = Readonly<Record<string, unknown>>;
|
|
41
|
+
/** Evaluates a hole against the scopes (innermost first). */
|
|
42
|
+
export declare function evaluateHole(hole: Hole, scopes: readonly Scope[]): unknown;
|
|
43
|
+
/** Converts a value to the text a hole renders as. */
|
|
44
|
+
export declare function holeText(value: unknown): string;
|
|
45
|
+
/** Interpolates text: every hole becomes its text. */
|
|
46
|
+
export declare function interpolate(text: string, scopes: readonly Scope[]): string;
|
package/src/holes.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Template holes: `{{ path }}`.
|
|
3
|
+
*
|
|
4
|
+
* A hole is a dotted lookup or a literal, never an expression. Anything else
|
|
5
|
+
* renders as an empty value (and `check` reports it), so a broken hole fails
|
|
6
|
+
* visibly in checks but never throws while rendering.
|
|
7
|
+
*/
|
|
8
|
+
const HOLE = /\{\{([\s\S]*?)\}\}/g;
|
|
9
|
+
const PATH = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$0-9][\w$]*)*$/;
|
|
10
|
+
const NUMBER = /^-?\d+(\.\d+)?$/;
|
|
11
|
+
/** Parses the inside of one `{{ … }}`. */
|
|
12
|
+
export function parseHole(inner) {
|
|
13
|
+
const raw = inner.trim();
|
|
14
|
+
if (raw === 'true')
|
|
15
|
+
return { kind: 'literal', value: true, raw };
|
|
16
|
+
if (raw === 'false')
|
|
17
|
+
return { kind: 'literal', value: false, raw };
|
|
18
|
+
if (raw === 'null')
|
|
19
|
+
return { kind: 'literal', value: null, raw };
|
|
20
|
+
if (raw === 'undefined')
|
|
21
|
+
return { kind: 'literal', value: undefined, raw };
|
|
22
|
+
if (NUMBER.test(raw))
|
|
23
|
+
return { kind: 'literal', value: Number(raw), raw };
|
|
24
|
+
if (/^'[^']*'$|^"[^"]*"$/.test(raw))
|
|
25
|
+
return { kind: 'literal', value: raw.slice(1, -1), raw };
|
|
26
|
+
if (PATH.test(raw))
|
|
27
|
+
return { kind: 'path', segments: raw.split('.'), raw };
|
|
28
|
+
return { kind: 'invalid', raw };
|
|
29
|
+
}
|
|
30
|
+
/** Splits text into literal parts and holes. */
|
|
31
|
+
export function splitHoles(text) {
|
|
32
|
+
const parts = [];
|
|
33
|
+
let last = 0;
|
|
34
|
+
for (const match of text.matchAll(HOLE)) {
|
|
35
|
+
if (match.index > last)
|
|
36
|
+
parts.push({ kind: 'text', text: text.slice(last, match.index) });
|
|
37
|
+
parts.push({ kind: 'hole', hole: parseHole(match[1]) });
|
|
38
|
+
last = match.index + match[0].length;
|
|
39
|
+
}
|
|
40
|
+
if (last < text.length)
|
|
41
|
+
parts.push({ kind: 'text', text: text.slice(last) });
|
|
42
|
+
return parts;
|
|
43
|
+
}
|
|
44
|
+
/** True when the text contains at least one hole. */
|
|
45
|
+
export function hasHoles(text) {
|
|
46
|
+
return /\{\{[\s\S]*?\}\}/.test(text);
|
|
47
|
+
}
|
|
48
|
+
/** When the whole text is exactly one hole (ignoring surrounding spaces), returns it. */
|
|
49
|
+
export function wholeHole(text) {
|
|
50
|
+
const parts = splitHoles(text.trim());
|
|
51
|
+
return parts.length === 1 && parts[0].kind === 'hole' ? parts[0].hole : null;
|
|
52
|
+
}
|
|
53
|
+
/** Evaluates a hole against the scopes (innermost first). */
|
|
54
|
+
export function evaluateHole(hole, scopes) {
|
|
55
|
+
if (hole.kind === 'literal')
|
|
56
|
+
return hole.value;
|
|
57
|
+
if (hole.kind === 'invalid')
|
|
58
|
+
return undefined;
|
|
59
|
+
const [head, ...rest] = hole.segments;
|
|
60
|
+
let value = undefined;
|
|
61
|
+
for (const scope of scopes) {
|
|
62
|
+
if (scope && Object.prototype.hasOwnProperty.call(scope, head)) {
|
|
63
|
+
value = scope[head];
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (const key of rest) {
|
|
68
|
+
if (value === null || value === undefined)
|
|
69
|
+
return undefined;
|
|
70
|
+
value = value[key];
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/** Converts a value to the text a hole renders as. */
|
|
75
|
+
export function holeText(value) {
|
|
76
|
+
if (value === null || value === undefined || value === false)
|
|
77
|
+
return '';
|
|
78
|
+
if (typeof value === 'string')
|
|
79
|
+
return value;
|
|
80
|
+
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
|
|
81
|
+
return String(value);
|
|
82
|
+
return '';
|
|
83
|
+
}
|
|
84
|
+
/** Interpolates text: every hole becomes its text. */
|
|
85
|
+
export function interpolate(text, scopes) {
|
|
86
|
+
if (!text.includes('{{'))
|
|
87
|
+
return text;
|
|
88
|
+
return splitHoles(text)
|
|
89
|
+
.map((part) => (part.kind === 'text' ? part.text : holeText(evaluateHole(part.hole, scopes))))
|
|
90
|
+
.join('');
|
|
91
|
+
}
|