@tarve/svelte 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -3
- package/package.json +50 -4
- package/src/TitleBar.svelte +44 -0
- package/src/bun-preload.ts +4 -0
- package/src/bun.ts +13 -0
- package/src/compiler.ts +39 -0
- package/src/css.ts +606 -0
- package/src/dom.ts +1578 -0
- package/src/editable.ts +372 -0
- package/src/elements.d.ts +43 -0
- package/src/events.ts +87 -0
- package/src/index.ts +126 -0
- package/src/install.ts +4 -0
- package/src/plugin.ts +83 -0
- package/src/render.ts +460 -0
- package/src/resolve.ts +39 -0
- package/src/selectors.ts +316 -0
- package/src/svelte-client.ts +8 -0
package/src/editable.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { jsx, type Child } from "@tarve/core/jsx-runtime";
|
|
2
|
+
import { elementStyle } from "./css";
|
|
3
|
+
import { COMMENT_NODE, documentInstance, ELEMENT_NODE, setEditing, TEvent, TEXT_NODE, type TCharacterData, type TElement, type TNode } from "./dom";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `contenteditable` as rich text: the element's text is the value of a native
|
|
7
|
+
* text area, and its inline markup (`<b>`, `<em>`, `<span style>`…) styles runs
|
|
8
|
+
* of that text. Edits go back into the DOM where they happened, so typing inside
|
|
9
|
+
* `<b>` stays bold, and `execCommand` formats the native selection.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Phrasing elements that style a run; any other element is a line of its own (a `<div>` per line). */
|
|
13
|
+
const INLINE = new Set(["span", "strong", "b", "em", "i", "cite", "var", "dfn", "u", "ins", "s", "strike", "del", "code", "kbd", "samp", "mark", "small", "sub", "sup", "a", "abbr", "font"]);
|
|
14
|
+
/** Tags core styles by themselves; others render as a styled span. */
|
|
15
|
+
const NATIVE_INLINE = new Set(["span", "strong", "b", "em", "i", "cite", "var", "dfn", "u", "ins", "s", "del", "code", "kbd", "samp", "mark", "small", "sub", "sup", "a", "abbr"]);
|
|
16
|
+
|
|
17
|
+
/** A piece of the editable text: a text node, a `<br>`, or the line break before a block. */
|
|
18
|
+
interface Segment { node: TNode; start: number; end: number; kind: "text" | "br" | "block" }
|
|
19
|
+
export interface EditableModel { text: string; segments: Segment[]; children: Child[] }
|
|
20
|
+
|
|
21
|
+
function styleOf(element: TElement): Record<string, unknown> | undefined {
|
|
22
|
+
const classes = (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
|
|
23
|
+
return elementStyle(element, classes);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The text, where each piece sits, and the phrasing children that style it. */
|
|
27
|
+
export function editableModel(root: TElement): EditableModel {
|
|
28
|
+
let text = "";
|
|
29
|
+
const segments: Segment[] = [];
|
|
30
|
+
const children: Child[] = [];
|
|
31
|
+
const visit = (node: TNode, chain: TElement[]): void => {
|
|
32
|
+
for (let child = node._first; child; child = child._next) {
|
|
33
|
+
if (child.nodeType === TEXT_NODE) {
|
|
34
|
+
const data = (child as TCharacterData).data;
|
|
35
|
+
if (!data) continue;
|
|
36
|
+
segments.push({ node: child, start: text.length, end: text.length + data.length, kind: "text" });
|
|
37
|
+
text += data;
|
|
38
|
+
let piece: Child = data;
|
|
39
|
+
for (let index = chain.length - 1; index >= 0; index--) {
|
|
40
|
+
const element = chain[index]!;
|
|
41
|
+
const style = styleOf(element);
|
|
42
|
+
piece = jsx(NATIVE_INLINE.has(element.localName) ? element.localName : "span", { ...(style ? { style } : {}), children: piece });
|
|
43
|
+
}
|
|
44
|
+
children.push(piece);
|
|
45
|
+
} else if (child.nodeType === ELEMENT_NODE) {
|
|
46
|
+
const element = child as TElement;
|
|
47
|
+
if (element.localName === "br") {
|
|
48
|
+
segments.push({ node: element, start: text.length, end: text.length + 1, kind: "br" });
|
|
49
|
+
text += "\n";
|
|
50
|
+
children.push("\n");
|
|
51
|
+
} else if (INLINE.has(element.localName)) {
|
|
52
|
+
visit(element, [...chain, element]);
|
|
53
|
+
} else {
|
|
54
|
+
// A block (Chromium makes a <div> per line): it starts a new line.
|
|
55
|
+
if (text && !text.endsWith("\n")) {
|
|
56
|
+
segments.push({ node: element, start: text.length, end: text.length + 1, kind: "block" });
|
|
57
|
+
text += "\n";
|
|
58
|
+
children.push("\n");
|
|
59
|
+
}
|
|
60
|
+
visit(element, chain);
|
|
61
|
+
}
|
|
62
|
+
} else if (child.nodeType !== COMMENT_NODE) visit(child, chain);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
visit(root, []);
|
|
66
|
+
return { text, segments, children };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The common prefix and suffix of two strings, never splitting a surrogate pair. */
|
|
70
|
+
function changedRange(before: string, after: string): { start: number; end: number; inserted: string } {
|
|
71
|
+
let prefix = 0;
|
|
72
|
+
const limit = Math.min(before.length, after.length);
|
|
73
|
+
while (prefix < limit && before.charCodeAt(prefix) === after.charCodeAt(prefix)) prefix++;
|
|
74
|
+
if (prefix > 0 && prefix < limit && isLowSurrogate(before.charCodeAt(prefix))) prefix--;
|
|
75
|
+
let suffix = 0;
|
|
76
|
+
while (suffix < limit - prefix && before.charCodeAt(before.length - 1 - suffix) === after.charCodeAt(after.length - 1 - suffix)) suffix++;
|
|
77
|
+
if (suffix > 0 && isLowSurrogate(before.charCodeAt(before.length - suffix))) suffix--;
|
|
78
|
+
return { start: prefix, end: before.length - suffix, inserted: after.slice(prefix, after.length - suffix) };
|
|
79
|
+
}
|
|
80
|
+
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
|
|
81
|
+
|
|
82
|
+
/** Applies a native edit (the whole new value) to the DOM. */
|
|
83
|
+
export function applyValue(root: TElement, value: string): { inputType: string; data: string | null } | undefined {
|
|
84
|
+
const model = editableModel(root);
|
|
85
|
+
if (model.text === value) return undefined;
|
|
86
|
+
const { start, end, inserted } = changedRange(model.text, value);
|
|
87
|
+
replaceRange(root, start, end, inserted, model);
|
|
88
|
+
return {
|
|
89
|
+
inputType: inserted.includes("\n") && end === start ? "insertLineBreak" : inserted ? (end > start ? "insertReplacementText" : "insertText") : "deleteContent" + (value.length < model.text.length ? "Backward" : ""),
|
|
90
|
+
data: inserted || null,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Replaces text [start, end) with `inserted`, which takes the style of the text before `start`. */
|
|
95
|
+
export function replaceRange(root: TElement, start: number, end: number, inserted: string, model = editableModel(root)): void {
|
|
96
|
+
// Where the new text goes: the text node that ends at (or contains) start, else the one starting there.
|
|
97
|
+
let anchor: Segment | undefined;
|
|
98
|
+
for (const segment of model.segments) {
|
|
99
|
+
if (segment.kind !== "text") continue;
|
|
100
|
+
if (segment.start < start && start <= segment.end) { anchor = segment; break; }
|
|
101
|
+
if (segment.start === start && start === 0 && !anchor) anchor = segment;
|
|
102
|
+
}
|
|
103
|
+
anchor ??= model.segments.find(segment => segment.kind === "text" && segment.start === start);
|
|
104
|
+
// Delete, from the end so earlier offsets stay valid.
|
|
105
|
+
for (const segment of [...model.segments].reverse()) {
|
|
106
|
+
const from = Math.max(start, segment.start);
|
|
107
|
+
const to = Math.min(end, segment.end);
|
|
108
|
+
if (from >= to) continue;
|
|
109
|
+
if (segment.kind === "text") {
|
|
110
|
+
const node = segment.node as TCharacterData;
|
|
111
|
+
node.data = node.data.slice(0, from - segment.start) + node.data.slice(to - segment.start);
|
|
112
|
+
} else if (segment.kind === "br") segment.node.remove();
|
|
113
|
+
else {
|
|
114
|
+
// The line break before a block: the block's content joins the line before.
|
|
115
|
+
const block = segment.node as TElement;
|
|
116
|
+
while (block._first) block.parentNode!.insertBefore(block._first, block);
|
|
117
|
+
block.remove();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (inserted) {
|
|
121
|
+
const lines = inserted.split("\n");
|
|
122
|
+
let node: TCharacterData;
|
|
123
|
+
let tail = "";
|
|
124
|
+
if (anchor && anchor.node.parentNode) {
|
|
125
|
+
node = anchor.node as TCharacterData;
|
|
126
|
+
const offset = Math.min(start - anchor.start, node.data.length);
|
|
127
|
+
tail = node.data.slice(offset);
|
|
128
|
+
node.data = node.data.slice(0, offset) + lines[0];
|
|
129
|
+
} else {
|
|
130
|
+
// No text there yet (empty editor, next to a <br>): a new text node at that point.
|
|
131
|
+
node = documentInstance.createTextNode(lines[0]!);
|
|
132
|
+
const after = model.segments.find(segment => segment.start >= start && segment.node.parentNode);
|
|
133
|
+
if (after) after.node.parentNode!.insertBefore(node, after.node); else root.appendChild(node);
|
|
134
|
+
}
|
|
135
|
+
let last = node;
|
|
136
|
+
for (const line of lines.slice(1)) {
|
|
137
|
+
const br = documentInstance.createElement("br");
|
|
138
|
+
last.parentNode!.insertBefore(br, last._next);
|
|
139
|
+
const next = documentInstance.createTextNode(line);
|
|
140
|
+
br.parentNode!.insertBefore(next, br._next);
|
|
141
|
+
last = next;
|
|
142
|
+
}
|
|
143
|
+
if (tail) last.data += tail;
|
|
144
|
+
}
|
|
145
|
+
for (const segment of model.segments) {
|
|
146
|
+
if (segment.kind === "text" && !(segment.node as TCharacterData).data && segment.node.parentNode) segment.node.remove();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Splits text nodes at start and end and returns the text nodes inside [start, end). */
|
|
151
|
+
function textNodesIn(root: TElement, start: number, end: number): TCharacterData[] {
|
|
152
|
+
const model = editableModel(root);
|
|
153
|
+
const nodes: TCharacterData[] = [];
|
|
154
|
+
for (const segment of model.segments) {
|
|
155
|
+
if (segment.kind !== "text" || segment.end <= start || segment.start >= end) continue;
|
|
156
|
+
let node = segment.node as TCharacterData;
|
|
157
|
+
const from = Math.max(start, segment.start) - segment.start;
|
|
158
|
+
const to = Math.min(end, segment.end) - segment.start;
|
|
159
|
+
if (to < node.data.length) {
|
|
160
|
+
const after = documentInstance.createTextNode(node.data.slice(to));
|
|
161
|
+
node.parentNode!.insertBefore(after, node._next);
|
|
162
|
+
node.data = node.data.slice(0, to);
|
|
163
|
+
}
|
|
164
|
+
if (from > 0) {
|
|
165
|
+
const inside = documentInstance.createTextNode(node.data.slice(from));
|
|
166
|
+
node.parentNode!.insertBefore(inside, node._next);
|
|
167
|
+
node.data = node.data.slice(0, from);
|
|
168
|
+
node = inside;
|
|
169
|
+
}
|
|
170
|
+
nodes.push(node);
|
|
171
|
+
}
|
|
172
|
+
return nodes;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const FORMATS: Record<string, { tags: string[]; wrap: string; off: string; style: (style: Record<string, unknown>) => boolean | undefined }> = {
|
|
176
|
+
bold: { tags: ["b", "strong"], wrap: "b", off: "font-weight: 400", style: s => s.fontWeight === undefined ? undefined : Number(s.fontWeight) >= 600 || s.fontWeight === "bold" },
|
|
177
|
+
italic: { tags: ["i", "em"], wrap: "i", off: "font-style: normal", style: s => s.fontStyle === undefined ? undefined : s.fontStyle === "italic" },
|
|
178
|
+
underline: { tags: ["u", "ins"], wrap: "u", off: "text-decoration: none", style: s => s.textDecoration === undefined ? undefined : String(s.textDecoration).includes("underline") },
|
|
179
|
+
strikethrough: { tags: ["s", "strike", "del"], wrap: "s", off: "text-decoration: none", style: s => s.textDecoration === undefined ? undefined : String(s.textDecoration).includes("line-through") },
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** Whether a format applies to a text node: the nearest element that sets it decides. */
|
|
183
|
+
function formatted(node: TNode, root: TElement, format: (typeof FORMATS)[string]): boolean {
|
|
184
|
+
for (let element = node.parentElement; element && element !== root; element = element.parentElement) {
|
|
185
|
+
const own = element.getAttribute("style") ? format.style(styleOf(element) ?? {}) : undefined;
|
|
186
|
+
if (own !== undefined) return own;
|
|
187
|
+
if (format.tags.includes(element.localName)) return true;
|
|
188
|
+
}
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Joins a new format element with a plain neighbour of the same tag: `<b>a</b><b>b</b>` → `<b>ab</b>`. */
|
|
193
|
+
function mergeSiblings(element: TElement): void {
|
|
194
|
+
const same = (node: TNode | null): node is TElement => !!node && node.nodeType === ELEMENT_NODE && (node as TElement).localName === element.localName && !(node as TElement).attributes?.length;
|
|
195
|
+
const previous = element._prev;
|
|
196
|
+
if (same(previous)) {
|
|
197
|
+
while (element._first) previous.appendChild(element._first);
|
|
198
|
+
element.remove();
|
|
199
|
+
element = previous;
|
|
200
|
+
}
|
|
201
|
+
const next = element._next;
|
|
202
|
+
if (same(next)) {
|
|
203
|
+
while (next._first) element.appendChild(next._first);
|
|
204
|
+
next.remove();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** execCommand bold / italic / underline / strikeThrough over [start, end). */
|
|
209
|
+
export function toggleFormat(root: TElement, command: string, start: number, end: number): boolean {
|
|
210
|
+
const format = FORMATS[command];
|
|
211
|
+
if (!format || start >= end) return false;
|
|
212
|
+
const nodes = textNodesIn(root, start, end);
|
|
213
|
+
if (!nodes.length) return false;
|
|
214
|
+
const on = !nodes.every(node => formatted(node, root, format));
|
|
215
|
+
for (const node of nodes) {
|
|
216
|
+
if (formatted(node, root, format) === on) continue;
|
|
217
|
+
const parent = node.parentElement!;
|
|
218
|
+
// The node alone in a tag that sets exactly this: unwrap it instead of nesting an override.
|
|
219
|
+
const alone = parent !== root && parent._first === node && parent._last === node;
|
|
220
|
+
if (alone && (on ? (parent.getAttribute("style") ?? "").replace(/;\s*$/, "") === format.off : format.tags.includes(parent.localName) && !parent.getAttribute("style"))) {
|
|
221
|
+
parent.parentNode!.insertBefore(node, parent);
|
|
222
|
+
parent.remove();
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const wrapper = documentInstance.createElement(on ? format.wrap : "span");
|
|
226
|
+
if (!on) wrapper.setAttribute("style", format.off);
|
|
227
|
+
parent.insertBefore(wrapper, node);
|
|
228
|
+
wrapper.appendChild(node);
|
|
229
|
+
if (on) mergeSiblings(wrapper);
|
|
230
|
+
}
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function queryFormat(root: TElement, command: string, position: number): boolean {
|
|
235
|
+
const format = FORMATS[command];
|
|
236
|
+
if (!format) return false;
|
|
237
|
+
const model = editableModel(root);
|
|
238
|
+
const segment = model.segments.find(item => item.kind === "text" && item.start < position && position <= item.end)
|
|
239
|
+
?? model.segments.find(item => item.kind === "text" && item.start === position);
|
|
240
|
+
return !!segment && formatted(segment.node, root, format);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** A DOM position (node, offset) for a text offset, as Selection and Range report it. */
|
|
244
|
+
export function domPosition(root: TElement, offset: number): { node: TNode; offset: number } {
|
|
245
|
+
const model = editableModel(root);
|
|
246
|
+
for (const segment of model.segments) {
|
|
247
|
+
if (segment.kind === "text" && segment.start <= offset && offset <= segment.end) return { node: segment.node, offset: offset - segment.start };
|
|
248
|
+
}
|
|
249
|
+
const children = root.childNodes;
|
|
250
|
+
const after = model.segments.find(segment => segment.start >= offset);
|
|
251
|
+
const index = after ? children.indexOf(after.node) : -1;
|
|
252
|
+
return { node: root, offset: index >= 0 ? index : children.length };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function fireInput(root: TElement, inputType: string, data: string | null): void {
|
|
256
|
+
root.dispatchEvent(new TEvent("input", { bubbles: true, inputType, data, isComposing: false }));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The UTF-16 index of a UTF-8 offset (native reports selections in UTF-8). */
|
|
260
|
+
export function utf16Offset(text: string, bytes: number): number {
|
|
261
|
+
let count = 0;
|
|
262
|
+
for (let index = 0; index < text.length; index++) {
|
|
263
|
+
if (count >= bytes) return index;
|
|
264
|
+
const code = text.charCodeAt(index);
|
|
265
|
+
if (code < 0x80) count += 1;
|
|
266
|
+
else if (code < 0x800) count += 2;
|
|
267
|
+
else if (code >= 0xd800 && code <= 0xdbff) { count += 4; index++; }
|
|
268
|
+
else count += 3;
|
|
269
|
+
}
|
|
270
|
+
return text.length;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The focused editable's selection (UTF-16 offsets into its text), asked of native synchronously. */
|
|
274
|
+
export interface TextSelection { element: TElement; anchor: number; focus: number }
|
|
275
|
+
let readSelection: (() => TextSelection | undefined) | undefined;
|
|
276
|
+
export function setSelectionReader(next: (() => TextSelection | undefined) | undefined): void { readSelection = next; }
|
|
277
|
+
|
|
278
|
+
export function textOfEditable(element: TElement): string {
|
|
279
|
+
return element.isContentEditable ? editableModel(element).text : element.value ?? "";
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
class TRange {
|
|
283
|
+
constructor(readonly startContainer: TNode, readonly startOffset: number, readonly endContainer: TNode, readonly endOffset: number, private readonly text: string) {}
|
|
284
|
+
get collapsed(): boolean { return this.startContainer === this.endContainer && this.startOffset === this.endOffset; }
|
|
285
|
+
get commonAncestorContainer(): TNode {
|
|
286
|
+
for (let node: TNode | null = this.startContainer; node; node = node.parentNode) if (node.contains(this.endContainer)) return node;
|
|
287
|
+
return this.startContainer;
|
|
288
|
+
}
|
|
289
|
+
toString(): string { return this.text; }
|
|
290
|
+
cloneRange(): TRange { return this; }
|
|
291
|
+
getBoundingClientRect() { return (this.startContainer.nodeType === ELEMENT_NODE ? this.startContainer as TElement : this.startContainer.parentElement)?.getBoundingClientRect(); }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** window.getSelection(): the native selection inside a contenteditable (read-only: native owns the caret). */
|
|
295
|
+
class TSelection {
|
|
296
|
+
anchorNode: TNode | null = null;
|
|
297
|
+
anchorOffset = 0;
|
|
298
|
+
focusNode: TNode | null = null;
|
|
299
|
+
focusOffset = 0;
|
|
300
|
+
private range?: TRange;
|
|
301
|
+
constructor(selection?: TextSelection) {
|
|
302
|
+
if (!selection?.element.isContentEditable) return;
|
|
303
|
+
const { element, anchor, focus } = selection;
|
|
304
|
+
const start = Math.min(anchor, focus), end = Math.max(anchor, focus);
|
|
305
|
+
const a = domPosition(element, anchor), f = domPosition(element, focus);
|
|
306
|
+
this.anchorNode = a.node; this.anchorOffset = a.offset;
|
|
307
|
+
this.focusNode = f.node; this.focusOffset = f.offset;
|
|
308
|
+
const s = anchor <= focus ? a : f, e = anchor <= focus ? f : a;
|
|
309
|
+
this.range = new TRange(s.node, s.offset, e.node, e.offset, editableModel(element).text.slice(start, end));
|
|
310
|
+
}
|
|
311
|
+
get rangeCount(): number { return this.range ? 1 : 0; }
|
|
312
|
+
get isCollapsed(): boolean { return !this.range || this.range.collapsed; }
|
|
313
|
+
get type(): string { return !this.range ? "None" : this.range.collapsed ? "Caret" : "Range"; }
|
|
314
|
+
getRangeAt(index: number): TRange {
|
|
315
|
+
if (index !== 0 || !this.range) throw new RangeError("The index is not in the allowed range.");
|
|
316
|
+
return this.range;
|
|
317
|
+
}
|
|
318
|
+
toString(): string { return this.range?.toString() ?? ""; }
|
|
319
|
+
containsNode(node: TNode): boolean { return !!this.range && this.range.commonAncestorContainer.contains(node); }
|
|
320
|
+
removeAllRanges(): void {}
|
|
321
|
+
addRange(): void {}
|
|
322
|
+
collapse(): void {}
|
|
323
|
+
collapseToEnd(): void {}
|
|
324
|
+
collapseToStart(): void {}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const COMMANDS: Record<string, string> = { bold: "bold", italic: "italic", underline: "underline", strikethrough: "strikethrough" };
|
|
328
|
+
|
|
329
|
+
/** document.execCommand over the native selection of the focused contenteditable. */
|
|
330
|
+
function execCommand(command: string, _ui?: boolean, value?: string): boolean {
|
|
331
|
+
const selection = readSelection?.();
|
|
332
|
+
if (!selection?.element.isContentEditable) return false;
|
|
333
|
+
const { element } = selection;
|
|
334
|
+
let start = Math.min(selection.anchor, selection.focus), end = Math.max(selection.anchor, selection.focus);
|
|
335
|
+
const name = command.toLowerCase();
|
|
336
|
+
const format = COMMANDS[name];
|
|
337
|
+
if (format) {
|
|
338
|
+
if (!toggleFormat(element, format, start, end)) return false;
|
|
339
|
+
fireInput(element, "format" + format[0]!.toUpperCase() + format.slice(1).replace("through", "Through"), null);
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
const text = editableModel(element).text;
|
|
343
|
+
let inserted = "";
|
|
344
|
+
let inputType: string;
|
|
345
|
+
if (name === "inserttext") { inserted = String(value ?? ""); inputType = "insertText"; }
|
|
346
|
+
else if (name === "insertlinebreak" || name === "insertparagraph") { inserted = "\n"; inputType = name === "insertlinebreak" ? "insertLineBreak" : "insertParagraph"; }
|
|
347
|
+
else if (name === "delete") { if (start === end) start = Math.max(0, start - 1); inputType = "deleteContentBackward"; }
|
|
348
|
+
else if (name === "forwarddelete") { if (start === end) end = Math.min(text.length, end + 1); inputType = "deleteContentForward"; }
|
|
349
|
+
else return false;
|
|
350
|
+
if (start === end && !inserted) return false;
|
|
351
|
+
replaceRange(element, start, end, inserted);
|
|
352
|
+
fireInput(element, inputType, inserted || null);
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function queryCommandState(command: string): boolean {
|
|
357
|
+
const format = COMMANDS[command.toLowerCase()];
|
|
358
|
+
const selection = format ? readSelection?.() : undefined;
|
|
359
|
+
if (!format || !selection?.element.isContentEditable) return false;
|
|
360
|
+
return queryFormat(selection.element, format, Math.min(selection.anchor, selection.focus));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
setEditing({
|
|
364
|
+
getSelection: () => new TSelection(readSelection?.()),
|
|
365
|
+
execCommand,
|
|
366
|
+
queryCommandState,
|
|
367
|
+
queryCommandSupported: command => command.toLowerCase() in COMMANDS || ["inserttext", "insertlinebreak", "insertparagraph", "delete", "forwarddelete"].includes(command.toLowerCase()),
|
|
368
|
+
selectionOf: element => {
|
|
369
|
+
const selection = readSelection?.();
|
|
370
|
+
return selection && selection.element === element ? { start: Math.min(selection.anchor, selection.focus), end: Math.max(selection.anchor, selection.focus), backward: selection.focus < selection.anchor } : undefined;
|
|
371
|
+
},
|
|
372
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tarve's attributes and elements for Svelte's markup types (svelte-check, the
|
|
3
|
+
* Svelte language server). Applies wherever `@tarve/svelte` is part of the program.
|
|
4
|
+
*/
|
|
5
|
+
import type { HTMLAttributes } from "svelte/elements";
|
|
6
|
+
|
|
7
|
+
type Flag = boolean | "true" | "false" | "" | undefined | null;
|
|
8
|
+
|
|
9
|
+
interface TitleBarAttributes extends HTMLAttributes<HTMLElement> {
|
|
10
|
+
title?: string | undefined | null;
|
|
11
|
+
height?: number | string | undefined | null;
|
|
12
|
+
glass?: Flag | "regular" | "clear";
|
|
13
|
+
appearance?: "light" | "dark" | undefined | null;
|
|
14
|
+
"show-minimize"?: Flag;
|
|
15
|
+
"show-maximize"?: Flag;
|
|
16
|
+
"show-close"?: Flag;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
declare module "svelte/elements" {
|
|
20
|
+
export interface HTMLAttributes<T extends EventTarget> {
|
|
21
|
+
/** Drag the window by this element (a custom title bar, a widget body). */
|
|
22
|
+
"drag-region"?: Flag;
|
|
23
|
+
/** Make this element a window control. */
|
|
24
|
+
"window-action"?: "minimize" | "toggleMaximize" | "close" | undefined | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SvelteHTMLElements {
|
|
28
|
+
/** Tarve layout: a flex row. */
|
|
29
|
+
row: HTMLAttributes<HTMLElement>;
|
|
30
|
+
/** Tarve layout: a flex column. */
|
|
31
|
+
column: HTMLAttributes<HTMLElement>;
|
|
32
|
+
/** Tarve's plain box. */
|
|
33
|
+
view: HTMLAttributes<HTMLElement>;
|
|
34
|
+
/** Tarve's scroll container. */
|
|
35
|
+
scroll: HTMLAttributes<HTMLElement>;
|
|
36
|
+
/** Tarve's rendered Markdown (`source`). */
|
|
37
|
+
markdown: HTMLAttributes<HTMLElement> & { source?: string | undefined | null };
|
|
38
|
+
/** Tarve's custom title bar; prefer the `TitleBar` component. */
|
|
39
|
+
titlebar: TitleBarAttributes;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export {};
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { AppHandle } from "@tarve/core";
|
|
2
|
+
import type { NativeEvent } from "@tarve/core/protocol";
|
|
3
|
+
import { documentInstance, isFocusable, moveFocus, layout, restyleAll, scheduleIntersections, setFocusHook, setMediaHook, TEvent, windowInstance, type TElement } from "./dom";
|
|
4
|
+
import { resizeRestyles } from "./css";
|
|
5
|
+
import { elementForNativeId, nativeIdOf, setPointerPosition } from "./render";
|
|
6
|
+
|
|
7
|
+
const BUTTONS = [1, 4, 2, 8, 16];
|
|
8
|
+
const SHORTCUTS: Record<string, string> = { b: "bold", i: "italic", u: "underline" };
|
|
9
|
+
let buttons = 0;
|
|
10
|
+
|
|
11
|
+
/** Native events that are not one element's handler: keys, focus, the window size. */
|
|
12
|
+
export function connectNativeEvents(app: AppHandle): () => void {
|
|
13
|
+
setFocusHook(element => { if (element) app.focus(nativeIdOf(element)); });
|
|
14
|
+
setMediaHook((element, action, value) => {
|
|
15
|
+
const media = app.media(nativeIdOf(element));
|
|
16
|
+
if (action === "seek") media.seek(value ?? 0); else media[action]();
|
|
17
|
+
});
|
|
18
|
+
const off = app.onEvent((event: NativeEvent) => {
|
|
19
|
+
switch (event.type) {
|
|
20
|
+
case "keyboard": {
|
|
21
|
+
const focused = elementForNativeId(event.id) ?? null;
|
|
22
|
+
// Native names the focused node with every key: script focus follows it.
|
|
23
|
+
if (focused !== documentInstance.activeElement && (focused === null || isFocusable(focused))) moveFocus(focused, true);
|
|
24
|
+
const target: TElement = documentInstance.activeElement ?? documentInstance.body;
|
|
25
|
+
const proceed = target.dispatchEvent(new TEvent(event.phase === "down" ? "keydown" : "keyup", {
|
|
26
|
+
bubbles: true, cancelable: true, composed: true,
|
|
27
|
+
key: event.key, code: event.code, repeat: event.repeat,
|
|
28
|
+
ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, metaKey: event.metaKey,
|
|
29
|
+
isComposing: false, location: 0,
|
|
30
|
+
getModifierState: (key: string) => ({ Control: event.ctrlKey, Alt: event.altKey, Shift: event.shiftKey, Meta: event.metaKey } as Record<string, boolean>)[key] ?? false,
|
|
31
|
+
}));
|
|
32
|
+
// A contenteditable's formatting shortcuts, unless a keydown handler cancelled them.
|
|
33
|
+
const shortcut = SHORTCUTS[event.key.toLowerCase()];
|
|
34
|
+
if (proceed && shortcut && event.phase === "down" && (event.ctrlKey || event.metaKey) && !event.altKey && target.isContentEditable) documentInstance.execCommand(shortcut);
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
case "pointer": {
|
|
38
|
+
setPointerPosition(event.x, event.y);
|
|
39
|
+
const target: TElement = elementForNativeId(event.id) ?? documentInstance.body;
|
|
40
|
+
const position = { clientX: event.x, clientY: event.y, pageX: event.x, pageY: event.y, screenX: event.x, screenY: event.y, offsetX: event.x - (target._box?.x ?? 0), offsetY: event.y - (target._box?.y ?? 0) };
|
|
41
|
+
const modifiers = { ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, metaKey: event.metaKey };
|
|
42
|
+
if (event.phase === "wheel") {
|
|
43
|
+
target.dispatchEvent(new TEvent("wheel", { bubbles: true, cancelable: true, ...position, ...modifiers, deltaX: event.deltaX ?? 0, deltaY: event.deltaY ?? 0, deltaZ: 0, deltaMode: 0, buttons }));
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
const button = event.button ?? 0;
|
|
47
|
+
if (event.phase === "down") buttons |= BUTTONS[button] ?? 0; else buttons &= ~(BUTTONS[button] ?? 0);
|
|
48
|
+
const init = { bubbles: true, cancelable: true, composed: true, ...position, ...modifiers, button, buttons, pointerId: 1, pointerType: "mouse", isPrimary: true };
|
|
49
|
+
const kind = event.phase === "down" ? "down" : "up";
|
|
50
|
+
target.dispatchEvent(new TEvent(`pointer${kind}`, init));
|
|
51
|
+
target.dispatchEvent(new TEvent(`mouse${kind}`, init));
|
|
52
|
+
// Other buttons click as auxclick; the primary click comes from native activation.
|
|
53
|
+
if (kind === "up" && button === 1) target.dispatchEvent(new TEvent("auxclick", init));
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
case "size": {
|
|
57
|
+
elementForNativeId(event.id)?._sized(event);
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
case "blur": {
|
|
61
|
+
const element = elementForNativeId(event.id);
|
|
62
|
+
if (element && element === documentInstance.activeElement) moveFocus(null, true);
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
case "click": case "change": case "submit": case "valueChange": {
|
|
66
|
+
// Clicking or editing a control focuses it natively.
|
|
67
|
+
const element = elementForNativeId(event.id);
|
|
68
|
+
if (element && isFocusable(element) && element !== documentInstance.activeElement) moveFocus(element, true);
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
return () => { off(); setFocusHook(undefined); setMediaHook(undefined); };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The window's content size changed: `window.innerWidth`, `bind:innerWidth`, `onresize`. */
|
|
77
|
+
export function windowResized(size: { width: number; height: number }): void {
|
|
78
|
+
if (windowInstance.innerWidth === size.width && windowInstance.innerHeight === size.height) return;
|
|
79
|
+
const before = { width: windowInstance.innerWidth, height: windowInstance.innerHeight };
|
|
80
|
+
windowInstance.innerWidth = size.width;
|
|
81
|
+
windowInstance.innerHeight = size.height;
|
|
82
|
+
layout.epoch++;
|
|
83
|
+
// @media width queries and vw/vh: restyle once a threshold is crossed.
|
|
84
|
+
if (resizeRestyles(before, size)) restyleAll(documentInstance);
|
|
85
|
+
windowInstance.dispatchEvent(new TEvent("resize"));
|
|
86
|
+
scheduleIntersections();
|
|
87
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/// <reference path="./elements.d.ts" />
|
|
2
|
+
import "./install";
|
|
3
|
+
import { createApp, TitleBar as NativeTitleBar, Window, type AppHandle, type AppOptions, type TitleBarProps, type WindowProps } from "@tarve/core";
|
|
4
|
+
import type { Component } from "svelte";
|
|
5
|
+
import { flushSync, mount as mountSvelte, unmount as unmountSvelte } from "./svelte-client";
|
|
6
|
+
import { beginRender, documentInstance, endRender, restyle, setLayoutReader, setScheduler, type TElement } from "./dom";
|
|
7
|
+
import { elementForNativeId, nativeIdOf, rootChildren } from "./render";
|
|
8
|
+
import { setSelectionReader, textOfEditable, utf16Offset } from "./editable";
|
|
9
|
+
import { connectNativeEvents, windowResized } from "./events";
|
|
10
|
+
|
|
11
|
+
export { installDom, TEvent } from "./dom";
|
|
12
|
+
export { default as TitleBar } from "./TitleBar.svelte";
|
|
13
|
+
export { registerCss, parseCss, cssStyle } from "./css";
|
|
14
|
+
export type { CssRule } from "./css";
|
|
15
|
+
|
|
16
|
+
export interface MountOptions<Props extends Record<string, any>> extends AppOptions {
|
|
17
|
+
props?: Props;
|
|
18
|
+
context?: Map<any, any>;
|
|
19
|
+
/** The native window: title, size, theme… `<svelte:head><title>` overrides the title. */
|
|
20
|
+
window?: Omit<WindowProps, "children"> & {
|
|
21
|
+
/**
|
|
22
|
+
* Draw Tarve's title bar instead of the native frame, showing the
|
|
23
|
+
* `<svelte:head><title>`: `true`, or its options. For a bar with your own
|
|
24
|
+
* content, use the `TitleBar` component instead.
|
|
25
|
+
*/
|
|
26
|
+
titleBar?: boolean | Omit<TitleBarProps, "children" | "title">;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SvelteApp<Exports> {
|
|
31
|
+
app: AppHandle;
|
|
32
|
+
component: Exports;
|
|
33
|
+
/** The element the component renders into (Svelte's mount target). */
|
|
34
|
+
target: TElement;
|
|
35
|
+
unmount(): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let mounted = false;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Mounts a Svelte 5 component in a native Tarve window. Svelte keeps its own
|
|
42
|
+
* fine-grained updates; each update re-renders only the elements it touched.
|
|
43
|
+
*/
|
|
44
|
+
export function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(
|
|
45
|
+
component: Component<Props, Exports>,
|
|
46
|
+
options: MountOptions<Props> = {},
|
|
47
|
+
): SvelteApp<Exports> {
|
|
48
|
+
if (mounted) throw new Error("@tarve/svelte mounts one app per process.");
|
|
49
|
+
const { props, context, window: windowProps = {}, ...appOptions } = options;
|
|
50
|
+
// Until native reports the content size, the window's requested size stands in (Window's defaults).
|
|
51
|
+
windowResized({ width: windowProps.width ?? 1120, height: windowProps.height ?? 820 });
|
|
52
|
+
const target = documentInstance.createElement("tarve-root");
|
|
53
|
+
documentInstance.body.appendChild(target);
|
|
54
|
+
const { titleBar, ...windowOptions } = windowProps;
|
|
55
|
+
// Options are camelCase like every other one (`minWidth`): `titlebar` would be silently ignored.
|
|
56
|
+
for (const key of Object.keys(windowOptions)) {
|
|
57
|
+
if (key.toLowerCase() === "titlebar") console.warn(`[tarve/svelte] window.${key} is not an option; did you mean window.titleBar?`);
|
|
58
|
+
}
|
|
59
|
+
let app: AppHandle | undefined;
|
|
60
|
+
let disconnect: () => void = () => {};
|
|
61
|
+
/** The native window, created from the mounted DOM: after the first flush, or at the first layout read. */
|
|
62
|
+
const start = (): AppHandle => {
|
|
63
|
+
if (app) return app;
|
|
64
|
+
app = createApp(() => {
|
|
65
|
+
const title = documentInstance.title || windowOptions.title;
|
|
66
|
+
beginRender();
|
|
67
|
+
let content;
|
|
68
|
+
try { content = rootChildren(target); } finally { endRender(); }
|
|
69
|
+
return Window({
|
|
70
|
+
...windowOptions,
|
|
71
|
+
title,
|
|
72
|
+
onSize: windowResized,
|
|
73
|
+
// A window has one title bar: a <TitleBar> in the component wins over the option's.
|
|
74
|
+
children: titleBar && !target.querySelector("titlebar") ? [NativeTitleBar({ ...(titleBar === true ? {} : titleBar), title }), content] : content,
|
|
75
|
+
});
|
|
76
|
+
}, { keyboardEvents: true, pointerEvents: true, ...appOptions });
|
|
77
|
+
disconnect = connectNativeEvents(app);
|
|
78
|
+
return app;
|
|
79
|
+
};
|
|
80
|
+
setScheduler(() => app?.update());
|
|
81
|
+
// A layout read (getBoundingClientRect, offsetWidth…) is answered by native synchronously;
|
|
82
|
+
// one in onMount opens the window first.
|
|
83
|
+
setLayoutReader(elements => {
|
|
84
|
+
const ids = elements.map(nativeIdOf);
|
|
85
|
+
const boxes = start().layout(ids);
|
|
86
|
+
if (!boxes) return false;
|
|
87
|
+
elements.forEach((element, index) => { const box = boxes[ids[index]!]; if (box) element._sized(box); });
|
|
88
|
+
return true;
|
|
89
|
+
});
|
|
90
|
+
// window.getSelection(), execCommand and input.selectionStart read the native selection.
|
|
91
|
+
setSelectionReader(() => {
|
|
92
|
+
const selection = app?.textSelection();
|
|
93
|
+
const element = selection && elementForNativeId(selection.id);
|
|
94
|
+
if (!selection || !element) return undefined;
|
|
95
|
+
const text = textOfEditable(element);
|
|
96
|
+
return { element, anchor: utf16Offset(text, selection.anchor), focus: utf16Offset(text, selection.focus) };
|
|
97
|
+
});
|
|
98
|
+
documentInstance.onTitle = () => {
|
|
99
|
+
// A title bar without its own title shows the document's: it renders again.
|
|
100
|
+
for (const bar of target.querySelectorAll("titlebar")) if (!bar.hasAttribute("title")) restyle(bar);
|
|
101
|
+
app?.update();
|
|
102
|
+
};
|
|
103
|
+
const instance = mountSvelte(component, { target: target as unknown as Element, props: (props ?? {}) as Props, ...(context ? { context } : {}) });
|
|
104
|
+
mounted = true;
|
|
105
|
+
// Effects (<svelte:head>, onMount) run here: the window opens with their title.
|
|
106
|
+
flushSync();
|
|
107
|
+
const handle = start();
|
|
108
|
+
return {
|
|
109
|
+
app: handle,
|
|
110
|
+
component: instance,
|
|
111
|
+
target,
|
|
112
|
+
async unmount() {
|
|
113
|
+
// The window closes with the app as it was: tearing the component down renders nothing.
|
|
114
|
+
setScheduler(undefined);
|
|
115
|
+
setLayoutReader(undefined);
|
|
116
|
+
setSelectionReader(undefined);
|
|
117
|
+
documentInstance.onTitle = undefined;
|
|
118
|
+
await unmountSvelte(instance);
|
|
119
|
+
disconnect();
|
|
120
|
+
documentInstance.onTitle = undefined;
|
|
121
|
+
target.remove();
|
|
122
|
+
mounted = false;
|
|
123
|
+
handle.close();
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
package/src/install.ts
ADDED