diff --git a/CLAUDE.md b/CLAUDE.md
index 2a27e520..edaa6440 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -35,7 +35,7 @@ Run a single test file: `npx vitest tests/flex.spec.ts`
- `src/core/elementNode.ts` — `ElementNode` is the core node abstraction. Manages properties, children, flex layout, focus, states, animations, and syncs to the underlying `@solidtv/renderer` INode.
- `src/core/focusManager.ts` — Handles keyboard/remote input, focus path traversal, and key mapping. Focus walks the component tree via `onUp`/`onDown`/`onLeft`/`onRight`/`onEnter` handlers.
- `src/core/config.ts` — Runtime `Config` object (debug flags, animation settings, font defaults, focus state key).
-- `src/core/flex.ts` / `src/core/flexLayout.ts` — Two flex layout implementations; toggled by `VITE_USE_NEW_FLEX` env var.
+- `src/core/flexLayout.ts` — The flex layout engine (one pass over one container). `elementNode.ts` runs it from a depth-ordered layout queue in the post-mutation pass.
### Build-Time Globals
diff --git a/bench/micro/accessors.test.tsx b/bench/micro/accessors.test.tsx
new file mode 100644
index 00000000..fdbf0f5c
--- /dev/null
+++ b/bench/micro/accessors.test.tsx
@@ -0,0 +1,80 @@
+/**
+ * The cost of ElementNode's forwarded-prop accessors (design 3.6.6), on real
+ * renderer v2 handles: 100 rendered s, read and written in a tight
+ * loop. Unthrottled; prints the best of 15 repetitions (no timing assertion).
+ *
+ * npx vitest run --config=bench/micro/vitest.config.ts --reporter=verbose
+ *
+ * To compare two versions of src/core/elementNode.ts, run it at each (for
+ * the loop-made accessors before 3.6.6: `git show d342c37:src/core/elementNode.ts`).
+ * The `[accessor-micro]` line is the result. On an M4 Pro, Chromium 141
+ * headless, 2026-10-03 (six runs each): loop-made accessors (d342c37)
+ * 15.9-16.3 ms read / 14.7-15.5 ms write; written out (3.6.6)
+ * 1.00-1.20 ms read / 1.40-1.60 ms write.
+ */
+import * as v from 'vitest';
+import * as s from 'solid-js';
+import type { ElementNode } from '@solidtv/solid';
+import { render } from '../../tests/webgl/setup.js';
+
+const NODES = 100;
+const LOOPS = 2000;
+
+v.test('accessor micro', () => {
+ let row!: ElementNode;
+ const dispose = render(() => (
+
+ i)}>
+ {(i) => (
+
+ )}
+
+
+ ));
+ const kids = row.children as ElementNode[];
+ // 8 reads per node: x, width, y, height, alpha, scale, w, h.
+ const read = () => {
+ let sum = 0;
+ for (let i = 0; i < kids.length; i++) {
+ const c = kids[i]!;
+ sum +=
+ c.x + c.width / 2 + c.y + c.height / 2 + c.alpha + c.scale + c.w + c.h;
+ }
+ return sum;
+ };
+ // 2 writes per node: x and alpha.
+ const write = (k: number) => {
+ for (let i = 0; i < kids.length; i++) {
+ const c = kids[i]!;
+ c.x = i * 20 + k;
+ c.alpha = k & 1 ? 0.5 : 1;
+ }
+ };
+ // Warm up until both are optimized.
+ for (let w = 0; w < 3000; w++) {
+ read();
+ write(w);
+ }
+ const bestOf = (fn: () => void) => {
+ let best = Infinity;
+ for (let r = 0; r < 15; r++) {
+ const t0 = performance.now();
+ fn();
+ best = Math.min(best, performance.now() - t0);
+ }
+ return best;
+ };
+ let sink = 0;
+ const readMs = bestOf(() => {
+ for (let n = 0; n < LOOPS; n++) sink += read();
+ });
+ const writeMs = bestOf(() => {
+ for (let n = 0; n < LOOPS; n++) write(n);
+ });
+ console.info(
+ `[accessor-micro] read ${readMs.toFixed(2)} ms (${LOOPS * NODES * 8} reads), ` +
+ `write ${writeMs.toFixed(2)} ms (${LOOPS * NODES * 2} writes)`,
+ );
+ v.expect(sink).toBeGreaterThan(0);
+ dispose();
+});
diff --git a/bench/micro/vitest.config.ts b/bench/micro/vitest.config.ts
new file mode 100644
index 00000000..b5ed4db4
--- /dev/null
+++ b/bench/micro/vitest.config.ts
@@ -0,0 +1,17 @@
+// Micro-benchmarks on the real renderer: the browser setup of
+// vitest.webgl.config.ts (headless Chromium, renderer v2, WebGL), with
+// bench/micro as the only test directory. `npx vitest run` excludes bench/
+// and `pnpm test:webgl` only includes tests/webgl, so neither runs these.
+//
+// npx vitest run --config=bench/micro/vitest.config.ts
+import { fileURLToPath } from 'node:url';
+import webgl from '../../vitest.webgl.config';
+
+export default {
+ ...webgl,
+ root: fileURLToPath(new URL('../..', import.meta.url)),
+ test: {
+ ...webgl.test,
+ include: ['bench/micro/**/*.test.tsx'],
+ },
+};
diff --git a/docs/flow/layout.md b/docs/flow/layout.md
index d52b0bbc..b6906e78 100644
--- a/docs/flow/layout.md
+++ b/docs/flow/layout.md
@@ -15,19 +15,13 @@ The `` element does not require any of these properties, as it will use th
## Flex
-A fundamental tool for layout is the Flex container. Currently, there is a minimal implementation of flex (`display: flex`) that supports the following properties: `flexDirection`, `justifyContent`, `alignItems`, `flexOrder`, `flexGrow` and `gap`. This is useful for laying out elements in rows and columns.
+A fundamental tool for layout is the Flex container (`display: flex`). SolidTV has one flex engine (`src/core/flexLayout.ts`), modelled on CSS flexbox. It supports `flexDirection`, `justifyContent`, `alignItems`, `alignSelf`, `flexOrder`, `flexGrow`, `flexShrink`, `flexBasis`, `flexWrap`, `gap`, `padding` (a number, an array, or per side) and `margin` (a number, an array, or per side). This is useful for laying out elements in rows and columns.
-### New Flex Engine Toggle
+The engine allocates nothing during a layout pass and writes only the values that changed, so a relayout that moves nothing writes nothing and starts no transition.
-The framework now includes a modern, high-performance, CSS-aligned flex engine alongside the legacy engine. To opt into the new flex engine, define the following environment variable during your Vite build process:
+### One flex engine
-```bash
-VITE_USE_NEW_FLEX=true
-```
-
-This will add `flexShrink`, `flexBasis` support and padding / margin full support with array syntax.
-
-Because the engines are conditionally evaluated at build time via `import.meta.env`, your bundler (e.g., Rollup) will automatically perform **Dead-Code Elimination (tree-shaking)**. This means whichever layout engine isn't selected will be completely omitted from your application's final production bundle.
+Before 1.8 there were two engines, a legacy one and a CSS-aligned one chosen at build time with the `VITE_USE_NEW_FLEX` environment variable. Since 1.8 there is only the CSS-aligned one, with everything below. The variable is ignored; delete it from your `.env`. If your app ran on the legacy engine, see the 1.8 release notes for the layouts that change.
### Example
@@ -63,8 +57,8 @@ When a `` with `display: flex` contains text nodes as children, it automat
- **`flexItem`**: boolean (Set to `false` on a child to exclude it from flex calculations.)
- **`flexOrder`**: number (Set the order on children to change the layout order.)
- **`flexGrow`**: number (Set to number on children to specify how much room elements should take up.)
-- **`flexShrink`**: number (Set to number on children to specify how much an element should shrink proportionally if the container overflows. Defaults to 0.) Only in new flex engine.
-- **`flexBasis`**: number | 'auto' (Set the default size of an item before the remaining space is distributed. Overrides width/height.) Only in new flex engine.
+- **`flexShrink`**: number (Set to number on children to specify how much an element should shrink proportionally if the container overflows. Defaults to 0.) With two or more items, a `flexShrink` or `flexGrow` on any of them makes a container without a `flexBoundary` behave as `fixed`: it keeps its own size instead of sizing itself to its items.
+- **`flexBasis`**: number | 'auto' (Set the default size of an item before the remaining space is distributed. Overrides width/height for positioning.)
- **`flexWrap`**: 'nowrap' | 'wrap' | 'wrap-reverse' (Set to `wrap` or `wrap-reverse` to have elements flow to the next line on overflow.)
- **`gap`**: number
- **`rowGap`**: number
@@ -99,23 +93,23 @@ We can also have multiple elements with flexGrow property. Flex will divide up t
Produces:

-### Item-Specific Properties in flex containers
+### Padding and margin
-To control the layout further, you can use the following properties on individual items:
+`padding` is read from the flex container: it is the space between the container's edges and its items. `margin` is read from each item. Both take a number for all four sides, or a CSS-style array:
-- **`padding`**: number (Specifies padding on the element itself on main axis. Only in legacy flex engine.)
-
-- **`padding`**: number | [number, number, number, number] (Specifies padding on the element itself. Using an array aligns with the CSS `[Top, Right, Bottom, Left]` specification. Available in the new flex engine.)
-- **`paddingTop`**: number (Overrides the top value of the padding array. Available in the new flex engine.)
-- **`paddingRight`**: number (Overrides the right value of the padding array. Available in the new flex engine.)
-- **`paddingBottom`**: number (Overrides the bottom value of the padding array. Available in the new flex engine.)
-- **`paddingLeft`**: number (Overrides the left value of the padding array. Available in the new flex engine.)
-- **`margin`**: [number, number, number, number] (Specifies margins on the element using the `[Top, Right, Bottom, Left]` CSS array syntax. Available in the new flex engine.)
+- **`padding`**: number | [number, number] | [number, number, number] | [number, number, number, number] (Specifies the padding on the container. A four value array is `[Top, Right, Bottom, Left]`, as in CSS. Two values are `[vertical, horizontal]`, three are `[Top, horizontal, Bottom]`.) A padding applies to both axes: items start at the padding on the main axis and, with `alignItems`, `alignSelf` or wrapping, on the cross axis.
+- **`paddingTop`**: number (Overrides the top value of `padding`.)
+- **`paddingRight`**: number (Overrides the right value of `padding`.)
+- **`paddingBottom`**: number (Overrides the bottom value of `padding`.)
+- **`paddingLeft`**: number (Overrides the left value of `padding`.)
+- **`margin`**: number | [number, number] | [number, number, number] | [number, number, number, number] (Specifies the margins on an item, with the same array forms as `padding`.)
- **`marginBottom`**: number
- **`marginLeft`**: number
- **`marginRight`**: number
- **`marginTop`**: number
+A non-zero `marginTop`, `marginRight`, `marginBottom` or `marginLeft` takes precedence over the same side of `margin`.
+
Note: `alignItems` supports `flexStart`, `flexEnd`, and `center`, but requires the container to have a height/width set.
## Layout Callbacks
diff --git a/src/core/dom-renderer/domRenderer.ts b/src/core/dom-renderer/domRenderer.ts
index 5f735e24..4d55544d 100644
--- a/src/core/dom-renderer/domRenderer.ts
+++ b/src/core/dom-renderer/domRenderer.ts
@@ -1145,7 +1145,16 @@ function updateDOMTextSize(node: DOMText, emitLoaded = true): void {
break;
}
- if (emitLoaded && (!node.loaded || dimensionsChanged)) {
+ // Against the size last emitted, not the size before this measure: a
+ // `measure()` (Solid, before its layout) takes the new size without
+ // emitting, and `loaded` listeners must still hear it.
+ if (
+ emitLoaded &&
+ (!node.loaded ||
+ dimensionsChanged ||
+ node.w !== node.loadedW ||
+ node.h !== node.loadedH)
+ ) {
const payload: lng.NodeTextLoadedPayload = {
type: 'text',
dimensions: {
@@ -1153,11 +1162,43 @@ function updateDOMTextSize(node: DOMText, emitLoaded = true): void {
h: node.h,
},
};
+ node.loadedW = node.w;
+ node.loadedH = node.h;
node.emit('loaded', payload);
node.loaded = true;
}
}
+/**
+ * Whether the text's font is loaded, as `document.fonts.check` says (a
+ * family no font face names counts as loaded: a system font). Without a
+ * FontFaceSet, or for a font string it cannot parse, it is taken as loaded.
+ */
+function isFontLoaded(node: DOMText): boolean {
+ if (typeof document === 'undefined') {
+ return true;
+ }
+ const fonts = document.fonts as FontFaceSet | undefined;
+ if (
+ fonts === undefined ||
+ fonts === null ||
+ typeof fonts.check !== 'function'
+ ) {
+ return true;
+ }
+ let font = node.font;
+ if (font === undefined) {
+ const props = node.props;
+ font = `${props.fontStyle} ${props.fontWeight} ${props.fontSize}px "${props.fontFamily}"`;
+ node.font = font;
+ }
+ try {
+ return fonts.check(font);
+ } catch {
+ return true;
+ }
+}
+
function updateDOMTextMeasurements() {
textNodesToMeasure.forEach((node) => updateDOMTextSize(node));
textNodesToMeasure.clear();
@@ -1430,6 +1471,59 @@ export class DOMNode extends EventEmitter implements IRendererNode {
updateNodeParent(this);
}
+ /**
+ * Renderer v2's `Node.insertBefore`: makes `child` a child of this node,
+ * before `before` (`null`, or a node that is not a child, appends); a child
+ * of this node moves, and one placed before itself stays. A destroyed
+ * parent or child does nothing; a destroyed `before` appends. The div order
+ * is the paint order among equal z-index, as v2's sibling order is its
+ * draw order.
+ */
+ insertBefore(child: IRendererNode, before: IRendererNode | null): void {
+ if (
+ !(child instanceof DOMNode) ||
+ child === before ||
+ !elMap.has(this) ||
+ !elMap.has(child)
+ ) {
+ return;
+ }
+ const anchor =
+ before instanceof DOMNode &&
+ before.props.parent === this &&
+ elMap.has(before)
+ ? before
+ : null;
+
+ // A new parent: adds it to this node's children and appends its div.
+ child.parent = this;
+
+ const children = this.children;
+ children.delete(child);
+ if (anchor === null) {
+ children.add(child);
+ this.div.appendChild(child.div);
+ } else {
+ // A Set keeps insertion order: add the child at the end, then move the
+ // anchor and everything after it behind the child (no array: stop at
+ // the last one before the child, as re-added entries come after it).
+ let last: DOMNode | undefined;
+ for (const c of children) last = c;
+ children.add(child);
+ let moving = false;
+ for (const c of children) {
+ if (c === anchor) moving = true;
+ if (moving) {
+ children.delete(c);
+ children.add(c);
+ }
+ if (c === last) break;
+ }
+ this.div.insertBefore(child.div, anchor.div);
+ }
+ this.markChildrenBoundsDirty();
+ }
+
public markChildrenBoundsDirty() {
for (const child of this.children) {
child.boundsDirty = true;
@@ -1883,6 +1977,11 @@ export class DOMNode extends EventEmitter implements IRendererNode {
class DOMText extends DOMNode {
public loaded = false;
+ /** The size `loaded` last told (updateDOMTextSize). */
+ public loadedW = 0;
+ public loadedH = 0;
+ /** Its CSS font, for document.fonts.check; undefined once a font prop changes. */
+ public font: string | undefined = undefined;
constructor(
stage: IRendererStage,
@@ -1902,6 +2001,21 @@ class DOMText extends DOMNode {
super.destroy();
}
+ /**
+ * Renderer v2's `TextNode.measure()`: sizes the text now, synchronously
+ * (`getBoundingClientRect`), when its font is loaded, and returns true.
+ * While it is not (document.fonts.check), returns false and measures
+ * nothing: the async measurement emits `loaded` once it is. False for a
+ * destroyed node too.
+ */
+ measure(): boolean {
+ if (!elMap.has(this) || !isFontLoaded(this)) {
+ return false;
+ }
+ updateDOMTextSize(this, false);
+ return true;
+ }
+
get text() {
return this.props.text;
}
@@ -1917,6 +2031,7 @@ class DOMText extends DOMNode {
set fontFamily(v) {
if (this.props.fontFamily === v) return;
this.props.fontFamily = v;
+ this.font = undefined;
updateNodeStyles(this);
scheduleUpdateDOMTextMeasurement(this);
}
@@ -1926,6 +2041,7 @@ class DOMText extends DOMNode {
set fontSize(v) {
if (this.props.fontSize === v) return;
this.props.fontSize = v;
+ this.font = undefined;
updateNodeStyles(this);
scheduleUpdateDOMTextMeasurement(this);
}
@@ -1935,6 +2051,7 @@ class DOMText extends DOMNode {
set fontStyle(v) {
if (this.props.fontStyle === v) return;
this.props.fontStyle = v;
+ this.font = undefined;
updateNodeStyles(this);
scheduleUpdateDOMTextMeasurement(this);
}
@@ -1944,6 +2061,7 @@ class DOMText extends DOMNode {
set fontWeight(v) {
if (this.props.fontWeight === v) return;
this.props.fontWeight = v;
+ this.font = undefined;
updateNodeStyles(this);
scheduleUpdateDOMTextMeasurement(this);
}
diff --git a/src/core/dom-renderer/domRendererTypes.ts b/src/core/dom-renderer/domRendererTypes.ts
index b7cd9872..cb2af74f 100644
--- a/src/core/dom-renderer/domRendererTypes.ts
+++ b/src/core/dom-renderer/domRendererTypes.ts
@@ -80,6 +80,10 @@ export interface IRendererNodeShaded extends EventEmitter {
) => lng.IAnimationController;
get absX(): number;
get absY(): number;
+ /** Renderer v2's `Node.destroyed`: true once destroyed. */
+ get destroyed(): boolean;
+ /** Renderer v2's `Node.insertBefore` (draw order follows Solid's children). */
+ insertBefore(child: IRendererNode, before: IRendererNode | null): void;
}
/** Based on {@link lng.INodeProps} */
@@ -115,6 +119,12 @@ export interface IRendererTextNode
div?: HTMLElement;
props: IRendererTextNodeProps;
renderState: lng.CoreNodeRenderState;
+ /**
+ * Renderer v2's `TextNode.measure()`: lays the text out now, outside the
+ * walk, so `w` and `h` read its size at once; false, changing nothing,
+ * while its font is not loaded (and for a destroyed node).
+ */
+ measure(): boolean;
}
/** Based on {@link lng.RendererMain} */
diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts
index 7201f2b3..219eb598 100644
--- a/src/core/elementNode.ts
+++ b/src/core/elementNode.ts
@@ -16,12 +16,7 @@ import {
type DollarString,
} from './intrinsicTypes.js';
import States, { type NodeStates } from './states.js';
-import calculateFlexOld from './flex.js';
-import calculateFlexNew from './flexLayout.js';
-
-const calculateFlex = import.meta.env?.VITE_USE_NEW_FLEX
- ? calculateFlexNew
- : calculateFlexOld;
+import calculateFlex, { getArrayValue } from './flexLayout.js';
import {
log,
isArray,
@@ -53,6 +48,7 @@ import {
FocusNode,
} from './focusManager.js';
import { initClickInspector } from './clickInspector.js';
+import { onFontLoaded } from './fontLoaded.js';
import {
IRendererNode,
@@ -65,25 +61,65 @@ import {
// Unified post-mutation scheduler.
//
-// Three phases run in one microtask (or one renderer-tick callback):
+// Three phases run in one microtask (or, for a `loaded` handler, in the
+// renderer frame between its walks: schedulePostMutationInFrame):
// 1. delete-flush — destroy nodes that were removed and not re-inserted
-// 2. layout — recompute flex layout for any dirty subtree
+// 2. layout — measure the texts written since the last run (and
+// those that waited for a font), then recompute flex
+// layout for any dirty subtree
// 3. focus — resolve forwardFocus on deferred elements, then apply
//
// Order matters: layout reads the rendered tree (so destroyed nodes must be
// gone), and focus reads the laid-out tree.
let postMutationQueued = false;
+let postMutationInFrame = false;
let nextActiveElement: ElementNode | null = null;
let deferredFocusElement: ElementNode | null = null;
-const layoutQueue = new Set();
-const elementDeleteQueue: ElementNode[] = [];
+// Entries past elementDeleteCount are undefined; the array keeps its
+// capacity between runs.
+const elementDeleteQueue: Array = [];
+let elementDeleteCount = 0;
+
+// The layout queue: containers bucketed by depth (the root's children are at
+// depth 1), laid out deepest first, so a container runs after every queued
+// container inside it. A node is in at most one bucket entry that counts
+// (`_layoutQueued`); updateLayout() clears it, so a node laid out directly is
+// skipped when its entry comes up. Buckets keep their capacity: no allocation
+// per run once the tree's depth has been seen.
+const layoutBuckets: Array> = [];
+const layoutBucketSize: number[] = [];
+let layoutMaxDepth = -1; // deepest bucket that may hold a node
+let layoutSweepDepth = -1; // bucket the layout phase is on, -1 outside it
+
+// Text measurement (design 3.4): a `` whose parent lays out is sized by
+// the renderer's synchronous `measure()` before the parent's flex, not by the
+// walk and its `loaded` event. A write to a prop its layout reads queues it
+// here (`TextMeasure.due`); the layout phase measures the queue and queues
+// the parent of a text whose size, as flex reads it, changed. Entries past
+// textMeasureCount are undefined; the array keeps its capacity.
+const textMeasureQueue: Array = [];
+let textMeasureCount = 0;
+// Texts whose font's description was missing when measured (`waiting`):
+// each hears `loaded` once (the walk lays it out when the font arrives), and
+// loadFonts() tells when a font has loaded, for those no walk visits. Both
+// set fontWaitingDue; the layout phase then measures them.
+const fontWaiting: ElementNode[] = [];
+let fontWaitingDue = false;
+// Length at which the list is next swept of texts that no longer wait
+// (destroyed: nothing else takes them off while their font never loads).
+// Never while measureFontWaiting walks it (`measuringFontWaiting`).
+let fontWaitingSweepAt = 64;
+let measuringFontWaiting = false;
+// Re-measures in one layout phase before the rest waits for its next change:
+// a text whose size flex writes (flexGrow, flexShrink, minWidth) settles in
+// one or two, so more means a layout that does not converge.
+const MAX_TEXT_SWEEPS = 16;
export function enqueueDelete(node: ElementNode, n: number): void {
if (node._queueDelete === undefined) {
node._queueDelete = n;
- if (elementDeleteQueue.push(node) === 1) {
- schedulePostMutation();
- }
+ elementDeleteQueue[elementDeleteCount++] = node;
+ schedulePostMutation();
} else {
node._queueDelete += n;
}
@@ -92,35 +128,50 @@ export function enqueueDelete(node: ElementNode, n: number): void {
function schedulePostMutation() {
if (postMutationQueued) return;
postMutationQueued = true;
- if ('reprocessUpdates' in renderer.stage && renderer.stage.reprocessUpdates) {
- renderer.stage.reprocessUpdates(runPostMutation);
- }
queueMicrotask(runPostMutation);
}
+/**
+ * Also runs the post-mutation pass inside the renderer's current or next
+ * frame, after its walk and before the draw, so what it writes is drawn in
+ * that frame. For handlers the renderer calls between its walks (`loaded`).
+ */
+function schedulePostMutationInFrame(): void {
+ schedulePostMutation();
+ if (postMutationInFrame) return;
+ const stage = renderer.stage;
+ if ('reprocessUpdates' in stage && stage.reprocessUpdates) {
+ postMutationInFrame = true;
+ stage.reprocessUpdates(runPostMutation);
+ }
+}
+
function runPostMutation() {
postMutationQueued = false;
-
- // Phase 1: delete-flush
- if (elementDeleteQueue.length > 0) {
- for (const el of elementDeleteQueue) {
- if ((el._queueDelete ?? 0) < 0) {
+ postMutationInFrame = false;
+
+ // Phase 1: delete-flush (the count is read every time: a destroy can
+ // queue more). An entry is cleared before its destroy, so one whose
+ // onDestroy threw is not retried and the next run carries on after it.
+ if (elementDeleteCount > 0) {
+ for (let i = 0; i < elementDeleteCount; i++) {
+ const el = elementDeleteQueue[i];
+ elementDeleteQueue[i] = undefined;
+ if (el === undefined) continue;
+ const queued = el._queueDelete ?? 0;
+ el._queueDelete = undefined;
+ if (queued < 0) {
el.destroy();
}
- el._queueDelete = undefined;
}
- elementDeleteQueue.length = 0;
+ elementDeleteCount = 0;
}
// Phase 2: layout
- while (layoutQueue.size > 0) {
- const queue = [...layoutQueue];
- layoutQueue.clear();
- for (let i = queue.length - 1; i >= 0; i--) {
- const node = queue[i] as ElementNode;
- node.updateLayout();
- }
+ if (fontWaitingDue === true) {
+ measureFontWaiting();
}
+ runLayoutQueue();
// Phase 3: focus. setFocus() may have evaluated forwardFocus pre-render
// (when no children existed yet); deferredFocusElement re-runs setFocus
@@ -136,28 +187,241 @@ function runPostMutation() {
}
}
-function addToLayoutQueue(node: ElementNode) {
- layoutQueue.add(node);
+function enqueueLayout(node: ElementNode): void {
+ if (node._layoutQueued === true) return;
+ node._layoutQueued = true;
+ // The depth in its tree: a removed node's tree ends at it.
+ let depth = 0;
+ for (
+ let n: ElementNode = node, p = n.parent;
+ n._detached !== true && p !== undefined && p !== null;
+ n = p, p = n.parent
+ ) {
+ depth++;
+ }
+ while (layoutBuckets.length <= depth) {
+ layoutBuckets.push([]);
+ layoutBucketSize.push(0);
+ }
+ const size = layoutBucketSize[depth]!;
+ layoutBuckets[depth]![size] = node;
+ layoutBucketSize[depth] = size + 1;
+ // During a sweep, a node at the bucket being run or shallower is reached
+ // by that sweep; a deeper one needs another.
+ if (depth > layoutMaxDepth && depth > layoutSweepDepth) {
+ layoutMaxDepth = depth;
+ }
+}
+
+/**
+ * Queue `node`'s layout (flex and `onLayout`) for the post-mutation pass.
+ * Within one pass, containers run deepest first, each at most once unless a
+ * child's size changed after its run.
+ */
+function queueLayout(node: ElementNode): void {
+ enqueueLayout(node);
schedulePostMutation();
}
+function runLayoutQueue(): void {
+ measureQueuedTexts();
+ // Start from the deepest bucket there is, so entries a run that threw left
+ // behind are not stranded.
+ layoutMaxDepth = layoutBuckets.length - 1;
+ let textSweeps = 0;
+ while (layoutMaxDepth >= 0) {
+ let depth = layoutMaxDepth;
+ layoutMaxDepth = -1;
+ for (; depth >= 0; depth--) {
+ layoutSweepDepth = depth;
+ const bucket = layoutBuckets[depth]!;
+ // Read the size every time: a run can queue more at this depth.
+ for (let i = 0; i < layoutBucketSize[depth]!; i++) {
+ const node = bucket[i];
+ bucket[i] = undefined;
+ if (node !== undefined && node._layoutQueued === true) {
+ node.updateLayout();
+ }
+ }
+ layoutBucketSize[depth] = 0;
+ }
+ layoutSweepDepth = -1;
+ // Texts the sweep wrote (flex sizing a text, an onLayout): measured now,
+ // so the container of one that resized runs again in another sweep.
+ if (textMeasureCount > 0 && textSweeps < MAX_TEXT_SWEEPS) {
+ textSweeps++;
+ measureQueuedTexts();
+ }
+ }
+ if (textMeasureCount > 0) {
+ // Not converging: drop the rest (each is measured again at its next
+ // change), or the run its writes scheduled would start over.
+ for (let i = 0; i < textMeasureCount; i++) {
+ const t = textMeasureQueue[i];
+ textMeasureQueue[i] = undefined;
+ if (t !== undefined) {
+ t._text!.due = false;
+ }
+ }
+ textMeasureCount = 0;
+ if (isDev) {
+ console.warn(
+ '[solid] Text sizes did not settle in ' +
+ MAX_TEXT_SWEEPS +
+ ' layout passes (a layout that changes the size of a text it lays out); the rest waits for its next change.',
+ );
+ }
+ }
+}
+
/**
- * Removes the first `item` from `arr` in place, as `splice(index, 1)` did,
- * without the array of removed items splice returns. Returns its index, or
- * -1 when it is not there.
+ * Measures the texts written since the last call (`_textLayoutDirty`) and
+ * queues the parent of each whose size, as flex reads it, changed. A text
+ * the parent's updateLayout() measured already is skipped.
*/
-function removeItem(arr: T[], item: T): number {
- const index = arr.indexOf(item);
- if (index > -1) {
- const last = arr.length - 1;
- for (let i = index; i < last; i++) {
- arr[i] = arr[i + 1]!;
+function measureQueuedTexts(): void {
+ for (let i = 0; i < textMeasureCount; i++) {
+ const t = textMeasureQueue[i];
+ textMeasureQueue[i] = undefined;
+ // Cleared by a run that threw part way (the count was not reset).
+ if (t === undefined) {
+ continue;
+ }
+ const m = t._text!;
+ if (m.due !== true) {
+ continue;
+ }
+ const parent = t._parent;
+ if (parent === undefined || parent._requiresLayout !== true) {
+ // Moved out, or the parent stopped laying out: nothing to size.
+ m.due = false;
+ m.w = NaN;
+ continue;
+ }
+ if (t._measureText() === true) {
+ enqueueLayout(parent);
}
- arr.pop();
}
- return index;
+ textMeasureCount = 0;
}
+/**
+ * A text that waited for its font heard `loaded`: the walk laid it out, as
+ * the font's description arrived. Shared by every waiting text (no closure
+ * per text); the layout phase, in this frame, measures them all.
+ */
+function fontWaitHeard(): void {
+ fontWaitingDue = true;
+ schedulePostMutationInFrame();
+}
+
+/**
+ * Measures the texts that waited for a font (`_waitForFont`): one whose font
+ * is there now stops waiting and, if its size changed, queues its parent; one
+ * whose font is still missing waits again.
+ */
+function measureFontWaiting(): void {
+ fontWaitingDue = false;
+ const n = fontWaiting.length;
+ // A text whose font is still missing is appended again (_waitForFont),
+ // which must not sweep the list under this loop.
+ measuringFontWaiting = true;
+ try {
+ for (let i = 0; i < n; i++) {
+ const t = fontWaiting[i]!;
+ const m = t._text!;
+ if (m.waiting !== true) {
+ continue; // measured meanwhile
+ }
+ // Off first, so a measure() now queues no `loaded` for it.
+ (t.lng as IRendererTextNode).off('loaded', fontWaitHeard);
+ m.waiting = false;
+ if (t.destroyed === true) {
+ continue;
+ }
+ const parent = t._parent;
+ if (parent === undefined || parent._requiresLayout !== true) {
+ m.w = NaN;
+ continue;
+ }
+ // Waits again (appended past n) while the font is still missing.
+ if (t._measureText() === true) {
+ enqueueLayout(parent);
+ }
+ }
+ } finally {
+ measuringFontWaiting = false;
+ }
+ // Keep the entries appended meanwhile, without allocating.
+ const length = fontWaiting.length;
+ for (let i = n; i < length; i++) {
+ fontWaiting[i - n] = fontWaiting[i]!;
+ }
+ fontWaiting.length = length - n;
+}
+
+/** Drops the texts that no longer wait for a font (destroyed ones). */
+function sweepFontWaiting(): void {
+ let kept = 0;
+ for (let i = 0; i < fontWaiting.length; i++) {
+ const t = fontWaiting[i]!;
+ if (t._text!.waiting === true && t.destroyed !== true) {
+ fontWaiting[kept++] = t;
+ }
+ }
+ fontWaiting.length = kept;
+ fontWaitingSweepAt = kept * 2 > 64 ? kept * 2 : 64;
+}
+
+/** The props a text's layout reads that an animation can change. */
+function animatesTextLayout(props: Partial): boolean {
+ return (
+ 'fontSize' in props ||
+ 'lineHeight' in props ||
+ 'letterSpacing' in props ||
+ 'maxWidth' in props ||
+ 'maxHeight' in props ||
+ 'maxLines' in props ||
+ 'w' in props ||
+ 'h' in props
+ );
+}
+
+/**
+ * What Solid knows of a `` it measures (`ElementNode._text`), made the
+ * first time: only texts in a container that lays out have one. Its sizes
+ * start as doubles, so storing a measured size allocates nothing.
+ */
+class TextMeasure {
+ /** A prop its layout reads was written since it was last measured; queued. */
+ due: boolean;
+ /** Its font was missing when measured (`_waitForFont`). */
+ waiting: boolean;
+ /** Width and height, as flex reads them, when last measured; NaN before. */
+ w: number;
+ h: number;
+ /**
+ * Hears every layout (`_listenTextLoaded`): a text Solid animated a layout
+ * prop of, and every measured text in DOM builds. For its lifetime.
+ */
+ listening: boolean;
+
+ constructor() {
+ this.due = false;
+ this.waiting = false;
+ this.w = NaN;
+ this.h = NaN;
+ this.listening = false;
+ }
+}
+
+onFontLoaded(() => {
+ if (fontWaiting.length > 0) {
+ fontWaitingDue = true;
+ schedulePostMutation();
+ }
+});
+
// Text-default template, built once on first use. Config.fontSettings is
// expected to be set at app startup and not change afterwards.
let _fontTemplate: Array<[string, any]> | undefined;
@@ -311,89 +575,6 @@ export function convertToShader(
) as IRendererShader;
}
-function getPropertyAlias(name: string) {
- if (name === 'w') return 'width';
- if (name === 'h') return 'height';
- return name;
-}
-
-const LightningRendererNumberProps = [
- 'alpha',
- 'color',
- 'colorTop',
- 'colorRight',
- 'colorLeft',
- 'colorBottom',
- 'colorTl',
- 'colorTr',
- 'colorBl',
- 'colorBr',
- 'h',
- 'fontSize',
- 'lineHeight',
- 'mount',
- 'mountX',
- 'mountY',
- 'pivot',
- 'pivotX',
- 'pivotY',
- 'rotation',
- 'scale',
- 'scaleX',
- 'scaleY',
- 'w',
- 'worldX',
- 'worldY',
- 'x',
- 'y',
- 'zIndex',
- 'zIndexLocked',
-];
-
-const LightningRendererNonAnimatingProps = [
- 'absX',
- 'absY',
- 'atlasGroup',
- 'autosize',
- 'clipping',
- 'contain',
- 'componentName',
- 'componentLocation',
- 'data',
- 'destroyed',
- 'forceLoad',
- 'fontStretch',
- 'fontStyle',
- 'group',
- 'ignoreParentAlpha',
- 'imageType',
- 'letterSpacing',
- 'maxHeight',
- 'maxLines',
- 'maxWidth',
- 'offsetY',
- 'overflowSuffix',
- 'placeholderColor',
- 'preventCleanup',
- 'scrollable',
- 'scrollY',
- 'srcHeight',
- 'srcWidth',
- 'srcX',
- 'srcY',
- 'strictBounds',
- 'text',
- 'textAlign',
- 'textBaseline',
- 'textOverflow',
- 'texture',
- 'textureOptions',
- 'textRendererOverride',
- 'verticalAlign',
- 'wordBreak',
- 'wordWrap',
-];
-
declare global {
interface HTMLElement {
/** Assigned for development, to quickly get ElementNode from selected HTMLElement */
@@ -429,6 +610,23 @@ export interface ElementNode extends RendererNode, FocusNode {
_animationSettings?: AnimationSettings;
_autofocus?: any;
_containsFlexGrow?: boolean | null;
+ /** @internal flexGrow record (B8): the size before the last growth. */
+ _flexBase?: number;
+ /** @internal flexGrow record (B8): the size the last growth wrote. */
+ _flexGrown?: number;
+ /** @internal the last x, y, width, height flex wrote with a transition */
+ _flexX?: number;
+ _flexY?: number;
+ _flexW?: number;
+ _flexH?: number;
+ /** @internal in the layout queue (queueLayout) */
+ _layoutQueued: boolean;
+ /**
+ * @internal a `` in a container that lays out: what Solid's text
+ * measurement knows of it (`_textLayoutDirty`, `_measureText`); undefined
+ * until it is first queued or measured
+ */
+ _text: TextMeasure | undefined;
_hasRenderedChildren?: boolean;
_effects?: Record;
/** The props of a shader convertToShader made, kept to swap its type. */
@@ -441,6 +639,14 @@ export interface ElementNode extends RendererNode, FocusNode {
_rendererProps?: any;
_states?: States;
_style?: Styles;
+ /** @internal text-only props written to an element that is not a `` (B20) */
+ _textProps?: Record;
+ /**
+ * @internal removed from its parent's children and not inserted since. Its
+ * `parent` link stays (1.6: keys and events still bubble through it), but
+ * it does not lay out that parent.
+ */
+ _detached: boolean;
_theme?: Styles;
_lastAnyKeyPressTime?: number;
_type: 'element' | 'textNode';
@@ -502,12 +708,10 @@ export interface ElementNode extends RendererNode, FocusNode {
/**
* Defines the ability for a flex item to shrink if necessary.
* Defaults to 0 since existing legacy implementations did not shrink layout boxes.
- * Only available in NEW flex layout.
*/
flexShrink?: number;
/**
* Defines the default size of an element before the remaining space is distributed.
- * Only available in NEW flex layout.
*/
flexBasis?: number | string;
/**
@@ -871,7 +1075,6 @@ export interface ElementNode extends RendererNode, FocusNode {
/**
* The individual padding on each side of an element, acting as an override to the `padding` array property.
* `paddingTop`, `paddingRight`, `paddingBottom`, `paddingLeft`.
- * Only in the new flex engine.
*
* @see https://solid-tv.github.io/solid/#/flow/layout?id=flex
*/
@@ -920,6 +1123,12 @@ export class ElementNode {
this._calcWidth = undefined;
this._calcHeight = undefined;
this._containsFlexGrow = undefined;
+ this._flexBase = undefined;
+ this._flexGrown = undefined;
+ this._flexX = undefined;
+ this._flexY = undefined;
+ this._flexW = undefined;
+ this._flexH = undefined;
this._hasRenderedChildren = undefined;
this._effects = undefined;
this._shaderProps = undefined;
@@ -937,6 +1146,10 @@ export class ElementNode {
this._onLayout = undefined;
this._requiresLayout = false;
this._focusGen = 0;
+ this._layoutQueued = false;
+ this._textProps = undefined;
+ this._detached = false;
+ this._text = undefined;
}
get effects(): StyleEffects | undefined {
@@ -1062,9 +1275,14 @@ export class ElementNode {
/**
* The renderer's family name from `fontFamily` and `fontWeight`, resolved
- * in one place so either JSX order gives the same name (B17).
+ * in one place so either JSX order gives the same name (B17). Only a
+ * `` has a font: another element keeps both on the ElementNode and
+ * writes nothing to its renderer node (B20).
*/
_writeFontFamily() {
+ if (this._type !== NodeType.TextNode) {
+ return;
+ }
const weight = this._fontWeight as number | string | undefined;
if (weight === undefined) {
// No family of its own: before render, undefined lets render's font
@@ -1074,62 +1292,117 @@ export class ElementNode {
const family = this._fontFamily;
(this.lng as ElementNode).fontFamily =
family === undefined && this.rendered ? _fontFamilyWithWeight : family;
- return;
+ } else {
+ const alias = Config.fontWeightAlias;
+ const aliased =
+ alias !== undefined && alias !== null
+ ? (alias[weight] as number | string | undefined)
+ : undefined;
+ (this.lng as ElementNode).fontFamily =
+ `${this._fontFamily || Config.fontSettings?.fontFamily}${aliased ?? weight}`;
}
- const alias = Config.fontWeightAlias;
- const aliased =
- alias !== undefined && alias !== null
- ? (alias[weight] as number | string | undefined)
- : undefined;
- (this.lng as ElementNode).fontFamily =
- `${this._fontFamily || Config.fontSettings?.fontFamily}${aliased ?? weight}`;
+ this._textLayoutDirty();
}
insertChild(
node: ElementNode | ElementText | TextNode,
beforeNode?: ElementNode | ElementText | TextNode | null,
) {
- // always remove nodes if they have a parent - for back swap of node
- // this will then put the node at the end of the array when re-added
- if (node.parent) {
- node.parent.removeChild(node);
-
- // We're inserting a node thats been rendered into a node that hasn't been
- if (!this.rendered) {
- this._hasRenderedChildren = true;
- }
- }
-
- node.parent = this;
-
- if (beforeNode) {
- // SolidJS can move nodes around in the children array.
- // We need to insert following DOM insertBefore which moves elements.
- const children = this.children;
- removeItem(children, node as ElementNode);
- const index = children.indexOf(beforeNode as ElementNode);
- if (index > -1) {
- // In front of beforeNode, the rest moved up one: splice(index, 0,
- // node) without its argument list and result array.
- for (let i = children.length; i > index; i--) {
- children[i] = children[i - 1]!;
- }
- children[index] = node as ElementNode;
- return;
+ const children = this.children;
+ const prevParent = node.parent;
+ // Removed earlier (its parent link stays, as in 1.6): it is in no child
+ // list, so there is nothing to take it out of.
+ const detached = isElementNode(node) && node._detached;
+ // The renderer node of a rendered element is placed among its siblings
+ // in `children` order (B19: renderer v2 draws siblings in that order).
+ // The renderer keeps siblings sorted by zIndex: when the anchor's zIndex
+ // is not the child's, it takes the nearest sorted place instead, so
+ // among equal-zIndex siblings its order can then differ from `children`.
+ const drawn = this.rendered && isElementNode(node) && node.rendered;
+ // A move within this node: the renderer sibling it was drawn before, so
+ // a move that leaves it there costs the renderer nothing.
+ let drawnBefore: ElementNode | null = null;
+ // Before itself: it stays where it is (DOM semantics). Solid's swap of
+ // adjacent items asks for this (insertNode(parent, y, nextSibling(x))).
+ if (beforeNode === node) {
+ beforeNode =
+ prevParent === this && !detached
+ ? children[lastIndexOf(children, node) + 1]
+ : undefined;
+ }
+ // A node in a parent (this one too) is taken out first, then inserted
+ // before `beforeNode`, or appended.
+ if (prevParent !== undefined && !detached) {
+ if (drawn && prevParent === this) {
+ drawnBefore = nextDrawn(children, lastIndexOf(children, node) + 1);
}
+ prevParent.removeChild(node);
+ }
+ // In a child list again (removeChild above marked it detached).
+ if (isElementNode(node)) {
+ node._detached = false;
+ }
+
+ // We're inserting a node thats been rendered into a node that hasn't been
+ if (!this.rendered && isElementNode(node) && node.rendered) {
+ this._hasRenderedChildren = true;
+ }
+
+ // DOM insertBefore semantics: an anchor that is not a child appends.
+ let index =
+ beforeNode !== undefined && beforeNode !== null
+ ? lastIndexOf(children, beforeNode)
+ : -1;
+ if (index === -1) {
+ index = children.length;
+ children.push(node as ElementNode);
+ } else {
+ insertAt(children, index, node as ElementNode);
}
- this.children.push(node as ElementNode);
+ if (!drawn) {
+ node.parent = this;
+ return;
+ }
+ // insertBefore reparents the renderer node too, so the parent setter's
+ // renderer write is skipped.
+ (node as ElementNode)._parent = this;
+ const next = nextDrawn(children, index + 1);
+ if (prevParent !== this || detached || next !== drawnBefore) {
+ (this.lng as INode).insertBefore(
+ (node as ElementNode).lng as INode,
+ next === null ? null : (next.lng as INode),
+ );
+ }
+ }
+
+ /**
+ * After `render()` made `node`'s renderer node (it appends), move it before
+ * the renderer node of its next rendered sibling (B19). solidOpts calls it
+ * for a node inserted before an anchor.
+ */
+ _drawInOrder(node: ElementNode) {
+ const children = this.children;
+ const next = nextDrawn(children, lastIndexOf(children, node) + 1);
+ if (next !== null) {
+ (this.lng as INode).insertBefore(node.lng as INode, next.lng as INode);
+ }
}
removeChild(node: ElementNode | ElementText | TextNode) {
- if (removeItem(this.children, node as ElementNode) > -1) {
- if (isElementNode(node) && node.onRemove) {
- node.onRemove.call(node, node);
+ const children = this.children;
+ const index = lastIndexOf(children, node);
+ if (index > -1) {
+ removeAt(children, index);
+ if (isElementNode(node)) {
+ node._detached = true;
+ if (node.onRemove) {
+ node.onRemove.call(node, node);
+ }
}
if (this.requiresLayout()) {
- addToLayoutQueue(this);
+ queueLayout(this);
}
}
}
@@ -1157,45 +1430,66 @@ export class ElementNode {
: shaderProps;
}
- _sendToLightningAnimatable(name: string, value: number) {
- if (
- this.rendered &&
- this.transition &&
- Config.animationsEnabled &&
- (this.transition === true ||
- this.transition[name] ||
- this.transition[getPropertyAlias(name)])
- ) {
- const animationSettings =
- this.transition === true || this.transition[name] === true
- ? undefined
- : this.transition[name] ||
- (this.transition[getPropertyAlias(name)] as
- | undefined
- | AnimationSettings);
-
- // If the renderer doesn't support animateProp,
- // keep backwards compatible with LightningRenderer
- if (!('animateProp' in this.lng)) {
- const animationController = this.animate(
- { [name]: value },
- animationSettings,
- );
- this._fireAnimationEvents(name, value, animationSettings);
- return animationController.start();
+ /**
+ * The transition path of an animatable prop's setter, which calls it only
+ * when the node has a `transition`. Returns true when the write became an
+ * animation; false when the setter stores the value itself (the common
+ * case is a direct store in the setter, under its own name).
+ */
+ _sendToLightningAnimatable(name: string, value: number): boolean {
+ const transition = this.transition;
+ if (!this.rendered || !transition || !Config.animationsEnabled) {
+ return false;
+ }
+ let animationSettings: AnimationSettings | undefined;
+ if (transition !== true) {
+ const own = transition[name];
+ // The transition may name w/h as width/height. Written inline: a
+ // single-use helper here is what terser inlines as an IIFE (a closure
+ // per call) under its default compress options.
+ const setting =
+ own ||
+ (name === 'w'
+ ? transition.width
+ : name === 'h'
+ ? transition.height
+ : undefined);
+ if (!setting) {
+ return false;
}
+ animationSettings =
+ own === true ? undefined : (setting as AnimationSettings | undefined);
+ }
- const result = (this.lng as INode).animateProp(
- name,
- value,
- animationSettings || this.animationSettings || {},
+ // If the renderer doesn't support animateProp,
+ // keep backwards compatible with LightningRenderer
+ if (!('animateProp' in this.lng)) {
+ const animationController = this.animate(
+ { [name]: value },
+ animationSettings,
);
this._fireAnimationEvents(name, value, animationSettings);
- return result;
+ animationController.start();
+ return true;
}
- (this.lng[name as keyof (IRendererNode | INode)] as number | string) =
- value;
+ (this.lng as INode).animateProp(
+ name,
+ value,
+ animationSettings || this.animationSettings || {},
+ );
+ // A text's layout prop: its container follows the animated sizes.
+ if (
+ this._type === NodeType.TextNode &&
+ (name === 'fontSize' ||
+ name === 'lineHeight' ||
+ name === 'w' ||
+ name === 'h')
+ ) {
+ this._textLayoutAnimated();
+ }
+ this._fireAnimationEvents(name, value, animationSettings);
+ return true;
}
_fireAnimationEvents(
@@ -1223,10 +1517,16 @@ export class ElementNode {
if (isDev) console.log('NOT RENDERED! CANNOT ANIMATE');
return { start: () => {} } as IAnimationController;
}
- return (this.lng as IRendererNode).animate(
+ const controller = (this.lng as IRendererNode).animate(
props,
animationSettings || this.animationSettings || {},
);
+ if (this._type === NodeType.TextNode && animatesTextLayout(props)) {
+ // Started now or later, again or not at all: the text hears its
+ // layouts from now on (`_listenTextLoaded`).
+ this._textLayoutAnimated();
+ }
+ return controller;
}
chain(props: Partial, animationSettings?: AnimationSettings) {
@@ -1305,12 +1605,220 @@ export class ElementNode {
}
_layoutOnLoad() {
+ // An autosize node takes its size from its texture: the size the
+ // parent's last layout saw, so a load that leaves it unchanged needs no
+ // layout; a new one queues the parent and runs the pass in the frame.
+ // (A text in a layout parent is measured instead: _measureText.)
+ let width = this.width;
+ let height = this.height;
(this.lng as IRendererNode).on('loaded', () => {
- schedulePostMutation();
- this.parent!.updateLayout();
+ const w = this.width;
+ const h = this.height;
+ if (w === width && h === height) return;
+ width = w;
+ height = h;
+ const parent = this.parent;
+ if (parent !== undefined && parent !== null && !this._detached) {
+ enqueueLayout(parent);
+ schedulePostMutationInFrame();
+ }
+ });
+ }
+
+ /**
+ * @internal A prop the text layout reads was written on this element:
+ * `text`, `fontFamily`/`fontWeight`, `fontSize`, `lineHeight`,
+ * `letterSpacing`, `maxWidth`/`width`, `maxHeight`/`height`, `maxLines`,
+ * `wordBreak`, `overflowSuffix`. A rendered `` whose parent lays out
+ * is measured again in the post-mutation pass, and its parent laid out if
+ * its size changed. Anything else returns at once.
+ */
+ _textLayoutDirty(): void {
+ if (this._type !== NodeType.TextNode || this.rendered !== true) {
+ return;
+ }
+ let m = this._text;
+ if (m !== undefined && m.due === true) {
+ return;
+ }
+ const parent = this._parent;
+ if (parent === undefined || parent._requiresLayout !== true) {
+ // No layout reads it: a parent that lays it out later measures it
+ // first (updateLayout), as one it never measured.
+ if (m !== undefined) {
+ m.w = NaN;
+ }
+ return;
+ }
+ if (m === undefined) {
+ m = new TextMeasure();
+ this._text = m;
+ }
+ m.due = true;
+ textMeasureQueue[textMeasureCount++] = this;
+ schedulePostMutation();
+ }
+
+ /**
+ * @internal Size this rendered `` for its parent's layout now, with
+ * the renderer's synchronous `measure()` (renderer v2 lays it out into its
+ * layout cache, and the walk reuses that layout). Returns whether its
+ * width or height, as flex reads them (`maxWidth || w`, `maxHeight || h`),
+ * changed since the last call. A text with both max sizes is that large to
+ * flex whatever its layout: the walk lays it out. While its font is
+ * missing it waits (`_waitForFont`).
+ */
+ _measureText(): boolean {
+ let m = this._text;
+ if (m === undefined) {
+ m = new TextMeasure();
+ this._text = m;
+ }
+ m.due = false;
+ const lng = this.lng as IRendererTextNode;
+ const maxWidth = lng.maxWidth;
+ const maxHeight = lng.maxHeight;
+ if (!(maxWidth > 0 && maxHeight > 0)) {
+ if (lng.measure() === true) {
+ if (m.waiting === true) {
+ // The font arrived: stop listening (the list entry goes at the
+ // next measureFontWaiting).
+ m.waiting = false;
+ lng.off('loaded', fontWaitHeard);
+ fontWaitingDue = true;
+ }
+ } else if (lng.destroyed === true) {
+ return false; // in a subtree destroyed since it was written
+ } else if (m.waiting === false) {
+ this._waitForFont(m);
+ }
+ }
+ const w = maxWidth || lng.w;
+ const h = maxHeight || lng.h;
+ if (w === m.w && h === m.h) {
+ return false;
+ }
+ m.w = w;
+ m.h = h;
+ return true;
+ }
+
+ /**
+ * @internal Development only, on `loaded`: a layout Solid did not ask for
+ * (the walk's) changed the size of a text Solid measures, so its parent's
+ * flex has the old one. A prop the layout reads was written on the
+ * renderer node (`el.lng`) rather than on the element, or animated there.
+ */
+ _warnUnmeasuredLayout(): void {
+ const m = this._text;
+ if (
+ m === undefined ||
+ m.due === true ||
+ m.waiting === true ||
+ m.listening === true ||
+ m.w !== m.w ||
+ this._parent === undefined ||
+ this._parent._requiresLayout !== true
+ ) {
+ return;
+ }
+ const lng = this.lng as IRendererTextNode;
+ if ((lng.maxWidth || lng.w) !== m.w || (lng.maxHeight || lng.h) !== m.h) {
+ console.warn(
+ '[solid] A text in a flex container was laid out at a size Solid did not measure: a prop its layout reads was written, or animated, on its renderer node (el.lng) instead of on the element. Its container keeps the old size.',
+ this,
+ );
+ }
+ }
+
+ /**
+ * @internal `measure()` found no font description: hear `loaded` once,
+ * when the walk lays the text out (the renderer wakes the nodes it
+ * visited), and wait for loadFonts() to say a font loaded (for one no walk
+ * visits). Either way measureFontWaiting measures it again.
+ */
+ _waitForFont(m: TextMeasure): void {
+ m.waiting = true;
+ (this.lng as IRendererTextNode).on('loaded', fontWaitHeard);
+ if (
+ measuringFontWaiting === false &&
+ fontWaiting.length >= fontWaitingSweepAt
+ ) {
+ sweepFontWaiting();
+ }
+ fontWaiting.push(this);
+ }
+
+ /**
+ * @internal Solid animated a prop this text's layout reads
+ * (`_sendToLightningAnimatable`, `animate()`): from now on, for the text's
+ * lifetime, each layout the walk makes of an animated value lays its
+ * container out again in that frame, as 1.6's `loaded` listener did.
+ * Lifetime, not the animation's: Solid does not see a controller started
+ * later, or again (`animate()` returns it to the app).
+ */
+ _textLayoutAnimated(): void {
+ if (this.rendered !== true) {
+ return;
+ }
+ const parent = this._parent;
+ if (parent === undefined || parent._requiresLayout !== true) {
+ return;
+ }
+ this._listenTextLoaded();
+ }
+
+ /**
+ * @internal Hear every layout of this text: one whose size, as flex reads
+ * it, Solid did not measure lays the container out in that frame. One
+ * closure per text, made once and kept for its lifetime, on its renderer
+ * node only (nothing else holds it, so it goes with the node). A layout
+ * Solid measured changes nothing, and asks for no second walk.
+ */
+ _listenTextLoaded(): void {
+ let m = this._text;
+ if (m === undefined) {
+ m = new TextMeasure();
+ this._text = m;
+ }
+ if (m.listening === true) {
+ return;
+ }
+ m.listening = true;
+ (this.lng as IRendererTextNode).on('loaded', () => {
+ if (this._textSizeChanged() === true) {
+ enqueueLayout(this._parent!);
+ schedulePostMutationInFrame();
+ }
});
}
+ /**
+ * @internal After a layout Solid did not make (the walk's, of an animated
+ * value; the DOM renderer's late re-measure): whether this text's size, as
+ * flex reads it, changed since Solid last saw it. If so, it is recorded
+ * and the caller lays the parent out. False while a measure is due.
+ */
+ _textSizeChanged(): boolean {
+ const m = this._text;
+ if (m === undefined || m.due === true || m.waiting === true) {
+ return false;
+ }
+ const parent = this._parent;
+ if (parent === undefined || parent._requiresLayout !== true) {
+ return false;
+ }
+ const lng = this.lng as IRendererTextNode;
+ const w = lng.maxWidth || lng.w;
+ const h = lng.maxHeight || lng.h;
+ if (w === m.w && h === m.h) {
+ return false;
+ }
+ m.w = w;
+ m.h = h;
+ return true;
+ }
+
getText(this: ElementText) {
const len = this.children.length;
if (len === 1) return this.children[0]!.text;
@@ -1539,33 +2047,66 @@ export class ElementNode {
}
updateLayout() {
- if (this.hasChildren) {
- if (isDev) log('Layout: ', this);
+ this._layoutQueued = false;
+ const children = this.children;
+ const numChildren = children.length;
+ if (numChildren === 0) return;
+ if (isDev) log('Layout: ', this);
+
+ const isFlex = this._display === 'flex';
+ if (isFlex && this.flexGrow && this.width === 0) {
+ return;
+ }
- if (this.display === 'flex' && this.flexGrow && this.width === 0) {
- return;
+ // Texts written since Solid last measured them (a direct updateLayout()
+ // before the post-mutation pass), or never measured (this container lays
+ // out only now): sized before the pass reads them.
+ for (let i = 0; i < numChildren; i++) {
+ const c = children[i] as ElementNode;
+ if (c._type === NodeType.TextNode && c.rendered === true) {
+ const m = c._text;
+ if (m === undefined || m.due === true || m.w !== m.w) {
+ c._measureText();
+ }
}
+ }
- const flexChanged = this.display === 'flex' && calculateFlex(this);
- layoutQueue.delete(this);
- const onLayoutChanged =
- isFunction(this.onLayout) && this.onLayout.call(this, this);
-
- if ((flexChanged || onLayoutChanged) && this.parent) {
- addToLayoutQueue(this.parent);
- }
+ let flexChanged = isFlex && calculateFlex(this);
- if (this._containsFlexGrow === true) {
- // Need to reprocess children
- this.children.forEach((c) => {
- if (c.display === 'flex' && isElementNode(c)) {
- // calculating directly to prevent infinite loops recalculating parents
- calculateFlex(c);
- isFunction(c.onLayout) && c.onLayout.call(c, c);
- addToLayoutQueue(this);
+ if (isFlex && this._containsFlexGrow === true) {
+ // This pass changed its children's sizes: lay out the flex ones again,
+ // directly, so they do not queue this container back through their
+ // own size. If one of them resized, lay this container out once more.
+ let childResized = false;
+ for (let i = 0; i < numChildren; i++) {
+ const c = children[i]!;
+ if (isElementNode(c) && c._display === 'flex') {
+ if (calculateFlex(c)) childResized = true;
+ const childOnLayout = c._onLayout;
+ if (childOnLayout !== undefined && isFunction(childOnLayout)) {
+ childOnLayout.call(c, c);
}
- });
+ }
}
+ if (childResized && calculateFlex(this)) {
+ flexChanged = true;
+ }
+ this._containsFlexGrow = null;
+ }
+
+ // One onLayout, after the final layout (the children's included).
+ const onLayout = this._onLayout;
+ const onLayoutChanged =
+ onLayout !== undefined &&
+ isFunction(onLayout) &&
+ onLayout.call(this, this);
+
+ // A container whose size changed queues its parent (one with nothing to
+ // lay out would do nothing).
+ // A removed container keeps its parent link but not its place.
+ const parent = this._detached ? undefined : this.parent;
+ if ((flexChanged || onLayoutChanged) && parent && parent._requiresLayout) {
+ queueLayout(parent);
}
}
@@ -1688,7 +2229,7 @@ export class ElementNode {
}
if (parent.requiresLayout()) {
- layoutQueue.add(parent);
+ queueLayout(parent);
}
if (this.rendered) {
@@ -1774,17 +2315,27 @@ export class ElementNode {
textProps.maxLines = textProps.maxLines ?? 99;
}
+ // B11: margins live on the ElementNode, not in the renderer props;
+ // resolved as flex resolves them (a side, else the margin array).
if (!textProps.maxWidth) {
textProps.maxWidth =
- parentWidth - textProps.x! - (textProps.marginRight || 0);
+ parentWidth -
+ textProps.x! -
+ (node.marginRight || getArrayValue(node.margin, 1));
}
if (textProps.contain === 'both' && !textProps.maxHeight) {
textProps.maxHeight =
- parentHeight - textProps.y! - (textProps.marginBottom || 0);
- } else if (textProps.maxLines === 1) {
+ parentHeight -
+ textProps.y! -
+ (node.marginBottom || getArrayValue(node.margin, 2));
+ } else if (textProps.maxLines === 1 && !textProps.maxHeight) {
+ // B12: a lineHeight at or below 3 multiplies the font size.
+ const lineHeight = textProps.lineHeight;
textProps.maxHeight =
- textProps.maxHeight || textProps.lineHeight || textProps.fontSize;
+ lineHeight && lineHeight <= 3 && textProps.fontSize
+ ? lineHeight * textProps.fontSize
+ : lineHeight || textProps.fontSize;
}
// textProps.w = textProps.h = 0;
}
@@ -1803,11 +2354,9 @@ export class ElementNode {
props as Partial & Partial,
) as IRendererTextNode;
- if (parent.requiresLayout()) {
- if (!textProps.maxWidth || !textProps.maxHeight) {
- node._layoutOnLoad();
- }
- }
+ // A text in a layout parent is queued to be measured below, once its
+ // listeners are on (an `onEvent.loaded` hears the layout measure()
+ // makes).
} else {
// If its not an image or texture apply some defaults
if (!props.texture) {
@@ -1872,16 +2421,6 @@ export class ElementNode {
node.lng = renderer.createNode(
props as Partial & Partial,
);
-
- if (node._hasRenderedChildren) {
- node._hasRenderedChildren = false;
-
- for (const child of node.children) {
- if (isElementNode(child) && isINode(child.lng)) {
- child.lng.parent = node.lng as INode;
- }
- }
- }
}
node.rendered = true;
@@ -1909,6 +2448,24 @@ export class ElementNode {
}
}
+ if (node._type === NodeType.TextNode && parent._requiresLayout === true) {
+ // Its parent's flex reads its size: it is measured in the post-mutation
+ // pass, before the parent's layout (queued above) and before the frame,
+ // instead of waiting for the walk's `loaded`. Not here: a write later
+ // in this tick would lay it out twice (and `loaded` twice).
+ if (isDomRendererActive()) {
+ // The DOM renderer measures again when a web font loads after the
+ // text was measured (its size then was the fallback font's): lay the
+ // container out at that size, as before 1.7.
+ node._listenTextLoaded();
+ } else if (isDev) {
+ (node.lng as IRendererTextNode).on('loaded', () =>
+ node._warnUnmeasuredLayout(),
+ );
+ }
+ node._textLayoutDirty();
+ }
+
// L3 Inspector adds div to the lng object
const div: HTMLElement | undefined = (node.lng as IRendererNode)?.div;
if (isDev && div) {
@@ -1920,12 +2477,19 @@ export class ElementNode {
if (node._type === NodeType.Element) {
// only element nodes will have children that need rendering
+ // Children rendered before this node (moved in) are reparented here,
+ // in children order with the new ones (B19: v2 draws in that order).
+ const reparent = node._hasRenderedChildren === true;
+ node._hasRenderedChildren = false;
const numChildren = node.children.length;
for (let i = 0; i < numChildren; i++) {
const c = node.children[i];
if (isDev) assertTruthy(c, 'Child is undefined');
// Text elements sneak in from Solid creating tracked nodes
if (isElementNode(c)) {
+ if (reparent && isINode(c.lng)) {
+ c.lng.parent = node.lng as INode;
+ }
c.render();
}
}
@@ -1940,27 +2504,743 @@ export class ElementNode {
}
}
-for (const key of LightningRendererNumberProps) {
- Object.defineProperty(ElementNode.prototype, key, {
- get(): number {
- return this.lng[key];
+/**
+ * The index of `item` in `list`, scanning from the end: Solid appends and
+ * removes at the tail most often. The first item is checked first, for
+ * Solid's cleanChildren, which removes the first child until none is left.
+ */
+function lastIndexOf(list: T[], item: T): number {
+ if (list[0] === item) {
+ return 0;
+ }
+ let i = list.length - 1;
+ while (i > 0 && list[i] !== item) {
+ i--;
+ }
+ return i === 0 ? -1 : i;
+}
+
+/** Removes `list[index]` without allocating (`splice` returns an array). */
+function removeAt(list: T[], index: number): void {
+ if (index === 0) {
+ list.shift();
+ return;
+ }
+ const last = list.length - 1;
+ for (let i = index; i < last; i++) {
+ list[i] = list[i + 1]!;
+ }
+ list.pop();
+}
+
+/** Inserts `item` at `index` without allocating. */
+function insertAt(list: T[], index: number, item: T): void {
+ let i = list.length;
+ list.push(item);
+ for (; i > index; i--) {
+ list[i] = list[i - 1]!;
+ }
+ list[index] = item;
+}
+
+/** The first rendered element in `children` from `from` on: the renderer sibling to draw before. */
+function nextDrawn(
+ children: ElementNode['children'],
+ from: number,
+): ElementNode | null {
+ for (let i = from; i < children.length; i++) {
+ const c = children[i];
+ if (c instanceof ElementNode && c.rendered) {
+ return c;
+ }
+ }
+ return null;
+}
+
+// Props forwarded to the renderer node, one accessor per prop (design
+// 3.6.6): every getter and setter below loads or stores one constant name,
+// so each has its own inline cache. A shared `this.lng[key]` body made from
+// a loop sees every name at one site: a megamorphic keyed access, and into
+// renderer v2's prototype accessors a call V8 does not inline (the double
+// it returns is boxed). Written out rather than made with `new Function`,
+// which a TV app's CSP may forbid.
+//
+// `lng` is the props bag before render and the renderer node after it. An
+// animatable setter stores directly unless the node has a `transition`,
+// then `_sendToLightningAnimatable` may animate instead.
+type Forwarding = Pick<
+ ElementNode,
+ 'transition' | '_sendToLightningAnimatable' | '_type' | '_textLayoutDirty'
+> & { lng: Record };
+
+const NO_TEXT_PROPS: Readonly> = Object.freeze({});
+
+/**
+ * Where a text-only prop is written: a ``'s renderer node (its props
+ * bag before render); on any other element, the ElementNode's `_textProps`.
+ * A renderer v2 handle takes no field it does not know (it would become a
+ * field of its own) and a view draws no text (B20).
+ */
+function textPropsFor(node: ElementNode): Record {
+ if (node._type === NodeType.TextNode) {
+ return node.lng as Record;
+ }
+ let own = node._textProps;
+ if (own === undefined) {
+ own = {};
+ node._textProps = own;
+ }
+ return own;
+}
+
+/** Where a text-only prop is read (textPropsFor), without allocating. */
+function textPropsOf(node: ElementNode): Readonly> {
+ if (node._type === NodeType.TextNode) {
+ return node.lng as Record;
+ }
+ const own = node._textProps;
+ return own === undefined ? NO_TEXT_PROPS : own;
+}
+
+/** The setter of a read-only forwarded prop: the write is ignored. */
+function ignoreWrite(_v: unknown) {}
+
+Object.defineProperties(ElementNode.prototype, {
+ // Animatable
+ alpha: {
+ get(this: Forwarding) {
+ return this.lng.alpha;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('alpha', v)
+ ) {
+ this.lng.alpha = v;
+ }
+ },
+ },
+ color: {
+ get(this: Forwarding) {
+ return this.lng.color;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('color', v)
+ ) {
+ this.lng.color = v;
+ }
+ },
+ },
+ colorTop: {
+ get(this: Forwarding) {
+ return this.lng.colorTop;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorTop', v)
+ ) {
+ this.lng.colorTop = v;
+ }
+ },
+ },
+ colorRight: {
+ get(this: Forwarding) {
+ return this.lng.colorRight;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorRight', v)
+ ) {
+ this.lng.colorRight = v;
+ }
+ },
+ },
+ colorLeft: {
+ get(this: Forwarding) {
+ return this.lng.colorLeft;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorLeft', v)
+ ) {
+ this.lng.colorLeft = v;
+ }
+ },
+ },
+ colorBottom: {
+ get(this: Forwarding) {
+ return this.lng.colorBottom;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorBottom', v)
+ ) {
+ this.lng.colorBottom = v;
+ }
+ },
+ },
+ colorTl: {
+ get(this: Forwarding) {
+ return this.lng.colorTl;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorTl', v)
+ ) {
+ this.lng.colorTl = v;
+ }
+ },
+ },
+ colorTr: {
+ get(this: Forwarding) {
+ return this.lng.colorTr;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorTr', v)
+ ) {
+ this.lng.colorTr = v;
+ }
+ },
+ },
+ colorBl: {
+ get(this: Forwarding) {
+ return this.lng.colorBl;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorBl', v)
+ ) {
+ this.lng.colorBl = v;
+ }
+ },
+ },
+ colorBr: {
+ get(this: Forwarding) {
+ return this.lng.colorBr;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('colorBr', v)
+ ) {
+ this.lng.colorBr = v;
+ }
+ },
+ },
+ h: {
+ get(this: Forwarding) {
+ return this.lng.h;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('h', v)
+ ) {
+ this.lng.h = v;
+ }
+ // On a text, the max height (renderer v2), which its layout reads.
+ if (this._type === NodeType.TextNode) {
+ this._textLayoutDirty();
+ }
+ },
+ },
+ mount: {
+ get(this: Forwarding) {
+ return this.lng.mount;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('mount', v)
+ ) {
+ this.lng.mount = v;
+ }
+ },
+ },
+ mountX: {
+ get(this: Forwarding) {
+ return this.lng.mountX;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('mountX', v)
+ ) {
+ this.lng.mountX = v;
+ }
+ },
+ },
+ mountY: {
+ get(this: Forwarding) {
+ return this.lng.mountY;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('mountY', v)
+ ) {
+ this.lng.mountY = v;
+ }
+ },
+ },
+ pivot: {
+ get(this: Forwarding) {
+ return this.lng.pivot;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('pivot', v)
+ ) {
+ this.lng.pivot = v;
+ }
+ },
+ },
+ pivotX: {
+ get(this: Forwarding) {
+ return this.lng.pivotX;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('pivotX', v)
+ ) {
+ this.lng.pivotX = v;
+ }
+ },
+ },
+ pivotY: {
+ get(this: Forwarding) {
+ return this.lng.pivotY;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('pivotY', v)
+ ) {
+ this.lng.pivotY = v;
+ }
+ },
+ },
+ rotation: {
+ get(this: Forwarding) {
+ return this.lng.rotation;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('rotation', v)
+ ) {
+ this.lng.rotation = v;
+ }
+ },
+ },
+ scale: {
+ get(this: Forwarding) {
+ return this.lng.scale;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('scale', v)
+ ) {
+ this.lng.scale = v;
+ }
+ },
+ },
+ scaleX: {
+ get(this: Forwarding) {
+ return this.lng.scaleX;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('scaleX', v)
+ ) {
+ this.lng.scaleX = v;
+ }
+ },
+ },
+ scaleY: {
+ get(this: Forwarding) {
+ return this.lng.scaleY;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('scaleY', v)
+ ) {
+ this.lng.scaleY = v;
+ }
+ },
+ },
+ w: {
+ get(this: Forwarding) {
+ return this.lng.w;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('w', v)
+ ) {
+ this.lng.w = v;
+ }
+ // On a text, the max width (renderer v2), which its layout reads.
+ if (this._type === NodeType.TextNode) {
+ this._textLayoutDirty();
+ }
+ },
+ },
+ x: {
+ get(this: Forwarding) {
+ return this.lng.x;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('x', v)
+ ) {
+ this.lng.x = v;
+ }
+ },
+ },
+ y: {
+ get(this: Forwarding) {
+ return this.lng.y;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('y', v)
+ ) {
+ this.lng.y = v;
+ }
+ },
+ },
+ zIndex: {
+ get(this: Forwarding) {
+ return this.lng.zIndex;
+ },
+ set(this: Forwarding, v: number) {
+ if (
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('zIndex', v)
+ ) {
+ this.lng.zIndex = v;
+ }
+ },
+ },
+ // Animatable, text only
+ fontSize: {
+ get(this: ElementNode) {
+ return textPropsOf(this).fontSize;
},
set(this: ElementNode, v: number) {
- this._sendToLightningAnimatable(key, v);
+ if (
+ this._type !== NodeType.TextNode ||
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('fontSize', v)
+ ) {
+ textPropsFor(this).fontSize = v;
+ }
+ this._textLayoutDirty();
},
- });
-}
-
-for (const key of LightningRendererNonAnimatingProps) {
- Object.defineProperty(ElementNode.prototype, key, {
- get(): unknown {
- return this.lng[key];
+ },
+ lineHeight: {
+ get(this: ElementNode) {
+ return textPropsOf(this).lineHeight;
},
- set(v: unknown) {
- this.lng[key] = v;
+ set(this: ElementNode, v: number) {
+ if (
+ this._type !== NodeType.TextNode ||
+ this.transition === undefined ||
+ !this._sendToLightningAnimatable('lineHeight', v)
+ ) {
+ textPropsFor(this).lineHeight = v;
+ }
+ this._textLayoutDirty();
},
- });
-}
+ },
+ // Not animated
+ atlasGroup: {
+ get(this: Forwarding) {
+ return this.lng.atlasGroup;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.atlasGroup = v;
+ },
+ },
+ autosize: {
+ get(this: Forwarding) {
+ return this.lng.autosize;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.autosize = v;
+ },
+ },
+ clipping: {
+ get(this: Forwarding) {
+ return this.lng.clipping;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.clipping = v;
+ },
+ },
+ componentName: {
+ get(this: Forwarding) {
+ return this.lng.componentName;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.componentName = v;
+ },
+ },
+ componentLocation: {
+ get(this: Forwarding) {
+ return this.lng.componentLocation;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.componentLocation = v;
+ },
+ },
+ data: {
+ get(this: Forwarding) {
+ return this.lng.data;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.data = v;
+ },
+ },
+ ignoreParentAlpha: {
+ get(this: Forwarding) {
+ return this.lng.ignoreParentAlpha;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.ignoreParentAlpha = v;
+ },
+ },
+ imageType: {
+ get(this: Forwarding) {
+ return this.lng.imageType;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.imageType = v;
+ },
+ },
+ placeholderColor: {
+ get(this: Forwarding) {
+ return this.lng.placeholderColor;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.placeholderColor = v;
+ },
+ },
+ srcHeight: {
+ get(this: Forwarding) {
+ return this.lng.srcHeight;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.srcHeight = v;
+ },
+ },
+ srcWidth: {
+ get(this: Forwarding) {
+ return this.lng.srcWidth;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.srcWidth = v;
+ },
+ },
+ srcX: {
+ get(this: Forwarding) {
+ return this.lng.srcX;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.srcX = v;
+ },
+ },
+ srcY: {
+ get(this: Forwarding) {
+ return this.lng.srcY;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.srcY = v;
+ },
+ },
+ texture: {
+ get(this: Forwarding) {
+ return this.lng.texture;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.texture = v;
+ },
+ },
+ textureOptions: {
+ get(this: Forwarding) {
+ return this.lng.textureOptions;
+ },
+ set(this: Forwarding, v: unknown) {
+ this.lng.textureOptions = v;
+ },
+ },
+ // Not animated, text only
+ contain: {
+ get(this: ElementNode) {
+ return textPropsOf(this).contain;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).contain = v;
+ // The DOM renderer sizes a text by it (renderer v2 only moves the
+ // block: the measure finds nothing to lay out).
+ this._textLayoutDirty();
+ },
+ },
+ forceLoad: {
+ get(this: ElementNode) {
+ return textPropsOf(this).forceLoad;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).forceLoad = v;
+ },
+ },
+ fontStyle: {
+ get(this: ElementNode) {
+ return textPropsOf(this).fontStyle;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).fontStyle = v;
+ },
+ },
+ letterSpacing: {
+ get(this: ElementNode) {
+ return textPropsOf(this).letterSpacing;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).letterSpacing = v;
+ this._textLayoutDirty();
+ },
+ },
+ maxHeight: {
+ get(this: ElementNode) {
+ return textPropsOf(this).maxHeight;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).maxHeight = v;
+ this._textLayoutDirty();
+ },
+ },
+ maxLines: {
+ get(this: ElementNode) {
+ return textPropsOf(this).maxLines;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).maxLines = v;
+ this._textLayoutDirty();
+ },
+ },
+ maxWidth: {
+ get(this: ElementNode) {
+ return textPropsOf(this).maxWidth;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).maxWidth = v;
+ this._textLayoutDirty();
+ },
+ },
+ offsetY: {
+ get(this: ElementNode) {
+ return textPropsOf(this).offsetY;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).offsetY = v;
+ },
+ },
+ overflowSuffix: {
+ get(this: ElementNode) {
+ return textPropsOf(this).overflowSuffix;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).overflowSuffix = v;
+ this._textLayoutDirty();
+ },
+ },
+ text: {
+ get(this: ElementNode) {
+ return textPropsOf(this).text;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).text = v;
+ this._textLayoutDirty();
+ },
+ },
+ textAlign: {
+ get(this: ElementNode) {
+ return textPropsOf(this).textAlign;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).textAlign = v;
+ },
+ },
+ verticalAlign: {
+ get(this: ElementNode) {
+ return textPropsOf(this).verticalAlign;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).verticalAlign = v;
+ },
+ },
+ wordBreak: {
+ get(this: ElementNode) {
+ return textPropsOf(this).wordBreak;
+ },
+ set(this: ElementNode, v: unknown) {
+ textPropsFor(this).wordBreak = v;
+ this._textLayoutDirty();
+ },
+ },
+ // Read-only on the renderer node: a write would throw there (B20)
+ absX: {
+ get(this: Forwarding) {
+ return this.lng.absX;
+ },
+ set: ignoreWrite,
+ },
+ absY: {
+ get(this: Forwarding) {
+ return this.lng.absY;
+ },
+ set: ignoreWrite,
+ },
+ destroyed: {
+ get(this: Forwarding) {
+ return this.lng.destroyed;
+ },
+ set: ignoreWrite,
+ },
+});
+
+// The DOM renderer draws fontStretch; a rendered WebGL text node has no such
+// prop, and a @solidtv/renderer 2.0 node would take it as a field of its own.
+// Before render the value waits in the props bag, which the renderer's
+// createTextNode ignores.
+Object.defineProperty(ElementNode.prototype, 'fontStretch', {
+ get(this: ElementNode): unknown {
+ return (this.lng as unknown as Record).fontStretch;
+ },
+ set(this: ElementNode, v: unknown) {
+ if (this.rendered && !isDomRendererActive()) return;
+ (this.lng as unknown as Record).fontStretch = v;
+ },
+});
export function createRawShaderAccessor(key: keyof StyleEffects) {
return {
diff --git a/src/core/flex.ts b/src/core/flex.ts
deleted file mode 100644
index 29beef37..00000000
--- a/src/core/flex.ts
+++ /dev/null
@@ -1,332 +0,0 @@
-import { type ElementNode } from './elementNode.js';
-import { isTextNode, isElementText } from './utils.js';
-import { isDev } from './env.js';
-
-export default function (node: ElementNode): boolean {
- const direction = node.flexDirection || 'row';
- const isRow = direction === 'row' || direction === 'row-reverse';
- const isReverse =
- direction === 'row-reverse' || direction === 'column-reverse';
- const dimension = isRow ? 'width' : 'height';
- const crossDimension = isRow ? 'height' : 'width';
- const marginOne = isRow ? 'marginLeft' : 'marginTop';
- const crossMarginOne = isRow ? 'marginTop' : 'marginLeft';
- const marginTwo = isRow ? 'marginRight' : 'marginBottom';
- const crossMarginTwo = isRow ? 'marginBottom' : 'marginRight';
- const minDimension = isRow ? 'minWidth' : 'minHeight';
- const crossMinDimension = isRow ? 'minHeight' : 'minWidth';
-
- const children = node.children;
- const numChildren = children.length;
-
- if (numChildren === 0) {
- return false;
- }
-
- const processableChildrenIndices: number[] = [];
- let hasOrder = false;
- let totalFlexGrow = 0;
-
- for (let i = 0; i < numChildren; i++) {
- const c = children[i]!;
-
- if (isElementText(c) && c.text && !(c.width || c.height)) {
- return false;
- }
-
- if (isTextNode(c) || c.flexItem === false) {
- continue;
- }
-
- if (c.flexOrder !== undefined) {
- hasOrder = true;
- }
-
- const flexGrow = c.flexGrow;
- if (flexGrow !== undefined && flexGrow >= 0) {
- totalFlexGrow += flexGrow;
- }
-
- if (c[minDimension] && (c[dimension] || 0) < c[minDimension]) {
- c[dimension] = c[minDimension]!;
- }
-
- if (
- c[crossMinDimension] &&
- (c[crossDimension] || 0) < c[crossMinDimension]
- ) {
- c[crossDimension] = c[crossMinDimension]!;
- }
-
- processableChildrenIndices.push(i);
- }
-
- if (hasOrder) {
- processableChildrenIndices.sort((aIdx, bIdx) => {
- const a = children[aIdx] as ElementNode;
- const b = children[bIdx] as ElementNode;
- return (a.flexOrder || 0) - (b.flexOrder || 0);
- });
- }
-
- if (isReverse || node.direction === 'rtl') {
- processableChildrenIndices.reverse();
- }
-
- const numProcessedChildren = processableChildrenIndices.length;
- if (numProcessedChildren === 0) {
- return false; // No layout changes if no processable children
- }
-
- const prop = isRow ? 'x' : 'y';
- const crossProp = isRow ? 'y' : 'x';
- const containerSize = Math.max(
- node[dimension] || 0,
- node[minDimension] || 0,
- 0,
- );
- let containerCrossSize = Math.max(
- node[crossDimension] || 0,
- node[crossMinDimension] || 0,
- 0,
- );
- const isWrapReverse = node.flexWrap === 'wrap-reverse';
- const gap = node.gap || 0;
- const justify = node.justifyContent || 'flexStart';
- const nodePadding = (node.padding as number) || 0;
- let containerUpdated = false;
-
- const childMainSizes = new Float32Array(numProcessedChildren);
- const childMarginStarts = new Float32Array(numProcessedChildren);
- const childMarginEnds = new Float32Array(numProcessedChildren);
- const childTotalMainSizes = new Float32Array(numProcessedChildren);
- const childCrossSizes = new Float32Array(numProcessedChildren);
- const childMarginCrossStarts = new Float32Array(numProcessedChildren);
- const childMarginCrossEnds = new Float32Array(numProcessedChildren);
-
- let sumOfFlexBaseSizesWithMargins = 0;
-
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
-
- const baseMainSize = c[dimension] || 0;
- const marginStart = (c[marginOne] as number) || 0;
- const marginEnd = (c[marginTwo] as number) || 0;
-
- childMainSizes[idx] = baseMainSize;
- childMarginStarts[idx] = marginStart;
- childMarginEnds[idx] = marginEnd;
- childTotalMainSizes[idx] = baseMainSize + marginStart + marginEnd;
-
- childCrossSizes[idx] = c[crossDimension] || 0;
- childMarginCrossStarts[idx] = (c[crossMarginOne] as number) || 0;
- childMarginCrossEnds[idx] = (c[crossMarginTwo] as number) || 0;
-
- sumOfFlexBaseSizesWithMargins += childTotalMainSizes[idx]!;
- }
-
- if (totalFlexGrow > 0 && numProcessedChildren > 1) {
- // When flex-grow is used, the container's size is considered fixed for this calculation pass,
- // unless flexBoundary is explicitly set to allow container resizing based on content.
- node.flexBoundary = node.flexBoundary || 'fixed';
-
- // Calculate the total space occupied by gaps between items.
- const totalGapSpace =
- numProcessedChildren > 0 ? gap * (numProcessedChildren - 1) : 0;
-
- // Calculate the available space for flex items to grow into.
- const availableSpace =
- containerSize - sumOfFlexBaseSizesWithMargins - totalGapSpace;
-
- if (availableSpace > 0) {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- const flexGrowValue = c.flexGrow;
- if (flexGrowValue !== undefined && flexGrowValue > 0) {
- const shareOfSpace = (flexGrowValue / totalFlexGrow) * availableSpace;
- const newMainSize = childMainSizes[idx]! + shareOfSpace;
- c[dimension] = newMainSize;
- childMainSizes[idx] = newMainSize;
- childTotalMainSizes[idx] =
- newMainSize + childMarginStarts[idx]! + childMarginEnds[idx]!;
- }
- }
- // prevent infinite loops by only doing this once
- node._containsFlexGrow = node._containsFlexGrow ? null : true;
- } else if (node._containsFlexGrow) {
- node._containsFlexGrow = null;
- } else if (isDev) {
- // No positive space available for items to grow, or items overflow.
- // flex-grow has no effect in this case.
- console.warn(
- 'No available space for flex-grow items to expand, or items overflow.',
- );
- }
- }
-
- let totalItemSize = 0;
- if (
- justify === 'center' ||
- justify === 'spaceBetween' ||
- justify === 'spaceEvenly' ||
- justify === 'spaceAround'
- ) {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- totalItemSize += childTotalMainSizes[idx]!;
- }
- }
-
- const align = node.alignItems || (node.flexWrap ? 'flexStart' : undefined);
- const doCrossAlign = containerCrossSize
- ? (c: ElementNode, idx: number, crossCurrentPos: number = 0) => {
- const alignSelf = c.alignSelf || align;
- if (!alignSelf) {
- return;
- }
- if (alignSelf === 'flexStart') {
- c[crossProp] = crossCurrentPos + childMarginCrossStarts[idx]!;
- } else if (alignSelf === 'center') {
- c[crossProp] =
- crossCurrentPos +
- (containerCrossSize - childCrossSizes[idx]!) / 2 +
- childMarginCrossStarts[idx]!;
- } else if (alignSelf === 'flexEnd') {
- c[crossProp] =
- crossCurrentPos +
- containerCrossSize -
- childCrossSizes[idx]! -
- childMarginCrossEnds[idx]!;
- }
- }
- : (_c: ElementNode, _idx: number, _crossCurrentPos: number = 0) => {
- /* no-op */
- };
-
- if (isRow && node._calcHeight && !node.flexCrossBoundary) {
- let maxHeight = 0;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- if (childCrossSizes[idx]! > maxHeight) maxHeight = childCrossSizes[idx]!;
- }
- const newHeight = maxHeight || node.height;
- if (newHeight !== node.height) {
- containerUpdated = true;
- node.height = containerCrossSize = newHeight;
- }
- }
-
- let currentPos = nodePadding;
- if (justify === 'flexStart') {
- if (node.flexWrap === 'wrap' || isWrapReverse) {
- const childCrossSizeVar =
- numProcessedChildren > 0 ? childCrossSizes[0]! : containerCrossSize;
- let crossCurrentPos = isWrapReverse
- ? containerCrossSize - childCrossSizeVar
- : 0;
- const crossGap = isRow ? (node.columnGap ?? gap) : (node.rowGap ?? gap);
-
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- if (
- currentPos + childTotalMainSizes[idx]! > containerSize &&
- currentPos > nodePadding
- ) {
- currentPos = nodePadding;
- crossCurrentPos += isWrapReverse
- ? -(childCrossSizeVar + crossGap)
- : childCrossSizeVar + crossGap;
- }
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx, crossCurrentPos);
- }
-
- const finalCrossSize = isWrapReverse
- ? containerCrossSize - crossCurrentPos
- : crossCurrentPos + childCrossSizeVar;
-
- if (node[crossDimension] !== finalCrossSize) {
- node[`preFlex${crossDimension}`] = node[crossDimension];
- node[crossDimension] = finalCrossSize;
- containerUpdated = true;
- }
- } else {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx);
- }
- }
- // Update container size
- if (node.flexBoundary !== 'fixed' && node.flexWrap !== 'wrap') {
- let calculatedSize = currentPos - gap + nodePadding;
- const minSize = node[minDimension] || 0;
- if (calculatedSize < minSize) {
- calculatedSize = minSize;
- }
- if (calculatedSize !== (node[dimension] || 0)) {
- // store the original size for Row & Column
- node[`preFlex${dimension}`] = containerSize;
- node[dimension] = calculatedSize;
- return true;
- }
- }
- } else if (justify === 'flexEnd') {
- currentPos = containerSize - nodePadding;
- for (let idx = numProcessedChildren - 1; idx >= 0; idx--) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos - childMainSizes[idx]! - childMarginEnds[idx]!;
- currentPos -= childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx);
- }
- } else if (justify === 'center') {
- currentPos =
- (containerSize - (totalItemSize + gap * (numProcessedChildren - 1))) / 2 +
- nodePadding;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx);
- }
- } else if (justify === 'spaceBetween') {
- const spaceBetween =
- numProcessedChildren > 1
- ? (containerSize - totalItemSize - nodePadding * 2) /
- (numProcessedChildren - 1)
- : 0;
- currentPos = nodePadding;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + spaceBetween;
- doCrossAlign(c, idx);
- }
- } else if (justify === 'spaceAround') {
- const spaceAround =
- numProcessedChildren > 0
- ? (containerSize - totalItemSize - nodePadding * 2) /
- numProcessedChildren
- : 0;
- currentPos = nodePadding + spaceAround / 2;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + spaceAround;
- doCrossAlign(c, idx);
- }
- } else if (justify === 'spaceEvenly') {
- const spaceEvenly =
- (containerSize - totalItemSize - nodePadding * 2) /
- (numProcessedChildren + 1);
- currentPos = spaceEvenly + nodePadding;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + spaceEvenly;
- doCrossAlign(c, idx);
- }
- }
-
- return containerUpdated;
-}
diff --git a/src/core/flexLayout.ts b/src/core/flexLayout.ts
index f8045033..8fe5bdc4 100644
--- a/src/core/flexLayout.ts
+++ b/src/core/flexLayout.ts
@@ -1,7 +1,69 @@
import { type ElementNode } from './elementNode.js';
+import { Config } from './config.js';
import { isTextNode, isElementText } from './utils.js';
-function getArrayValue(
+// One flex pass over one container. It allocates nothing in the steady
+// state: the per-child values live in module-level typed arrays that grow on
+// demand and are reused by every pass, and the children are reached through
+// an index array (`order`), sorted by `flexOrder` only when a child has one.
+// A prop is written only when it must be, so a relayout that moves nothing
+// writes nothing (and starts no transition). A prop with a transition reads
+// back its current, animated value, not its target, so for those the last
+// value this engine wrote is kept on the node (`_flexX`, `_flexY`, `_flexW`,
+// `_flexH`) and the write is skipped only when both match.
+
+/** Slot flags. */
+const FROM_RECORD = 1; // the main size came from the flexGrow record (B8)
+const GROWN = 2;
+const SHRUNK = 4;
+
+let capacity = 0;
+let childIndex = new Int32Array(0); // slot -> index in node.children
+let order = new Int32Array(0); // layout position -> slot
+let flags = new Uint8Array(0);
+let mainSize = new Float64Array(0);
+let mainRead = new Float64Array(0); // the main size read from the child
+let ownSize = new Float64Array(0); // the size before flexGrow (B8)
+let marginStart = new Float64Array(0);
+let marginEnd = new Float64Array(0);
+let totalMain = new Float64Array(0);
+let crossSize = new Float64Array(0);
+let marginCrossStart = new Float64Array(0);
+let marginCrossEnd = new Float64Array(0);
+let growFactor = new Float64Array(0);
+let shrinkFactor = new Float64Array(0);
+let orderKey = new Float64Array(0);
+let lineStart = new Float64Array(0);
+
+function ensureCapacity(n: number): void {
+ if (n <= capacity) {
+ return;
+ }
+ let c = capacity * 2;
+ if (c < n) {
+ c = n < 16 ? 16 : n;
+ }
+ capacity = c;
+ childIndex = new Int32Array(c);
+ order = new Int32Array(c);
+ flags = new Uint8Array(c);
+ mainSize = new Float64Array(c);
+ mainRead = new Float64Array(c);
+ ownSize = new Float64Array(c);
+ marginStart = new Float64Array(c);
+ marginEnd = new Float64Array(c);
+ totalMain = new Float64Array(c);
+ crossSize = new Float64Array(c);
+ marginCrossStart = new Float64Array(c);
+ marginCrossEnd = new Float64Array(c);
+ growFactor = new Float64Array(c);
+ shrinkFactor = new Float64Array(c);
+ orderKey = new Float64Array(c);
+ lineStart = new Float64Array(c);
+}
+
+/** A `padding`/`margin` side from a number or a 2-4 value array. */
+export function getArrayValue(
val: number | number[] | undefined,
index: number,
defaultValue: number = 0,
@@ -21,13 +83,178 @@ function getArrayValue(
return result ?? defaultValue;
}
+/**
+ * Whether a write of `name` (or its alias) on `c` starts a transition, as
+ * ElementNode's animatable setter decides it.
+ */
+function animates(c: ElementNode, name: string, alias: string): boolean {
+ const t = c.transition;
+ if (!t || c.rendered !== true || !Config.animationsEnabled) {
+ return false;
+ }
+ return t === true || !!t[name] || !!t[alias];
+}
+
+function setSize(c: ElementNode, isWidth: boolean, v: number): void {
+ if (isWidth) {
+ c.width = v;
+ } else {
+ c.height = v;
+ }
+}
+
+/**
+ * Writes a size the engine computed, unless `current` (read from the node)
+ * is already `v` and, with a transition on it (`current` is then the
+ * animated value), `v` is also what this engine last wrote. Returns whether
+ * it wrote. Callers test `current !== v || c.transition` first, so the
+ * common no-write case passes no doubles to a call.
+ */
+function writeSize(
+ c: ElementNode,
+ isWidth: boolean,
+ current: number,
+ v: number,
+): boolean {
+ const animated = c.transition
+ ? isWidth
+ ? animates(c, 'w', 'width')
+ : animates(c, 'h', 'height')
+ : false;
+ if (current === v && (!animated || (isWidth ? c._flexW : c._flexH) === v)) {
+ return false;
+ }
+ if (animated) {
+ if (isWidth) {
+ c._flexW = v;
+ } else {
+ c._flexH = v;
+ }
+ }
+ setSize(c, isWidth, v);
+ return true;
+}
+
+/** Writes x or y as writeSize writes a size. */
+function setPos(c: ElementNode, isX: boolean, v: number): void {
+ if (isX) {
+ const animated = c.transition ? animates(c, 'x', 'x') : false;
+ if (c.x === v && (!animated || c._flexX === v)) return;
+ if (animated) c._flexX = v;
+ c.x = v;
+ } else {
+ const animated = c.transition ? animates(c, 'y', 'y') : false;
+ if (c.y === v && (!animated || c._flexY === v)) return;
+ if (animated) c._flexY = v;
+ c.y = v;
+ }
+}
+
+/**
+ * Places child `c` (slot `k`) on the cross axis of a line that starts at
+ * `start` and is `size` long.
+ */
+function alignCross(
+ c: ElementNode,
+ k: number,
+ isRow: boolean,
+ align: string | undefined,
+ start: number,
+ size: number,
+): void {
+ const alignSelf = c.alignSelf || align;
+ if (alignSelf === 'flexStart') {
+ setPos(c, !isRow, start + marginCrossStart[k]!);
+ } else if (alignSelf === 'center') {
+ setPos(
+ c,
+ !isRow,
+ start + (size - crossSize[k]!) / 2 + marginCrossStart[k]!,
+ );
+ } else if (alignSelf === 'flexEnd') {
+ setPos(c, !isRow, start + size - crossSize[k]! - marginCrossEnd[k]!);
+ }
+}
+
+let passDepth = 0;
+
+/**
+ * Lays out the children of a `display: 'flex'` container. Returns true when
+ * the container's own size changed, so its parent must be laid out again.
+ */
export default function (node: ElementNode): boolean {
+ if (passDepth === 0) {
+ passDepth = 1;
+ try {
+ return layout(node);
+ } finally {
+ passDepth = 0;
+ }
+ }
+ return nestedLayout(node);
+}
+
+/**
+ * A pass started while another runs (from an app callback a write fired,
+ * such as onAnimation calling updateLayout): it gets its own scratch, so
+ * the outer pass's is intact when it resumes. Allocates; not the hot path.
+ */
+function nestedLayout(node: ElementNode): boolean {
+ const sCapacity = capacity;
+ const sChildIndex = childIndex;
+ const sOrder = order;
+ const sFlags = flags;
+ const sMainSize = mainSize;
+ const sMainRead = mainRead;
+ const sOwnSize = ownSize;
+ const sMarginStart = marginStart;
+ const sMarginEnd = marginEnd;
+ const sTotalMain = totalMain;
+ const sCrossSize = crossSize;
+ const sMarginCrossStart = marginCrossStart;
+ const sMarginCrossEnd = marginCrossEnd;
+ const sGrowFactor = growFactor;
+ const sShrinkFactor = shrinkFactor;
+ const sOrderKey = orderKey;
+ const sLineStart = lineStart;
+ capacity = 0;
+ passDepth++;
+ try {
+ return layout(node);
+ } finally {
+ passDepth--;
+ capacity = sCapacity;
+ childIndex = sChildIndex;
+ order = sOrder;
+ flags = sFlags;
+ mainSize = sMainSize;
+ mainRead = sMainRead;
+ ownSize = sOwnSize;
+ marginStart = sMarginStart;
+ marginEnd = sMarginEnd;
+ totalMain = sTotalMain;
+ crossSize = sCrossSize;
+ marginCrossStart = sMarginCrossStart;
+ marginCrossEnd = sMarginCrossEnd;
+ growFactor = sGrowFactor;
+ shrinkFactor = sShrinkFactor;
+ orderKey = sOrderKey;
+ lineStart = sLineStart;
+ }
+}
+
+function layout(node: ElementNode): boolean {
+ const children = node.children;
+ const numChildren = children.length;
+
+ if (numChildren === 0) {
+ return false;
+ }
+
const direction = node.flexDirection || 'row';
const isRow = direction === 'row' || direction === 'row-reverse';
const isReverse =
direction === 'row-reverse' || direction === 'column-reverse';
- const dimension = isRow ? 'width' : 'height';
- const crossDimension = isRow ? 'height' : 'width';
// padding order: Top, Right, Bottom, Left
const nodePadding = node.padding;
@@ -42,207 +269,287 @@ export default function (node: ElementNode): boolean {
const paddingCrossEnd = isRow ? paddingBottom : paddingRight;
const nodePaddingTotal = paddingStart + paddingEnd;
- const minDimension = isRow ? 'minWidth' : 'minHeight';
- const crossMinDimension = isRow ? 'minHeight' : 'minWidth';
+ const flexWrap = node.flexWrap;
+ const isWrapReverse = flexWrap === 'wrap-reverse';
+ // B10: wrap-reverse wraps too.
+ const wrapping = flexWrap === 'wrap' || isWrapReverse;
+ const align = node.alignItems || (flexWrap ? 'flexStart' : undefined);
- const children = node.children;
- const numChildren = children.length;
+ ensureCapacity(numChildren);
- if (numChildren === 0) {
- return false;
- }
-
- // Optimize arrays caching
- const processableChildrenIndices: number[] = [];
+ let n = 0;
let hasOrder = false;
let totalFlexGrow = 0;
let totalFlexShrink = 0;
+ let sizeWork = false;
for (let i = 0; i < numChildren; i++) {
const c = children[i]!;
- if (isElementText(c) && c.text && !(c.width || c.height)) {
- return false; // specific text layout constraint
- }
-
+ // B5: a child that is not a flex item is skipped before the text check,
+ // so an unsized text with flexItem={false} does not block the pass.
if (isTextNode(c) || c.flexItem === false) {
continue;
}
- if (c.flexOrder !== undefined) {
+ const w = c.width;
+ const h = c.height;
+ if (isElementText(c) && c.text && !(w || h)) {
+ return false; // specific text layout constraint
+ }
+
+ const flexOrder = c.flexOrder;
+ if (flexOrder !== undefined) {
hasOrder = true;
}
const flexGrow = c.flexGrow;
- if (flexGrow !== undefined && flexGrow > 0) {
- totalFlexGrow += flexGrow;
- }
+ const grow = flexGrow !== undefined && flexGrow > 0 ? flexGrow : 0;
+ totalFlexGrow += grow;
const flexShrink = c.flexShrink;
if (flexShrink !== undefined && flexShrink > 0) {
totalFlexShrink += flexShrink;
}
- if (c[minDimension] && (c[dimension] || 0) < c[minDimension]) {
- c[dimension] = c[minDimension]!;
+ let main = isRow ? w : h;
+ let cross = isRow ? h : w;
+ const minMain = isRow ? c.minWidth : c.minHeight;
+ if (minMain && (main || 0) < minMain) {
+ setSize(c as ElementNode, isRow, minMain);
+ main = isRow ? c.width : c.height;
+ }
+ const minCross = isRow ? c.minHeight : c.minWidth;
+ if (minCross && (cross || 0) < minCross) {
+ setSize(c as ElementNode, !isRow, minCross);
+ cross = isRow ? c.height : c.width;
}
- if (
- c[crossMinDimension] &&
- (c[crossDimension] || 0) < c[crossMinDimension]
- ) {
- c[crossDimension] = c[crossMinDimension]!;
+ // B8: flexGrow starts from the item's own size, not from the size the
+ // last pass grew it to. The record holds both; a size written since
+ // (anything but the grown one) is the new own size. With a transition
+ // the read is the animated value, so the record is kept as it is.
+ const read = main || 0;
+ let own = read;
+ let flag = 0;
+ const grown = c._flexGrown;
+ if (grown !== undefined) {
+ if (
+ grow > 0 &&
+ (read === grown ||
+ (isRow
+ ? animates(c as ElementNode, 'w', 'width')
+ : animates(c as ElementNode, 'h', 'height')))
+ ) {
+ own = c._flexBase!;
+ flag = FROM_RECORD;
+ sizeWork = true;
+ } else {
+ c._flexGrown = undefined;
+ }
}
- processableChildrenIndices.push(i);
+ const flexBasis = c.flexBasis;
+ const base =
+ flexBasis === undefined || flexBasis === 'auto'
+ ? own
+ : Math.max(flexBasis as number, minMain || 0);
+
+ // index mappings for margins: Top: 0, Right: 1, Bottom: 2, Left: 3
+ const margin = c.margin;
+ let mStart: number;
+ let mEnd: number;
+ let mCrossStart: number;
+ let mCrossEnd: number;
+ if (isRow) {
+ mStart = c.marginLeft || getArrayValue(margin, 3);
+ mEnd = c.marginRight || getArrayValue(margin, 1);
+ mCrossStart = c.marginTop || getArrayValue(margin, 0);
+ mCrossEnd = c.marginBottom || getArrayValue(margin, 2);
+ } else {
+ mStart = c.marginTop || getArrayValue(margin, 0);
+ mEnd = c.marginBottom || getArrayValue(margin, 2);
+ mCrossStart = c.marginLeft || getArrayValue(margin, 3);
+ mCrossEnd = c.marginRight || getArrayValue(margin, 1);
+ }
+
+ const k = n++;
+ childIndex[k] = i;
+ flags[k] = flag;
+ mainSize[k] = base;
+ mainRead[k] = read;
+ ownSize[k] = own;
+ marginStart[k] = mStart;
+ marginEnd[k] = mEnd;
+ totalMain[k] = base + mStart + mEnd;
+ crossSize[k] = cross || 0;
+ marginCrossStart[k] = mCrossStart;
+ marginCrossEnd[k] = mCrossEnd;
+ growFactor[k] = grow;
+ shrinkFactor[k] = flexShrink || 0;
+ orderKey[k] = flexOrder || 0;
}
- if (hasOrder) {
- processableChildrenIndices.sort((aIdx, bIdx) => {
- const a = children[aIdx] as ElementNode;
- const b = children[bIdx] as ElementNode;
- return (a.flexOrder || 0) - (b.flexOrder || 0);
- });
+ if (n === 0) {
+ return false;
}
+ for (let p = 0; p < n; p++) {
+ order[p] = p;
+ }
+ if (hasOrder) {
+ // Stable insertion sort by flexOrder (a missing one counts as 0).
+ for (let p = 1; p < n; p++) {
+ const k = order[p]!;
+ const key = orderKey[k]!;
+ let q = p - 1;
+ while (q >= 0 && orderKey[order[q]!]! > key) {
+ order[q + 1] = order[q]!;
+ q--;
+ }
+ order[q + 1] = k;
+ }
+ }
// Apply reverse layout ordering
if (isReverse || node.direction === 'rtl') {
- processableChildrenIndices.reverse();
- }
-
- const numProcessedChildren = processableChildrenIndices.length;
- if (numProcessedChildren === 0) {
- return false;
+ for (let lo = 0, hi = n - 1; lo < hi; lo++, hi--) {
+ const t = order[lo]!;
+ order[lo] = order[hi]!;
+ order[hi] = t;
+ }
}
- const prop = isRow ? 'x' : 'y';
- const crossProp = isRow ? 'y' : 'x';
+ const nodeWidth = node.width;
+ const nodeHeight = node.height;
+ const nodeMain = isRow ? nodeWidth : nodeHeight;
const containerSize = Math.max(
- node[dimension] || 0,
- node[minDimension] || 0,
+ nodeMain || 0,
+ (isRow ? node.minWidth : node.minHeight) || 0,
0,
);
let containerCrossSize = Math.max(
- node[crossDimension] || 0,
- node[crossMinDimension] || 0,
+ (isRow ? nodeHeight : nodeWidth) || 0,
+ (isRow ? node.minHeight : node.minWidth) || 0,
0,
);
- const isWrapReverse = node.flexWrap === 'wrap-reverse';
const gap = node.gap || 0;
const justify = node.justifyContent || 'flexStart';
- const align = node.alignItems || (node.flexWrap ? 'flexStart' : undefined);
let containerUpdated = false;
- // Resolve sizes matching old processed calculation
- const childMainSizes = new Float32Array(numProcessedChildren);
- const childMarginStarts = new Float32Array(numProcessedChildren);
- const childMarginEnds = new Float32Array(numProcessedChildren);
- const childTotalMainSizes = new Float32Array(numProcessedChildren);
- const childCrossSizes = new Float32Array(numProcessedChildren);
- const childMarginCrossStarts = new Float32Array(numProcessedChildren);
- const childMarginCrossEnds = new Float32Array(numProcessedChildren);
-
let sumOfFlexBaseSizesWithMargins = 0;
-
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- const marginArray = c.margin;
- // index mappings for margins: Top: 0, Right: 1, Bottom: 2, Left: 3
- // if row: main = left/right (3/1),
- const flexBasis = c.flexBasis;
- const isBasisAuto = flexBasis === undefined || flexBasis === 'auto';
- const computedBasis = isBasisAuto
- ? c[dimension] || 0
- : (flexBasis as number);
- const baseMainSize = isBasisAuto
- ? computedBasis
- : Math.max(computedBasis, c[minDimension] || 0);
-
- const marginStart = isRow
- ? c.marginLeft || getArrayValue(marginArray, 3)
- : c.marginTop || getArrayValue(marginArray, 0);
- const marginEnd = isRow
- ? c.marginRight || getArrayValue(marginArray, 1)
- : c.marginBottom || getArrayValue(marginArray, 2);
- const marginCrossStart = isRow
- ? c.marginTop || getArrayValue(marginArray, 0)
- : c.marginLeft || getArrayValue(marginArray, 3);
- const marginCrossEnd = isRow
- ? c.marginBottom || getArrayValue(marginArray, 2)
- : c.marginRight || getArrayValue(marginArray, 1);
-
- childMainSizes[idx] = baseMainSize;
- childMarginStarts[idx] = marginStart;
- childMarginEnds[idx] = marginEnd;
- childTotalMainSizes[idx] = baseMainSize + marginStart + marginEnd;
- childCrossSizes[idx] = c[crossDimension] || 0;
- childMarginCrossStarts[idx] = marginCrossStart;
- childMarginCrossEnds[idx] = marginCrossEnd;
-
- sumOfFlexBaseSizesWithMargins += childTotalMainSizes[idx]!;
+ for (let p = 0; p < n; p++) {
+ sumOfFlexBaseSizesWithMargins += totalMain[order[p]!]!;
}
- if ((totalFlexGrow > 0 || totalFlexShrink > 0) && numProcessedChildren > 1) {
- node.flexBoundary = node.flexBoundary || 'fixed';
+ if ((totalFlexGrow > 0 || totalFlexShrink > 0) && n > 1) {
+ if (!node.flexBoundary) {
+ node.flexBoundary = 'fixed';
+ }
- const totalGapSpace =
- numProcessedChildren > 0 ? gap * (numProcessedChildren - 1) : 0;
const availableSpace =
- containerSize - sumOfFlexBaseSizesWithMargins - totalGapSpace;
+ containerSize - sumOfFlexBaseSizesWithMargins - gap * (n - 1);
if (availableSpace > 0 && totalFlexGrow > 0) {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- const flexGrowValue = c.flexGrow || 0;
- if (flexGrowValue > 0) {
- const shareOfSpace = (flexGrowValue / totalFlexGrow) * availableSpace;
- const newMainSize = childMainSizes[idx]! + shareOfSpace;
- c[dimension] = newMainSize;
- childMainSizes[idx] = newMainSize;
- childTotalMainSizes[idx] =
- newMainSize + childMarginStarts[idx]! + childMarginEnds[idx]!;
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const grow = growFactor[k]!;
+ if (grow > 0) {
+ const newMainSize =
+ mainSize[k]! + (grow / totalFlexGrow) * availableSpace;
+ mainSize[k] = newMainSize;
+ totalMain[k] = newMainSize + marginStart[k]! + marginEnd[k]!;
+ flags[k] = flags[k]! | GROWN;
}
}
- node._containsFlexGrow = node._containsFlexGrow ? null : true;
+ sizeWork = true;
} else if (availableSpace < 0 && totalFlexShrink > 0) {
// Flex Shrink Phase
let totalScaledShrinkFactor = 0;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- const flexShrinkValue = c.flexShrink || 0;
- totalScaledShrinkFactor += flexShrinkValue * childMainSizes[idx]!;
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ totalScaledShrinkFactor += shrinkFactor[k]! * mainSize[k]!;
}
if (totalScaledShrinkFactor > 0) {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- const flexShrinkValue = c.flexShrink || 0;
- if (flexShrinkValue > 0) {
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const shrink = shrinkFactor[k]!;
+ if (shrink > 0) {
const shrinkRatio =
- (flexShrinkValue * childMainSizes[idx]!) /
- totalScaledShrinkFactor;
- const sizeReduction = shrinkRatio * Math.abs(availableSpace);
- let newMainSize = childMainSizes[idx]! - sizeReduction;
+ (shrink * mainSize[k]!) / totalScaledShrinkFactor;
+ let newMainSize =
+ mainSize[k]! - shrinkRatio * Math.abs(availableSpace);
// Constrain by min width/height
- const minBound = c[minDimension] || 0;
+ const c = children[childIndex[k]!] as ElementNode;
+ const minBound = (isRow ? c.minWidth : c.minHeight) || 0;
if (newMainSize < minBound) {
newMainSize = minBound;
}
- c[dimension] = newMainSize;
- childMainSizes[idx] = newMainSize;
- childTotalMainSizes[idx] =
- newMainSize + childMarginStarts[idx]! + childMarginEnds[idx]!;
+ mainSize[k] = newMainSize;
+ totalMain[k] = newMainSize + marginStart[k]! + marginEnd[k]!;
+ flags[k] = flags[k]! | SHRUNK;
+ sizeWork = true;
}
}
}
- node._containsFlexGrow = node._containsFlexGrow ? null : true;
- } else if (node._containsFlexGrow) {
- node._containsFlexGrow = null;
}
}
+ // Whether this pass changed a child's size: updateLayout then lays the
+ // flex ones out again (`_containsFlexGrow`). A relayout that changes none
+ // asks for nothing, so a grown child that sizes itself to its content is
+ // not shrunk and regrown on every relayout.
+ let resized = false;
+ if (sizeWork) {
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const flag = flags[k]!;
+ if (flag === 0) {
+ continue;
+ }
+ const c = children[childIndex[k]!] as ElementNode;
+ const read = mainRead[k]!;
+ if ((flag & GROWN) !== 0) {
+ const size = mainSize[k]!;
+ if (
+ (size !== read || c.transition) &&
+ writeSize(c, isRow, read, size)
+ ) {
+ resized = true;
+ }
+ const own = ownSize[k]!;
+ if (c._flexBase !== own) c._flexBase = own;
+ if (c._flexGrown !== size) c._flexGrown = size;
+ } else if ((flag & SHRUNK) !== 0) {
+ const size = mainSize[k]!;
+ if (
+ (size !== read || c.transition) &&
+ writeSize(c, isRow, read, size)
+ ) {
+ resized = true;
+ }
+ if ((flag & FROM_RECORD) !== 0) c._flexGrown = undefined;
+ } else {
+ // B8: grown by an earlier pass, not by this one: back to its own size.
+ const size = ownSize[k]!;
+ if (
+ (size !== read || c.transition) &&
+ writeSize(c, isRow, read, size)
+ ) {
+ resized = true;
+ }
+ c._flexGrown = undefined;
+ }
+ }
+ }
+ if (resized) {
+ node._containsFlexGrow = true;
+ } else if (node._containsFlexGrow) {
+ node._containsFlexGrow = null;
+ }
+
let totalItemSize = 0;
if (
justify === 'center' ||
@@ -250,159 +557,196 @@ export default function (node: ElementNode): boolean {
justify === 'spaceEvenly' ||
justify === 'spaceAround'
) {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- totalItemSize += childTotalMainSizes[idx]!;
+ for (let p = 0; p < n; p++) {
+ totalItemSize += totalMain[order[p]!]!;
}
}
- const doCrossAlign = containerCrossSize
- ? (c: ElementNode, idx: number, crossCurrentPos: number = 0) => {
- const alignSelf = c.alignSelf || align;
- if (!alignSelf) {
- return;
- }
- if (alignSelf === 'flexStart') {
- c[crossProp] = crossCurrentPos + childMarginCrossStarts[idx]!;
- } else if (alignSelf === 'center') {
- c[crossProp] =
- crossCurrentPos +
- (containerCrossSize - childCrossSizes[idx]!) / 2 +
- childMarginCrossStarts[idx]!;
- } else if (alignSelf === 'flexEnd') {
- c[crossProp] =
- crossCurrentPos +
- containerCrossSize -
- childCrossSizes[idx]! -
- childMarginCrossEnds[idx]!;
- }
- }
- : (_c: ElementNode, _idx: number, _crossCurrentPos: number = 0) => {
- /* no-op */
- };
+ // Decided before the row's height is fitted below (as before 1.7).
+ const crossAlign = containerCrossSize > 0;
if (isRow && node._calcHeight && !node.flexCrossBoundary) {
let maxHeight = 0;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- if (childCrossSizes[idx]! > maxHeight) maxHeight = childCrossSizes[idx]!;
+ for (let p = 0; p < n; p++) {
+ const size = crossSize[order[p]!]!;
+ if (size > maxHeight) maxHeight = size;
}
- const newHeight = maxHeight || node.height;
- if (newHeight !== node.height) {
+ const newHeight = maxHeight || nodeHeight;
+ if (
+ (newHeight !== nodeHeight || node.transition) &&
+ writeSize(node, false, nodeHeight, newHeight)
+ ) {
containerUpdated = true;
- node.height = containerCrossSize = newHeight;
+ containerCrossSize = newHeight;
}
}
+ // B7: center and flexEnd align inside the padded box, not the full size.
+ const crossBox = containerCrossSize - paddingCrossStart - paddingCrossEnd;
+
let currentPos = paddingStart;
if (justify === 'flexStart') {
- if (node.flexWrap === 'wrap') {
- const childCrossSizeVar =
- numProcessedChildren > 0 ? childCrossSizes[0]! : containerCrossSize;
- let crossCurrentPos = isWrapReverse
- ? containerCrossSize - paddingCrossEnd - childCrossSizeVar
- : paddingCrossStart;
+ if (wrapping) {
+ const lineSize = crossSize[order[0]!]!;
const crossGap = isRow ? (node.columnGap ?? gap) : (node.rowGap ?? gap);
+ let line = paddingCrossStart;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
if (
- currentPos + childTotalMainSizes[idx]! > containerSize &&
+ currentPos + totalMain[k]! > containerSize &&
currentPos > paddingStart
) {
currentPos = paddingStart;
- crossCurrentPos += isWrapReverse
- ? -(childCrossSizeVar + crossGap)
- : childCrossSizeVar + crossGap;
+ line += lineSize + crossGap;
}
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx, crossCurrentPos);
+ setPos(
+ children[childIndex[k]!] as ElementNode,
+ isRow,
+ currentPos + marginStart[k]!,
+ );
+ currentPos += totalMain[k]! + gap;
+ lineStart[k] = line;
}
- const finalCrossSize = isWrapReverse
- ? containerCrossSize - crossCurrentPos + paddingCrossStart
- : crossCurrentPos + childCrossSizeVar + paddingCrossEnd;
+ // Each item is aligned from its line's start; center and flexEnd
+ // measure against the container's cross size (B7: less its padding),
+ // as before 1.7. B9: a container with no cross size places its items
+ // too, against the line. B10: wrap-reverse mirrors the lines, so the
+ // first one is at the end.
+ const alignSize = crossAlign ? crossBox : lineSize;
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ alignCross(
+ children[childIndex[k]!] as ElementNode,
+ k,
+ isRow,
+ align,
+ isWrapReverse
+ ? line + paddingCrossStart - lineStart[k]!
+ : lineStart[k]!,
+ alignSize,
+ );
+ }
- if (node[crossDimension] !== finalCrossSize) {
- node[`preFlex${crossDimension}`] = node[crossDimension];
- node[crossDimension] = finalCrossSize;
- containerUpdated = true;
+ const finalCrossSize = line + lineSize + paddingCrossEnd;
+ if (isRow) {
+ const height = node.height;
+ if (
+ (height !== finalCrossSize || node.transition) &&
+ writeSize(node, false, height, finalCrossSize)
+ ) {
+ node.preFlexheight = height;
+ containerUpdated = true;
+ }
+ } else {
+ const width = node.width;
+ if (
+ (width !== finalCrossSize || node.transition) &&
+ writeSize(node, true, width, finalCrossSize)
+ ) {
+ node.preFlexwidth = width;
+ containerUpdated = true;
+ }
}
} else {
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx, paddingCrossStart);
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const c = children[childIndex[k]!] as ElementNode;
+ setPos(c, isRow, currentPos + marginStart[k]!);
+ currentPos += totalMain[k]! + gap;
+ if (crossAlign) {
+ alignCross(c, k, isRow, align, paddingCrossStart, crossBox);
+ }
}
}
// Update container size
- if (node.flexBoundary !== 'fixed' && node.flexWrap !== 'wrap') {
+ if (node.flexBoundary !== 'fixed' && !wrapping) {
let calculatedSize = currentPos - gap + paddingEnd;
- const minSize = node[minDimension] || 0;
+ const minSize = (isRow ? node.minWidth : node.minHeight) || 0;
if (calculatedSize < minSize) {
calculatedSize = minSize;
}
- if (calculatedSize !== (node[dimension] || 0)) {
- node[`preFlex${dimension}`] = containerSize;
- node[dimension] = calculatedSize;
+ const current = nodeMain || 0;
+ if (
+ (calculatedSize !== current || node.transition) &&
+ writeSize(node, isRow, current, calculatedSize)
+ ) {
+ if (isRow) {
+ node.preFlexwidth = containerSize;
+ } else {
+ node.preFlexheight = containerSize;
+ }
return true;
}
}
} else if (justify === 'flexEnd') {
currentPos = containerSize - paddingEnd;
- for (let idx = numProcessedChildren - 1; idx >= 0; idx--) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos - childMainSizes[idx]! - childMarginEnds[idx]!;
- currentPos -= childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx, paddingCrossStart);
+ for (let p = n - 1; p >= 0; p--) {
+ const k = order[p]!;
+ const c = children[childIndex[k]!] as ElementNode;
+ setPos(c, isRow, currentPos - mainSize[k]! - marginEnd[k]!);
+ currentPos -= totalMain[k]! + gap;
+ if (crossAlign) {
+ alignCross(c, k, isRow, align, paddingCrossStart, crossBox);
+ }
}
} else if (justify === 'center') {
+ // B6: centred inside the padded box.
currentPos =
- (containerSize - (totalItemSize + gap * (numProcessedChildren - 1))) / 2 +
+ (containerSize -
+ paddingStart -
+ paddingEnd -
+ (totalItemSize + gap * (n - 1))) /
+ 2 +
paddingStart;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + gap;
- doCrossAlign(c, idx, paddingCrossStart);
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const c = children[childIndex[k]!] as ElementNode;
+ setPos(c, isRow, currentPos + marginStart[k]!);
+ currentPos += totalMain[k]! + gap;
+ if (crossAlign) {
+ alignCross(c, k, isRow, align, paddingCrossStart, crossBox);
+ }
}
} else if (justify === 'spaceBetween') {
const spaceBetween =
- numProcessedChildren > 1
- ? (containerSize - totalItemSize - nodePaddingTotal) /
- (numProcessedChildren - 1)
- : 0;
+ n > 1 ? (containerSize - totalItemSize - nodePaddingTotal) / (n - 1) : 0;
currentPos = paddingStart;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + spaceBetween;
- doCrossAlign(c, idx, paddingCrossStart);
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const c = children[childIndex[k]!] as ElementNode;
+ setPos(c, isRow, currentPos + marginStart[k]!);
+ currentPos += totalMain[k]! + spaceBetween;
+ if (crossAlign) {
+ alignCross(c, k, isRow, align, paddingCrossStart, crossBox);
+ }
}
} else if (justify === 'spaceAround') {
- const spaceAround =
- numProcessedChildren > 0
- ? (containerSize - totalItemSize - nodePaddingTotal) /
- numProcessedChildren
- : 0;
+ const spaceAround = (containerSize - totalItemSize - nodePaddingTotal) / n;
currentPos = paddingStart + spaceAround / 2;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + spaceAround;
- doCrossAlign(c, idx, paddingCrossStart);
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const c = children[childIndex[k]!] as ElementNode;
+ setPos(c, isRow, currentPos + marginStart[k]!);
+ currentPos += totalMain[k]! + spaceAround;
+ if (crossAlign) {
+ alignCross(c, k, isRow, align, paddingCrossStart, crossBox);
+ }
}
} else if (justify === 'spaceEvenly') {
const spaceEvenly =
- (containerSize - totalItemSize - nodePaddingTotal) /
- (numProcessedChildren + 1);
+ (containerSize - totalItemSize - nodePaddingTotal) / (n + 1);
currentPos = spaceEvenly + paddingStart;
- for (let idx = 0; idx < numProcessedChildren; idx++) {
- const c = children[processableChildrenIndices[idx]!] as ElementNode;
- c[prop] = currentPos + childMarginStarts[idx]!;
- currentPos += childTotalMainSizes[idx]! + spaceEvenly;
- doCrossAlign(c, idx, paddingCrossStart);
+ for (let p = 0; p < n; p++) {
+ const k = order[p]!;
+ const c = children[childIndex[k]!] as ElementNode;
+ setPos(c, isRow, currentPos + marginStart[k]!);
+ currentPos += totalMain[k]! + spaceEvenly;
+ if (crossAlign) {
+ alignCross(c, k, isRow, align, paddingCrossStart, crossBox);
+ }
}
}
diff --git a/src/core/fontLoaded.ts b/src/core/fontLoaded.ts
new file mode 100644
index 00000000..cd1336ce
--- /dev/null
+++ b/src/core/fontLoaded.ts
@@ -0,0 +1,29 @@
+// A font loaded through loadFonts() (lightningInit.ts): Solid's text
+// measurement (elementNode.ts) measures again the texts that waited for
+// their font, including those no renderer walk visits (under a hidden or
+// out-of-bounds ancestor), which hear no `loaded`. Internal: this module is
+// not re-exported, so neither name is part of the package's API.
+
+let listener: (() => void) | undefined;
+
+/** elementNode.ts: what to run when a font has loaded. */
+export function onFontLoaded(fn: () => void): void {
+ listener = fn;
+}
+
+/** lightningInit.ts: a font passed to loadFonts() has loaded. */
+export function fontLoaded(): void {
+ if (listener !== undefined) {
+ listener();
+ }
+}
+
+/**
+ * lightningInit.ts: a font passed to loadFonts() failed for good. The texts
+ * that waited are measured again (one whose font is still missing waits
+ * again; a destroyed one is dropped), and the failure goes on to the caller.
+ */
+export function fontFailed(error: unknown): never {
+ fontLoaded();
+ throw error;
+}
diff --git a/src/core/lightningInit.ts b/src/core/lightningInit.ts
index 6a7e9cc4..69f1193b 100644
--- a/src/core/lightningInit.ts
+++ b/src/core/lightningInit.ts
@@ -3,6 +3,7 @@ import { prefetchFont } from '@solidtv/renderer';
import { Config, DOM_RENDERING } from './config.js';
import { DOMRendererMain, loadFontToDom } from './dom-renderer/domRenderer.js';
import { DomRendererMainSettings } from './dom-renderer/domRendererTypes.js';
+import { fontFailed, fontLoaded } from './fontLoaded.js';
import { FontLoadOptions } from './intrinsicTypes.js';
export type SdfFontType = 'ssdf' | 'msdf';
@@ -129,7 +130,13 @@ function attachFonts(fonts: FontLoadOptions[]) {
'type' in font &&
(font.type === 'msdf' || font.type === 'ssdf')
) {
- return renderer.stage.loadFont('sdf', font as lng.FontLoadOptions);
+ // Loaded: Solid measures the texts that waited for a font, those
+ // under a hidden or out-of-bounds ancestor too (no walk visits
+ // them, so they hear no `loaded`). Failed: the same, so destroyed
+ // ones leave the list; the rejection goes on.
+ return renderer.stage
+ .loadFont('sdf', font as lng.FontLoadOptions)
+ .then(fontLoaded, fontFailed);
}
// DOM — Web
if ('fontUrl' in font && enableDomRenderer) {
diff --git a/src/primitives/utils/withScrolling.ts b/src/primitives/utils/withScrolling.ts
index 09b7b9f8..c7781e44 100644
--- a/src/primitives/utils/withScrolling.ts
+++ b/src/primitives/utils/withScrolling.ts
@@ -93,8 +93,9 @@ export function withScrolling(isRow: boolean): Scroller {
let endOffset = componentRef.endOffset;
let screenOffset = componentRef._screenOffset;
if (screenOffset === undefined) {
- const p = componentRef.parent!;
- if (p.clipping) {
+ // A Row/Column with no parent (a root) has no clipping parent.
+ const p = componentRef.parent;
+ if (p !== undefined && p !== null && p.clipping) {
endOffset =
endOffset ??
screenSize - ((isRow ? p.absX : p.absY) || 0) - p[dimension];
diff --git a/src/solidOpts.ts b/src/solidOpts.ts
index 1a8bf366..c76925ed 100644
--- a/src/solidOpts.ts
+++ b/src/solidOpts.ts
@@ -1,5 +1,4 @@
import {
- assertTruthy,
isElementText,
ElementNode,
TextNode,
@@ -21,8 +20,10 @@ export default {
log('Replace Text: ', node, value);
node.text = value;
const parent = node.parent;
- assertTruthy(parent);
- parent.text = parent.getText();
+ // A text node never inserted has no parent.
+ if (parent !== undefined) {
+ parent.text = parent.getText();
+ }
},
setProperty(node: ElementNode, name: string, value: any): void {
node[name] = value;
@@ -35,7 +36,12 @@ export default {
if (node instanceof ElementNode) {
if (node.parent!.rendered) {
+ const wasRendered = node.rendered;
node.render(true);
+ // render() appended the new renderer node: place it (B19).
+ if (!wasRendered && anchor && node.rendered) {
+ parent._drawInOrder(node);
+ }
}
if (prevParent !== undefined) {
enqueueDelete(node, 1);
@@ -67,11 +73,20 @@ export default {
return node.children[0];
},
getNextSibling(node: SolidNode): SolidNode | undefined {
- const children = (node.parent!.children || []) as SolidNode[];
- const index = children.indexOf(node) + 1;
- if (index < children.length) {
- return children[index];
+ const parent = node.parent;
+ // A removed node keeps its parent link, but has no sibling there.
+ if (
+ parent === undefined ||
+ (node instanceof ElementNode && node._detached)
+ ) {
+ return undefined;
+ }
+ // From the end: Solid asks for the sibling after a list's last item.
+ const children = parent.children as SolidNode[];
+ let i = children.length - 1;
+ while (i >= 0 && children[i] !== node) {
+ i--;
}
- return undefined;
+ return i >= 0 ? children[i + 1] : undefined;
},
} satisfies SolidRendererOptions;
diff --git a/tests/childList.test.ts b/tests/childList.test.ts
index e316a283..f0d8d29d 100644
--- a/tests/childList.test.ts
+++ b/tests/childList.test.ts
@@ -46,8 +46,8 @@ v.describe('child list', () => {
v.expect(ids(parent)).toEqual(['d', 'b', 'c', 'a']);
parent.insertChild(a, b); // backward
v.expect(ids(parent)).toEqual(['d', 'a', 'b', 'c']);
- parent.insertChild(b, b); // before itself: appended
- v.expect(ids(parent)).toEqual(['d', 'a', 'c', 'b']);
+ parent.insertChild(b, b); // before itself: stays in place (B19)
+ v.expect(ids(parent)).toEqual(['d', 'a', 'b', 'c']);
});
v.test('moving a child from another parent', () => {
diff --git a/tests/contract-flex.test.tsx b/tests/contract-flex.test.tsx
index db19cd7c..6e9fd2e5 100644
--- a/tests/contract-flex.test.tsx
+++ b/tests/contract-flex.test.tsx
@@ -1,35 +1,30 @@
/**
* Contract tests: flex layout.
*
- * Part 1 runs ONE table of flex cases against BOTH engines by calling them
- * directly on ElementNode trees:
- * - src/core/flex.ts (default)
- * - src/core/flexLayout.ts (selected in src/core/elementNode.ts:22 by
- * `import.meta.env?.VITE_USE_NEW_FLEX` being truthy — note any non-empty
- * string, including "false", selects it)
- * Where the engines differ today, a case carries `expectedNew` and a
- * `newDiffers` note, so the cases show what each engine does and where they
- * differ.
+ * Part 1 runs one table of flex cases against the flex engine
+ * (src/core/flexLayout.ts) by calling it directly on ElementNode trees.
+ *
+ * Until 1.7 there were two engines: src/core/flex.ts (the default build) and
+ * flexLayout.ts (selected by a non-empty `VITE_USE_NEW_FLEX`, as the demo app
+ * does). 1.7 keeps flexLayout.ts only (decision 5.3). Where flex.ts gave a
+ * different result, the case keeps it in a `flex.ts (default build until
+ * 1.7)` comment: that is what changes for apps that did not set
+ * VITE_USE_NEW_FLEX. A pin changed by an approved bug fix (B5-B10) names the
+ * bug and the result before the fix.
*
* Part 2 pins the end-to-end behaviour through JSX, the renderer and the
- * post-mutation layout queue, on whichever engine elementNode.ts selected.
- * Run it on both:
- * npx vitest run tests/contract-flex.test.tsx
- * VITE_USE_NEW_FLEX=true npx vitest run tests/contract-flex.test.tsx
+ * post-mutation layout queue.
*/
import { describe, it, expect, vi } from 'vitest';
import * as s from 'solid-js';
import * as lng from '@solidtv/solid';
import { ElementNode } from '../src/core/elementNode.ts';
import { TextNode } from '../src/core/nodeTypes.ts';
-import flexOld from '../src/core/flex.ts';
-import flexNew from '../src/core/flexLayout.ts';
+import calculateFlex from '../src/core/flexLayout.ts';
import { renderer, waitForUpdate } from './setup.js';
-const NEW_FLEX_ACTIVE = !!import.meta.env?.VITE_USE_NEW_FLEX;
-
// ---------------------------------------------------------------------------
-// Part 1: table of flex cases, run on both engines
+// Part 1: table of flex cases
// ---------------------------------------------------------------------------
type Props = Record;
@@ -55,10 +50,6 @@ interface FlexCase {
container: Props;
kids: KidSpec[];
expected: FlexResult;
- /** flexLayout.ts result, when it differs from flex.ts today. */
- expectedNew?: FlexResult;
- /** Why the engines differ. */
- newDiffers?: string;
}
const view = (width: number, height: number, extra: Props = {}): KidSpec => ({
@@ -105,9 +96,9 @@ function snapshot(
};
}
-function run(engine: typeof flexOld, c: Pick) {
+function run(c: Pick) {
const { node, children } = build(c.container, c.kids);
- const returned = engine(node);
+ const returned = calculateFlex(node);
return snapshot(node, children, returned);
}
@@ -474,7 +465,7 @@ const cases: FlexCase[] = [
// --- padding (a number) ---------------------------------------------------
{
- name: 'padding number + flexStart: main-axis start and auto-size include padding; cross-axis padding only in flexLayout.ts',
+ name: 'padding number + flexStart: main-axis start and auto-size include padding; the cross axis starts at paddingTop',
container: {
width: 300,
height: 100,
@@ -483,18 +474,14 @@ const cases: FlexCase[] = [
},
kids: [A(), B()],
expected: res(true, { w: 130, h: 100 }, [
- { x: 10, y: 0, w: 50, h: 50 },
- { x: 60, y: 0, w: 60, h: 40 },
- ]),
- expectedNew: res(true, { w: 130, h: 100 }, [
{ x: 10, y: 10, w: 50, h: 50 },
{ x: 60, y: 10, w: 60, h: 40 },
]),
- newDiffers:
- 'flex.ts applies a number padding on the main axis only; flexLayout.ts also offsets the cross axis by paddingTop',
+ // flex.ts (default build until 1.7): y 0 and 0 (padding on the main axis
+ // only).
},
{
- name: 'padding number + alignItems flexEnd: flexLayout.ts adds the top padding instead of subtracting the bottom one',
+ name: 'padding number + alignItems flexEnd: children end at the bottom padding',
container: {
width: 300,
height: 100,
@@ -503,21 +490,16 @@ const cases: FlexCase[] = [
alignItems: 'flexEnd',
},
kids: [A(), B()],
+ // B7: 100 - 10 - 50 = 40. Before the fix flexLayout.ts added the top
+ // padding instead (y 60 and 70, the first child 10px past the bottom
+ // edge). flex.ts (default build until 1.7): y 50 and 60 (no cross padding).
expected: res(false, { w: 300, h: 100 }, [
- { x: 10, y: 50, w: 50, h: 50 },
- { x: 60, y: 60, w: 60, h: 40 },
+ { x: 10, y: 40, w: 50, h: 50 },
+ { x: 60, y: 50, w: 60, h: 40 },
]),
- // BUG (flexLayout.ts:271-276): flexEnd adds paddingCrossStart, pushing the
- // child 10px past the container's bottom edge (60 + 50 = 110 > 100).
- expectedNew: res(false, { w: 300, h: 100 }, [
- { x: 10, y: 60, w: 50, h: 50 },
- { x: 60, y: 70, w: 60, h: 40 },
- ]),
- newDiffers:
- 'cross-axis flexEnd/center with padding: flexLayout.ts offsets by paddingTop (child overflows the bottom); flex.ts ignores cross padding',
},
{
- name: 'padding number + alignItems center',
+ name: 'padding number + alignItems center: centred in the padded box',
container: {
width: 300,
height: 100,
@@ -526,16 +508,13 @@ const cases: FlexCase[] = [
alignItems: 'center',
},
kids: [A(), B()],
+ // B7: 10 + (100 - 20 - 50) / 2 = 25. Before the fix flexLayout.ts added
+ // the top padding to the centre of the full height (y 35 and 40).
+ // flex.ts gave 25 and 30 as well.
expected: res(false, { w: 300, h: 100 }, [
{ x: 10, y: 25, w: 50, h: 50 },
{ x: 60, y: 30, w: 60, h: 40 },
]),
- expectedNew: res(false, { w: 300, h: 100 }, [
- { x: 10, y: 35, w: 50, h: 50 },
- { x: 60, y: 40, w: 60, h: 40 },
- ]),
- newDiffers:
- 'cross-axis center with padding: flexLayout.ts shifts by paddingTop instead of centering in the padded box',
},
{
name: 'padding number + flexEnd (row)',
@@ -552,7 +531,7 @@ const cases: FlexCase[] = [
]),
},
{
- name: 'padding number + center (row): content is shifted right by the padding (see BUG test below)',
+ name: 'padding number + center (row): centred in the padded box',
container: {
width: 300,
height: 100,
@@ -560,9 +539,11 @@ const cases: FlexCase[] = [
justifyContent: 'center',
},
kids: [A(), B()],
+ // B6: 10 + (300 - 20 - 110) / 2 = 95. Before the fix both engines added
+ // the padding to the centre of the full width (x 105 and 155).
expected: res(false, { w: 300, h: 100 }, [
- { x: 105, y: U, w: 50, h: 50 },
- { x: 155, y: U, w: 60, h: 40 },
+ { x: 95, y: U, w: 50, h: 50 },
+ { x: 145, y: U, w: 60, h: 40 },
]),
},
{
@@ -670,19 +651,15 @@ const cases: FlexCase[] = [
]),
},
{
- name: 'margin array [t, r, b, l]: only flexLayout.ts reads it',
+ name: 'margin array [t, r, b, l]',
container: { width: 300, height: 100, alignItems: 'flexStart' },
kids: [A({ margin: [1, 2, 3, 4] }), B()],
- expected: res(true, { w: 110, h: 100 }, [
- { x: 0, y: 0, w: 50, h: 50 },
- { x: 50, y: 0, w: 60, h: 40 },
- ]),
- expectedNew: res(true, { w: 116, h: 100 }, [
+ expected: res(true, { w: 116, h: 100 }, [
{ x: 4, y: 1, w: 50, h: 50 },
{ x: 56, y: 0, w: 60, h: 40 },
]),
- newDiffers:
- '`margin` array is read by flexLayout.ts only; flex.ts ignores it',
+ // flex.ts (default build until 1.7) ignored the array: w 110, x 0 and 50,
+ // y 0 and 0.
},
// --- flexGrow -------------------------------------------------------------
@@ -711,7 +688,7 @@ const cases: FlexCase[] = [
expected: res(true, { w: 50, h: 100 }, [{ x: 0, y: U, w: 50, h: 50 }]),
},
{
- name: 'flexGrow: no free space means no growth (flex.ts also console.warns)',
+ name: 'flexGrow: no free space means no growth (flex.ts also console.warned until 1.7)',
container: { width: 100, height: 100 },
kids: [A({ flexGrow: 1 }), B()],
expected: res(false, { w: 100, h: 100 }, [
@@ -784,7 +761,7 @@ const cases: FlexCase[] = [
]),
},
{
- name: 'flexWrap + padding: cross-axis padding only in flexLayout.ts',
+ name: 'flexWrap + padding: lines start at paddingTop and the height adds paddingBottom',
container: {
width: 250,
height: 50,
@@ -793,45 +770,99 @@ const cases: FlexCase[] = [
flexWrap: 'wrap',
},
kids: [view(100, 50), view(100, 50), view(100, 50)],
- expected: res(true, { w: 250, h: 110 }, [
- { x: 10, y: 0, w: 100, h: 50 },
- { x: 120, y: 0, w: 100, h: 50 },
- { x: 10, y: 60, w: 100, h: 50 },
- ]),
- expectedNew: res(true, { w: 250, h: 130 }, [
+ expected: res(true, { w: 250, h: 130 }, [
{ x: 10, y: 10, w: 100, h: 50 },
{ x: 120, y: 10, w: 100, h: 50 },
{ x: 10, y: 70, w: 100, h: 50 },
]),
- newDiffers:
- 'wrap + padding: flexLayout.ts starts lines at paddingTop and adds paddingBottom to the height; flex.ts ignores cross padding',
+ // flex.ts (default build until 1.7) ignored the cross padding: h 110,
+ // y 0, 0 and 60.
+ },
+ {
+ name: 'flexWrap + alignItems center: each line offsets the centre in the full container height',
+ container: {
+ width: 250,
+ height: 110,
+ gap: 10,
+ flexWrap: 'wrap',
+ alignItems: 'center',
+ },
+ kids: [view(100, 100), view(100, 100), view(100, 100)],
+ // Line start + (110 - 100) / 2; the height then fits the two lines.
+ expected: res(true, { w: 250, h: 210 }, [
+ { x: 0, y: 5, w: 100, h: 100 },
+ { x: 110, y: 5, w: 100, h: 100 },
+ { x: 0, y: 115, w: 100, h: 100 },
+ ]),
},
{
- name: 'flexWrap with no container height: lines are counted but children are never moved on the cross axis (see BUG test)',
+ name: 'flexWrap with no container height: wrapped items move to the next line',
container: { width: 250, gap: 10, flexWrap: 'wrap' },
kids: [view(100, 50), view(100, 50), view(100, 50)],
+ // B9: before the fix y was never written (both engines), so the wrapped
+ // item overlapped the first line. With alignItems center or flexEnd,
+ // wrapped items align against the container's cross size, which the pass
+ // then sets to the content: a second pass gives other positions (as
+ // before 1.7, see 'flexWrap + alignItems center').
expected: res(true, { w: 250, h: 110 }, [
- { x: 0, y: U, w: 100, h: 50 },
- { x: 110, y: U, w: 100, h: 50 },
- { x: 0, y: U, w: 100, h: 50 },
+ { x: 0, y: 0, w: 100, h: 50 },
+ { x: 110, y: 0, w: 100, h: 50 },
+ { x: 0, y: 60, w: 100, h: 50 },
]),
},
{
- name: 'flexWrap wrap-reverse: flex.ts stacks lines upward to negative y and shrinks the width; flexLayout.ts does not wrap',
+ name: 'flexWrap wrap-reverse: lines stack from the bottom of the grown container',
container: { width: 250, height: 50, gap: 10, flexWrap: 'wrap-reverse' },
kids: [view(100, 50), view(100, 50), view(100, 50)],
- expected: res(true, { w: 100, h: 110 }, [
+ // B10: before the fix flexLayout.ts did not wrap (one line, x 220 for the
+ // third item, width auto-sized to 320, height 50); flex.ts (default build
+ // until 1.7) stacked lines upward to y -60 and shrank the width to 100.
+ expected: res(true, { w: 250, h: 110 }, [
+ { x: 0, y: 60, w: 100, h: 50 },
+ { x: 110, y: 60, w: 100, h: 50 },
{ x: 0, y: 0, w: 100, h: 50 },
- { x: 110, y: 0, w: 100, h: 50 },
- { x: 0, y: -60, w: 100, h: 50 },
]),
- expectedNew: res(true, { w: 320, h: 50 }, [
- { x: 0, y: 0, w: 100, h: 50 },
- { x: 110, y: 0, w: 100, h: 50 },
- { x: 220, y: 0, w: 100, h: 50 },
+ },
+ {
+ name: 'flexWrap wrap-reverse + padding: the last line starts at paddingTop',
+ container: {
+ width: 250,
+ height: 50,
+ gap: 10,
+ padding: 10,
+ flexWrap: 'wrap-reverse',
+ },
+ kids: [view(100, 50), view(100, 50), view(100, 50)],
+ // B10: the mirror of 'flexWrap + padding' inside the padded box.
+ expected: res(true, { w: 250, h: 130 }, [
+ { x: 10, y: 70, w: 100, h: 50 },
+ { x: 120, y: 70, w: 100, h: 50 },
+ { x: 10, y: 10, w: 100, h: 50 },
+ ]),
+ },
+
+ // --- flexShrink, flexBasis (5.3: flex.ts read neither) -------------------
+ {
+ name: 'flexShrink: overflowing items shrink by shrink x size; the container keeps its width',
+ container: { width: 90, height: 100 },
+ kids: [A({ width: 40, flexShrink: 1 }), B({ flexShrink: 1 })],
+ // 100 wanted, 90 available: 40 - 0.4 * 10, 60 - 0.6 * 10.
+ expected: res(false, { w: 90, h: 100 }, [
+ { x: 0, y: U, w: 36, h: 50 },
+ { x: 36, y: U, w: 54, h: 40 },
+ ]),
+ // flex.ts (default build until 1.7) ignored flexShrink: widths 40 and
+ // 60, x 0 and 40, and the container auto-sized to 100 (returned true).
+ },
+ {
+ name: 'flexBasis: the basis replaces the width for positions; the width itself is not written',
+ container: { width: 300 },
+ kids: [A({ flexBasis: 80 }), B()],
+ expected: res(true, { w: 140, h: U }, [
+ { x: 0, y: U, w: 50, h: 50 },
+ { x: 80, y: U, w: 60, h: 40 },
]),
- newDiffers:
- 'wrap-reverse: flexLayout.ts only wraps for "wrap" (flexLayout.ts:297), so it lays out one line and auto-sizes the width',
+ // flex.ts (default build until 1.7) ignored flexBasis: x 0 and 50, w 110.
},
// --- flexOrder ------------------------------------------------------------
@@ -876,6 +907,22 @@ const cases: FlexCase[] = [
{ x: U, y: U, w: 60, h: 40 },
]),
},
+ {
+ name: 'flexItem={false} on an unsized does not block the pass',
+ container: { width: 300 },
+ kids: [
+ A(),
+ { kind: 'text', props: { text: 'Badge', flexItem: false } },
+ B(),
+ ],
+ // B5: before the fix the text check came first, so the unsized text
+ // aborted the whole pass (returned false, nothing placed).
+ expected: res(true, { w: 110, h: U }, [
+ { x: 0, y: U, w: 50, h: 50 },
+ { x: U, y: U, w: U, h: U },
+ { x: 50, y: U, w: 60, h: 40 },
+ ]),
+ },
{
name: 'a raw string child (TextNode) is skipped',
container: { width: 300 },
@@ -944,120 +991,146 @@ const cases: FlexCase[] = [
},
];
-describe.each([
- ['flex.ts', flexOld, false],
- ['flexLayout.ts', flexNew, true],
-] as const)(
- 'contract: flex props, table run on %s',
- (_label, engine, isNew) => {
- it.each(cases.map((c) => [c.name, c] as const))('%s', (_name, c) => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- const expected = isNew && c.expectedNew ? c.expectedNew : c.expected;
- expect(run(engine, c)).toEqual(expected);
- } finally {
- warn.mockRestore();
- }
+describe('contract: flex props, table', () => {
+ it.each(cases.map((c) => [c.name, c] as const))('%s', (_name, c) => {
+ expect(run(c)).toEqual(c.expected);
+ });
+});
+
+describe('contract: flex props, details', () => {
+ it('flexGrow: a second pass on the same tree gives the same result', () => {
+ const { node, children } = build({ width: 300, gap: 10 }, [
+ A({ flexGrow: 1 }),
+ B(),
+ ]);
+ const first = snapshot(node, children, calculateFlex(node));
+ const second = snapshot(node, children, calculateFlex(node));
+ expect(second).toEqual(first);
+ expect(first.children[0]).toEqual({ x: 0, y: U, w: 230, h: 50 });
+ });
+
+ // B8: flexGrow starts from the item's own size on every pass. Before the
+ // fix the grown width (230) became the next pass's base, so the item kept
+ // 230 and the sibling went to x 240 (the row overflowed: 230 + 10 + 100).
+ it('flexGrow: a grown item shrinks back when a sibling grows', () => {
+ const { node, children } = build({ width: 300, gap: 10 }, [
+ A({ flexGrow: 1 }),
+ B(),
+ ]);
+ calculateFlex(node);
+ const [grow, sibling] = children as ElementNode[];
+ expect(grow!.width).toBe(230);
+ sibling!.width = 100;
+ calculateFlex(node);
+ expect(grow!.width).toBe(190);
+ expect(sibling!.x).toBe(200);
+ sibling!.width = 60;
+ calculateFlex(node);
+ expect(grow!.width).toBe(230);
+ expect(sibling!.x).toBe(240);
+ });
+
+ // B8: with no free space left the item goes back to its own size (50)
+ // instead of keeping the last grown one.
+ it('flexGrow: a grown item returns to its own size when no space is left', () => {
+ const { node, children } = build({ width: 300, gap: 10 }, [
+ A({ flexGrow: 1 }),
+ B(),
+ ]);
+ calculateFlex(node);
+ const [grow, sibling] = children as ElementNode[];
+ sibling!.width = 280;
+ calculateFlex(node);
+ expect(grow!.width).toBe(50);
+ expect(sibling!.x).toBe(60);
+ });
+
+ it('flexGrow: a width the app writes on a grown item is its new own size', () => {
+ const { node, children } = build({ width: 300, gap: 10 }, [
+ A({ flexGrow: 1 }),
+ B(),
+ ]);
+ calculateFlex(node);
+ const [grow, sibling] = children as ElementNode[];
+ grow!.width = 100;
+ calculateFlex(node);
+ // 300 - 100 - 60 - 10 = 130 free, all to the grow item.
+ expect(grow!.width).toBe(230);
+ sibling!.width = 160;
+ calculateFlex(node);
+ // Own size 100: 300 - 100 - 160 - 10 = 30 free.
+ expect(grow!.width).toBe(130);
+ });
+
+ it('flexGrow: the container gets flexBoundary "fixed" written onto it', () => {
+ const { node } = build({ width: 300 }, [A({ flexGrow: 1 }), B()]);
+ expect(node.flexBoundary).toBeUndefined();
+ calculateFlex(node);
+ expect(node.flexBoundary).toBe('fixed');
+ });
+
+ // 5.3: flex.ts only did this for flexGrow; a container whose items only
+ // have flexShrink gets it too now.
+ it('flexShrink: the container gets flexBoundary "fixed" written onto it', () => {
+ const { node } = build({ width: 300 }, [A({ flexShrink: 1 }), B()]);
+ calculateFlex(node);
+ expect(node.flexBoundary).toBe('fixed');
+ });
+
+ it('a pass started while another runs (an app callback on a write) leaves the outer pass intact', () => {
+ const other = build({ width: 900, gap: 7 }, [
+ view(11, 11),
+ view(13, 13),
+ view(17, 17),
+ view(19, 19),
+ ]);
+ const { node, children } = build({ width: 300, gap: 10 }, [A(), B(), A()]);
+ const first = children[0] as ElementNode;
+ const desc = Object.getOwnPropertyDescriptor(
+ Object.getPrototypeOf(first),
+ 'x',
+ )!;
+ let nested = 0;
+ Object.defineProperty(first, 'x', {
+ configurable: true,
+ get: desc.get,
+ set(v: number) {
+ desc.set!.call(this, v);
+ // e.g. onAnimation.animating calling updateLayout on another node
+ nested++;
+ calculateFlex(other.node);
+ },
});
- },
-);
-
-describe('contract: flex props, engine-specific details', () => {
- const both = [
- ['flex.ts', flexOld],
- ['flexLayout.ts', flexNew],
- ] as const;
-
- it.each(both)(
- 'flexGrow: a second pass on the same tree gives the same result (%s)',
- (_label, engine) => {
- const { node, children } = build({ width: 300, gap: 10 }, [
- A({ flexGrow: 1 }),
- B(),
- ]);
- const first = snapshot(node, children, engine(node));
- const second = snapshot(node, children, engine(node));
- expect(second).toEqual(first);
- expect(first.children[0]).toEqual({ x: 0, y: U, w: 230, h: 50 });
- },
- );
-
- it.each(both)(
- 'flexGrow: on a relayout the grown width is the new base, so the item never shrinks back (%s)',
- (_label, engine) => {
- const { node, children } = build({ width: 300, gap: 10 }, [
- A({ flexGrow: 1 }),
- B(),
- ]);
- engine(node);
- const [grow, sibling] = children as ElementNode[];
- expect(grow!.width).toBe(230);
- sibling!.width = 100;
- engine(node);
- // 230 + 10 + 100 = 340 > 300: the row overflows (see BUG test below).
- expect(grow!.width).toBe(230);
- expect(sibling!.x).toBe(240);
- },
- );
-
- // BUG: flexGrow should start from the item's own size on every pass; after
- // the sibling grows to 100 the grow item should be 300 - 100 - 10 = 190.
- // flex.ts:146 / flexLayout.ts:199 add the free space to the current, already
- // grown, width.
- it.skip.each(both)(
- 'BUG: flexGrow: a grown item shrinks back when a sibling grows (%s)',
- (_label, engine) => {
- const { node, children } = build({ width: 300, gap: 10 }, [
- A({ flexGrow: 1 }),
- B(),
- ]);
- engine(node);
- const [grow, sibling] = children as ElementNode[];
- sibling!.width = 100;
- engine(node);
- expect(grow!.width).toBe(190);
- expect(sibling!.x).toBe(200);
- },
- );
-
- it.each(both)(
- 'flexGrow: the container gets flexBoundary "fixed" written onto it (%s)',
- (_label, engine) => {
- const { node } = build({ width: 300 }, [A({ flexGrow: 1 }), B()]);
- expect(node.flexBoundary).toBeUndefined();
- engine(node);
- expect(node.flexBoundary).toBe('fixed');
- },
- );
+ expect(snapshot(node, children, calculateFlex(node))).toEqual(
+ res(true, { w: 180, h: U }, [
+ { x: 0, y: U, w: 50, h: 50 },
+ { x: 60, y: U, w: 60, h: 40 },
+ { x: 130, y: U, w: 50, h: 50 },
+ ]),
+ );
+ expect(nested).toBe(1);
+ expect(other.children.map((c) => (c as ElementNode).x)).toEqual([
+ 0, 18, 38, 62,
+ ]);
+ });
- it('flexGrow with no free space: flex.ts warns, flexLayout.ts is silent', () => {
+ // 5.3: flex.ts (default build until 1.7) called console.warn here, in
+ // production too.
+ it('flexGrow with no free space does not warn', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
- flexOld(build({ width: 100 }, [A({ flexGrow: 1 }), B()]).node);
- expect(warn).toHaveBeenCalledTimes(1);
- warn.mockClear();
- flexNew(build({ width: 100 }, [A({ flexGrow: 1 }), B()]).node);
+ calculateFlex(build({ width: 100 }, [A({ flexGrow: 1 }), B()]).node);
expect(warn).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
}
});
- it('padding array: flex.ts does not support it (docs: number only); positions become non-numeric', () => {
- // flex.ts:95 casts `padding` to a number; an array then string-concatenates.
- const { node, children } = build(
- { width: 300, height: 100, padding: [5, 20, 15, 10] },
- [A(), B()],
- );
- flexOld(node);
- const [a, b] = children as ElementNode[];
- expect(Number.isFinite(a!.x)).toBe(false);
- expect(Number.isFinite(b!.x)).toBe(false);
- expect(Number.isFinite(node.width)).toBe(false);
- });
-
- it('padding array [t, r, b, l] (flexLayout.ts)', () => {
- const r = run(flexNew, {
+ // flex.ts (default build until 1.7) did not support a padding array: it
+ // cast `padding` to a number, so positions and the auto-size became
+ // non-numeric (NaN or concatenated strings).
+ it('padding array [t, r, b, l]', () => {
+ const r = run({
container: {
width: 300,
height: 100,
@@ -1074,8 +1147,8 @@ describe('contract: flex props, engine-specific details', () => {
);
});
- it('padding array [v, h] and [t, h, b] (flexLayout.ts)', () => {
- const two = run(flexNew, {
+ it('padding array [v, h] and [t, h, b]', () => {
+ const two = run({
container: {
width: 300,
height: 100,
@@ -1090,7 +1163,7 @@ describe('contract: flex props, engine-specific details', () => {
{ x: 60, y: 5, w: 60, h: 40 },
]),
);
- const three = run(flexNew, {
+ const three = run({
container: {
width: 200,
height: 500,
@@ -1108,7 +1181,9 @@ describe('contract: flex props, engine-specific details', () => {
);
});
- it('paddingLeft/paddingTop override the padding value (flexLayout.ts only)', () => {
+ // flex.ts (default build until 1.7) ignored paddingLeft/paddingTop: w 130,
+ // x 10 and 60, y 0 and 0.
+ it('paddingLeft/paddingTop override the padding value', () => {
const container = {
width: 300,
height: 100,
@@ -1117,106 +1192,81 @@ describe('contract: flex props, engine-specific details', () => {
paddingTop: 2,
alignItems: 'flexStart',
};
- expect(run(flexNew, { container, kids: [A(), B()] })).toEqual(
+ expect(run({ container, kids: [A(), B()] })).toEqual(
res(true, { w: 150, h: 100 }, [
{ x: 30, y: 2, w: 50, h: 50 },
{ x: 80, y: 2, w: 60, h: 40 },
]),
);
- // flex.ts ignores paddingLeft/paddingTop.
- expect(run(flexOld, { container, kids: [A(), B()] })).toEqual(
- res(true, { w: 130, h: 100 }, [
- { x: 10, y: 0, w: 50, h: 50 },
- { x: 60, y: 0, w: 60, h: 40 },
- ]),
- );
});
- // BUG: with a symmetric padding, justifyContent center should center the
- // items in the container: (300 - 110) / 2 = 95. Both engines add the padding
- // on top of an already-centered start (flex.ts:282-284,
- // flexLayout.ts:361-363), giving 105.
- it.skip.each(both)(
- 'BUG: padding + justifyContent center centers the items (%s)',
- (_label, engine) => {
- const r = run(engine, {
- container: {
- width: 300,
- height: 100,
- padding: 10,
- justifyContent: 'center',
- },
- kids: [A(), B()],
- });
- expect(r.children.map((c) => c.x)).toEqual([95, 145]);
- },
- );
-
- // BUG: a wrapped row with no height never writes y, so the wrapped item
- // overlaps the first line (doCrossAlign is a no-op when the container cross
- // size is 0: flex.ts:179, flexLayout.ts:258).
- it.skip.each(both)(
- 'BUG: flexWrap moves wrapped items to the next line even when the container has no height (%s)',
- (_label, engine) => {
- const r = run(engine, {
- container: { width: 250, gap: 10, flexWrap: 'wrap' },
- kids: [view(100, 50), view(100, 50), view(100, 50)],
- });
- expect(r.children.map((c) => c.y)).toEqual([0, 0, 60]);
- },
- );
-
- // BUG: wrap-reverse should put the first line at the bottom of the grown
- // container (CSS): lines at y 60 and 0 in a 110-high container, width kept.
- // flex.ts stacks lines upward to y = -60 and shrinks the width to the last
- // line; flexLayout.ts does not wrap at all.
- it.skip.each(both)(
- 'BUG: flexWrap wrap-reverse stacks lines from the bottom (%s)',
- (_label, engine) => {
- const r = run(engine, {
- container: {
- width: 250,
- height: 50,
- gap: 10,
- flexWrap: 'wrap-reverse',
- },
- kids: [view(100, 50), view(100, 50), view(100, 50)],
- });
- expect(r).toEqual(
- res(true, { w: 250, h: 110 }, [
- { x: 0, y: 60, w: 100, h: 50 },
- { x: 110, y: 60, w: 100, h: 50 },
- { x: 0, y: 0, w: 100, h: 50 },
- ]),
- );
- },
- );
+ // B6, with asymmetric padding: centred between paddingLeft and paddingRight.
+ it('padding + justifyContent center centres the items in the padded box', () => {
+ const r = run({
+ container: {
+ width: 300,
+ height: 100,
+ padding: [0, 30, 0, 10],
+ justifyContent: 'center',
+ },
+ kids: [A(), B()],
+ });
+ // 10 + (300 - 40 - 110) / 2 = 85
+ expect(r.children.map((c) => c.x)).toEqual([85, 135]);
+ });
- // BUG (flexLayout.ts only): cross-axis flexEnd with padding should keep the
- // child inside the padded box: y = 100 - 10 - 50 = 40 for a 50-high child.
- it.skip('BUG: padding + alignItems flexEnd keeps children inside the padding (flexLayout.ts)', () => {
- const r = run(flexNew, {
+ // B7, with asymmetric padding: center and flexEnd stay inside the padded
+ // box on the cross axis.
+ it('padding + alignItems center/flexEnd use the padded box', () => {
+ const r = run({
container: {
width: 300,
height: 100,
- padding: 10,
+ padding: [20, 0, 10, 0],
flexBoundary: 'fixed',
- alignItems: 'flexEnd',
+ alignItems: 'center',
},
- kids: [A(), B()],
+ kids: [A(), B({ alignSelf: 'flexEnd' })],
});
- expect(r.children.map((c) => c.y)).toEqual([40, 50]);
+ // center: 20 + (100 - 30 - 50) / 2 = 30; flexEnd: 100 - 10 - 40 = 50
+ expect(r.children.map((c) => c.y)).toEqual([30, 50]);
+ });
+
+ it('a relayout that changes nothing writes nothing', () => {
+ const { node, children } = build(
+ { width: 300, height: 100, gap: 10, alignItems: 'center' },
+ [A(), B()],
+ );
+ calculateFlex(node);
+ const writes: string[] = [];
+ for (const c of [node, ...children] as ElementNode[]) {
+ for (const key of ['x', 'y', 'w', 'h']) {
+ const desc = Object.getOwnPropertyDescriptor(
+ Object.getPrototypeOf(c),
+ key,
+ )!;
+ Object.defineProperty(c, key, {
+ configurable: true,
+ get: desc.get,
+ set(v: number) {
+ writes.push(key);
+ desc.set!.call(this, v);
+ },
+ });
+ }
+ }
+ expect(calculateFlex(node)).toBe(false);
+ expect(writes).toEqual([]);
});
});
// ---------------------------------------------------------------------------
-// Part 2: end to end through JSX and the layout queue (active engine)
+// Part 2: end to end through JSX and the layout queue
// ---------------------------------------------------------------------------
-describe(`contract: flex through the renderer (active engine: ${
- NEW_FLEX_ACTIVE ? 'flexLayout.ts' : 'flex.ts'
-})`, () => {
- it('engine selection: a truthy VITE_USE_NEW_FLEX string selects flexLayout.ts (margin arrays only work there)', async () => {
+describe('contract: flex through the renderer', () => {
+ // flex.ts (the default build until 1.7) ignored the margin array: x 0.
+ it('one engine: margin arrays work through JSX', async () => {
let item!: lng.ElementNode;
const dispose = renderer.render(() => (
@@ -1224,7 +1274,7 @@ describe(`contract: flex through the renderer (active engine: ${
));
await waitForUpdate();
- expect(item.x).toBe(NEW_FLEX_ACTIVE ? 10 : 0);
+ expect(item.x).toBe(10);
dispose();
});
@@ -1370,6 +1420,167 @@ describe(`contract: flex through the renderer (active engine: ${
dispose();
});
+ it('flexGrow: the container calls onLayout once per layout, after its grown flex children are laid out', async () => {
+ const seen: unknown[] = [];
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void seen.push(last.x)}
+ >
+
+
+
+
+
+
+ ));
+ await waitForUpdate();
+ // Until 1.7 it was called twice per layout, first before the children
+ // were laid out again (last.x 0), then after (280).
+ expect(seen).toEqual([280]);
+ dispose();
+ });
+
+ it('flexGrow: a grown child that fits its content resizes when laid out again, so the container runs once more before its one onLayout', async () => {
+ const seen: unknown[] = [];
+ let fit!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void seen.push([fit.width, last.x])}
+ >
+
+
+
+
+
+
+ ));
+ await waitForUpdate();
+ expect(seen).toEqual([[300, 20]]);
+ dispose();
+ });
+
+ it('flexGrow: relaying out a container whose grown child fits its content writes nothing and lays the child out no more', async () => {
+ let outer!: lng.ElementNode;
+ let fit!: lng.ElementNode;
+ let fitPasses = 0;
+ const dispose = renderer.render(() => (
+
+
+ void fitPasses++}
+ >
+
+
+
+
+ ));
+ await waitForUpdate();
+ expect(fit.width).toBe(300);
+
+ const widths: number[] = [];
+ const desc = Object.getOwnPropertyDescriptor(
+ Object.getPrototypeOf(fit),
+ 'w',
+ )!;
+ Object.defineProperty(fit, 'w', {
+ configurable: true,
+ get: desc.get,
+ set(v: number) {
+ widths.push(v);
+ desc.set!.call(this, v);
+ },
+ });
+ fitPasses = 0;
+ outer.updateLayout();
+ outer.updateLayout();
+ // Nothing changed: no write and no pass of the child (it used to be
+ // shrunk to its content and grown back each time: 40, 300, 40, 300).
+ expect(widths).toEqual([]);
+ expect(fitPasses).toBe(0);
+ expect(fit.width).toBe(300);
+ dispose();
+ });
+
+ it('transition: a node moved by one layout and back by the next, before its animation advances, is sent back', async () => {
+ const [w, setW] = s.createSignal(50);
+ const [transition, setTransition] = s.createSignal<
+ lng.ElementNode['transition'] | undefined
+ >(undefined);
+ let row!: lng.ElementNode;
+ let moving!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+ ));
+ await waitForUpdate();
+ expect(moving.x).toBe(50);
+ setTransition({ x: { duration: 1000 } });
+ const animate = vi.spyOn(moving, 'animate');
+
+ setW(100);
+ row.updateLayout(); // moving: 50 -> 100, animated; it still reads 50
+ setW(50);
+ row.updateLayout(); // back to 50 before any animation frame
+ // The second layout retargets the animation (before 1.7 every layout
+ // wrote): skipping it because x still reads 50 would leave it on 100.
+ expect(animate.mock.calls.map((c) => c[0])).toEqual([
+ { x: 100 },
+ { x: 50 },
+ ]);
+
+ row.updateLayout(); // nothing moved since: no write, no restart
+ expect(animate).toHaveBeenCalledTimes(2);
+ dispose();
+ });
+
+ it('transition (B8): a grown item with a width transition goes back to its own size when no space is left, before its animation advances', async () => {
+ const [w, setW] = s.createSignal(60);
+ const [transition, setTransition] = s.createSignal<
+ lng.ElementNode['transition'] | undefined
+ >(undefined);
+ let row!: lng.ElementNode;
+ let grow!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+ ));
+ await waitForUpdate();
+ expect(grow.width).toBe(230);
+ setTransition({ width: { duration: 1000 } });
+ const animate = vi.spyOn(grow, 'animate');
+
+ setW(100);
+ row.updateLayout(); // 230 -> 190, animated; it still reads 230
+ setW(280);
+ row.updateLayout(); // no space left: back to its own 50
+ expect(animate.mock.calls.map((c) => c[0])).toEqual([
+ { w: 190 },
+ { w: 50 },
+ ]);
+ dispose();
+ });
+
it('onLayout: called once after the first flex pass, with this = node and (node) as the only argument, after children are placed', async () => {
const calls: Array<{ self: unknown; args: unknown[]; secondX: unknown }> =
[];
diff --git a/tests/contract-focus.test.tsx b/tests/contract-focus.test.tsx
index 9c1db7df..64a0872c 100644
--- a/tests/contract-focus.test.tsx
+++ b/tests/contract-focus.test.tsx
@@ -694,3 +694,50 @@ v.describe('contract: autofocus', () => {
},
);
});
+
+v.describe('contract: a removed focused subtree', () => {
+ // 1.6 behaviour (found by the demo port, #/complexflex): a removed node
+ // keeps its `parent`, so when the focused element's subtree is removed and
+ // nothing re-focuses, a focus path built inside it (here: navigation within
+ // the removed parent) still reaches the removed node's former ancestors,
+ // and their key handlers still run.
+ v.it(
+ "keys from a removed subtree still bubble to its former ancestors' handlers",
+ async () => {
+ const [show, setShow] = createSignal(true);
+ const onDown = v.vi.fn(() => true);
+ let g!: ElementNode, p!: ElementNode, a!: ElementNode, b!: ElementNode;
+ const { target, dispose } = await mount(() => (
+
+ {show() && (
+ {
+ b.setFocus();
+ return true;
+ }}
+ >
+
+
+
+ )}
+
+ ));
+ v.expect(activeElement()).toBe(a);
+
+ setShow(false);
+ await flush();
+ v.expect(g.children).not.toContain(p);
+ v.expect(p.parent).toBe(g);
+
+ target.down('ArrowRight');
+ await flush();
+ v.expect(activeElement()).toBe(b);
+ v.expect(focusPath()).toContain(g);
+
+ target.down('ArrowDown');
+ v.expect(onDown).toHaveBeenCalledTimes(1);
+ dispose();
+ },
+ );
+});
diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx
index e2c2dc0e..e04e9c65 100644
--- a/tests/contract-text.test.tsx
+++ b/tests/contract-text.test.tsx
@@ -6,8 +6,11 @@
* (getBoundingClientRect). Tests that need real sizes install
* `mockTextMeasure()`: 10px per character, 20px per line, for text divs only.
* The DOM renderer measures a text once when it is created (synchronously)
- * and again after `document.fonts.ready`, when it emits `loaded`.
- * Real-WebGL text-in-flex is covered elsewhere.
+ * and again after `document.fonts.ready`, when it emits `loaded`. From 1.7
+ * Solid also measures a text in a flex container itself (`measure()`, which
+ * the DOM renderer answers synchronously while `document.fonts.check` says
+ * its font is loaded) before laying the container out.
+ * Real-WebGL text-in-flex is covered elsewhere (tests/webgl/flex-text).
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import * as s from 'solid-js';
@@ -48,6 +51,12 @@ afterEach(() => {
vi.restoreAllMocks();
});
+// The DOM renderer re-measures a changed text in a microtask and emits
+// `loaded`; the handler queues the flex pass for the post-mutation microtask
+// after that (design 3.4.4), which `waitForUpdate` (a few microtasks) can
+// miss. A macrotask is after both.
+const nextTask = () => new Promise((r) => setTimeout(r, 0));
+
describe('contract: text children concatenated from several JSX expressions', () => {
it('static text and several expressions concatenate into el.text and el.lng.text', () => {
const [name] = s.createSignal('Bob');
@@ -132,7 +141,10 @@ describe('contract: text props reach the renderer node (el.lng)', () => {
dispose();
});
- it('contain "width" without a width: maxWidth = parent width - x (marginRight is ignored today)', () => {
+ // B11: before the fix marginRight was read from the renderer props bag,
+ // where it is never stored (margins live on the ElementNode), so the
+ // subtraction was always 0 (maxWidth 700).
+ it('contain "width" without a width: maxWidth = parent width - x - marginRight', () => {
let t!: lng.ElementNode;
const dispose = renderer.render(() => (
@@ -141,24 +153,45 @@ describe('contract: text props reach the renderer node (el.lng)', () => {
));
- expect(raw(t).maxWidth).toBe(700);
+ expect(raw(t).maxWidth).toBe(660);
expect(raw(t).maxLines).toBe(99);
dispose();
});
- // BUG: src/core/elementNode.ts:1612 (and :1617 for marginBottom) reads
- // marginRight from the renderer props bag, where it is never stored (margins
- // live on the ElementNode), so the subtraction is always 0.
- it.skip('BUG: contain "width" without a width subtracts marginRight from maxWidth', () => {
+ // B11: the margin array counts as in flex ([top, right, bottom, left]).
+ it('contain "both" without a size: the margin array counts too', () => {
let t!: lng.ElementNode;
const dispose = renderer.render(() => (
-
+
+ B
+
+
+ ));
+ expect(raw(t).maxWidth).toBe(660);
+ expect(raw(t).maxHeight).toBe(520);
+ dispose();
+ });
+
+ // B11: as above for marginBottom (maxHeight was 550).
+ it('contain "both" without a size: maxHeight = parent height - y - marginBottom', () => {
+ let t!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
B
));
expect(raw(t).maxWidth).toBe(660);
+ expect(raw(t).maxHeight).toBe(520);
dispose();
});
@@ -227,6 +260,30 @@ describe('contract: text props reach the renderer node (el.lng)', () => {
dispose();
});
+ // B12: a lineHeight at or below 3 is a multiplier of the font size (as the
+ // renderer reads it). Before the fix maxHeight was the bare multiplier
+ // (1.2 px), so the text was 1.2 px high in flex.
+ it('maxLines={1} with contain and a multiplier lineHeight: maxHeight = lineHeight * fontSize', () => {
+ let t!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+ E
+
+
+ ));
+ expect(raw(t).maxHeight).toBe(36);
+ expect(t.height).toBe(36);
+ dispose();
+ });
+
it('maxWidth/maxHeight without contain pass through, and el.width/el.height read them', () => {
let t!: lng.ElementNode;
const dispose = renderer.render(() => (
@@ -475,7 +532,7 @@ describe('contract: font defaults from Config.fontSettings', () => {
});
describe('contract: autosize', () => {
- it('autosize reaches the renderer node; a loaded event on an autosize flex child relays out its parent synchronously', async () => {
+ it('autosize reaches the renderer node; a loaded event on an autosize flex child relays out its parent', async () => {
let count = 0;
let row!: lng.ElementNode;
let auto!: lng.ElementNode;
@@ -499,6 +556,12 @@ describe('contract: autosize', () => {
type: 'texture',
dimensions: { w: 120, h: 50 },
});
+ // Design 3.4.4: the loaded handler queues the parent for the
+ // post-mutation pass (in the renderer frame, between its walks) instead of
+ // laying it out synchronously, so several loads in a frame cost one pass.
+ // Until 1.7 the count was 2 right after emit.
+ expect(count).toBe(1);
+ await waitForUpdate();
expect(count).toBe(2);
expect(last.x).toBe(140);
expect(row.width).toBe(190);
@@ -528,6 +591,8 @@ describe('contract: text in a flex container (DOM renderer)', () => {
));
await waitForUpdate();
+ // The DOM renderer re-measures on a timer once fonts are loaded.
+ await nextTask();
expect(t.width).toBe(0);
expect(t.height).toBe(0);
expect(raw(t).loaded).toBe(true);
@@ -567,6 +632,7 @@ describe('contract: text in a flex container (DOM renderer)', () => {
expect(t.width).toBe(5 * CHAR_W);
expect(t.height).toBe(LINE_H);
await waitForUpdate();
+ await nextTask(); // the DOM renderer's re-measure timer
expect(t.x).toBe(60);
expect(last.x).toBe(120);
expect(row.width).toBe(170);
@@ -574,13 +640,26 @@ describe('contract: text in a flex container (DOM renderer)', () => {
expect(loaded).toEqual([
[t, t, { type: 'text', dimensions: { w: 50, h: 20 } }],
]);
- // The loaded handler runs the first flex pass and takes the container off
- // the layout queue, so onLayout fires once.
+ // The loaded handler queues the container, which render() already queued:
+ // one flex pass, so onLayout fires once.
expect(count).toBe(1);
dispose();
});
- it('flex waits for the text size: nothing is placed until the text is measured, then loaded relays out', async () => {
+ // 1.7 (stream T): Solid measures a flex text itself; it waits for
+ // `loaded` (once) only while the text's font is not loaded, which the DOM
+ // renderer reads from document.fonts.check. Until 1.7 every flex text
+ // waited for `loaded`, the font loaded or not.
+ it('flex waits for the text size: nothing is placed until the font loads and the text is measured, then loaded relays out', async () => {
+ const fontSet = document.fonts as unknown as {
+ check: (font: string) => boolean;
+ };
+ const savedCheck = fontSet.check;
+ const checked: string[] = [];
+ fontSet.check = (font: string) => {
+ checked.push(font);
+ return false;
+ };
const spy = mockTextMeasure();
// Hold the font-ready measurement and report 0 x 0 until then.
spy.mockImplementation(
@@ -597,10 +676,14 @@ describe('contract: text in a flex container (DOM renderer)', () => {
toJSON() {},
}) as DOMRect,
);
- const fonts = document.fonts as unknown as { ready: Promise };
+ const fonts = document.fonts as unknown as {
+ ready: Promise;
+ status: string;
+ };
const savedReady = fonts.ready;
let fontsReady!: () => void;
fonts.ready = new Promise((r) => (fontsReady = r));
+ fonts.status = 'loading';
let dispose = () => {};
try {
let count = 0;
@@ -619,10 +702,18 @@ describe('contract: text in a flex container (DOM renderer)', () => {
expect(row.width).toBe(0);
expect(count).toBe(1);
+ // The text's font, as CSS reads it.
+ expect(checked[0]).toBe(
+ `normal normal ${lng.Config.fontSettings.fontSize}px "${lng.Config.fontSettings.fontFamily}"`,
+ );
+
spy.mockRestore();
mockTextMeasure();
+ fontSet.check = savedCheck;
+ fonts.status = 'loaded';
fontsReady();
await waitForUpdate();
+ await nextTask();
expect(raw(t).loaded).toBe(true);
expect(t.width).toBe(50);
expect(last.x).toBe(60);
@@ -630,6 +721,8 @@ describe('contract: text in a flex container (DOM renderer)', () => {
expect(row.height).toBe(50);
expect(count).toBe(2);
} finally {
+ fontSet.check = savedCheck;
+ fonts.status = 'loaded';
fontsReady();
fonts.ready = savedReady;
await waitForUpdate();
@@ -658,6 +751,7 @@ describe('contract: text in a flex container (DOM renderer)', () => {
expect(t.text).toBe('Hello world');
expect(last.x).toBe(60); // stale until the renderer re-measures
await waitForUpdate();
+ await nextTask();
expect(t.width).toBe(110);
expect(last.x).toBe(120);
expect(row.width).toBe(170);
@@ -750,7 +844,7 @@ describe('contract: text in a flex container (DOM renderer)', () => {
dispose();
});
- it('flexGrow next to a text (docs example): the grow item takes the rest; it never shrinks back when the text grows', async () => {
+ it('flexGrow next to a text (docs example): the grow item takes the rest and follows the text size', async () => {
mockTextMeasure();
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const [label, setLabel] = s.createSignal('Flex Grow');
@@ -769,42 +863,327 @@ describe('contract: text in a flex container (DOM renderer)', () => {
expect(grow.width).toBe(490);
expect(row.width).toBe(600);
- // Today the grown width is the item's base on the next pass, so it keeps
- // 490 and the row overflows (200 + 490 = 690 > 600).
+ // B8: the grow item shrinks to 600 - 180 - 20 = 400. Before the fix the
+ // grown width was the item's base on the next pass, so it kept 490 and
+ // the row overflowed (200 + 490 = 690 > 600).
setLabel('Flex Grow Longer!!');
await waitForUpdate();
+ await nextTask();
expect(t.width).toBe(180);
expect(grow.x).toBe(200);
- expect(grow.width).toBe(490);
+ expect(grow.width).toBe(400);
// A shorter text lets it grow again.
setLabel('Flex');
await waitForUpdate();
+ await nextTask();
expect(grow.x).toBe(60);
expect(grow.width).toBe(540);
expect(warn).not.toHaveBeenCalled();
dispose();
});
+});
- // BUG: flexGrow should be computed from the item's own size each pass, so
- // the grow item shrinks to 600 - 180 - 20 = 400 when the text grows.
- // flex.ts:146 / flexLayout.ts:199 add the free space to the current
- // (already grown) width.
- it.skip('BUG: a flexGrow item shrinks back when a text sibling grows', async () => {
+/**
+ * A text size from the text and its font props, as the renderers' layouts
+ * read them: `fontSize / 2` per character plus `letterSpacing` (twice that
+ * in a family named 'Wide'), and a line of `lineHeight || fontSize`, wrapped
+ * at `maxWidth` (contain="width").
+ */
+function mockFontMeasure() {
+ return vi
+ .spyOn(Element.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: Element) {
+ const props = (
+ this as unknown as { _node?: { props?: Record } }
+ )._node?.props;
+ const text = props?.text;
+ let width = 0;
+ let height = 0;
+ if (typeof text === 'string' && props !== undefined) {
+ const size = props.fontSize as number;
+ const wide = props.fontFamily === 'Wide' ? 2 : 1;
+ const char = (size / 2) * wide + (props.letterSpacing as number);
+ const line = (props.lineHeight as number) || size;
+ width = text.length * char;
+ height = line;
+ const max = props.maxWidth as number;
+ if (props.contain === 'width' && max > 0 && width > max) {
+ height = Math.ceil(width / max) * line;
+ width = max;
+ }
+ }
+ return {
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: height,
+ width,
+ height,
+ toJSON() {},
+ } as DOMRect;
+ });
+}
+
+/** After the post-mutation microtask that a write queued (nothing else). */
+const microtask = () => Promise.resolve();
+
+describe('contract: Solid measures text before flex (1.7, stream T)', () => {
+ it('a text change is measured and laid out in the post-mutation microtask, once', async () => {
mockTextMeasure();
- const [label, setLabel] = s.createSignal('Flex Grow');
- let grow!: lng.ElementNode;
+ const [label, setLabel] = s.createSignal('Hello');
+ let count = 0;
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
const dispose = renderer.render(() => (
-
+ void count++}>
+ {label()}
+
+
+ ));
+ await nextTask();
+ expect(last.x).toBe(60);
+ count = 0;
+
+ setLabel('Hello world');
+ expect(last.x).toBe(60); // not synchronously
+ await microtask();
+ // Until 1.7: after the DOM renderer's own re-measure (a timer) and its
+ // `loaded`.
+ expect(t.width).toBe(110);
+ expect(last.x).toBe(120);
+ expect(count).toBe(1);
+ await nextTask();
+ expect(count).toBe(1);
+ dispose();
+ });
+
+ it('updateLayout() right after a text change measures the text first', () => {
+ mockTextMeasure();
+ const [label, setLabel] = s.createSignal('Hello');
+ let row!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
{label()}
-
+
));
- await waitForUpdate();
- setLabel('Flex Grow Longer!!');
- await waitForUpdate();
- expect(grow.x).toBe(200);
- expect(grow.width).toBe(400);
+ row.updateLayout();
+ expect(last.x).toBe(60);
+
+ setLabel('Hello world');
+ row.updateLayout();
+ expect(last.x).toBe(120);
+ dispose();
+ });
+
+ it('a text change that keeps the measured size lays nothing out', async () => {
+ mockTextMeasure();
+ const [label, setLabel] = s.createSignal('Hello');
+ let count = 0;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+ {label()}
+
+
+ ));
+ await nextTask();
+ count = 0;
+
+ setLabel('World'); // 5 characters, as before
+ await nextTask();
+ expect(count).toBe(0);
+ expect(last.x).toBe(60);
+ dispose();
+ });
+
+ it('every font prop the text layout reads lays the container out again: fontSize, lineHeight, letterSpacing, fontFamily, fontWeight', async () => {
+ mockFontMeasure();
+ const [size, setSize] = s.createSignal(20);
+ const [lineHeight, setLineHeight] = s.createSignal(0);
+ const [spacing, setSpacing] = s.createSignal(0);
+ const [family, setFamily] = s.createSignal('Narrow');
+ let count = 0;
+ let row!: lng.ElementNode;
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+
+ Hello
+
+
+
+ ));
+ await nextTask();
+ expect(last.x).toBe(60); // 5 * 10 + 10
+ expect(row.height).toBe(20);
+
+ const step = async (change: () => void, x: number, height: number) => {
+ count = 0;
+ change();
+ await microtask();
+ expect([last.x, row.height, count]).toEqual([x, height, 1]);
+ };
+ await step(() => setSize(40), 110, 40); // 5 * 20 + 10
+ await step(() => setLineHeight(50), 110, 50);
+ await step(() => setSpacing(2), 120, 50); // 5 * 22 + 10
+ await step(() => setFamily('Wide'), 220, 50); // 5 * 42 + 10
+ // fontWeight renames the family ('Wide700'): no longer wide.
+ await step(() => (t.fontWeight = 'bold'), 120, 50);
+ dispose();
+ });
+
+ it('a maxWidth change on a contained text lays the container out again', async () => {
+ mockFontMeasure();
+ const [width, setWidth] = s.createSignal(300);
+ let count = 0;
+ let row!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}
+ >
+
+ Hello world, twice
+
+
+
+ ));
+ await nextTask();
+ expect(last.y).toBe(20); // 18 * 10 = 180: one line of 20
+ count = 0;
+
+ setWidth(100); // two lines
+ await microtask();
+ expect(last.y).toBe(40);
+ expect(count).toBe(1);
+ dispose();
+ });
+
+ it('a new text in a flex container is measured once, in the post-mutation pass, with the writes of its tick; text in a plain view is not measured by Solid', async () => {
+ let first!: lng.ElementNode;
+ const d1 = renderer.render(() => a);
+ const proto = Object.getPrototypeOf(first.lng) as { measure(): boolean };
+ d1();
+ const measure = vi.spyOn(proto, 'measure');
+
+ const [label, setLabel] = s.createSignal('Hello');
+ let inFlex!: lng.ElementNode;
+ const d2 = renderer.render(() => (
+
+ {label()}
+
+ ));
+ setLabel('Hello again');
+ expect(measure).not.toHaveBeenCalled();
+ await microtask();
+ expect(measure).toHaveBeenCalledTimes(1);
+ expect(measure.mock.contexts[0]).toBe(inFlex.lng);
+ d2();
+
+ measure.mockClear();
+ const d3 = renderer.render(() => (
+
+ Hello
+
+ ));
+ await nextTask();
+ expect(measure).not.toHaveBeenCalled();
+ d3();
+ });
+
+ it('an onEvent.loaded on a flex text hears every new size, after Solid measured it first', async () => {
+ mockTextMeasure();
+ const [label, setLabel] = s.createSignal('Hello');
+ const heard: unknown[] = [];
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+ {label()}
+
+
+
+ ));
+ await nextTask();
+ expect(heard).toEqual([{ w: 50, h: 20 }]);
+
+ setLabel('Hello world');
+ await microtask();
+ expect(last.x).toBe(120); // Solid measured and laid out first
+ await nextTask(); // the DOM renderer's re-measure timer
+ expect(heard).toEqual([
+ { w: 50, h: 20 },
+ { w: 110, h: 20 },
+ ]);
+ dispose();
+ });
+
+ it('a loaded at a size Solid did not measure (a web font that loaded after the text was measured) lays the container out again', async () => {
+ mockTextMeasure();
+ let count = 0;
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+ Hello
+
+
+ ));
+ await nextTask();
+ expect(last.x).toBe(60);
+ count = 0;
+
+ // The face arrived: the DOM renderer measured the text again.
+ t.lng.w = 80;
+ (t.lng as unknown as lng.IEventEmitter).emit('loaded', {
+ type: 'text',
+ dimensions: { w: 80, h: 20 },
+ });
+ await nextTask();
+ expect(last.x).toBe(90);
+ expect(count).toBe(1);
+ dispose();
+ });
+
+ it('a contain change lays the container out again (the DOM renderer sizes the text by it)', async () => {
+ mockFontMeasure();
+ const [contain, setContain] = s.createSignal<'none' | 'width'>('none');
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+ Hello world, twice
+
+
+
+ ));
+ await nextTask();
+ expect(last.y).toBe(20); // one line of 180
+
+ setContain('width'); // two lines of 100
+ await microtask();
+ expect(last.y).toBe(40);
dispose();
});
});
diff --git a/tests/contract-virtual-grid.test.tsx b/tests/contract-virtual-grid.test.tsx
index 7ce8767a..5e2c154d 100644
--- a/tests/contract-virtual-grid.test.tsx
+++ b/tests/contract-virtual-grid.test.tsx
@@ -721,11 +721,17 @@ v.describe('VirtualGrid', () => {
const settle = async () => {
for (let i = 0; i < 4; i++) await flush();
};
+ const jsdomFrame = globalThis.requestAnimationFrame;
v.vi.stubGlobal(
'requestAnimationFrame',
(cb: (time: number) => void) =>
setTimeout(() => cb(performance.now() + 1e6), 0),
);
+ // Animations of earlier tests (on by default) can leave the DOM
+ // renderer's loop waiting on a jsdom frame, up to ~16 ms away, and the
+ // loop requests no other frame meanwhile. Let that frame run: its
+ // next request goes to the stub.
+ await new Promise((resolve) => jsdomFrame(() => resolve()));
lng.Config.animationsEnabled = true;
try {
let grid!: lng.ElementNode;
diff --git a/tests/contract-virtual.test.tsx b/tests/contract-virtual.test.tsx
index 754f0fe7..c6d90039 100644
--- a/tests/contract-virtual.test.tsx
+++ b/tests/contract-virtual.test.tsx
@@ -481,11 +481,17 @@ v.describe('VirtualRow: window and scroll modes', () => {
const settle = async () => {
for (let i = 0; i < 4; i++) await flush();
};
+ const jsdomFrame = globalThis.requestAnimationFrame;
v.vi.stubGlobal(
'requestAnimationFrame',
(cb: (time: number) => void) =>
setTimeout(() => cb(performance.now() + 1e6), 0),
);
+ // Animations of earlier tests (on by default) can leave the DOM
+ // renderer's loop waiting on a jsdom frame, up to ~16 ms away, and the
+ // loop requests no other frame meanwhile. Let that frame run: its
+ // next request goes to the stub.
+ await new Promise((resolve) => jsdomFrame(() => resolve()));
lng.Config.animationsEnabled = true;
try {
// Focused item's screen x (row x + its x) at mount, then after Right
diff --git a/tests/drawOrder.test.tsx b/tests/drawOrder.test.tsx
new file mode 100644
index 00000000..075777c9
--- /dev/null
+++ b/tests/drawOrder.test.tsx
@@ -0,0 +1,424 @@
+/**
+ * B19 on the DOM renderer: a node's `div` order among its parent's divs is
+ * its paint order (among equal z-index), and its `children` set is its child
+ * list. Both must follow the ElementNode's `children`, as renderer v2's child
+ * list does (tests/webgl/drawOrder.test.tsx).
+ */
+import * as v from 'vitest';
+import * as s from 'solid-js';
+import { ElementNode, TextNode } from '@solidtv/solid';
+import { scrollRow } from '@solidtv/solid/primitives';
+import nodeOpts from '../src/solidOpts.js';
+import { renderer } from './setup.js';
+
+type DomHandle = { div: HTMLElement; children: Set };
+const dom = (el: ElementNode) => el.lng as unknown as DomHandle;
+
+/** The ids of the rendered element children, in `children` order. */
+const expected = (parent: ElementNode) =>
+ parent.children
+ .filter((c) => c instanceof ElementNode && c.rendered)
+ .map((c) => (c as ElementNode).id);
+
+function byHandle(parent: ElementNode) {
+ const map = new Map();
+ for (const c of parent.children) {
+ if (c instanceof ElementNode) map.set(c.lng, c.id);
+ }
+ return map;
+}
+
+/** The ids behind the parent's child divs, in DOM (paint) order. */
+const painted = (parent: ElementNode) => {
+ const map = byHandle(parent);
+ const out: Array = [];
+ for (const div of Array.from(dom(parent).div.children)) {
+ const node = (div as unknown as { _node?: unknown })._node;
+ if (node !== undefined) out.push(map.has(node) ? map.get(node) : '?');
+ }
+ return out;
+};
+
+/** The ids behind the parent's DOM renderer child list. */
+const listed = (parent: ElementNode) => {
+ const map = byHandle(parent);
+ return Array.from(dom(parent).children).map((n) =>
+ map.has(n) ? map.get(n) : '?',
+ );
+};
+
+const ids = (parent: ElementNode) =>
+ parent.children.map((c) => (c instanceof ElementNode ? c.id : '#text'));
+
+const tick = () => new Promise((r) => setTimeout(r, 0));
+
+const expectOrder = (parent: ElementNode) => {
+ v.expect(painted(parent)).toEqual(expected(parent));
+ v.expect(listed(parent)).toEqual(expected(parent));
+};
+
+v.describe('B19: the DOM renderer draws children in children order', () => {
+ v.test(' inserted before an anchor', async () => {
+ const [show, setShow] = s.createSignal(false);
+ let parent!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+
+
+
+ ));
+ await tick();
+ expectOrder(parent);
+
+ setShow(true);
+ await tick();
+ v.expect(ids(parent)).toEqual(['first', 'middle', 'last']);
+ expectOrder(parent);
+ dispose();
+ });
+
+ v.test(' insert in the middle and reorder', async () => {
+ const [items, setItems] = s.createSignal(['a', 'c']);
+ let parent!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+ {(id) => }
+
+
+
+ ));
+ await tick();
+ expectOrder(parent);
+
+ setItems(['a', 'b', 'c']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'a', 'b', 'c', 'tail']);
+ expectOrder(parent);
+
+ setItems(['c', 'b', 'a']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'c', 'b', 'a', 'tail']);
+ expectOrder(parent);
+ dispose();
+ });
+
+ v.test('insertChild(node, before) between rendered parents', () => {
+ let left!: ElementNode;
+ let right!: ElementNode;
+ let moved!: ElementNode;
+ let anchor!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+
+
+
+
+
+
+ ));
+ right.insertChild(moved, anchor);
+ v.expect(ids(right)).toEqual(['moved', 'anchor', 'y']);
+ expectOrder(right);
+ expectOrder(left);
+
+ const y = right.children[2] as ElementNode;
+ right.insertChild(y, moved);
+ v.expect(ids(right)).toEqual(['y', 'moved', 'anchor']);
+ expectOrder(right);
+ right.insertChild(y);
+ v.expect(ids(right)).toEqual(['moved', 'anchor', 'y']);
+ expectOrder(right);
+ dispose();
+ });
+
+ // Solid's swap of adjacent items asks for insertNode(parent, y, y): a node
+ // placed before itself stays (DOM semantics), it is not appended.
+ v.test(
+ 'an adjacent swap with a later sibling keeps the declared order',
+ async () => {
+ const [items, setItems] = s.createSignal(['a', 'x', 'y', 'b']);
+ let parent!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+ {(id) => }
+
+
+
+ ));
+ await tick();
+ setItems(['a', 'y', 'x', 'b']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'a', 'y', 'x', 'b', 'tail']);
+ expectOrder(parent);
+ dispose();
+ },
+ );
+
+ v.test(
+ 'a move that leaves a child where it is does not call the renderer',
+ () => {
+ let parent!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+
+ ));
+ const [a, b, c] = parent.children as [
+ ElementNode,
+ ElementNode,
+ ElementNode,
+ ];
+ const spy = v.vi.spyOn(
+ parent.lng as unknown as { insertBefore: () => void },
+ 'insertBefore',
+ );
+ try {
+ parent.insertChild(b, c);
+ parent.insertChild(c);
+ parent.insertChild(a, a);
+ v.expect(ids(parent)).toEqual(['a', 'b', 'c']);
+ v.expect(spy).not.toHaveBeenCalled();
+
+ parent.insertChild(c, a);
+ v.expect(ids(parent)).toEqual(['c', 'a', 'b']);
+ v.expect(spy).toHaveBeenCalledTimes(1);
+ expectOrder(parent);
+ } finally {
+ spy.mockRestore();
+ dispose();
+ }
+ },
+ );
+
+ v.test(
+ 'a parent rendered after it got rendered and new children draws them in order',
+ () => {
+ let host!: ElementNode;
+ let moved!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+ ));
+ const fresh = new ElementNode('view');
+ fresh.id = 'fresh';
+ const [n1, n2] = ['n1', 'n2'].map((id) => {
+ const n = new ElementNode('view');
+ n.id = id;
+ return n;
+ }) as [ElementNode, ElementNode];
+ fresh.insertChild(n1);
+ fresh.insertChild(moved);
+ fresh.insertChild(n2);
+ v.expect(moved.rendered).toBe(true);
+ host.insertChild(fresh);
+ fresh.render(true);
+ v.expect(ids(fresh)).toEqual(['n1', 'moved', 'n2']);
+ expectOrder(fresh);
+ v.expect(listed(host)).toEqual(['fresh']);
+ dispose();
+ },
+ );
+
+ // As renderer v2: a destroyed child is left alone, a destroyed anchor
+ // appends (its div is gone from the parent's).
+ v.test('DOM renderer insertBefore with a destroyed child or anchor', () => {
+ let parent!: ElementNode;
+ let a!: ElementNode;
+ let b!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+ ));
+ type Insert = {
+ insertBefore: (child: unknown, before: unknown) => void;
+ destroy: () => void;
+ };
+ const lngOf = (el: ElementNode) => el.lng as unknown as Insert;
+ lngOf(a).destroy();
+ lngOf(parent).insertBefore(lngOf(a), null);
+ v.expect(painted(parent)).toEqual(['b']);
+ v.expect(listed(parent)).toEqual(['b']);
+ v.expect(() =>
+ lngOf(parent).insertBefore(lngOf(b), lngOf(a)),
+ ).not.toThrow();
+ v.expect(painted(parent)).toEqual(['b']);
+ v.expect(listed(parent)).toEqual(['b']);
+ dispose();
+ });
+});
+
+v.describe('child list', () => {
+ // N3: a removed node keeps its parent link, as in 1.6 (keys and events
+ // from a removed focused subtree still bubble through it).
+ v.test(
+ 'removeChild takes the child out and keeps its parent link (1.6)',
+ () => {
+ const parent = new ElementNode('view');
+ const [a, b, c] = ['a', 'b', 'c'].map((id) => {
+ const n = new ElementNode('view');
+ n.id = id;
+ parent.insertChild(n);
+ return n;
+ }) as [ElementNode, ElementNode, ElementNode];
+
+ parent.removeChild(b);
+ v.expect(ids(parent)).toEqual(['a', 'c']);
+ v.expect(b.parent).toBe(parent);
+
+ // Not a child: nothing changes.
+ parent.removeChild(b);
+ v.expect(ids(parent)).toEqual(['a', 'c']);
+
+ // Re-inserted elsewhere: it is in one child list only.
+ const other = new ElementNode('view');
+ other.insertChild(b);
+ v.expect(ids(other)).toEqual(['b']);
+ v.expect(ids(parent)).toEqual(['a', 'c']);
+ v.expect(b.parent).toBe(other);
+
+ // Re-inserted where it was, before a sibling.
+ parent.removeChild(a);
+ v.expect(a.parent).toBe(parent);
+ parent.insertChild(a, c);
+ v.expect(ids(parent)).toEqual(['a', 'c']);
+ parent.insertChild(a, a);
+ v.expect(ids(parent)).toEqual(['a', 'c']);
+ },
+ );
+
+ v.test('replaceText on a removed text child changes only its text', () => {
+ const text = new ElementNode('text');
+ const child = new TextNode('a');
+ text.insertChild(child);
+ text.removeChild(child);
+ v.expect(() => nodeOpts.replaceText(child, 'b')).not.toThrow();
+ v.expect(child.text).toBe('b');
+ });
+
+ v.test(
+ 'a preserved element stays preserved through a remove and re-insert',
+ async () => {
+ const [show, setShow] = s.createSignal(true);
+ let el!: ElementNode;
+ let destroyed = 0;
+ const dispose = renderer.render(() => {
+ const kept = (
+ void destroyed++}
+ />
+ );
+ return {show() ? kept : null};
+ });
+ await tick();
+ v.expect(el.preserve).toBe(true);
+
+ const host = el.parent!;
+ setShow(false);
+ await tick();
+ v.expect(host.children).not.toContain(el);
+ v.expect(el.parent).toBe(host);
+ setShow(true);
+ await tick();
+ v.expect(host.children).toContain(el);
+ v.expect(el.preserve).toBe(true);
+ v.expect(destroyed).toBe(0);
+ dispose();
+ },
+ );
+
+ // A Row that is itself a removed root, with focus still in it, takes its
+ // first scroll (its parent link is kept, as in 1.6).
+ v.test('a removed Row still scrolls', () => {
+ let host!: ElementNode;
+ let row!: ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+
+
+
+ ));
+ host.removeChild(row);
+ v.expect(row.parent).toBe(host);
+ v.expect(() => scrollRow(1, row, undefined, 0)).not.toThrow();
+ dispose();
+ });
+
+ // N3: a removed node keeps its parent link, but must not lay out its old
+ // parent: not on a load, not when its own layout changes its size.
+ v.test("a removed node's load does not lay out its old parent", async () => {
+ let count = 0;
+ let row!: ElementNode;
+ let auto!: ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+
+
+
+ ));
+ await tick();
+ const before = count;
+ row.removeChild(auto);
+ await tick();
+ const afterRemove = count;
+ v.expect(afterRemove).toBeGreaterThan(before);
+
+ auto.lng.w = 120;
+ (auto.lng as unknown as { emit: (e: string, d: unknown) => void }).emit(
+ 'loaded',
+ { type: 'texture', dimensions: { w: 120, h: 50 } },
+ );
+ await tick();
+ v.expect(count).toBe(afterRemove);
+ dispose();
+ });
+
+ v.test(
+ "a removed container's resize does not lay out its old parent",
+ async () => {
+ let count = 0;
+ let outer!: ElementNode;
+ let inner!: ElementNode;
+ let item!: ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+
+
+
+
+
+ ));
+ await tick();
+ outer.removeChild(inner);
+ await tick();
+ const afterRemove = count;
+
+ item.width = 70;
+ inner.updateLayout();
+ await tick();
+ v.expect(inner.width).toBe(70);
+ v.expect(count).toBe(afterRemove);
+ dispose();
+ },
+ );
+});
diff --git a/tests/flex.performance.spec.ts b/tests/flex.performance.spec.ts
index dfcfd8b1..4d89b4c7 100644
--- a/tests/flex.performance.spec.ts
+++ b/tests/flex.performance.spec.ts
@@ -1,5 +1,5 @@
import { ElementNode } from '../src/core/elementNode.ts';
-import calculateFlex from '../src/core/flex.ts';
+import calculateFlex from '../src/core/flexLayout.ts';
import {
describe,
it,
diff --git a/tests/flex.spec.ts b/tests/flex.spec.ts
index 53575851..68eea376 100644
--- a/tests/flex.spec.ts
+++ b/tests/flex.spec.ts
@@ -1,5 +1,5 @@
import { ElementNode } from '../src/core/elementNode.ts';
-import calculateFlex from '../src/core/flex.ts';
+import calculateFlex from '../src/core/flexLayout.ts';
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import { isElementNode } from '../src/core/utils.ts';
import { TextNode } from '../src/core/nodeTypes.ts';
@@ -320,9 +320,8 @@ describe('Flexbox Layout (calculateFlex)', () => {
calculateFlex(parent);
expect(child1.width).toBe(150); // Unchanged
expect(child2.width).toBe(150); // Unchanged
- expect(console.warn).toHaveBeenCalledWith(
- 'No available space for flex-grow items to expand, or items overflow.',
- );
+ // 5.3: flex.ts warned here (in production too) until 1.7.
+ expect(console.warn).not.toHaveBeenCalled();
});
it('should not apply flexGrow if only one child', () => {
diff --git a/tests/flex_min_size.spec.ts b/tests/flex_min_size.spec.ts
index 5ed5498f..ee97adb0 100644
--- a/tests/flex_min_size.spec.ts
+++ b/tests/flex_min_size.spec.ts
@@ -1,5 +1,5 @@
import { ElementNode } from '../src/core/elementNode.ts';
-import calculateFlex from '../src/core/flex.ts';
+import calculateFlex from '../src/core/flexLayout.ts';
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import { isElementNode } from '../src/core/utils.ts';
import { TextNode } from '../src/core/nodeTypes.ts';
diff --git a/tests/fontWaiting.test.ts b/tests/fontWaiting.test.ts
new file mode 100644
index 00000000..95c158b5
--- /dev/null
+++ b/tests/fontWaiting.test.ts
@@ -0,0 +1,178 @@
+/**
+ * Texts that wait for their font (Solid's text measurement, stream T): many
+ * texts in two families render before either font loads; one family loads
+ * while the other is still missing, so the texts of the missing one wait
+ * again while the waiting list is being measured (T1 review 2, Important 1:
+ * the list used to be swept under that loop once it reached its sweep
+ * length, losing waiting texts or throwing).
+ *
+ * The waiting list and its sweep length are module state, and this suite
+ * runs with `isolate: false`: each case imports a fresh @solidtv/solid
+ * (vi.resetModules) with its own renderer, so no earlier test has grown the
+ * sweep length or left a DOM-renderer re-measure pending. No JSX: the JSX
+ * runtime is the shared instance, so the trees are built with the fresh
+ * instance's ElementNode.
+ *
+ * DOM renderer (jsdom). `document.fonts.check` answers per family; the DOM
+ * renderer's own re-measure is held (fonts loading, `ready` pending), so only
+ * Solid's font-loaded pass (fontLoaded(), as loadFonts() calls it) measures.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import './setup.js';
+
+type Solid = typeof import('@solidtv/solid');
+type ElementNode = InstanceType;
+
+const settle = () => new Promise((r) => setTimeout(r, 0));
+
+/** A fresh @solidtv/solid and its fontLoaded(), with a DOM renderer of its own. */
+async function freshSolid() {
+ vi.resetModules();
+ const solid = await import('@solidtv/solid');
+ // The instance @solidtv/solid's elementNode registered with.
+ const { fontLoaded } = await import('../src/core/fontLoaded.js');
+ solid.Config.rendererOptions = {};
+ solid.Config.domRendererEnabled = true;
+ const root = document.createElement('div');
+ document.body.appendChild(root);
+ const app = solid.createRenderer(undefined, root);
+ return {
+ solid,
+ fontLoaded,
+ render: app.render,
+ remove() {
+ root.remove();
+ },
+ };
+}
+
+/** `document.fonts.check` per family, with the DOM renderer's re-measure held. */
+function fontsByFamily() {
+ const loaded = new Set();
+ const fonts = document.fonts as unknown as {
+ check: (font: string) => boolean;
+ status: string;
+ ready: Promise;
+ };
+ const saved = fonts.check;
+ const savedReady = fonts.ready;
+ fonts.check = (font: string) => {
+ const m = /"([^"]+)"$/.exec(font);
+ return m !== null && loaded.has(m[1]!);
+ };
+ let ready!: () => void;
+ fonts.ready = new Promise((r) => (ready = r));
+ fonts.status = 'loading';
+ return {
+ loaded,
+ restore() {
+ fonts.check = saved;
+ fonts.status = 'loaded';
+ ready();
+ fonts.ready = savedReady;
+ },
+ };
+}
+
+/** Errors thrown by post-mutation runs (microtasks) meanwhile. */
+function catchMicrotaskErrors() {
+ const errors: unknown[] = [];
+ const saved = globalThis.queueMicrotask;
+ globalThis.queueMicrotask = (fn: () => void) =>
+ saved(() => {
+ try {
+ fn();
+ } catch (e) {
+ errors.push(e);
+ }
+ });
+ return {
+ errors,
+ restore() {
+ globalThis.queueMicrotask = saved;
+ },
+ };
+}
+
+/** Whether Solid still waits for the font of each text. */
+const waiting = (texts: ElementNode[]) =>
+ texts.map(
+ (t) =>
+ (t as unknown as { _text?: { waiting: boolean } })._text?.waiting ===
+ true,
+ );
+
+const cases: Array<[string, string[]]> = [
+ [
+ '120 texts, two families alternating',
+ [...Array(120)].map((_, i) => (i % 2 === 0 ? 'FA' : 'FB')),
+ ],
+ [
+ '100 texts, two families alternating',
+ [...Array(100)].map((_, i) => (i % 2 === 0 ? 'FA' : 'FB')),
+ ],
+ [
+ '100 texts of one family, then 20 of another',
+ [...Array(120)].map((_, i) => (i < 100 ? 'FA' : 'FB')),
+ ],
+];
+
+describe('texts that wait for their font', () => {
+ for (const [name, families] of cases) {
+ it(`${name}: each is measured when its font loads, and none is lost`, async () => {
+ const fonts = fontsByFamily();
+ const caught = catchMicrotaskErrors();
+ const app = await freshSolid();
+ try {
+ const { ElementNode } = app.solid;
+ // Each text in a flex row of its own, so Solid measures it.
+ const container = new ElementNode('view');
+ const texts: ElementNode[] = [];
+ for (let i = 0; i < families.length; i++) {
+ const row = new ElementNode('view');
+ row.display = 'flex';
+ row.y = i * 30;
+ const t = new ElementNode('text');
+ t.fontFamily = families[i];
+ t.text = 'Hello';
+ row.insertChild(t);
+ container.insertChild(row);
+ texts.push(t);
+ }
+ const dispose = app.render(() => container as never);
+ let heard = 0;
+ for (const t of texts) {
+ (t.lng as unknown as { on(e: string, f: () => void): void }).on(
+ 'loaded',
+ () => void heard++,
+ );
+ }
+ await settle();
+ expect(waiting(texts).every((w) => w)).toBe(true);
+
+ // Precondition: only Solid's font-loaded pass measures them (no
+ // `loaded` has woken the waiting list).
+ expect(heard).toBe(0);
+
+ fonts.loaded.add('FA');
+ app.fontLoaded();
+ await settle();
+ expect(caught.errors).toEqual([]);
+ expect(waiting(texts)).toEqual(families.map((f) => f === 'FB'));
+
+ fonts.loaded.add('FB');
+ app.fontLoaded();
+ await settle();
+ expect(caught.errors).toEqual([]);
+ expect(waiting(texts).some((w) => w)).toBe(false);
+ dispose();
+ await settle();
+ } finally {
+ caught.restore();
+ fonts.restore();
+ app.remove();
+ vi.resetModules();
+ }
+ });
+ }
+});
diff --git a/tests/layoutQueue.test.tsx b/tests/layoutQueue.test.tsx
new file mode 100644
index 00000000..a8d9f485
--- /dev/null
+++ b/tests/layoutQueue.test.tsx
@@ -0,0 +1,524 @@
+/**
+ * The layout queue and the post-mutation scheduler (design 3.4.4, 3.5).
+ *
+ * Within one post-mutation run, flex containers are laid out deepest first,
+ * each at most once unless a child's size changed after its pass; a
+ * container queues its parent only when its own size changed. The run is
+ * scheduled as a microtask; only a `loaded` handler (an autosize node's, or
+ * a text's while its font loads: Solid measures text itself from 1.7) also
+ * asks the renderer to run it inside the frame, between its walks.
+ *
+ * The `loaded` cases use an autosize view: until stream T a text's size
+ * reached flex through `loaded` too (tests/contract-text.test.tsx has the
+ * text cases now).
+ *
+ * DOM renderer (jsdom) with the text measurement mocked as in
+ * contract-text.test.tsx: 10px per character, 20px per line.
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import * as s from 'solid-js';
+import * as lng from '@solidtv/solid';
+import { renderer } from './setup.js';
+
+const CHAR_W = 10;
+const LINE_H = 20;
+
+function mockTextMeasure() {
+ return vi
+ .spyOn(Element.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: Element) {
+ const text = (
+ this as unknown as { _node?: { props?: { text?: unknown } } }
+ )._node?.props?.text;
+ const isText = typeof text === 'string';
+ const width = isText ? text.length * CHAR_W : 0;
+ const height = isText ? LINE_H : 0;
+ return {
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: height,
+ width,
+ height,
+ toJSON() {},
+ } as DOMRect;
+ });
+}
+
+type Stage = { reprocessUpdates?: (cb?: () => void) => void };
+const stage = () => lng.getRenderer().stage as unknown as Stage;
+const emitter = (el: lng.ElementNode) => el.lng as unknown as lng.IEventEmitter;
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+/** After every microtask: the text re-measure, `loaded` and the layout pass. */
+const settle = () => new Promise((r) => setTimeout(r, 0));
+
+describe('layout queue', () => {
+ it('a press that changes texts in three nested flex containers lays each container out once, deepest first', async () => {
+ mockTextMeasure();
+ const [title, setTitle] = s.createSignal('Title');
+ const [a, setA] = s.createSignal('A');
+ const [b, setB] = s.createSignal('B');
+ const [c, setC] = s.createSignal('C');
+ const passes: string[] = [];
+ let outer!: lng.ElementNode;
+ let middle!: lng.ElementNode;
+ let inner!: lng.ElementNode;
+ let tA!: lng.ElementNode;
+ let tB!: lng.ElementNode;
+ let tC!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void passes.push('outer')}
+ >
+ {title()}
+ void passes.push('middle')}
+ >
+ {a()}
+ void passes.push('inner')}
+ >
+ {b()}
+ {c()}
+
+
+
+ ));
+ await settle();
+ passes.length = 0;
+
+ s.batch(() => {
+ setTitle('A longer title');
+ setA('AAAA');
+ setB('BBBBBB');
+ setC('CC');
+ });
+ await settle();
+
+ expect(passes).toEqual(['inner', 'middle', 'outer']);
+ // inner: 60 + 10 + 20
+ expect(tC.x).toBe(70);
+ expect(inner.width).toBe(90);
+ // middle: 40 + 10 + 90
+ expect(tA.width).toBe(40);
+ expect(inner.x).toBe(50);
+ expect(middle.width).toBe(140);
+ // outer (column): 20 + 10 + 20
+ expect(middle.y).toBe(30);
+ expect(outer.height).toBe(50);
+ void tB;
+ dispose();
+ });
+
+ it('a deep and a shallow container changed in one batch: the deep one first, each once', async () => {
+ const [deep, setDeep] = s.createSignal(false);
+ const [shallow, setShallow] = s.createSignal(false);
+ const passes: string[] = [];
+ let outer!: lng.ElementNode;
+ let inner!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void passes.push('outer')}
+ >
+ void passes.push('middle')}
+ >
+ void passes.push('inner')}
+ >
+
+
+
+
+
+
+
+
+
+
+
+ ));
+ await settle();
+ expect(last.x).toBe(60);
+ passes.length = 0;
+
+ s.batch(() => {
+ setDeep(true);
+ setShallow(true);
+ });
+ await settle();
+
+ expect(passes).toEqual(['inner', 'middle', 'outer']);
+ expect(inner.width).toBe(80);
+ // 80 + 10 + 20 + 10
+ expect(last.x).toBe(120);
+ expect(outer.width).toBe(160);
+ dispose();
+ });
+
+ it('a loaded event that reports an unchanged size does not lay the container out again', async () => {
+ let count = 0;
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+
+
+
+ ));
+ await settle();
+ expect(last.x).toBe(60);
+ count = 0;
+
+ emitter(t).emit('loaded', {
+ type: 'texture',
+ dimensions: { w: 50, h: 20 },
+ });
+ await settle();
+ expect(count).toBe(0);
+ dispose();
+ });
+
+ it('a loaded event that reports a new size lays the container out in the post-mutation pass', async () => {
+ let count = 0;
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ void count++}>
+
+
+
+ ));
+ await settle();
+ count = 0;
+
+ t.lng.w = 80;
+ emitter(t).emit('loaded', {
+ type: 'texture',
+ dimensions: { w: 80, h: 20 },
+ });
+ expect(count).toBe(0); // not synchronously
+ await settle();
+ expect(count).toBe(1);
+ expect(last.x).toBe(90);
+ dispose();
+ });
+});
+
+describe('layout queue: more cases', () => {
+ /** Holds the post-mutation runs so a test can run them one at a time. */
+ function holdMicrotasks() {
+ const held: Array<() => void> = [];
+ const saved = globalThis.queueMicrotask;
+ globalThis.queueMicrotask = (fn: () => void) => void held.push(fn);
+ return {
+ held,
+ restore() {
+ globalThis.queueMicrotask = saved;
+ },
+ };
+ }
+
+ it('a deeper container queued while a shallower one runs is laid out in the same run (another sweep)', async () => {
+ const [extra, setExtra] = s.createSignal(false);
+ const passes: string[] = [];
+ let shown = false;
+ let inner!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const hold = holdMicrotasks();
+ let dispose = () => {};
+ try {
+ dispose = renderer.render(() => (
+ {
+ passes.push('outer');
+ if (!shown) {
+ shown = true;
+ setExtra(true); // inserts into `inner`, which is deeper
+ }
+ }}
+ >
+ void passes.push('inner')}
+ >
+
+
+
+
+
+
+
+ ));
+ // One post-mutation run.
+ hold.held.shift()!();
+ expect(passes).toEqual(['inner', 'outer', 'inner', 'outer']);
+ expect(inner.width).toBe(80);
+ expect(last.x).toBe(90);
+ } finally {
+ hold.restore();
+ for (const fn of hold.held) fn();
+ }
+ await settle();
+ dispose();
+ });
+
+ it('a loaded event on an autosize node removed from its container does not throw, and the container stays laid out', async () => {
+ const [show, setShow] = s.createSignal(true);
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+
+
+
+
+ ));
+ await settle();
+ expect(last.x).toBe(60);
+ setShow(false);
+ await settle();
+ expect(last.x).toBe(0);
+
+ t.lng.w = 90;
+ expect(() =>
+ emitter(t).emit('loaded', {
+ type: 'texture',
+ dimensions: { w: 90, h: 20 },
+ }),
+ ).not.toThrow();
+ await settle();
+ expect(last.x).toBe(0);
+ dispose();
+ });
+
+ it('an onDestroy that throws does not stop later post-mutation runs', async () => {
+ const [show, setShow] = s.createSignal(true);
+ const [more, setMore] = s.createSignal(false);
+ let added!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+
+ {
+ throw new Error('onDestroy failed');
+ }}
+ />
+
+
+
+
+
+
+ ));
+ await settle();
+ expect(last.x).toBe(50);
+
+ const errors: unknown[] = [];
+ const saved = globalThis.queueMicrotask;
+ globalThis.queueMicrotask = (fn: () => void) =>
+ saved(() => {
+ try {
+ fn();
+ } catch (e) {
+ errors.push(e);
+ }
+ });
+ try {
+ setShow(false); // its run throws in the delete flush
+ await settle();
+ expect(errors).toHaveLength(1);
+
+ setMore(true); // a later run lays out
+ await settle();
+ expect(errors).toHaveLength(1);
+ expect(added.x).toBe(0);
+ expect(last.x).toBe(30);
+ } finally {
+ globalThis.queueMicrotask = saved;
+ }
+ dispose();
+ });
+});
+
+describe('post-mutation scheduling', () => {
+ it('a mutation runs the post-mutation pass as a microtask, not in the renderer frame; a loaded handler asks for the frame', async () => {
+ mockTextMeasure();
+ const st = stage();
+ const saved = st.reprocessUpdates;
+ const reprocess = vi.fn();
+ st.reprocessUpdates = reprocess;
+ try {
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+ Hi
+
+
+
+ ));
+ await settle();
+ expect(last.x).toBe(90); // 20 + 10 + 50 + 10
+ // A text measured by Solid needs no frame either (1.7, stream T).
+ expect(reprocess).not.toHaveBeenCalled();
+
+ t.lng.w = 80;
+ emitter(t).emit('loaded', {
+ type: 'texture',
+ dimensions: { w: 80, h: 20 },
+ });
+ expect(reprocess).toHaveBeenCalledTimes(1);
+ expect(typeof reprocess.mock.calls[0]![0]).toBe('function');
+ // The renderer runs the callback between its walks: the layout lands
+ // in the same frame.
+ reprocess.mock.calls[0]![0]();
+ expect(last.x).toBe(120); // 20 + 10 + 80 + 10
+ dispose();
+ } finally {
+ if (saved === undefined) {
+ delete st.reprocessUpdates;
+ } else {
+ st.reprocessUpdates = saved;
+ }
+ }
+ });
+});
+
+describe('text measurement in the layout phase', () => {
+ it('stops re-measuring after 16 sweeps of texts that never settle, warns once, and leaves later runs working', async () => {
+ mockTextMeasure();
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ let passes = 0;
+ let t!: lng.ElementNode;
+ let toggle = false;
+ let looping = true;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+ {
+ passes++;
+ if (!looping) return;
+ // A layout that changes the size of a text it lays out: never settles.
+ toggle = !toggle;
+ t.text = toggle ? 'Hello world' : 'Hi';
+ }}
+ >
+ Hello
+
+
+ ));
+ // One post-mutation run (microtasks only: the DOM renderer's own
+ // re-measure, on a timer, would start the loop again, as in 1.6).
+ for (let i = 0; i < 5; i++) await Promise.resolve();
+ // The first pass, then one per sweep: 16 more; then it stops.
+ expect(passes).toBe(17);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0]![0])).toContain('did not settle');
+ // Clean up: stop the loop, and let the DOM renderer's re-measure timer
+ // (scheduled by the text writes) run before the container goes, so it
+ // does not run into later tests.
+ looping = false;
+ await settle();
+ dispose();
+ await settle();
+ void last;
+
+ // Later runs lay out.
+ let next!: lng.ElementNode;
+ const dispose2 = renderer.render(() => (
+
+ Hello
+
+
+ ));
+ await settle();
+ expect(next.x).toBe(60);
+ dispose2();
+ });
+
+ it('a measure that throws does not stop later post-mutation runs', async () => {
+ mockTextMeasure();
+ const [label, setLabel] = s.createSignal('Hello');
+ let t!: lng.ElementNode;
+ let last!: lng.ElementNode;
+ const dispose = renderer.render(() => (
+
+ {label()}
+
+
+ ));
+ await settle();
+ expect(last.x).toBe(60);
+
+ const proto = Object.getPrototypeOf(t.lng) as { measure(): boolean };
+ const measure = proto.measure;
+ let throws = true;
+ const spy = vi.spyOn(proto, 'measure').mockImplementation(function (
+ this: unknown,
+ ) {
+ if (throws) {
+ throws = false;
+ throw new Error('measure failed');
+ }
+ return measure.call(this);
+ });
+ const errors: unknown[] = [];
+ const saved = globalThis.queueMicrotask;
+ globalThis.queueMicrotask = (fn: () => void) =>
+ saved(() => {
+ try {
+ fn();
+ } catch (e) {
+ errors.push(e);
+ }
+ });
+ try {
+ setLabel('Hello world'); // its run throws in the measure
+ await settle();
+ expect(errors).toHaveLength(1);
+
+ setLabel('Hi'); // a later run measures and lays out
+ await settle();
+ expect(errors).toHaveLength(1);
+ expect(last.x).toBe(30);
+ } finally {
+ globalThis.queueMicrotask = saved;
+ spy.mockRestore();
+ }
+ dispose();
+ });
+});
diff --git a/tests/setup.ts b/tests/setup.ts
index a8a479c7..22173452 100644
--- a/tests/setup.ts
+++ b/tests/setup.ts
@@ -28,6 +28,9 @@ if (!document.fonts) {
load: () => Promise.resolve(),
forEach: () => {},
ready: Promise.resolve(),
+ // As in a browser once its fonts are in: the DOM renderer re-measures a
+ // text on a timer then (not on `ready`, a microtask).
+ status: 'loaded',
};
}
diff --git a/tests/webgl/drawOrder.test.tsx b/tests/webgl/drawOrder.test.tsx
new file mode 100644
index 00000000..b1264fe8
--- /dev/null
+++ b/tests/webgl/drawOrder.test.tsx
@@ -0,0 +1,187 @@
+/**
+ * B19: renderer v2 draws siblings in its own child order (among equal
+ * zIndex), so that order must follow the ElementNode's `children`. Before
+ * 1.7, a node inserted before an anchor (`` between siblings, ``
+ * adding in the middle) was appended to the renderer's children, and a
+ * same-parent move (a `` reorder) never moved the renderer node.
+ *
+ * Read through the renderer's public children list (`Node.children`).
+ */
+import * as v from 'vitest';
+import * as s from 'solid-js';
+import { ElementNode } from '@solidtv/solid';
+import { render } from './setup.js';
+
+type Handle = { children: unknown[] };
+
+/** The ids of the rendered element children, in `children` order. */
+const expected = (parent: ElementNode) =>
+ parent.children
+ .filter((c) => c instanceof ElementNode && c.rendered)
+ .map((c) => (c as ElementNode).id);
+
+/** The ids behind the renderer's children of `parent`, in draw order. */
+const drawn = (parent: ElementNode) => {
+ const byHandle = new Map();
+ for (const c of parent.children) {
+ if (c instanceof ElementNode) byHandle.set(c.lng, c.id);
+ }
+ return (parent.lng as unknown as Handle).children.map((h) =>
+ byHandle.has(h) ? byHandle.get(h) : '?',
+ );
+};
+
+const ids = (parent: ElementNode) =>
+ parent.children.map((c) => (c instanceof ElementNode ? c.id : '#text'));
+
+const tick = () => new Promise((r) => setTimeout(r, 0));
+
+v.test(' inserted before an anchor is drawn before it', async () => {
+ const [show, setShow] = s.createSignal(false);
+ let parent!: ElementNode;
+ const dispose = render(() => (
+
+
+
+
+
+
+
+ ));
+ await tick();
+ v.expect(drawn(parent)).toEqual(expected(parent));
+
+ setShow(true);
+ await tick();
+ v.expect(ids(parent)).toEqual(['first', 'middle', 'last']);
+ v.expect(drawn(parent)).toEqual(expected(parent));
+
+ setShow(false);
+ await tick();
+ setShow(true);
+ await tick();
+ v.expect(drawn(parent)).toEqual(expected(parent));
+ dispose();
+});
+
+v.test(
+ ' insert in the middle and reorder keep the drawn order',
+ async () => {
+ const [items, setItems] = s.createSignal(['a', 'c']);
+ let parent!: ElementNode;
+ const dispose = render(() => (
+
+
+
+ {(id) => }
+
+
+
+ ));
+ await tick();
+ v.expect(drawn(parent)).toEqual(expected(parent));
+
+ setItems(['a', 'b', 'c']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'a', 'b', 'c', 'tail']);
+ v.expect(drawn(parent)).toEqual(expected(parent));
+
+ setItems(['c', 'b', 'a']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'c', 'b', 'a', 'tail']);
+ v.expect(drawn(parent)).toEqual(expected(parent));
+
+ setItems(['b', 'd', 'a', 'c']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'b', 'd', 'a', 'c', 'tail']);
+ v.expect(drawn(parent)).toEqual(expected(parent));
+ dispose();
+ },
+);
+
+v.test('insertChild(node, before) between rendered parents', () => {
+ let left!: ElementNode;
+ let right!: ElementNode;
+ let moved!: ElementNode;
+ let anchor!: ElementNode;
+ const dispose = render(() => (
+
+
+
+
+
+
+
+
+
+
+ ));
+ right.insertChild(moved, anchor);
+ v.expect(ids(right)).toEqual(['moved', 'anchor', 'y']);
+ v.expect(drawn(right)).toEqual(expected(right));
+ v.expect(drawn(left)).toEqual(expected(left));
+
+ // Same parent, before an earlier sibling, then back to the end.
+ const y = right.children[2] as ElementNode;
+ right.insertChild(y, moved);
+ v.expect(ids(right)).toEqual(['y', 'moved', 'anchor']);
+ v.expect(drawn(right)).toEqual(expected(right));
+ right.insertChild(y);
+ v.expect(ids(right)).toEqual(['moved', 'anchor', 'y']);
+ v.expect(drawn(right)).toEqual(expected(right));
+ dispose();
+});
+
+// Solid's swap of adjacent items asks for insertNode(parent, y, y): a node
+// placed before itself stays (DOM semantics), it is not appended.
+v.test(
+ 'an adjacent swap with a later sibling keeps the drawn order',
+ async () => {
+ const [items, setItems] = s.createSignal(['a', 'x', 'y', 'b']);
+ let parent!: ElementNode;
+ const dispose = render(() => (
+
+
+
+ {(id) => }
+
+
+
+ ));
+ await tick();
+ setItems(['a', 'y', 'x', 'b']);
+ await tick();
+ v.expect(ids(parent)).toEqual(['head', 'a', 'y', 'x', 'b', 'tail']);
+ v.expect(drawn(parent)).toEqual(expected(parent));
+ dispose();
+ },
+);
+
+v.test(
+ 'a parent rendered after it got rendered and new children draws them in order',
+ () => {
+ let host!: ElementNode;
+ let moved!: ElementNode;
+ const dispose = render(() => (
+
+
+
+ ));
+ const fresh = new ElementNode('view');
+ fresh.id = 'fresh';
+ const [n1, n2] = ['n1', 'n2'].map((id) => {
+ const n = new ElementNode('view');
+ n.id = id;
+ return n;
+ }) as [ElementNode, ElementNode];
+ fresh.insertChild(n1);
+ fresh.insertChild(moved);
+ fresh.insertChild(n2);
+ host.insertChild(fresh);
+ fresh.render(true);
+ v.expect(ids(fresh)).toEqual(['n1', 'moved', 'n2']);
+ v.expect(drawn(fresh)).toEqual(expected(fresh));
+ v.expect(drawn(host)).toEqual(['fresh']);
+ dispose();
+ },
+);
diff --git a/tests/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx
index 64e198b4..ff8cf139 100644
--- a/tests/webgl/flex-text.test.tsx
+++ b/tests/webgl/flex-text.test.tsx
@@ -3,8 +3,9 @@
*
* Runs in Vitest browser mode (headless Chromium through Playwright, WebGL
* on SwiftShader) against @solidtv/renderer with SDF text, not the DOM
- * renderer: SDF measurement differs from the DOM's, and text sizes arrive
- * through the renderer's `loaded` event, so these numbers only hold here.
+ * renderer: SDF measurement differs from the DOM's, and text sizes come from
+ * the renderer's `TextNode.measure()` (its `loaded` event while a font is
+ * missing), so these numbers only hold here.
*
* pnpm test:webgl
* npx vitest run --config=vitest.webgl.config.ts
@@ -17,23 +18,24 @@
* font size is 30 (Config.fontSettings). `settle()` waits until the
* renderer has no scene update pending for two frames in a row.
*
- * The numbers are the final positions and sizes, after fonts load, on
- * solid 1.6.4 with SDF text on renderer 1.9. They are not derived from a
- * formula, they were read from a run; the comments show how they add up.
- * Each one is compared with
- * `expect.closeTo(n, 3)`, |actual - expected| < 0.0005: flex.ts sums child
- * sizes in Float32Arrays, so positions carry float32 rounding (109.70999908
- * for 109.71) while text sizes are float64.
+ * The numbers are the final positions and sizes on solid 1.6.4 with the
+ * renderer v2 lockstep (arm B): "final positions after fonts load must match
+ * arm B". They are not derived from a formula, they were read from arm B;
+ * the comments show how they add up. Each one is compared with
+ * `expect.closeTo(n, 3)`, |actual - expected| < 0.0005: until 1.7 the flex
+ * engines summed child sizes in Float32Arrays, so arm B's positions carry
+ * float32 rounding (109.70999908 for 109.71); 1.7 sums in Float64Arrays.
*
- * Only final states are asserted. Intermediate ones (a container before its
- * texts have sizes, the number of frames, `loaded` events and flex
- * passes) are printed with console.info for information: a change to
- * Solid or the renderer may change them. Add `--reporter=verbose` if the reporter hides them.
+ * Final states are asserted, and from 1.7 (stream T, text measured before
+ * the frame) the walks per drawn frame and flex passes of a text change.
+ * Other intermediate ones (a container before its texts have sizes, the
+ * number of frames and `loaded` events) are printed with console.info for
+ * information. Add `--reporter=verbose` if the reporter hides them.
*/
import * as v from 'vitest';
import * as s from 'solid-js';
import { loadFonts, type ElementNode } from '@solidtv/solid';
-import { frameCount, latoFont, render, settle } from './setup.js';
+import { frameCount, latoFont, render, renderer, settle } from './setup.js';
/** x, y, width and height, as the app reads them from the ElementNode. */
function expectBox(
@@ -65,6 +67,27 @@ const info = (...args: unknown[]) =>
// Lato at the default size 30: a line is 43.2 high.
const LINE_30 = 43.2;
+/**
+ * Runs `change`, waits for the layout to settle, and returns the walks of
+ * every frame the renderer drew meanwhile (`updateIterations` after each
+ * `update()`): 1 unless a write landed between a frame's walks.
+ */
+async function walksPerFrame(change: () => void): Promise {
+ const walks: number[] = [];
+ const update = renderer.update;
+ renderer.update = function (this: typeof renderer) {
+ update.call(this);
+ walks.push(this.updateIterations);
+ };
+ try {
+ change();
+ await settle();
+ } finally {
+ delete (renderer as { update?: unknown }).update;
+ }
+ return walks;
+}
+
v.test('a row of text children with gap and padding', async () => {
let row!: ElementNode;
let home!: ElementNode;
@@ -339,6 +362,9 @@ v.test(
));
await settle();
info('3 texts, first render: flex passes on the row', flexPasses);
+ // The app's listener hears the first layout, once (1.7: the layout
+ // measure() makes before the frame; the walk reuses it).
+ v.expect(loaded).toBe(1);
expectBox(prev, 0, 0, 61.11, LINE_30);
expectBox(middle, 81.11, 0, 72.54, LINE_30); // 61.11 + 20
@@ -349,12 +375,20 @@ v.test(
loaded = 0;
flexPasses = 0;
const f0 = frameCount();
- setLabel(text);
- await settle();
+ const walks = await walksPerFrame(() => setLabel(text));
info(
`text change to "${text}": frames ${frameCount() - f0},` +
+ ` walks per drawn frame ${JSON.stringify(walks)},` +
` loaded events ${loaded}, flex passes on the row ${flexPasses}`,
);
+ // 1.7 (stream T): Solid measures the text before the frame, so the
+ // frame walks once (arm B: 2, the flex of `loaded` wrote between the
+ // walks), the row is laid out once, and the app's listener hears the
+ // one layout once.
+ v.expect(walks.length).toBeGreaterThan(0);
+ v.expect(walks.every((w) => w === 1)).toBe(true);
+ v.expect(flexPasses).toBe(1);
+ v.expect(loaded).toBe(1);
};
await measure('A much longer label');
@@ -619,7 +653,7 @@ v.test(
);
v.test(
- 'text in a row hidden with alpha 0 lays out when the row is shown',
+ 'text in a row hidden with alpha 0 is laid out while hidden (5.2), and the row shown in one walk',
async () => {
const [alpha, setAlpha] = s.createSignal(0);
let row!: ElementNode;
@@ -633,17 +667,20 @@ v.test(
));
await settle();
- info(
- 'under alpha 0: row',
- [row.width, row.height],
- 'texts',
- [one, two].map((t) => [t.x, t.width, t.height]),
- );
+ // 5.2 (1.7): text under a culled ancestor is measured at mount, so the
+ // row is laid out while hidden (arm B left it unlaid until shown).
+ expectBox(one, 0, 0, 56.34, LINE_30);
+ expectBox(two, 66.34, 0, 55.26, LINE_30);
+ expectBox(row, 0, 0, 121.6, LINE_30);
const f0 = frameCount();
- setAlpha(1);
- await settle();
- info(`shown: frames ${frameCount() - f0}`);
+ const walks = await walksPerFrame(() => setAlpha(1));
+ info(
+ `shown: frames ${frameCount() - f0},` +
+ ` walks per drawn frame ${JSON.stringify(walks)}`,
+ );
+ // Nothing is left to lay out when it is shown: one walk.
+ v.expect(walks.every((w) => w === 1)).toBe(true);
expectBox(one, 0, 0, 56.34, LINE_30);
expectBox(two, 66.34, 0, 55.26, LINE_30); // 56.34 + 10
@@ -652,3 +689,426 @@ v.test(
dispose();
},
);
+
+v.test(
+ 'texts changed in nested flex containers: one walk per drawn frame, each container laid out once',
+ async () => {
+ const [n, setN] = s.createSignal(0);
+ const DATA = [
+ { title: 'First title', year: '2001', rating: 'PG', cast: 'Ann, Bob' },
+ {
+ title: 'A second, longer title',
+ year: '1999',
+ rating: 'TV-MA',
+ cast: 'Cy',
+ },
+ ];
+ const item = () => DATA[n() % 2]!;
+ const passes: string[] = [];
+ let panel!: ElementNode;
+ let meta!: ElementNode;
+ let badge!: ElementNode;
+ let cast!: ElementNode;
+
+ const dispose = render(() => (
+ void passes.push('panel')}
+ >
+ {item().title}
+ void passes.push('meta')}
+ >
+ {item().year}
+ void passes.push('badge')}
+ >
+ {item().rating}
+
+
+ {item().cast}
+
+ ));
+ await settle();
+ const before = {
+ badge: badge.width,
+ meta: meta.width,
+ panel: panel.height,
+ cast: cast.y,
+ };
+
+ passes.length = 0;
+ const walks = await walksPerFrame(() => setN(1));
+ info(
+ `nested change: walks per drawn frame ${JSON.stringify(walks)},` +
+ ` flex passes ${JSON.stringify(passes)}`,
+ );
+ v.expect(walks.length).toBeGreaterThan(0);
+ v.expect(walks.every((w) => w === 1)).toBe(true);
+ // Deepest first, each once (the title row does not hold the panel's
+ // width: a column fills its parent).
+ v.expect(passes).toEqual(['badge', 'meta', 'panel']);
+ v.expect(badge.width).not.toBe(before.badge);
+ v.expect(meta.width).not.toBe(before.meta);
+
+ passes.length = 0;
+ await walksPerFrame(() => setN(2));
+ // Back to the first item: the same sizes as at mount.
+ v.expect(badge.width).toBeCloseTo(before.badge, 3);
+ v.expect(meta.width).toBeCloseTo(before.meta, 3);
+ v.expect(panel.height).toBeCloseTo(before.panel, 3);
+ v.expect(cast.y).toBeCloseTo(before.cast, 3);
+ v.expect(passes).toEqual(['badge', 'meta', 'panel']);
+
+ dispose();
+ },
+);
+
+v.test(
+ 'text in a flex row out of bounds is laid out while out of bounds (5.2)',
+ async () => {
+ let row!: ElementNode;
+ let one!: ElementNode;
+ let two!: ElementNode;
+
+ // A fixed size, so the row has an area entirely past the bounds margin.
+ const dispose = render(() => (
+
+ One
+ Two
+
+ ));
+ await settle();
+
+ expectBox(one, 0, 0, 56.34, LINE_30);
+ expectBox(two, 66.34, 0, 55.26, LINE_30);
+ v.expect([row.x, row.width]).toEqual([3000, 400]);
+
+ dispose();
+ },
+);
+
+v.test(
+ 'text under hidden and out-of-bounds flex rows, rendered before its font loads, is laid out when the font loads',
+ async () => {
+ let hidden!: ElementNode;
+ let away!: ElementNode;
+ const texts: ElementNode[] = [];
+
+ // A family nothing has loaded yet; no walk visits these texts.
+ const dispose = render(() => (
+ <>
+
+
+ One
+
+
+ Two
+
+
+
+
+ One
+
+
+ Two
+
+
+ >
+ ));
+ await settle();
+ info(
+ 'culled, before the font: rows',
+ [hidden.width, away.width],
+ 'texts',
+ texts.map((t) => [t.x, t.width]),
+ );
+
+ await loadFonts([latoFont('LatoCulled')]);
+ await settle();
+
+ // Still hidden and out of bounds, laid out as when shown.
+ expectBox(texts[0]!, 0, 0, 56.34, LINE_30);
+ expectBox(texts[1]!, 66.34, 0, 55.26, LINE_30);
+ expectBox(hidden, 0, 0, 121.6, LINE_30);
+ expectBox(texts[2]!, 0, 0, 56.34, LINE_30);
+ expectBox(texts[3]!, 66.34, 0, 55.26, LINE_30);
+ expectBox(away, 3000, 0, 121.6, LINE_30);
+
+ dispose();
+ },
+);
+
+v.test('flex writing a text child’s width settles', async () => {
+ let minRow!: ElementNode;
+ let minText!: ElementNode;
+ let minAfter!: ElementNode;
+ let shrinkRow!: ElementNode;
+ let shrinkText!: ElementNode;
+ let shrinkAfter!: ElementNode;
+ let shrinkPasses = 0;
+
+ const dispose = render(() => (
+ <>
+
+
+ Hi
+
+ After
+
+ void shrinkPasses++}
+ >
+
+ A text too long for its row
+
+
+
+ >
+ ));
+ // settle() throws if the layout does not settle in 300 frames.
+ await settle();
+ info(
+ 'flex-written text widths: min',
+ [minText.width, minText.height],
+ 'shrink',
+ [shrinkText.width, shrinkText.height, shrinkText.lng.w],
+ 'row',
+ [shrinkRow.width, shrinkRow.height],
+ 'passes',
+ shrinkPasses,
+ );
+
+ // minWidth: the flex write sets the text's width (its maxWidth).
+ expectBox(minText, 0, 0, 200, LINE_30);
+ expectBox(minAfter, 210, 0, 69.51, LINE_30); // 200 + 10
+ // flexShrink: the text takes what the view leaves (300 - 100), which wraps
+ // it onto two lines; the row then takes the two lines' height. Two passes:
+ // the one that shrank the text, and one after it was measured again.
+ expectBox(shrinkText, 0, 0, 200, 2 * LINE_30);
+ v.expect(shrinkText.lng.w).toBeCloseTo(191.01, 3); // the longer line
+ v.expect(shrinkAfter.x).toBeCloseTo(200, 3);
+ v.expect(shrinkRow.width).toBe(300);
+ v.expect(shrinkRow.height).toBeCloseTo(2 * LINE_30, 3);
+ v.expect(shrinkPasses).toBe(2);
+
+ dispose();
+});
+
+v.test(
+ 'a text layout Solid did not measure (a raw renderer write) warns in development',
+ async () => {
+ const warn = v.vi.spyOn(console, 'warn').mockImplementation(() => {});
+ let row!: ElementNode;
+ let t!: ElementNode;
+ const [label, setLabel] = s.createSignal('Short');
+ try {
+ const dispose = render(() => (
+
+ {label()}
+ After
+
+ ));
+ await settle();
+ // Writes through Solid are measured: no warning.
+ setLabel('A longer label');
+ await settle();
+ v.expect(warn).not.toHaveBeenCalled();
+
+ // A layout prop written on the renderer node bypasses Solid.
+ (t.lng as unknown as { text: string }).text = 'Bypassed Solid';
+ await settle();
+ if (import.meta.env.DEV) {
+ v.expect(warn).toHaveBeenCalledTimes(1);
+ v.expect(String(warn.mock.calls[0]![0])).toContain('measure');
+ } else {
+ v.expect(warn).not.toHaveBeenCalled();
+ }
+ void row;
+ dispose();
+ } finally {
+ warn.mockRestore();
+ }
+ },
+);
+
+v.test(
+ 'a fontSize transition on a text in a flex row moves its sibling every frame, and ends where the new size puts it',
+ async () => {
+ const [size, setSize] = s.createSignal(30);
+ let t!: ElementNode;
+ let after!: ElementNode;
+ let passes = 0;
+ const dispose = render(() => (
+ void passes++}>
+
+ After
+
+ After
+
+ ));
+ await settle();
+ expectBox(t, 0, 0, 69.51, LINE_30);
+ expectBox(after, 79.51, 0, 69.51, LINE_30); // 69.51 + 10
+
+ // Before each frame's walk: the text's last layout and the sibling's
+ // last flex position, which must not overlap it.
+ const overlaps: number[][] = [];
+ const sampled: number[] = [];
+ const sample = () => {
+ const w = t.lng.w as number;
+ sampled.push(w);
+ if (after.x < w + 10 - 0.001) {
+ overlaps.push([w, after.x]);
+ }
+ };
+ renderer.on('frameTick', sample);
+ passes = 0;
+ try {
+ setSize(60);
+ // settle() does not wait for an animation (it requests no frame).
+ await new Promise((r) => setTimeout(r, 900));
+ await settle();
+ } finally {
+ renderer.off('frameTick', sample);
+ }
+ info(
+ `fontSize transition: frames ${sampled.length}, flex passes ${passes},` +
+ ` widths ${JSON.stringify(sampled.map((w) => Math.round(w)))}`,
+ );
+
+ // As 1.6 (the `loaded` listener re-ran flex on each animated layout).
+ expectBox(t, 0, 0, 139.02, 86.4); // twice the size
+ expectBox(after, 149.02, 0, 69.51, LINE_30); // 139.02 + 10
+ v.expect(overlaps).toEqual([]);
+ // It animated: some frames saw an intermediate width.
+ v.expect(sampled.some((w) => w > 70 && w < 139)).toBe(true);
+
+ // The animation is over: a text change walks once again (Solid stopped
+ // listening for the animated layouts).
+ const walks = await walksPerFrame(() => (t.text = 'Afterwards'));
+ v.expect(walks.length).toBeGreaterThan(0);
+ v.expect(walks.every((w) => w === 1)).toBe(true);
+
+ dispose();
+ },
+);
+
+v.test(
+ 'text whose font is loaded with renderer.loadFont (not loadFonts) lays out when the font arrives',
+ async () => {
+ let row!: ElementNode;
+ let home!: ElementNode;
+ let movies!: ElementNode;
+
+ const dispose = render(() => (
+
+
+ Home
+
+
+ Movies
+
+
+ ));
+ await settle();
+
+ // The renderer's own loadFont: Solid hears of it only through the
+ // texts' `loaded` (the walk lays them out when the font arrives).
+ await renderer.loadFont('sdf', latoFont('LatoDirect'));
+ await settle();
+
+ expectBox(home, 10, 0, 79.71, LINE_30);
+ expectBox(movies, 109.71, 0, 95.67, LINE_30);
+ expectBox(row, 0, 0, 215.38, LINE_30); // 109.71 + 95.67 + 10
+
+ dispose();
+ },
+);
+
+/** A row of two 'After' texts, the first animated. */
+async function animatedRow() {
+ let t!: ElementNode;
+ let after!: ElementNode;
+ const dispose = render(() => (
+
+ After
+ After
+
+ ));
+ await settle();
+ expectBox(after, 79.51, 0, 69.51, LINE_30);
+ return { t, after, dispose };
+}
+
+/** Waits for a 150 ms animation to end, then for the layout to settle. */
+async function animationOver() {
+ // settle() does not wait for an animation (it requests no frame).
+ await new Promise((r) => setTimeout(r, 400));
+ await settle();
+}
+
+const ANIMATION = { duration: 150, easing: 'linear' };
+
+v.test(
+ 'el.animate() of a text layout prop, started again after it finished, moves the sibling again',
+ async () => {
+ const { t, after, dispose } = await animatedRow();
+ const a = t.animate({ fontSize: 60 }, ANIMATION);
+ a.start();
+ await animationOver();
+ expectBox(t, 0, 0, 139.02, 86.4);
+ expectBox(after, 149.02, 0, 69.51, LINE_30);
+
+ t.fontSize = 30;
+ await settle();
+ expectBox(after, 79.51, 0, 69.51, LINE_30);
+
+ a.start(); // 30 -> 60 again
+ await animationOver();
+ expectBox(t, 0, 0, 139.02, 86.4);
+ expectBox(after, 149.02, 0, 69.51, LINE_30);
+ dispose();
+ },
+);
+
+v.test(
+ 'el.animate() of a text layout prop, started after the text laid out again, moves the sibling',
+ async () => {
+ const { t, after, dispose } = await animatedRow();
+ const b = t.animate({ fontSize: 60 }, ANIMATION);
+ t.text = 'Afte';
+ await settle();
+ b.start();
+ await animationOver();
+ v.expect(t.width).toBeGreaterThan(100);
+ v.expect(after.x).toBeCloseTo(t.width + 10, 3);
+ dispose();
+ },
+);
diff --git a/tests/webgl/handleFields.test.tsx b/tests/webgl/handleFields.test.tsx
new file mode 100644
index 00000000..92fff226
--- /dev/null
+++ b/tests/webgl/handleFields.test.tsx
@@ -0,0 +1,247 @@
+/**
+ * B20: the renderer v2 handle has no fields of its own beyond `id`,
+ * `renderer`, `_uid` and its listener map; every prop is a prototype
+ * accessor over the node store. A name the handle does not know becomes a
+ * new own field (a new hidden class for that handle), and a write to one of
+ * its getter-only props throws. Solid must never do either.
+ *
+ * Runs on the real renderer (vitest.webgl.config.ts): the DOM renderer's
+ * nodes are plain objects that take any field.
+ */
+import * as v from 'vitest';
+import type { ElementNode } from '@solidtv/solid';
+import { render, renderer } from './setup.js';
+
+type Handle = Record;
+const handle = (el: ElementNode) => el.lng as unknown as Handle;
+
+v.test(
+ 'text-only props written to a rendered add no field to its handle',
+ () => {
+ let view!: ElementNode;
+ const dispose = render(() => );
+ v.expect(view.rendered).toBe(true);
+ const keys = Object.keys(view.lng);
+
+ view.fontSize = 20;
+ view.lineHeight = 30;
+ view.maxWidth = 50;
+ view.text = 'hello';
+ view.contain = 'width';
+ view.fontWeight = 'bold';
+
+ v.expect(Object.keys(view.lng)).toEqual(keys);
+ // The values stay on the ElementNode.
+ v.expect(view.fontSize).toBe(20);
+ v.expect(view.lineHeight).toBe(30);
+ v.expect(view.maxWidth).toBe(50);
+ v.expect(view.text).toBe('hello');
+ v.expect(view.contain).toBe('width');
+ v.expect(view.fontWeight).toBe('bold');
+ dispose();
+ },
+);
+
+v.test('text-only props written to a rendered reach its handle', () => {
+ let text!: ElementNode;
+ const dispose = render(() => a);
+ const keys = Object.keys(text.lng);
+
+ text.fontSize = 40;
+ text.maxWidth = 300;
+ text.contain = 'width';
+ text.text = 'b';
+
+ v.expect(Object.keys(text.lng)).toEqual(keys);
+ v.expect(handle(text).fontSize).toBe(40);
+ v.expect(handle(text).maxWidth).toBe(300);
+ v.expect(handle(text).contain).toBe('width');
+ v.expect(handle(text).text).toBe('b');
+ dispose();
+});
+
+v.test(
+ 'absX, absY and destroyed: writes do not throw, reads come from the handle',
+ () => {
+ let parent!: ElementNode;
+ let view!: ElementNode;
+ const dispose = render(() => (
+
+
+
+ ));
+ const keys = Object.keys(view.lng);
+
+ v.expect(() => {
+ view.absX = 1;
+ view.absY = 2;
+ view.destroyed = true;
+ }).not.toThrow();
+
+ v.expect(Object.keys(view.lng)).toEqual(keys);
+ v.expect(view.absX).toBe(handle(view).absX);
+ v.expect(view.absY).toBe(handle(view).absY);
+ v.expect(view.destroyed).toBe(false);
+ void parent;
+ dispose();
+ },
+);
+
+// Every prop Solid forwards to the renderer node, written alone on a
+// rendered node: the handle gets exactly the value (no field of its own) and
+// the ElementNode reads it back from there. Each value is distinct, so an
+// accessor wired to the wrong name fails.
+const NODE_PROPS: Array<[string, unknown]> = [
+ ['x', 11],
+ ['y', 12],
+ ['w', 13],
+ ['h', 14],
+ ['alpha', 0.5],
+ ['color', 0x01020304],
+ ['colorTop', 0x05060708],
+ ['colorBottom', 0x090a0b0c],
+ ['colorLeft', 0x0d0e0f10],
+ ['colorRight', 0x11121314],
+ ['colorTl', 0x15161718],
+ ['colorTr', 0x191a1b1c],
+ ['colorBl', 0x1d1e1f20],
+ ['colorBr', 0x21222324],
+ ['mount', 0.25],
+ ['mountX', 0.3],
+ ['mountY', 0.35],
+ ['pivot', 0.4],
+ ['pivotX', 0.45],
+ ['pivotY', 0.55],
+ ['rotation', 0.6],
+ ['scale', 1.5],
+ ['scaleX', 1.6],
+ ['scaleY', 1.7],
+ ['zIndex', 3],
+ ['autosize', true],
+ ['clipping', true],
+ ['componentName', 'Name'],
+ ['componentLocation', 'file.tsx:1'],
+ ['data', { a: 1 }],
+ ['ignoreParentAlpha', true],
+ ['imageType', 'png'],
+ ['placeholderColor', 0x25262728],
+ ['srcX', 1],
+ ['srcY', 2],
+ ['srcWidth', 3],
+ ['srcHeight', 4],
+ ['textureOptions', { preload: true }],
+];
+
+const TEXT_PROPS: Array<[string, unknown]> = [
+ ['fontSize', 40],
+ ['lineHeight', 50],
+ ['fontStyle', 'italic'],
+ ['letterSpacing', 2],
+ ['maxHeight', 200],
+ ['maxLines', 3],
+ ['maxWidth', 300],
+ ['offsetY', 4],
+ ['overflowSuffix', '..'],
+ ['text', 'b'],
+ ['textAlign', 'center'],
+ ['verticalAlign', 'middle'],
+ ['wordBreak', 'break-all'],
+ ['contain', 'width'],
+ ['forceLoad', true],
+];
+
+v.test('every forwarded prop reaches the handle under its own name', () => {
+ let view!: ElementNode;
+ let text!: ElementNode;
+ const dispose = render(() => (
+
+
+ a
+
+ ));
+ const viewKeys = Object.keys(view.lng);
+ const textKeys = Object.keys(text.lng);
+ const el = (n: ElementNode) => n as unknown as Handle;
+
+ for (const [name, value] of NODE_PROPS) {
+ el(view)[name] = value;
+ v.expect(handle(view)[name], name).toEqual(value);
+ v.expect(el(view)[name], name).toEqual(value);
+ }
+ for (const [name, value] of [...NODE_PROPS.slice(4), ...TEXT_PROPS]) {
+ el(text)[name] = value;
+ v.expect(handle(text)[name], name).toEqual(value);
+ v.expect(el(text)[name], name).toEqual(value);
+ }
+ const texture = renderer.createTexture('ColorTexture', {
+ color: 0xffffffff,
+ });
+ view.texture = texture;
+ v.expect(handle(view).texture).toBe(texture);
+ v.expect(view.texture).toBe(texture);
+
+ v.expect(Object.keys(view.lng)).toEqual(viewKeys);
+ v.expect(Object.keys(text.lng)).toEqual(textKeys);
+ dispose();
+});
+
+// The transition path. With `transition` on a rendered node, an animatable
+// setter hands the renderer's animateProp its own name and the value, and
+// does not store the value itself. animateProp is stubbed: this checks what
+// Solid passes, not the animation.
+const ANIMATABLE_NODE_PROPS = NODE_PROPS.slice(0, 25) as Array<
+ [string, number]
+>;
+const ANIMATABLE_TEXT_PROPS: Array<[string, number]> = [
+ ['fontSize', 40],
+ ['lineHeight', 50],
+];
+
+v.test(
+ 'with a transition, every animatable prop animates under its own name',
+ () => {
+ let view!: ElementNode;
+ let text!: ElementNode;
+ const dispose = render(() => (
+
+
+ a
+
+ ));
+ // Node.prototype (a TextNode inherits it).
+ const proto = Object.getPrototypeOf(view.lng) as {
+ animateProp: (name: string, value: number, settings: unknown) => unknown;
+ };
+ const animateProp = v.vi
+ .spyOn(proto, 'animateProp')
+ .mockImplementation(() => undefined);
+ try {
+ view.transition = true;
+ text.transition = true;
+ const el = (n: ElementNode) => n as unknown as Handle;
+ const check = (node: ElementNode, name: string, value: number) => {
+ const before = handle(node)[name];
+ v.expect(before, name).not.toBe(value);
+ const calls = animateProp.mock.calls.length;
+ el(node)[name] = value;
+ v.expect(animateProp.mock.calls.length, name).toBe(calls + 1);
+ v.expect(animateProp.mock.lastCall, name).toEqual([
+ name,
+ value,
+ v.expect.anything(),
+ ]);
+ v.expect(animateProp.mock.contexts.at(-1), name).toBe(node.lng);
+ v.expect(handle(node)[name], name).toBe(before);
+ };
+ for (const [name, value] of ANIMATABLE_NODE_PROPS) {
+ check(view, name, value);
+ }
+ for (const [name, value] of ANIMATABLE_TEXT_PROPS) {
+ check(text, name, value);
+ }
+ } finally {
+ animateProp.mockRestore();
+ dispose();
+ }
+ },
+);
diff --git a/vite-env.d.ts b/vite-env.d.ts
index bdb42113..8146931b 100644
--- a/vite-env.d.ts
+++ b/vite-env.d.ts
@@ -10,7 +10,6 @@ declare global {
interface ImportMetaEnv {
readonly __DEV__: boolean;
readonly DEV: boolean;
- readonly VITE_USE_NEW_FLEX?: string;
}
interface ImportMeta {