@tarve/svelte 0.9.0 → 0.10.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/package.json +2 -2
- package/src/css.ts +581 -28
- package/src/dom-animation.ts +30 -4
- package/src/dom.ts +134 -8
- package/src/events.ts +18 -6
- package/src/index.ts +18 -8
- package/src/plugin.ts +32 -7
- package/src/render.ts +387 -25
- package/src/selectors.ts +31 -5
package/src/dom-animation.ts
CHANGED
|
@@ -1,16 +1,42 @@
|
|
|
1
1
|
|
|
2
2
|
export type Keyframe = { offset: number; values: Record<string, string> };
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* The value a property animates from (or to) when a keyframe leaves it out: the element's own
|
|
6
|
+
* value when known, else the property's neutral one (`transform: rotate(360deg)` → `rotate(0deg)`,
|
|
7
|
+
* `opacity` → 1), as CSS's implicit `from`/`to` keyframes take the underlying value.
|
|
8
|
+
*/
|
|
9
|
+
export function neutralValue(key: string, value: string): string {
|
|
10
|
+
if (key === "opacity") return "1";
|
|
11
|
+
if (key === "transform") {
|
|
12
|
+
if (value.trim() === "none") return "none";
|
|
13
|
+
return value.replace(/([a-zA-Z0-9]+)\(([^)]*)\)/g, (_match, fn: string, args: string) =>
|
|
14
|
+
`${fn}(${args.replace(NUMBER, () => (/^scale/i.test(fn) ? "1" : "0"))})`);
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Keyframes with offsets (missing ones spread evenly, as Web Animations does). A missing first or last
|
|
21
|
+
* keyframe (`@keyframes spin { to { transform: rotate(360deg) } }`) is implicit: each property starts
|
|
22
|
+
* or ends at `underlying(key)`, else its neutral value.
|
|
23
|
+
*/
|
|
24
|
+
export function keyframesOf(input: Record<string, string | number | null | undefined>[], underlying?: (key: string) => string | undefined): Keyframe[] {
|
|
6
25
|
const frames = input.map(frame => {
|
|
7
26
|
const values: Record<string, string> = {};
|
|
8
27
|
for (const [key, value] of Object.entries(frame)) if (key !== "offset" && key !== "easing" && key !== "composite" && value != null) values[key] = String(value);
|
|
9
28
|
return { offset: typeof frame.offset === "number" ? frame.offset : NaN, values };
|
|
10
29
|
});
|
|
11
|
-
if (frames.length === 1
|
|
30
|
+
if (frames.length === 1 && Number.isNaN(frames[0]!.offset)) frames[0]!.offset = 1;
|
|
12
31
|
frames.forEach((frame, index) => { if (Number.isNaN(frame.offset)) frame.offset = frames.length > 1 ? index / (frames.length - 1) : 0; });
|
|
13
|
-
|
|
32
|
+
frames.sort((a, b) => a.offset - b.offset);
|
|
33
|
+
const implicit = (from: Keyframe, offset: number): Keyframe => ({
|
|
34
|
+
offset,
|
|
35
|
+
values: Object.fromEntries(Object.entries(from.values).map(([key, value]) => [key, underlying?.(key) ?? neutralValue(key, value)])),
|
|
36
|
+
});
|
|
37
|
+
if (frames.length && frames[0]!.offset > 0) frames.unshift(implicit(frames[0]!, 0));
|
|
38
|
+
if (frames.length && frames.at(-1)!.offset < 1) frames.push(implicit(frames.at(-1)!, 1));
|
|
39
|
+
return frames;
|
|
14
40
|
}
|
|
15
41
|
|
|
16
42
|
export const COLOR = /#([0-9a-f]{3,8})\b|rgba?\(([^)]*)\)/gi;
|
package/src/dom.ts
CHANGED
|
@@ -156,14 +156,38 @@ export function setLayoutReader(next: ((elements: TElement[]) => boolean) | unde
|
|
|
156
156
|
export function beginRender(): void { layout.rendering = true; layout.rendered = layout.epoch; }
|
|
157
157
|
export function endRender(): void { layout.rendering = false; }
|
|
158
158
|
|
|
159
|
+
/**
|
|
160
|
+
* The element standing for the browser viewport: the box the page lays out in, under any title bar.
|
|
161
|
+
* Client rects (`getBoundingClientRect`) are relative to it, as a page's are to its viewport.
|
|
162
|
+
*/
|
|
163
|
+
let viewportElement: TElement | undefined;
|
|
164
|
+
export function setViewportElement(element: TElement | undefined): void { viewportElement = element; }
|
|
165
|
+
|
|
166
|
+
/** A point in window coordinates (native pointer events) in the viewport's, as `clientX`/`clientY` are. */
|
|
167
|
+
export function windowToClient(x: number, y: number): { x: number; y: number } {
|
|
168
|
+
const origin = viewportElement?._box;
|
|
169
|
+
return origin ? { x: x - origin.x, y: y - origin.y } : { x, y };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* A point native reports relative to `element`'s border box (`pointerMove`) in client coordinates:
|
|
174
|
+
* the box's client rect plus the offset. Undefined until native has reported where the box is.
|
|
175
|
+
*/
|
|
176
|
+
export function elementToClient(element: TElement, x: number, y: number): { x: number; y: number } | undefined {
|
|
177
|
+
const box = clientBox(element);
|
|
178
|
+
return box ? { x: box.x + x, y: box.y + y } : undefined;
|
|
179
|
+
}
|
|
180
|
+
|
|
159
181
|
function readLayout(element: TElement, withParent: boolean): void {
|
|
160
182
|
if (!layoutReader || layout.rendering || !element.isConnected) return;
|
|
161
183
|
const stale = (item: TElement) => item._boxEpoch !== layout.epoch;
|
|
162
184
|
const parent = withParent ? element.parentElement : null;
|
|
163
|
-
|
|
185
|
+
const viewport = viewportElement && viewportElement !== element && stale(viewportElement) ? viewportElement : undefined;
|
|
186
|
+
if (!stale(element) && !(parent && stale(parent)) && !viewport) return;
|
|
164
187
|
// One round trip answers every element something reads: a loop of reads costs one layout.
|
|
165
188
|
const wanted = new Set<TElement>([element]);
|
|
166
189
|
if (parent) wanted.add(parent);
|
|
190
|
+
if (viewport) wanted.add(viewport);
|
|
167
191
|
for (const item of measuredElements) {
|
|
168
192
|
if (!item.isConnected) measuredElements.delete(item);
|
|
169
193
|
else if (wanted.size < 512 && stale(item)) wanted.add(item);
|
|
@@ -619,8 +643,15 @@ export class TElement extends TNode {
|
|
|
619
643
|
_cssVariables?: { version: number; map: Map<string, string> | undefined };
|
|
620
644
|
/** The CSS `animation` running on this element, keyed by its parsed shorthand. */
|
|
621
645
|
_cssAnimation?: { key: string; animation: unknown };
|
|
622
|
-
|
|
623
|
-
|
|
646
|
+
/** Scroll offsets and reach as native last reported them (scroll events, layout reads). */
|
|
647
|
+
_scrollTop = 0;
|
|
648
|
+
_scrollLeft = 0;
|
|
649
|
+
_scrollMaxX = 0;
|
|
650
|
+
_scrollMaxY = 0;
|
|
651
|
+
get scrollTop(): number { return this._scrollTop; }
|
|
652
|
+
set scrollTop(value: number) { this.scrollTo({ top: value }); }
|
|
653
|
+
get scrollLeft(): number { return this._scrollLeft; }
|
|
654
|
+
set scrollLeft(value: number) { this.scrollTo({ left: value }); }
|
|
624
655
|
constructor(tag: string, namespace = HTML_NAMESPACE) {
|
|
625
656
|
super();
|
|
626
657
|
this.namespaceURI = namespace;
|
|
@@ -804,8 +835,14 @@ export class TElement extends TNode {
|
|
|
804
835
|
this._measure();
|
|
805
836
|
readLayout(this, withParent);
|
|
806
837
|
}
|
|
807
|
-
_sized(size: { width: number; height: number; x?: number; y?: number; borderWidth?: number; borderHeight?: number }): void {
|
|
838
|
+
_sized(size: { width: number; height: number; x?: number; y?: number; borderWidth?: number; borderHeight?: number; scrollX?: number; scrollY?: number; scrollMaxX?: number; scrollMaxY?: number }): void {
|
|
808
839
|
this._boxEpoch = layout.rendered;
|
|
840
|
+
if (size.scrollY !== undefined) {
|
|
841
|
+
this._scrollLeft = size.scrollX ?? 0;
|
|
842
|
+
this._scrollTop = size.scrollY;
|
|
843
|
+
this._scrollMaxX = size.scrollMaxX ?? 0;
|
|
844
|
+
this._scrollMaxY = size.scrollMaxY ?? 0;
|
|
845
|
+
}
|
|
809
846
|
const previous = this._size;
|
|
810
847
|
this._size = { width: size.width, height: size.height };
|
|
811
848
|
if (size.x !== undefined && size.y !== undefined) this._box = { x: size.x, y: size.y, width: size.borderWidth ?? size.width, height: size.borderHeight ?? size.height };
|
|
@@ -833,6 +870,20 @@ export class TElement extends TNode {
|
|
|
833
870
|
return domRect(clientBox(this) ?? { x: 0, y: 0, ...(this._size ?? { width: 0, height: 0 }) });
|
|
834
871
|
}
|
|
835
872
|
getClientRects() { return [this.getBoundingClientRect()]; }
|
|
873
|
+
// Pointer capture (a drag that keeps going outside the element): native reports to it alone.
|
|
874
|
+
setPointerCapture(_pointerId?: number): void {
|
|
875
|
+
if (!this.isConnected) throw new DOMException("setPointerCapture on a disconnected element", "InvalidStateError");
|
|
876
|
+
if (pointerCapture === this) return;
|
|
877
|
+
const previous = pointerCapture;
|
|
878
|
+
pointerCapture = this;
|
|
879
|
+
previous?.dispatchEvent(new TEvent("lostpointercapture", { bubbles: true, pointerId: 1 }));
|
|
880
|
+
pointerCaptureHook?.(this);
|
|
881
|
+
this.dispatchEvent(new TEvent("gotpointercapture", { bubbles: true, pointerId: 1 }));
|
|
882
|
+
}
|
|
883
|
+
releasePointerCapture(_pointerId?: number): void {
|
|
884
|
+
if (pointerCapture === this) releasePointerCapture();
|
|
885
|
+
}
|
|
886
|
+
hasPointerCapture(_pointerId?: number): boolean { return pointerCapture === this; }
|
|
836
887
|
get clientWidth(): number { this._layout(); return this._size?.width ?? 0; }
|
|
837
888
|
get clientHeight(): number { this._layout(); return this._size?.height ?? 0; }
|
|
838
889
|
get offsetWidth(): number { this._layout(); return this._box?.width ?? this._size?.width ?? 0; }
|
|
@@ -840,8 +891,8 @@ export class TElement extends TNode {
|
|
|
840
891
|
get offsetLeft(): number { this._layout(true); return (this._box?.x ?? 0) - (this.parentElement?._box?.x ?? 0); }
|
|
841
892
|
get offsetTop(): number { this._layout(true); return (this._box?.y ?? 0) - (this.parentElement?._box?.y ?? 0); }
|
|
842
893
|
get offsetParent(): TElement | null { return this.parentElement; }
|
|
843
|
-
get scrollWidth(): number {
|
|
844
|
-
get scrollHeight(): number {
|
|
894
|
+
get scrollWidth(): number { const width = this.clientWidth; return width + this._scrollMaxX; }
|
|
895
|
+
get scrollHeight(): number { const height = this.clientHeight; return height + this._scrollMaxY; }
|
|
845
896
|
/** input/textarea selection, read from native while the field has focus. */
|
|
846
897
|
get selectionStart(): number | null { return this._textSelection()?.start ?? this._valueLength(); }
|
|
847
898
|
get selectionEnd(): number | null { return this._textSelection()?.end ?? this._valueLength(); }
|
|
@@ -855,7 +906,24 @@ export class TElement extends TNode {
|
|
|
855
906
|
}
|
|
856
907
|
get innerText(): string { return this.textContent ?? ""; }
|
|
857
908
|
set innerText(value: string) { this.textContent = value; }
|
|
858
|
-
scrollTo()
|
|
909
|
+
/** DOM scrollTo(x, y) or scrollTo({ left, top, behavior }): native scrolls after the next layout. */
|
|
910
|
+
scrollTo(first?: number | { left?: number; top?: number; behavior?: string }, second?: number): void {
|
|
911
|
+
const options = typeof first === "object" && first ? first : first === undefined ? {} : { left: Number(first), top: Number(second ?? 0) };
|
|
912
|
+
const left = options.left === undefined ? undefined : Number(options.left);
|
|
913
|
+
const top = options.top === undefined ? undefined : Number(options.top);
|
|
914
|
+
if ((left !== undefined && Number.isNaN(left)) || (top !== undefined && Number.isNaN(top))) return;
|
|
915
|
+
// Known now: clamped to the reach native last reported (it applies the exact end after layout).
|
|
916
|
+
const clamp = (value: number, max: number) => Math.max(0, max > 0 ? Math.min(value, max) : value);
|
|
917
|
+
if (left !== undefined) this._scrollLeft = clamp(left, this._scrollMaxX);
|
|
918
|
+
if (top !== undefined) this._scrollTop = clamp(top, this._scrollMaxY);
|
|
919
|
+
// Layout reads after this see native's offsets, not the guess above.
|
|
920
|
+
this._boxEpoch = -1;
|
|
921
|
+
scrollHook?.(this, left, top, options.behavior === "smooth");
|
|
922
|
+
}
|
|
923
|
+
scrollBy(first?: number | { left?: number; top?: number; behavior?: string }, second?: number): void {
|
|
924
|
+
const options = typeof first === "object" && first ? first : { left: Number(first ?? 0), top: Number(second ?? 0) };
|
|
925
|
+
this.scrollTo({ left: this._scrollLeft + Number(options.left ?? 0), top: this._scrollTop + Number(options.top ?? 0), behavior: options.behavior });
|
|
926
|
+
}
|
|
859
927
|
scrollIntoView(): void {}
|
|
860
928
|
querySelector(selector: string): TElement | null { return query(this, selector, true)[0] ?? null; }
|
|
861
929
|
querySelectorAll(selector: string): TElement[] { return query(this, selector, false); }
|
|
@@ -899,7 +967,8 @@ export class TElement extends TNode {
|
|
|
899
967
|
const iterations = timing.iterations === undefined ? 1 : Math.max(0, Number(timing.iterations));
|
|
900
968
|
const direction = timing.direction ?? "normal";
|
|
901
969
|
const ease = easing(timing.easing ?? "linear");
|
|
902
|
-
|
|
970
|
+
// An implicit first/last keyframe takes the element's own (inline) value, else the neutral one.
|
|
971
|
+
const frames = keyframesOf(keyframes ?? [], key => this.style?.getPropertyValue(key.replace(/[A-Z]/g, char => "-" + char.toLowerCase())) || undefined);
|
|
903
972
|
const element = this;
|
|
904
973
|
let resolveFinished!: () => void;
|
|
905
974
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -1139,6 +1208,9 @@ export class TDocument extends TNode {
|
|
|
1139
1208
|
readonly body: TElement;
|
|
1140
1209
|
activeElement: TElement | null = null;
|
|
1141
1210
|
readonly readyState = "complete";
|
|
1211
|
+
/** The window is shown (a minimized or hidden one still runs its app, as a background tab does). */
|
|
1212
|
+
visibilityState: "visible" | "hidden" = "visible";
|
|
1213
|
+
get hidden(): boolean { return this.visibilityState === "hidden"; }
|
|
1142
1214
|
_title = "";
|
|
1143
1215
|
onTitle?: (title: string) => void;
|
|
1144
1216
|
constructor() {
|
|
@@ -1181,12 +1253,38 @@ export class TDocument extends TNode {
|
|
|
1181
1253
|
hasFocus(): boolean { return true; }
|
|
1182
1254
|
}
|
|
1183
1255
|
|
|
1256
|
+
/** `sessionStorage`: string pairs that live as long as the app (one session, as a browser tab's). */
|
|
1257
|
+
export class TStorage {
|
|
1258
|
+
private _items = new Map<string, string>();
|
|
1259
|
+
get length(): number { return this._items.size; }
|
|
1260
|
+
key(index: number): string | null { return [...this._items.keys()][index] ?? null; }
|
|
1261
|
+
getItem(key: string): string | null { return this._items.get(String(key)) ?? null; }
|
|
1262
|
+
setItem(key: string, value: string): void { this._items.set(String(key), String(value)); }
|
|
1263
|
+
removeItem(key: string): void { this._items.delete(String(key)); }
|
|
1264
|
+
clear(): void { this._items.clear(); }
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1184
1267
|
export class TWindow extends TEventTarget {
|
|
1185
1268
|
getSelection(): unknown { return documentInstance.getSelection(); }
|
|
1269
|
+
// In a browser `window` is the global object: `window.setTimeout(…)` and friends work on it too.
|
|
1270
|
+
setTimeout(handler: (...args: unknown[]) => void, timeout?: number, ...args: unknown[]) { return globalThis.setTimeout(handler, timeout, ...args); }
|
|
1271
|
+
clearTimeout(id?: ReturnType<typeof setTimeout>) { globalThis.clearTimeout(id); }
|
|
1272
|
+
setInterval(handler: (...args: unknown[]) => void, timeout?: number, ...args: unknown[]) { return globalThis.setInterval(handler, timeout, ...args); }
|
|
1273
|
+
clearInterval(id?: ReturnType<typeof setInterval>) { globalThis.clearInterval(id); }
|
|
1274
|
+
requestAnimationFrame(callback: (time: number) => void) { return (globalThis as unknown as { requestAnimationFrame(callback: (time: number) => void): unknown }).requestAnimationFrame(callback); }
|
|
1275
|
+
cancelAnimationFrame(id: unknown) { (globalThis as unknown as { cancelAnimationFrame(id: unknown): void }).cancelAnimationFrame(id); }
|
|
1276
|
+
queueMicrotask(callback: () => void) { globalThis.queueMicrotask(callback); }
|
|
1277
|
+
get sessionStorage(): TStorage { return (globalThis as unknown as { sessionStorage: TStorage }).sessionStorage; }
|
|
1278
|
+
get performance() { return globalThis.performance; }
|
|
1279
|
+
get console() { return globalThis.console; }
|
|
1280
|
+
get navigator() { return (globalThis as unknown as { navigator: unknown }).navigator; }
|
|
1281
|
+
get location() { return locationInstance; }
|
|
1186
1282
|
innerWidth = 1120;
|
|
1187
1283
|
innerHeight = 820;
|
|
1188
1284
|
/** `prefers-color-scheme: dark`. */
|
|
1189
1285
|
_dark = false;
|
|
1286
|
+
/** The window fills the screen (`@media (display-mode: fullscreen)`). */
|
|
1287
|
+
_fullscreen = false;
|
|
1190
1288
|
devicePixelRatio = 1;
|
|
1191
1289
|
get document(): TDocument { return documentInstance; }
|
|
1192
1290
|
/**
|
|
@@ -1320,6 +1418,27 @@ export function isFocusable(element: TElement): boolean {
|
|
|
1320
1418
|
return tabindex !== null && Number.isFinite(Number(tabindex));
|
|
1321
1419
|
}
|
|
1322
1420
|
|
|
1421
|
+
let pointerCapture: TElement | undefined;
|
|
1422
|
+
let pointerCaptureHook: ((element: TElement | null) => void) | undefined;
|
|
1423
|
+
let scrollHook: ((element: TElement, left: number | undefined, top: number | undefined, smooth: boolean) => void) | undefined;
|
|
1424
|
+
/** Element scrollTo, scrollTop = … reach native; the mount sets this. */
|
|
1425
|
+
export function setScrollHook(hook: typeof scrollHook): void { scrollHook = hook; }
|
|
1426
|
+
/** Native pointer capture follows `setPointerCapture`; the mount sets this. */
|
|
1427
|
+
export function setPointerCaptureHook(hook: ((element: TElement | null) => void) | undefined): void { pointerCaptureHook = hook; }
|
|
1428
|
+
/** The element holding pointer capture: pointer events go to it. */
|
|
1429
|
+
export function capturedElement(): TElement | undefined {
|
|
1430
|
+
if (pointerCapture && !pointerCapture.isConnected) releasePointerCapture();
|
|
1431
|
+
return pointerCapture;
|
|
1432
|
+
}
|
|
1433
|
+
/** Ends pointer capture (`releasePointerCapture`, or a released button: implicit release). */
|
|
1434
|
+
export function releasePointerCapture(): void {
|
|
1435
|
+
const previous = pointerCapture;
|
|
1436
|
+
if (!previous) return;
|
|
1437
|
+
pointerCapture = undefined;
|
|
1438
|
+
pointerCaptureHook?.(null);
|
|
1439
|
+
previous.dispatchEvent(new TEvent("lostpointercapture", { bubbles: true, pointerId: 1 }));
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1323
1442
|
let focusHook: ((element: TElement | null) => void) | undefined;
|
|
1324
1443
|
/** Native focus follows script focus (`element.focus()`); the mount sets this. */
|
|
1325
1444
|
export function setFocusHook(hook: ((element: TElement | null) => void) | undefined): void { focusHook = hook; }
|
|
@@ -1402,6 +1521,9 @@ function clientBox(element: TElement): Rect | undefined {
|
|
|
1402
1521
|
if (!box) return undefined;
|
|
1403
1522
|
let { x, y } = box;
|
|
1404
1523
|
for (let parent = element.parentElement; parent; parent = parent.parentElement) { x -= parent.scrollLeft; y -= parent.scrollTop; }
|
|
1524
|
+
// Window coordinates → the viewport's (the title bar is not part of the page).
|
|
1525
|
+
const origin = viewportElement !== element ? viewportElement?._box : undefined;
|
|
1526
|
+
if (origin) { x -= origin.x; y -= origin.y; }
|
|
1405
1527
|
return { x, y, width: box.width, height: box.height };
|
|
1406
1528
|
}
|
|
1407
1529
|
|
|
@@ -1496,6 +1618,9 @@ class TIntersectionObserver {
|
|
|
1496
1618
|
}
|
|
1497
1619
|
}
|
|
1498
1620
|
|
|
1621
|
+
/** `location`: an app has one page; its URL is `app://local/`. */
|
|
1622
|
+
const locationInstance = { href: "app://local/", origin: "app://local", protocol: "app:", host: "local", hostname: "local", pathname: "/", search: "", hash: "", reload() {}, assign() {}, replace() {}, toString() { return this.href; } };
|
|
1623
|
+
|
|
1499
1624
|
/** Selection and editing commands, provided by the contenteditable module. */
|
|
1500
1625
|
interface Editing {
|
|
1501
1626
|
getSelection(): unknown;
|
|
@@ -1519,6 +1644,7 @@ export function installDom(): void {
|
|
|
1519
1644
|
customElements: { get: () => undefined, define() {}, whenDefined: () => Promise.resolve() },
|
|
1520
1645
|
DataTransfer: TDataTransfer, MutationObserver: TMutationObserver, ResizeObserver: TResizeObserver, IntersectionObserver: TIntersectionObserver,
|
|
1521
1646
|
getComputedStyle: (element: TElement) => windowInstance.getComputedStyle(element),
|
|
1647
|
+
sessionStorage: new TStorage(), Storage: TStorage, location: locationInstance,
|
|
1522
1648
|
requestAnimationFrame: (callback: (time: number) => void) => setTimeout(() => callback(performance.now()), 16),
|
|
1523
1649
|
cancelAnimationFrame: (id: ReturnType<typeof setTimeout>) => clearTimeout(id),
|
|
1524
1650
|
};
|
package/src/events.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AppHandle } from "@tarve/core";
|
|
2
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";
|
|
3
|
+
import { documentInstance, isFocusable, moveFocus, layout, restyleAll, scheduleIntersections, setFocusHook, setMediaHook, TEvent, windowInstance, windowToClient, capturedElement, releasePointerCapture, setPointerCaptureHook, setScrollHook, type TElement } from "./dom";
|
|
4
|
+
import { resizeRestyles, usesDisplayMode } from "./css";
|
|
5
5
|
import { elementForNativeId, nativeIdOf, setPointerPosition } from "./render";
|
|
6
6
|
|
|
7
7
|
const BUTTONS = [1, 4, 2, 8, 16];
|
|
@@ -11,6 +11,8 @@ let buttons = 0;
|
|
|
11
11
|
/** Native events that are not one element's handler: keys, focus, the window size. */
|
|
12
12
|
export function connectNativeEvents(app: AppHandle): () => void {
|
|
13
13
|
setFocusHook(element => { if (element) app.focus(nativeIdOf(element)); });
|
|
14
|
+
setPointerCaptureHook(element => app.capturePointer(element ? nativeIdOf(element) : null));
|
|
15
|
+
setScrollHook((element, x, y, smooth) => app.scrollTo(nativeIdOf(element), { x, y, smooth }));
|
|
14
16
|
setMediaHook((element, action, value) => {
|
|
15
17
|
const media = app.media(nativeIdOf(element));
|
|
16
18
|
if (action === "seek") media.seek(value ?? 0);
|
|
@@ -18,6 +20,11 @@ export function connectNativeEvents(app: AppHandle): () => void {
|
|
|
18
20
|
else if (action === "textTrack") media.setTextTrack(value ?? null);
|
|
19
21
|
else media[action]();
|
|
20
22
|
});
|
|
23
|
+
// `@media (display-mode: fullscreen)` follows the window.
|
|
24
|
+
const offFullscreen = app.onFullscreenChange(fullscreen => {
|
|
25
|
+
windowInstance._fullscreen = fullscreen;
|
|
26
|
+
if (usesDisplayMode()) restyleAll(documentInstance);
|
|
27
|
+
});
|
|
21
28
|
const off = app.onEvent((event: NativeEvent) => {
|
|
22
29
|
switch (event.type) {
|
|
23
30
|
case "keyboard": {
|
|
@@ -38,9 +45,12 @@ export function connectNativeEvents(app: AppHandle): () => void {
|
|
|
38
45
|
break;
|
|
39
46
|
}
|
|
40
47
|
case "pointer": {
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
-
|
|
48
|
+
// Native gives window coordinates; client ones start under the title bar, as client rects do.
|
|
49
|
+
const client = windowToClient(event.x, event.y);
|
|
50
|
+
setPointerPosition(client.x, client.y);
|
|
51
|
+
// A captured pointer's events go to the element holding it.
|
|
52
|
+
const target: TElement = capturedElement() ?? elementForNativeId(event.id) ?? documentInstance.body;
|
|
53
|
+
const position = { clientX: client.x, clientY: client.y, pageX: client.x, pageY: client.y, screenX: event.x, screenY: event.y, offsetX: event.x - (target._box?.x ?? 0), offsetY: event.y - (target._box?.y ?? 0) };
|
|
44
54
|
const modifiers = { ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, metaKey: event.metaKey };
|
|
45
55
|
if (event.phase === "wheel") {
|
|
46
56
|
target.dispatchEvent(new TEvent("wheel", { bubbles: true, cancelable: true, ...position, ...modifiers, deltaX: event.deltaX ?? 0, deltaY: event.deltaY ?? 0, deltaZ: 0, deltaMode: 0, buttons }));
|
|
@@ -54,6 +64,8 @@ export function connectNativeEvents(app: AppHandle): () => void {
|
|
|
54
64
|
target.dispatchEvent(new TEvent(`mouse${kind}`, init));
|
|
55
65
|
// Other buttons click as auxclick; the primary click comes from native activation.
|
|
56
66
|
if (kind === "up" && button === 1) target.dispatchEvent(new TEvent("auxclick", init));
|
|
67
|
+
// Releasing the last button releases capture, as browsers do after pointerup.
|
|
68
|
+
if (kind === "up" && buttons === 0) releasePointerCapture();
|
|
57
69
|
break;
|
|
58
70
|
}
|
|
59
71
|
case "size": {
|
|
@@ -73,7 +85,7 @@ export function connectNativeEvents(app: AppHandle): () => void {
|
|
|
73
85
|
}
|
|
74
86
|
}
|
|
75
87
|
});
|
|
76
|
-
return () => { off(); setFocusHook(undefined); setMediaHook(undefined); };
|
|
88
|
+
return () => { off(); offFullscreen(); setFocusHook(undefined); setPointerCaptureHook(undefined); setScrollHook(undefined); setMediaHook(undefined); };
|
|
77
89
|
}
|
|
78
90
|
|
|
79
91
|
/** The window's content size changed: `window.innerWidth`, `bind:innerWidth`, `onresize`. */
|
package/src/index.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/// <reference path="./elements.d.ts" />
|
|
2
2
|
import "./install";
|
|
3
|
-
import { createApp, TitleBar as NativeTitleBar, Window, type AppHandle, type AppOptions, type TitleBarProps, type WindowProps } from "@tarve/core";
|
|
3
|
+
import { createApp, TitleBar as NativeTitleBar, View, Window, type AppHandle, type AppOptions, type TitleBarProps, type WindowProps } from "@tarve/core";
|
|
4
4
|
import type { Component } from "svelte";
|
|
5
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";
|
|
6
|
+
import { beginRender, documentInstance, endRender, restyle, setLayoutReader, setScheduler, setViewportElement, type TElement } from "./dom";
|
|
7
|
+
import { canvasBackground, canvasText, elementForNativeId, nativeIdOf, rootChildren, viewportId } from "./render";
|
|
8
8
|
import { setSelectionReader, textOfEditable, utf16Offset } from "./editable";
|
|
9
9
|
import { connectNativeEvents, windowResized } from "./events";
|
|
10
10
|
|
|
@@ -64,14 +64,24 @@ export function mount<Props extends Record<string, any>, Exports extends Record<
|
|
|
64
64
|
app = createApp(() => {
|
|
65
65
|
const title = documentInstance.title || windowOptions.title;
|
|
66
66
|
beginRender();
|
|
67
|
-
let content;
|
|
68
|
-
try { content = rootChildren(target); } finally { endRender(); }
|
|
67
|
+
let content, canvas, text: Record<string, unknown> = {};
|
|
68
|
+
try { content = rootChildren(target); canvas = canvasBackground(); text = canvasText(); } finally { endRender(); }
|
|
69
|
+
// A window has one title bar: a <TitleBar> in the component wins over the option's.
|
|
70
|
+
const ownBar = Boolean(titleBar) && !target.querySelector("titlebar");
|
|
71
|
+
// With Tarve's bar the page is the box under it, as a browser's viewport is under its frame:
|
|
72
|
+
// `innerWidth`/`innerHeight` are its size and client rects start at its corner.
|
|
73
|
+
setViewportElement(ownBar ? target : undefined);
|
|
69
74
|
return Window({
|
|
70
75
|
...windowOptions,
|
|
76
|
+
// The page's `html`/`body` background is the window's, over the option's (`html.player { background: transparent }`).
|
|
77
|
+
// Without Tarve's bar the window is the page: it passes the html/body text down too.
|
|
78
|
+
style: { ...windowOptions.style, ...(ownBar ? {} : text), ...(canvas !== undefined ? { background: canvas } : {}) } as WindowProps["style"],
|
|
71
79
|
title,
|
|
72
|
-
onSize: windowResized,
|
|
73
|
-
|
|
74
|
-
|
|
80
|
+
...(ownBar ? {} : { onSize: windowResized }),
|
|
81
|
+
children: ownBar
|
|
82
|
+
? [NativeTitleBar({ ...(titleBar === true ? {} : titleBar as Omit<TitleBarProps, "children" | "title">), title }), View({ id: viewportId(target), onSize: windowResized, style: { flex: 1, minHeight: 0, width: "100%", position: "relative", display: "block", ...text }, children: content })]
|
|
83
|
+
// The page is a CSS block, as <body> is: its children's margins collapse as in a browser.
|
|
84
|
+
: View({ style: { flex: 1, minHeight: 0, width: "100%", position: "relative", display: "block" }, children: content }),
|
|
75
85
|
});
|
|
76
86
|
}, { keyboardEvents: true, pointerEvents: true, ...appOptions });
|
|
77
87
|
disconnect = connectNativeEvents(app);
|
package/src/plugin.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
2
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
3
|
import { resolveImport, resolveSvelte, resolveTarveSvelte, SVELTE_SPECIFIER, TARVE_SVELTE_SPECIFIER } from "./resolve";
|
|
4
4
|
|
|
@@ -15,6 +15,8 @@ export interface SveltePluginOptions {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
const NAMESPACE = "tarve-svelte";
|
|
18
|
+
/** Global style sheets an app imports (`import "./style.css"`). */
|
|
19
|
+
const CSS_NAMESPACE = "tarve-css";
|
|
18
20
|
|
|
19
21
|
/** Strips TypeScript from a `.svelte.ts` module before Svelte compiles its runes. */
|
|
20
22
|
async function stripTypes(source: string, path: string): Promise<string> {
|
|
@@ -29,7 +31,7 @@ function importsOf(file: string) {
|
|
|
29
31
|
return (specifier: string) => {
|
|
30
32
|
if (SVELTE_SPECIFIER.test(specifier) || TARVE_SVELTE_SPECIFIER.test(specifier)) return resolveImport(specifier);
|
|
31
33
|
// Relative `.svelte` imports stay relative: Bun hands absolute paths to its own loader, not to onResolve.
|
|
32
|
-
if (/\.svelte(\.(js|ts))
|
|
34
|
+
if (/\.svelte(\.(js|ts))?$|\.css$/.test(specifier)) return specifier;
|
|
33
35
|
if (specifier.startsWith("./") || specifier.startsWith("../")) return join(dirname(file), specifier).replace(/\\/g, "/");
|
|
34
36
|
return specifier;
|
|
35
37
|
};
|
|
@@ -54,12 +56,35 @@ export function sveltePlugin(options: SveltePluginOptions = {}) {
|
|
|
54
56
|
try { return { path: resolveSvelte(args.path) }; } finally { resolving = false; }
|
|
55
57
|
});
|
|
56
58
|
build.onResolve({ filter: TARVE_SVELTE_SPECIFIER }, args => ({ path: resolveTarveSvelte(args.path) }));
|
|
57
|
-
build.onResolve({ filter: /\.svelte(\.(js|ts))?$/ }, args =>
|
|
59
|
+
build.onResolve({ filter: /\.svelte(\.(js|ts))?$/ }, args => {
|
|
58
60
|
// Bun names a namespaced importer "tarve-svelte:<path>".
|
|
59
|
-
path
|
|
60
|
-
: resolve(args.importer?.startsWith(`${NAMESPACE}:`) ? dirname(args.importer.slice(NAMESPACE.length + 1)) : args.resolveDir ?? dirname(args.importer), args.path)
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
const path = isAbsolute(args.path) ? args.path
|
|
62
|
+
: resolve(args.importer?.startsWith(`${NAMESPACE}:`) ? dirname(args.importer.slice(NAMESPACE.length + 1)) : args.resolveDir ?? dirname(args.importer), args.path);
|
|
63
|
+
// `import { x } from "./store.svelte"` names the module store.svelte.ts (or .js), as Vite resolves it.
|
|
64
|
+
const module = path.endsWith(".svelte") && !existsSync(path) ? [path + ".ts", path + ".js"].find(existsSync) : undefined;
|
|
65
|
+
return { path: module ?? path, namespace: NAMESPACE };
|
|
66
|
+
});
|
|
67
|
+
// `import "./app.css"`: a global style sheet, registered as the module loads (like a <link>).
|
|
68
|
+
// Imports with attributes (`with { type: "file" }`) stay files.
|
|
69
|
+
build.onResolve({ filter: /\.css$/ }, args => {
|
|
70
|
+
if (Object.keys((args as { with?: object }).with ?? {}).length) return undefined;
|
|
71
|
+
if (!isAbsolute(args.path) && !args.path.startsWith(".")) return undefined;
|
|
72
|
+
const directory = args.importer?.startsWith(`${NAMESPACE}:`) || args.importer?.startsWith(`${CSS_NAMESPACE}:`)
|
|
73
|
+
? dirname(args.importer.slice(args.importer.indexOf(":") + 1)) : args.resolveDir ?? dirname(args.importer);
|
|
74
|
+
return { path: isAbsolute(args.path) ? args.path : resolve(directory, args.path), namespace: CSS_NAMESPACE };
|
|
75
|
+
});
|
|
76
|
+
build.onLoad({ filter: /.*/, namespace: CSS_NAMESPACE }, async args => {
|
|
77
|
+
const { parseCss, cssImports } = await import("./css");
|
|
78
|
+
const source = readFileSync(args.path, "utf8");
|
|
79
|
+
const rules = parseCss(source, message => warn(`${args.path}: ${message}`));
|
|
80
|
+
// `@import "./other.css"` registers the other sheet first, as the cascade orders them.
|
|
81
|
+
// Kept relative: Bun's runtime hands absolute paths to its own loader, not to onResolve.
|
|
82
|
+
const imports = cssImports(source).map(url => `import ${JSON.stringify(/^\.{1,2}\//.test(url) ? url : "./" + url)};`);
|
|
83
|
+
return {
|
|
84
|
+
contents: `${imports.join("\n")}\nimport { registerCss } from ${JSON.stringify(resolveImport("@tarve/svelte/css"))};\nregisterCss(${JSON.stringify(rules)});\n`,
|
|
85
|
+
loader: "js", resolveDir: dirname(args.path),
|
|
86
|
+
};
|
|
87
|
+
});
|
|
63
88
|
// A bundle resolves `svelte` through this plugin: no runtime lookup by path.
|
|
64
89
|
// The client build by absolute path: under Bun.plugin this hook also runs at runtime, where a
|
|
65
90
|
// bare "svelte" may reach Bun's resolver (no importer) and load the server build.
|