@glissade/scene 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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,89 @@
1
+ import { A as DisplayList, B as StrokeStyle, C as PropInit, D as estimatingMeasurer, E as breakLines, F as Paint, G as fromTRS, H as IDENTITY, I as PathSeg, K as matEquals, L as Rect$1, M as DrawCommand, N as FilterSpec, O as quantize, P as FontSpec, R as Resource, S as NodeProps, T as TextMetricsLite, U as Mat2x3, V as createDisplayListBuilder, W as applyToPoint, _ as Video, a as LayoutEngineMissingError, b as EvalContext, c as setLayoutEngine, d as ImageNode, f as ImageProps, g as TextProps, h as Text, i as LayoutEngine, j as DisplayListBuilder, k as BlendMode, l as Circle, m as ShapeProps, n as LayoutChildSpec, o as getLayoutEngine, p as Rect, q as multiply, r as LayoutContainerSpec, s as requireLayoutEngine, t as LayoutBox, u as Group, v as VideoProps, w as TextMeasurer, x as Node, y as BindablePropTarget, z as ResourceId } from "./layoutEngine.js";
2
+ import { BoundTimeline, CompiledTimeline, Playhead, Timeline } from "@glissade/core";
3
+
4
+ //#region src/assets.d.ts
5
+
6
+ /**
7
+ * Asset contracts (DESIGN.md §3.8): evaluate() never awaits — callers warm
8
+ * sources first (§2.5 readiness precondition), then emission is pure. The
9
+ * VideoFrameSource seam isolates decoder differences (WebCodecs vs FFmpeg);
10
+ * backends resolve asset ids to their own bitmap types.
11
+ */
12
+ interface VideoFrameSource {
13
+ /** Source duration in seconds. */
14
+ readonly duration: number;
15
+ /** Frames per second of the source grid (mediaT quantization). */
16
+ readonly fps: number;
17
+ /**
18
+ * Ensure getFrameSync can serve [fromT, toT] (seconds, media time).
19
+ * O(GOP) for backward/random seeks; a readiness latency, never state.
20
+ */
21
+ warm(fromT: number, toT: number): Promise<void>;
22
+ /**
23
+ * The decoded frame for the source-grid frame containing mediaT.
24
+ * Precondition: warmed. The return is backend-consumable (VideoFrame,
25
+ * ImageBitmap, HTMLCanvasElement, or a node Image) — opaque here.
26
+ */
27
+ getFrameSync(mediaT: number): unknown;
28
+ close(): void;
29
+ }
30
+ /** A decoded still image — opaque to scene/core, consumed by backends. */
31
+ type ImageHandle = unknown;
32
+ declare class ColdAssetError extends Error {
33
+ readonly assetId: string;
34
+ readonly detail: string;
35
+ /** Media time that was requested cold, when known — drives demand warming. */
36
+ readonly mediaT: number | undefined;
37
+ constructor(assetId: string, detail: string, mediaT?: number);
38
+ }
39
+ //#endregion
40
+ //#region src/scene.d.ts
41
+ interface Scene {
42
+ readonly root: Group;
43
+ readonly nodes: ReadonlyMap<string, Node>;
44
+ readonly size: {
45
+ w: number;
46
+ h: number;
47
+ };
48
+ /** Per-scene playhead; players and evaluate() write it. */
49
+ readonly playhead: Playhead;
50
+ resolveTarget(target: string): BindablePropTarget | undefined;
51
+ /**
52
+ * Inject the active backend's TextMeasurer (§3.2) so line breaking always
53
+ * measures with the rasterizer that will draw. Defaults to an estimator.
54
+ */
55
+ setTextMeasurer(measurer: TextMeasurer): void;
56
+ readonly textMeasurer: TextMeasurer;
57
+ }
58
+ declare class DuplicateNodeIdError extends Error {
59
+ constructor(id: string);
60
+ }
61
+ interface SceneInit {
62
+ size: {
63
+ w: number;
64
+ h: number;
65
+ };
66
+ children: Node[];
67
+ }
68
+ /**
69
+ * The scene-module convention: what `gs render`, the golden harness, and the
70
+ * studio load. createScene is a factory — every consumer gets a fresh graph.
71
+ */
72
+ interface SceneModule {
73
+ createScene(): Scene;
74
+ timeline: Timeline;
75
+ }
76
+ declare function createScene(init: SceneInit): Scene;
77
+ interface BindingCacheEntry {
78
+ compiled: CompiledTimeline;
79
+ bound: BoundTimeline;
80
+ }
81
+ declare function bindScene(scene: Scene, doc: Timeline): BindingCacheEntry;
82
+ /**
83
+ * The non-negotiable contract (§2.5): same (scene, timeline, t) → identical
84
+ * DisplayList, in any call order. Never awaits; asset readiness is the
85
+ * caller's precondition.
86
+ */
87
+ declare function evaluate(scene: Scene, doc: Timeline, t: number): DisplayList;
88
+ //#endregion
89
+ export { type BindablePropTarget, type BlendMode, Circle, ColdAssetError, type DisplayList, type DisplayListBuilder, type DrawCommand, DuplicateNodeIdError, type EvalContext, type FilterSpec, type FontSpec, Group, IDENTITY, type ImageHandle, ImageNode, type ImageProps, type LayoutBox, type LayoutChildSpec, type LayoutContainerSpec, type LayoutEngine, LayoutEngineMissingError, type Mat2x3, Node, type NodeProps, type Paint, type PathSeg, type PropInit, Rect, type Rect$1 as RectShape, type Resource, type ResourceId, type Scene, type SceneInit, type SceneModule, type ShapeProps, type StrokeStyle, Text, type TextMeasurer, type TextMetricsLite, type TextProps, Video, type VideoFrameSource, type VideoProps, applyToPoint, bindScene, breakLines, createDisplayListBuilder, createScene, estimatingMeasurer, evaluate, fromTRS, getLayoutEngine, matEquals, multiply, quantize, requireLayoutEngine, setLayoutEngine };
package/dist/index.js ADDED
@@ -0,0 +1,102 @@
1
+ import { _ as applyToPoint, a as Circle, b as multiply, c as Rect, d as Node, f as breakLines, g as IDENTITY, h as createDisplayListBuilder, i as setLayoutEngine, l as Text, m as quantize, n as getLayoutEngine, o as Group, p as estimatingMeasurer, r as requireLayoutEngine, s as ImageNode, t as LayoutEngineMissingError, u as Video, v as fromTRS, y as matEquals } from "./layoutEngine.js";
2
+ import { bindTimeline, compileTimeline, createPlayhead, evaluateAt } from "@glissade/core";
3
+ //#region src/assets.ts
4
+ var ColdAssetError = class extends Error {
5
+ assetId;
6
+ detail;
7
+ /** Media time that was requested cold, when known — drives demand warming. */
8
+ mediaT;
9
+ constructor(assetId, detail, mediaT) {
10
+ super(`asset '${assetId}' not ready: ${detail}. evaluate() never awaits — warm assets before evaluating (§2.5 readiness precondition)`);
11
+ this.name = "ColdAssetError";
12
+ this.assetId = assetId;
13
+ this.detail = detail;
14
+ this.mediaT = mediaT;
15
+ }
16
+ };
17
+ //#endregion
18
+ //#region src/scene.ts
19
+ /**
20
+ * Scene assembly + the canonical evaluate(scene, timeline, t) (DESIGN.md §2.5,
21
+ * §3.1): pure, total, deterministic — driver writes the playhead (sanctioned
22
+ * entry write), then a pull-only read phase collects the DisplayList.
23
+ */
24
+ var DuplicateNodeIdError = class extends Error {
25
+ constructor(id) {
26
+ super(`duplicate node id '${id}' — explicit ids must be unique (§3.1/§6.5)`);
27
+ this.name = "DuplicateNodeIdError";
28
+ }
29
+ };
30
+ function indexNodes(root, into) {
31
+ if (root.id !== void 0) {
32
+ if (into.has(root.id)) throw new DuplicateNodeIdError(root.id);
33
+ into.set(root.id, root);
34
+ }
35
+ if (root instanceof Group) for (const child of root.children) indexNodes(child, into);
36
+ }
37
+ function createScene(init) {
38
+ const root = new Group({
39
+ id: "__root",
40
+ children: init.children
41
+ });
42
+ const nodes = /* @__PURE__ */ new Map();
43
+ indexNodes(root, nodes);
44
+ const playhead = createPlayhead();
45
+ let measurer = estimatingMeasurer;
46
+ return {
47
+ root,
48
+ nodes,
49
+ size: init.size,
50
+ playhead,
51
+ resolveTarget: (target) => {
52
+ const slash = target.indexOf("/");
53
+ if (slash < 0) return void 0;
54
+ return nodes.get(target.slice(0, slash))?.resolveTarget(target.slice(slash + 1));
55
+ },
56
+ setTextMeasurer: (m) => {
57
+ measurer = m;
58
+ },
59
+ get textMeasurer() {
60
+ return measurer;
61
+ }
62
+ };
63
+ }
64
+ const bindings = /* @__PURE__ */ new WeakMap();
65
+ function bindScene(scene, doc) {
66
+ let perScene = bindings.get(scene);
67
+ if (!perScene) {
68
+ perScene = /* @__PURE__ */ new WeakMap();
69
+ bindings.set(scene, perScene);
70
+ }
71
+ let entry = perScene.get(doc);
72
+ if (!entry) {
73
+ const compiled = compileTimeline(doc);
74
+ entry = {
75
+ compiled,
76
+ bound: bindTimeline(compiled, scene.resolveTarget, scene.playhead)
77
+ };
78
+ perScene.set(doc, entry);
79
+ }
80
+ return entry;
81
+ }
82
+ /**
83
+ * The non-negotiable contract (§2.5): same (scene, timeline, t) → identical
84
+ * DisplayList, in any call order. Never awaits; asset readiness is the
85
+ * caller's precondition.
86
+ */
87
+ function evaluate(scene, doc, t) {
88
+ bindScene(scene, doc);
89
+ const fps = doc.fps;
90
+ const ctx = {
91
+ time: t,
92
+ frame: fps !== void 0 ? Math.round(t * fps) : -1,
93
+ measurer: scene.textMeasurer
94
+ };
95
+ return evaluateAt(scene.playhead, t, () => {
96
+ const out = createDisplayListBuilder(scene.size);
97
+ scene.root.emit(out, ctx);
98
+ return out.finish();
99
+ });
100
+ }
101
+ //#endregion
102
+ export { Circle, ColdAssetError, DuplicateNodeIdError, Group, IDENTITY, ImageNode, LayoutEngineMissingError, Node, Rect, Text, Video, applyToPoint, bindScene, breakLines, createDisplayListBuilder, createScene, estimatingMeasurer, evaluate, fromTRS, getLayoutEngine, matEquals, multiply, quantize, requireLayoutEngine, setLayoutEngine };
@@ -0,0 +1,46 @@
1
+ import { C as PropInit, S as NodeProps, a as LayoutEngineMissingError, b as EvalContext, c as setLayoutEngine, i as LayoutEngine, j as DisplayListBuilder, n as LayoutChildSpec, o as getLayoutEngine, r as LayoutContainerSpec, t as LayoutBox, u as Group, x as Node } from "./layoutEngine.js";
2
+ import { BindableSignal } from "@glissade/core";
3
+
4
+ //#region src/layout.d.ts
5
+
6
+ interface LayoutProps extends NodeProps {
7
+ children?: Node[];
8
+ width?: PropInit<number>;
9
+ height?: PropInit<number>;
10
+ direction?: 'row' | 'column';
11
+ gap?: PropInit<number>;
12
+ padding?: PropInit<number>;
13
+ justify?: LayoutContainerSpec['justify'];
14
+ align?: LayoutContainerSpec['align'];
15
+ }
16
+ /**
17
+ * Flexbox container (center-anchored like every node). Flowable children
18
+ * (intrinsicSize ≠ null) are placed by the engine anchor-aware via
19
+ * flowOffset(): shapes center into their box, Text aligns its baseline
20
+ * origin to the box edge — labels in a column share a true left edge.
21
+ * Non-flowable children (e.g. Groups) emit untouched at the layout origin,
22
+ * BEFORE the flow — their dominant use is backgrounds. Flowed paint order is
23
+ * zIndex-sorted; flow order is array order.
24
+ */
25
+ declare class Layout extends Group {
26
+ #private;
27
+ /** CLI/host detection marker — avoids importing this entry just to instanceof. */
28
+ static readonly isLayoutNode = true;
29
+ readonly width: BindableSignal<number>;
30
+ readonly height: BindableSignal<number>;
31
+ readonly gap: BindableSignal<number>;
32
+ readonly padding: BindableSignal<number>;
33
+ readonly direction: 'row' | 'column';
34
+ readonly justify: LayoutContainerSpec['justify'];
35
+ readonly align: LayoutContainerSpec['align'];
36
+ constructor(props?: LayoutProps);
37
+ intrinsicSize(): {
38
+ w: number;
39
+ h: number;
40
+ };
41
+ protected draw(out: DisplayListBuilder, ctx: EvalContext): void;
42
+ }
43
+ /** Load Yoga (wasm) and register it as the active LayoutEngine. Idempotent. */
44
+ declare function loadYogaLayoutEngine(): Promise<LayoutEngine>;
45
+ //#endregion
46
+ export { Layout, type LayoutBox, type LayoutChildSpec, type LayoutContainerSpec, type LayoutEngine, LayoutEngineMissingError, LayoutProps, getLayoutEngine, loadYogaLayoutEngine, setLayoutEngine };
package/dist/layout.js ADDED
@@ -0,0 +1,168 @@
1
+ import { i as setLayoutEngine, n as getLayoutEngine, o as Group, r as requireLayoutEngine, t as LayoutEngineMissingError } from "./layoutEngine.js";
2
+ import { signal } from "@glissade/core";
3
+ //#region src/layout.ts
4
+ /**
5
+ * '@glissade/scene/layout' (DESIGN.md §3.2): the flexbox Layout node and the
6
+ * Yoga-backed LayoutEngine. A SEPARATE entry point with its own budget — the
7
+ * base embed path never pays for the wasm. Determinism: the same Yoga build
8
+ * computes layout in browser preview and headless export.
9
+ *
10
+ * Usage: `await loadYogaLayoutEngine()` once before mounting/rendering a
11
+ * scene containing Layout nodes (the CLI does this automatically).
12
+ */
13
+ /**
14
+ * Flexbox container (center-anchored like every node). Flowable children
15
+ * (intrinsicSize ≠ null) are placed by the engine anchor-aware via
16
+ * flowOffset(): shapes center into their box, Text aligns its baseline
17
+ * origin to the box edge — labels in a column share a true left edge.
18
+ * Non-flowable children (e.g. Groups) emit untouched at the layout origin,
19
+ * BEFORE the flow — their dominant use is backgrounds. Flowed paint order is
20
+ * zIndex-sorted; flow order is array order.
21
+ */
22
+ var Layout = class extends Group {
23
+ /** CLI/host detection marker — avoids importing this entry just to instanceof. */
24
+ static isLayoutNode = true;
25
+ width;
26
+ height;
27
+ gap;
28
+ padding;
29
+ direction;
30
+ justify;
31
+ align;
32
+ #memoKey = "";
33
+ #memoBoxes = [];
34
+ constructor(props = {}) {
35
+ super(props);
36
+ this.width = initProp(signal(0), props.width);
37
+ this.height = initProp(signal(0), props.height);
38
+ this.gap = initProp(signal(0), props.gap);
39
+ this.padding = initProp(signal(0), props.padding);
40
+ this.direction = props.direction ?? "row";
41
+ this.justify = props.justify ?? "start";
42
+ this.align = props.align ?? "center";
43
+ this.registerTarget("width", this.width);
44
+ this.registerTarget("height", this.height);
45
+ this.registerTarget("gap", this.gap);
46
+ this.registerTarget("padding", this.padding);
47
+ }
48
+ intrinsicSize() {
49
+ return {
50
+ w: this.width(),
51
+ h: this.height()
52
+ };
53
+ }
54
+ draw(out, ctx) {
55
+ const container = {
56
+ width: this.width(),
57
+ height: this.height(),
58
+ direction: this.direction,
59
+ gap: this.gap(),
60
+ padding: this.padding(),
61
+ justify: this.justify,
62
+ align: this.align
63
+ };
64
+ const flowable = [];
65
+ const absolute = [];
66
+ this.children.forEach((child, index) => {
67
+ const size = child.intrinsicSize(ctx.measurer);
68
+ if (size) flowable.push({
69
+ node: child,
70
+ spec: {
71
+ width: size.w,
72
+ height: size.h
73
+ },
74
+ index
75
+ });
76
+ else absolute.push(child);
77
+ });
78
+ const key = JSON.stringify([container, flowable.map((f) => f.spec)]);
79
+ if (key !== this.#memoKey) {
80
+ this.#memoBoxes = requireLayoutEngine().compute(container, flowable.map((f) => f.spec));
81
+ this.#memoKey = key;
82
+ }
83
+ const boxes = this.#memoBoxes;
84
+ const order = [...flowable].sort((a, b) => a.node.zIndex() - b.node.zIndex() || a.index - b.index);
85
+ const ox = -container.width / 2;
86
+ const oy = -container.height / 2;
87
+ for (const child of absolute) child.emit(out, ctx);
88
+ for (const entry of order) {
89
+ const box = boxes[flowable.indexOf(entry)];
90
+ const off = entry.node.flowOffset(ctx.measurer);
91
+ out.push({ op: "save" });
92
+ out.push({
93
+ op: "transform",
94
+ m: [
95
+ 1,
96
+ 0,
97
+ 0,
98
+ 1,
99
+ ox + box.x - off.x,
100
+ oy + box.y - off.y
101
+ ]
102
+ });
103
+ entry.node.emit(out, ctx);
104
+ out.push({ op: "restore" });
105
+ }
106
+ }
107
+ };
108
+ function initProp(sig, init) {
109
+ if (typeof init === "function") sig.bindSource(init);
110
+ else if (init !== void 0) sig.set(init);
111
+ return sig;
112
+ }
113
+ /** Load Yoga (wasm) and register it as the active LayoutEngine. Idempotent. */
114
+ async function loadYogaLayoutEngine() {
115
+ const { loadYoga, FlexDirection, Justify, Align, Gutter, Edge, Direction } = await import("yoga-layout/load");
116
+ const yoga = await loadYoga();
117
+ const JUSTIFY = {
118
+ start: Justify.FlexStart,
119
+ center: Justify.Center,
120
+ end: Justify.FlexEnd,
121
+ "space-between": Justify.SpaceBetween,
122
+ "space-around": Justify.SpaceAround
123
+ };
124
+ const ALIGN = {
125
+ start: Align.FlexStart,
126
+ center: Align.Center,
127
+ end: Align.FlexEnd,
128
+ stretch: Align.Stretch
129
+ };
130
+ const engine = { compute(container, children) {
131
+ const root = yoga.Node.create();
132
+ try {
133
+ root.setWidth(container.width);
134
+ root.setHeight(container.height);
135
+ root.setFlexDirection(container.direction === "row" ? FlexDirection.Row : FlexDirection.Column);
136
+ root.setGap(Gutter.All, container.gap);
137
+ root.setPadding(Edge.All, container.padding);
138
+ root.setJustifyContent(JUSTIFY[container.justify]);
139
+ root.setAlignItems(ALIGN[container.align]);
140
+ for (let i = 0; i < children.length; i++) {
141
+ const child = yoga.Node.create();
142
+ child.setWidth(children[i].width);
143
+ child.setHeight(children[i].height);
144
+ if (children[i].grow !== void 0) child.setFlexGrow(children[i].grow);
145
+ if (children[i].margin !== void 0) child.setMargin(Edge.All, children[i].margin);
146
+ root.insertChild(child, i);
147
+ }
148
+ root.calculateLayout(container.width, container.height, Direction.LTR);
149
+ const boxes = [];
150
+ for (let i = 0; i < children.length; i++) {
151
+ const child = root.getChild(i);
152
+ boxes.push({
153
+ x: child.getComputedLeft(),
154
+ y: child.getComputedTop(),
155
+ width: child.getComputedWidth(),
156
+ height: child.getComputedHeight()
157
+ });
158
+ }
159
+ return boxes;
160
+ } finally {
161
+ root.freeRecursive();
162
+ }
163
+ } };
164
+ setLayoutEngine(engine);
165
+ return engine;
166
+ }
167
+ //#endregion
168
+ export { Layout, LayoutEngineMissingError, getLayoutEngine, loadYogaLayoutEngine, setLayoutEngine };