From 0bab2c24bc15375d803b5220be27d669a19ba720 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:16:46 -0400 Subject: [PATCH 01/34] perf(flex): one allocation-free flex engine with the B5-B10 fixes Keep src/core/flexLayout.ts (what the demo app runs) and delete flex.ts and the VITE_USE_NEW_FLEX switch (decision 5.3). The engine now: - allocates nothing per pass: per-child values live in module-level typed arrays grown on demand (Float64Array: positions no longer carry float32 rounding), children are reached through a reused index array, sorted by flexOrder (stable insertion sort) only when a child has one, and the cross alignment closure is a plain function; - writes x, y, width and height only when the value changes, so a relayout that moves nothing writes nothing; - no longer has flex.ts's production console.warn. Bug fixes (design 5.8), each pinned in contract-flex.test.tsx: - B5: a child with flexItem={false} is skipped before the text check, so an unsized text badge no longer blocks its container. - B6: justifyContent center centres inside the padded box. - B7: cross-axis center/flexEnd align inside the padded box (and, with wrap, inside the line) instead of offsetting the full size by paddingTop. - B8: flexGrow starts from the item's own size on every pass (the grown size and the size before it are recorded on the item); an item no longer grown goes back to its own size. - B9: wrapped items are placed on their line when the container has no height. - B10: wrap-reverse wraps, with the first line at the end. contract-flex.test.tsx runs its table once, on the one engine; where flex.ts gave a different result the case keeps it in a comment (what changes for apps on the default build). The flex specs run flexLayout.ts. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 23e9f9446164ab6ebd7106961a1de1f623f6ea02) --- CLAUDE.md | 2 +- src/core/elementNode.ts | 14 +- src/core/flex.ts | 332 ----------------- src/core/flexLayout.ts | 633 +++++++++++++++++++++------------ tests/contract-flex.test.tsx | 499 ++++++++++++-------------- tests/contract-text.test.tsx | 31 +- tests/flex.performance.spec.ts | 2 +- tests/flex.spec.ts | 7 +- tests/flex_min_size.spec.ts | 2 +- tests/webgl/flex-text.test.tsx | 14 +- vite-env.d.ts | 1 - 11 files changed, 662 insertions(+), 875 deletions(-) delete mode 100644 src/core/flex.ts 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/src/core/elementNode.ts b/src/core/elementNode.ts index 7201f2b3..95e26b83 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 from './flexLayout.js'; import { log, isArray, @@ -429,6 +424,10 @@ 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; _hasRenderedChildren?: boolean; _effects?: Record; /** The props of a shader convertToShader made, kept to swap its type. */ @@ -871,7 +870,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 +918,8 @@ export class ElementNode { this._calcWidth = undefined; this._calcHeight = undefined; this._containsFlexGrow = undefined; + this._flexBase = undefined; + this._flexGrown = undefined; this._hasRenderedChildren = undefined; this._effects = undefined; this._shaderProps = undefined; 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..02fbf9a4 100644 --- a/src/core/flexLayout.ts +++ b/src/core/flexLayout.ts @@ -1,6 +1,63 @@ import { type ElementNode } from './elementNode.js'; import { isTextNode, isElementText } from './utils.js'; +// 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 its value changes, so a relayout that moves +// nothing writes nothing (and starts no transition). + +/** 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); +} + function getArrayValue( val: number | number[] | undefined, index: number, @@ -21,13 +78,64 @@ function getArrayValue( return result ?? defaultValue; } +function setSize(c: ElementNode, isWidth: boolean, v: number): void { + if (isWidth) { + c.width = v; + } else { + c.height = v; + } +} + +function setPos(c: ElementNode, isX: boolean, v: number): void { + if (isX) { + if (c.x !== v) c.x = v; + } else if (c.y !== 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]!); + } +} + +/** + * 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 { + 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,198 +150,221 @@ 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 children = node.children; - const numChildren = children.length; - - if (numChildren === 0) { - return false; - } + ensureCapacity(numChildren); - // 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; + } + + // 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. + const read = main || 0; + let own = read; + let flag = 0; + const grown = c._flexGrown; + if (grown !== undefined) { + if (grow > 0 && read === grown) { + own = c._flexBase!; + flag = FROM_RECORD; + sizeWork = true; + } else { + c._flexGrown = undefined; + } } - if ( - c[crossMinDimension] && - (c[crossDimension] || 0) < c[crossMinDimension] - ) { - c[crossDimension] = c[crossMinDimension]!; + 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); } - processableChildrenIndices.push(i); + 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 flexWrap = node.flexWrap; + const isWrapReverse = flexWrap === 'wrap-reverse'; + // B10: wrap-reverse wraps too. + const wrapping = flexWrap === 'wrap' || isWrapReverse; const gap = node.gap || 0; const justify = node.justifyContent || 'flexStart'; - const align = node.alignItems || (node.flexWrap ? 'flexStart' : undefined); + const align = node.alignItems || (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; } } + sizeWork = true; node._containsFlexGrow = node._containsFlexGrow ? null : 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; } } } @@ -243,6 +374,32 @@ export default function (node: ElementNode): boolean { } } + 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; + if ((flag & GROWN) !== 0) { + const size = mainSize[k]!; + if (size !== mainRead[k]) setSize(c, isRow, size); + c._flexBase = ownSize[k]; + c._flexGrown = size; + } else if ((flag & SHRUNK) !== 0) { + const size = mainSize[k]!; + if (size !== mainRead[k]) setSize(c, isRow, size); + 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 !== mainRead[k]) setSize(c, isRow, size); + c._flexGrown = undefined; + } + } + } + let totalItemSize = 0; if ( justify === 'center' || @@ -250,159 +407,183 @@ 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) { containerUpdated = true; node.height = 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; + // B9: items are placed on their line even when the container has no + // cross size. B7: center and flexEnd align inside the line. B10: + // wrap-reverse mirrors the lines, so the first one is at the end. + 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]!, + lineSize, + ); + } - 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.preFlexheight = height; + node.height = finalCrossSize; + containerUpdated = true; + } + } else { + const width = node.width; + if (width !== finalCrossSize) { + node.preFlexwidth = width; + node.width = 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, 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; + if (calculatedSize !== (nodeMain || 0)) { + if (isRow) { + node.preFlexwidth = containerSize; + } else { + node.preFlexheight = containerSize; + } + setSize(node, isRow, calculatedSize); 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/tests/contract-flex.test.tsx b/tests/contract-flex.test.tsx index db19cd7c..5cfac0f3 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,55 @@ 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 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. 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 }, ]), - newDiffers: - 'wrap-reverse: flexLayout.ts only wraps for "wrap" (flexLayout.ts:297), so it lays out one line and auto-sizes the width', }, // --- flexOrder ------------------------------------------------------------ @@ -876,6 +863,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 +947,101 @@ 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, engine-specific details', () => { - const both = [ - ['flex.ts', flexOld], - ['flexLayout.ts', flexNew], - ] as const; +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 }); + }); - 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 }); - }, - ); + // 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); + }); - 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); - }, - ); + // 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); + }); - // 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('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.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'); - }, - ); + 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'); + }); - 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 +1058,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 +1074,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 +1092,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 +1103,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 +1185,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(); }); diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index e2c2dc0e..920999e5 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -750,7 +750,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,13 +769,14 @@ 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(); 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'); @@ -785,26 +786,4 @@ describe('contract: text in a flex container (DOM renderer)', () => { 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 () => { - mockTextMeasure(); - const [label, setLabel] = s.createSignal('Flex Grow'); - let grow!: 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); - 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/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index 64e198b4..45f30d59 100644 --- a/tests/webgl/flex-text.test.tsx +++ b/tests/webgl/flex-text.test.tsx @@ -17,13 +17,13 @@ * 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 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 { From 5687feb4d21ea35fdb2c6f04dce3c19cfbf2d086 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:17:35 -0400 Subject: [PATCH 02/34] fix(text): contain subtracts the node's margins; maxLines 1 reads a lineHeight multiplier In render()'s text path (design 5.8): - B11: `contain` without a size subtracts marginRight/marginBottom read from the ElementNode. They were read from the renderer props bag, where margins are never stored, so the subtraction was always 0. - B12: `maxLines={1}` resolves a lineHeight at or below 3 (a multiplier, as the renderer reads it) as lineHeight * fontSize. maxHeight was the bare multiplier (1.2 px), so such a text was 1.2 px high in flex. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 59ab929569bf69cfb2af95872652df5fbb720b8f) --- src/core/elementNode.ts | 13 +++++++--- tests/contract-text.test.tsx | 47 ++++++++++++++++++++++++++++++------ 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 95e26b83..5efd3143 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -1774,17 +1774,22 @@ export class ElementNode { textProps.maxLines = textProps.maxLines ?? 99; } + // B11: margins live on the ElementNode, not in the renderer props. if (!textProps.maxWidth) { textProps.maxWidth = - parentWidth - textProps.x! - (textProps.marginRight || 0); + parentWidth - textProps.x! - (node.marginRight || 0); } if (textProps.contain === 'both' && !textProps.maxHeight) { textProps.maxHeight = - parentHeight - textProps.y! - (textProps.marginBottom || 0); - } else if (textProps.maxLines === 1) { + parentHeight - textProps.y! - (node.marginBottom || 0); + } 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; } diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index 920999e5..2d5e7516 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -132,7 +132,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 +144,30 @@ 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: 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 +236,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(() => ( From 10ccd237aba7308db017bce0996716b6499239c3 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:30:01 -0400 Subject: [PATCH 03/34] perf(layout): depth-ordered layout queue; post-mutation pass as a microtask The layout queue (design 3.4.4, 3.5): - Containers are bucketed by depth (computed once when queued) and laid out deepest first, so within one post-mutation pass each container runs at most once unless a child's size changed after its run. No copy of the queue per run: the buckets keep their capacity, and a node carries a `_layoutQueued` flag that updateLayout() clears. - queueLayout(node) replaces addToLayoutQueue; a container queues its parent only when its own size changed (and the parent lays out). - A flexGrow container re-runs its flex children once per pass and runs again only if one of them resized (was: every other pass, and always twice). - The delete-flush keeps its array's capacity instead of resetting it. Scheduling: - schedulePostMutation queues the microtask only. It no longer also registers reprocessUpdates, whose in-frame run was a no-op that still requested a frame. - schedulePostMutationInFrame() also registers reprocessUpdates, for handlers the renderer calls between its walks. _layoutOnLoad's `loaded` handler uses it: it queues the parent instead of laying it out synchronously (several loads in a frame cost one pass), and does nothing when the node's size is unchanged. tests/layoutQueue.test.tsx pins one pass per affected container in a 3-level nested flex press, deepest first, the unchanged-size skip and the scheduling. contract-text.test.tsx: the autosize pin now waits for the pass, and text-change tests wait a macrotask (the re-measure's microtask and the pass's). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 31e6c7881277dfb494489b247330f0fbb00044b9) --- src/core/elementNode.ts | 205 +++++++++++++++++++------- tests/contract-text.test.tsx | 22 ++- tests/layoutQueue.test.tsx | 270 +++++++++++++++++++++++++++++++++++ 3 files changed, 446 insertions(+), 51 deletions(-) create mode 100644 tests/layoutQueue.test.tsx diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 5efd3143..976b3682 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -60,7 +60,8 @@ 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 // 3. focus — resolve forwardFocus on deferred elements, then apply @@ -68,15 +69,30 @@ import { // 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 export function enqueueDelete(node: ElementNode, n: number): void { if (node._queueDelete === undefined) { node._queueDelete = n; - if (elementDeleteQueue.push(node) === 1) { + elementDeleteQueue[elementDeleteCount++] = node; + if (elementDeleteCount === 1) { schedulePostMutation(); } } else { @@ -87,35 +103,44 @@ 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) { + postMutationInFrame = false; + + // Phase 1: delete-flush (the count is read every time: a destroy can + // queue more) + if (elementDeleteCount > 0) { + for (let i = 0; i < elementDeleteCount; i++) { + const el = elementDeleteQueue[i]!; + elementDeleteQueue[i] = undefined; if ((el._queueDelete ?? 0) < 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(); - } - } + runLayoutQueue(); // Phase 3: focus. setFocus() may have evaluated forwardFocus pre-render // (when no children existed yet); deferredFocusElement re-runs setFocus @@ -131,8 +156,34 @@ function runPostMutation() { } } -function addToLayoutQueue(node: ElementNode) { - layoutQueue.add(node); +function enqueueLayout(node: ElementNode): void { + if (node._layoutQueued === true) return; + node._layoutQueued = true; + let depth = 0; + for (let p = node.parent; p !== undefined && p !== null; p = p.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(); } @@ -153,6 +204,30 @@ function removeItem(arr: T[], item: T): number { return index; } +function runLayoutQueue(): void { + // Start from the deepest bucket there is, so entries a run that threw left + // behind are not stranded. + layoutMaxDepth = layoutBuckets.length - 1; + 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; + } +} + // 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; @@ -428,6 +503,8 @@ export interface ElementNode extends RendererNode, FocusNode { _flexBase?: number; /** @internal flexGrow record (B8): the size the last growth wrote. */ _flexGrown?: number; + /** @internal in the layout queue (queueLayout) */ + _layoutQueued: boolean; _hasRenderedChildren?: boolean; _effects?: Record; /** The props of a shader convertToShader made, kept to swap its type. */ @@ -937,6 +1014,7 @@ export class ElementNode { this._onLayout = undefined; this._requiresLayout = false; this._focusGen = 0; + this._layoutQueued = false; } get effects(): StyleEffects | undefined { @@ -1129,7 +1207,7 @@ export class ElementNode { } if (this.requiresLayout()) { - addToLayoutQueue(this); + queueLayout(this); } } } @@ -1305,9 +1383,22 @@ export class ElementNode { } _layoutOnLoad() { + // The size the parent's last layout saw: a load that leaves it unchanged + // needs no layout. Until Solid measures text itself, this is how a text + // size reaches flex: queue the parent and run the pass in the frame. + 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) { + enqueueLayout(parent); + schedulePostMutationInFrame(); + } }); } @@ -1539,32 +1630,50 @@ export class ElementNode { } updateLayout() { - if (this.hasChildren) { - if (isDev) log('Layout: ', this); - - if (this.display === 'flex' && this.flexGrow && this.width === 0) { - return; - } + 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; + } - const flexChanged = this.display === 'flex' && calculateFlex(this); - layoutQueue.delete(this); - const onLayoutChanged = - isFunction(this.onLayout) && this.onLayout.call(this, this); + const flexChanged = isFlex && calculateFlex(this); + const onLayout = this._onLayout; + const onLayoutChanged = + onLayout !== undefined && + isFunction(onLayout) && + onLayout.call(this, this); - if ((flexChanged || onLayoutChanged) && this.parent) { - addToLayoutQueue(this.parent); - } + // A container whose size changed queues its parent (one with nothing to + // lay out would do nothing). + const parent = this.parent; + if ((flexChanged || onLayoutChanged) && parent && parent._requiresLayout) { + queueLayout(parent); + } - 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 (this._containsFlexGrow === true) { + // This pass grew or shrank its children: lay out the flex ones again, + // directly, so they do not queue this container back through their + // own size. Run this container again only if one of them resized. + 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) { + queueLayout(this); + } else { + this._containsFlexGrow = null; } } } @@ -1688,7 +1797,7 @@ export class ElementNode { } if (parent.requiresLayout()) { - layoutQueue.add(parent); + queueLayout(parent); } if (this.rendered) { diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index 2d5e7516..c788725e 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -48,6 +48,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'); @@ -508,7 +514,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; @@ -532,6 +538,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); @@ -607,8 +619,8 @@ 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(); }); @@ -656,6 +668,7 @@ describe('contract: text in a flex container (DOM renderer)', () => { mockTextMeasure(); fontsReady(); await waitForUpdate(); + await nextTask(); expect(raw(t).loaded).toBe(true); expect(t.width).toBe(50); expect(last.x).toBe(60); @@ -691,6 +704,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); @@ -807,6 +821,7 @@ describe('contract: text in a flex container (DOM renderer)', () => { // 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(400); @@ -814,6 +829,7 @@ describe('contract: text in a flex container (DOM renderer)', () => { // 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(); diff --git a/tests/layoutQueue.test.tsx b/tests/layoutQueue.test.tsx new file mode 100644 index 00000000..b85e6685 --- /dev/null +++ b/tests/layoutQueue.test.tsx @@ -0,0 +1,270 @@ +/** + * 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 (the text fallback until + * Solid measures text itself) also asks the renderer to run it inside the + * frame, between its walks. + * + * 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 () => { + mockTextMeasure(); + let count = 0; + let t!: lng.ElementNode; + let last!: lng.ElementNode; + const dispose = renderer.render(() => ( + void count++}> + Hello + + + )); + await settle(); + expect(last.x).toBe(60); + count = 0; + + emitter(t).emit('loaded', { + type: 'text', + 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 () => { + mockTextMeasure(); + let count = 0; + let t!: lng.ElementNode; + let last!: lng.ElementNode; + const dispose = renderer.render(() => ( + void count++}> + Hello + + + )); + await settle(); + count = 0; + + t.lng.w = 80; + emitter(t).emit('loaded', { + type: 'text', + dimensions: { w: 80, h: 20 }, + }); + expect(count).toBe(0); // not synchronously + await settle(); + expect(count).toBe(1); + expect(last.x).toBe(90); + 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(() => ( + + Hello + + + )); + await settle(); + expect(last.x).toBe(60); + expect(reprocess).not.toHaveBeenCalled(); + + t.lng.w = 80; + emitter(t).emit('loaded', { + type: 'text', + 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(90); + dispose(); + } finally { + if (saved === undefined) { + delete st.reprocessUpdates; + } else { + st.reprocessUpdates = saved; + } + } + }); +}); From c5ee883beceb9bec8e666b4e94b2384487669c18 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:54:22 -0400 Subject: [PATCH 04/34] fix(flex): keep the pre-1.7 wrap alignment apart from B7, B9 and B10 The first flex commit aligned wrapped items against their line, which moved items in a wrapping container with a height and alignItems center or flexEnd even without padding (5px in the demo app's Flex page): a change no approved fix covers. Wrapped items align as before 1.7 again, from their line's start against the container's cross size, with only the approved changes: that size less the cross padding (B7), the line size when the container has no cross size (B9, previously unplaced), and mirrored lines for wrap-reverse (B10). A table case pins the unchanged result against the original engine. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 01d5fa1065773cba53ece68ef8c8606f63ed8bef) --- src/core/flexLayout.ts | 11 +++++++---- tests/contract-flex.test.tsx | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/core/flexLayout.ts b/src/core/flexLayout.ts index 02fbf9a4..ecb9c540 100644 --- a/src/core/flexLayout.ts +++ b/src/core/flexLayout.ts @@ -456,9 +456,12 @@ export default function (node: ElementNode): boolean { lineStart[k] = line; } - // B9: items are placed on their line even when the container has no - // cross size. B7: center and flexEnd align inside the line. B10: - // wrap-reverse mirrors the lines, so the first one is at the end. + // 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( @@ -469,7 +472,7 @@ export default function (node: ElementNode): boolean { isWrapReverse ? line + paddingCrossStart - lineStart[k]! : lineStart[k]!, - lineSize, + alignSize, ); } diff --git a/tests/contract-flex.test.tsx b/tests/contract-flex.test.tsx index 5cfac0f3..f4d2a466 100644 --- a/tests/contract-flex.test.tsx +++ b/tests/contract-flex.test.tsx @@ -778,6 +778,23 @@ const cases: FlexCase[] = [ // 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: wrapped items move to the next line', container: { width: 250, gap: 10, flexWrap: 'wrap' }, From 09cc0ab1cd2efca2c5076c3d46c464b80c4d4fc7 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:25:07 -0400 Subject: [PATCH 05/34] fix(flex): transition-aware writes, a reentrancy guard, one write loop Review fixes for the flex engine: - Compare-before-write read the current value, which with a transition is the animated one, not the target. A node moved A -> T by one layout and back to A by the next, before the animation advanced, read A and was not written, so it ended at T. With a transition on the prop the engine now also keeps the last value it wrote (`_flexX`, `_flexY`, `_flexW`, `_flexH`) and skips only when both the read and that value match; without one, the read alone decides (the renderer ignores an equal write anyway). This covers the container's own size writes too. - B8 with a width transition: the read is the animated width, so the flexGrow record is kept as it is instead of being taken for a size the app wrote. - A pass started while another runs (an app callback that a write fires, e.g. onAnimation calling updateLayout) gets its own scratch arrays, so the outer pass's are intact when it resumes. Only the nested case allocates. - Positions are computed into a scratch array and written by one loop (main then cross per child), so the writers stay small enough to be inlined and do not box their doubles; the child's alignment is resolved once in the collecting loop. - getArrayValue is exported for the text `contain` margins. contract-flex.test.tsx: the A -> T -> A case and the B8 mid-animation case (DOM renderer, `animate` spied), a nested pass, and the 5.3 record for flexShrink, flexBasis and a shrink-only container's flexBoundary, which flex.ts did not handle. A comment on the B9 pin notes that wrapped center/flexEnd alignment is not stable across passes (as before 1.7). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 57bb69aa834308794c554238ab681c8df5547a28) --- src/core/elementNode.ts | 11 +- src/core/flexLayout.ts | 491 ++++++++++++++++++++++------------- tests/contract-flex.test.tsx | 204 +++++++++------ 3 files changed, 448 insertions(+), 258 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 976b3682..86d22654 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -503,6 +503,11 @@ export interface ElementNode extends RendererNode, FocusNode { _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; _hasRenderedChildren?: boolean; @@ -578,12 +583,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; /** @@ -997,6 +1000,10 @@ export class ElementNode { 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; diff --git a/src/core/flexLayout.ts b/src/core/flexLayout.ts index ecb9c540..5085e15b 100644 --- a/src/core/flexLayout.ts +++ b/src/core/flexLayout.ts @@ -1,18 +1,28 @@ import { type ElementNode } from './elementNode.js'; +import { Config } from './config.js'; import { isTextNode, isElementText } from './utils.js'; // 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 its value changes, so a relayout that moves -// nothing writes nothing (and starts no transition). +// 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; +/** A child's resolved `alignSelf || alignItems`. */ +const ALIGN_NONE = 0; +const ALIGN_START = 1; +const ALIGN_CENTER = 2; +const ALIGN_END = 3; + let capacity = 0; let childIndex = new Int32Array(0); // slot -> index in node.children let order = new Int32Array(0); // layout position -> slot @@ -30,6 +40,8 @@ let growFactor = new Float64Array(0); let shrinkFactor = new Float64Array(0); let orderKey = new Float64Array(0); let lineStart = new Float64Array(0); +let mainPos = new Float64Array(0); +let alignCode = new Uint8Array(0); function ensureCapacity(n: number): void { if (n <= capacity) { @@ -56,9 +68,12 @@ function ensureCapacity(n: number): void { shrinkFactor = new Float64Array(c); orderKey = new Float64Array(c); lineStart = new Float64Array(c); + mainPos = new Float64Array(c); + alignCode = new Uint8Array(c); } -function getArrayValue( +/** 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, @@ -78,6 +93,18 @@ 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; @@ -86,45 +113,164 @@ function setSize(c: ElementNode, isWidth: boolean, v: number): void { } } +// Hands a value to the transition paths below without passing the double as +// an argument: a second boxed use of it in the small, inlined writers would +// make TurboFan box it on every call, transition or not. +const handoff = new Float64Array(2); + +/** + * Writes a size the engine computed, unless `current` (read from the node) + * is already `v`. Returns whether it wrote. A node with a transition takes + * writeSizeAnimated. + */ +function writeSize( + c: ElementNode, + isWidth: boolean, + current: number, + v: number, +): boolean { + if (c.transition) { + handoff[0] = current; + handoff[1] = v; + return writeSizeAnimated(c, isWidth); + } + if (current === v) { + return false; + } + setSize(c, isWidth, v); + return true; +} + +/** + * With a transition, the current value is the animated one, not the target: + * write unless it is the new value and that is also what this engine last + * wrote. Reads current and new value from `handoff`. + */ +function writeSizeAnimated(c: ElementNode, isWidth: boolean): boolean { + const current = handoff[0]!; + const v = handoff[1]!; + if (isWidth) { + if (animates(c, 'w', 'width')) { + if (current === v && c._flexW === v) return false; + c._flexW = v; + } else if (current === v) { + return false; + } + } else if (animates(c, 'h', 'height')) { + if (current === v && c._flexH === v) return false; + c._flexH = v; + } else if (current === v) { + return false; + } + setSize(c, isWidth, v); + return true; +} + function setPos(c: ElementNode, isX: boolean, v: number): void { - if (isX) { + if (c.transition) { + handoff[1] = v; + setPosAnimated(c, isX); + } else if (isX) { if (c.x !== v) c.x = v; } else if (c.y !== 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]!); +/** setPos for a node with a transition (see writeSizeAnimated). */ +function setPosAnimated(c: ElementNode, isX: boolean): void { + const v = handoff[1]!; + if (isX) { + if (animates(c, 'x', 'x')) { + if (c.x === v && c._flexX === v) return; + c._flexX = v; + } else if (c.x === v) { + return; + } + c.x = v; + } else { + if (animates(c, 'y', 'y')) { + if (c.y === v && c._flexY === v) return; + c._flexY = v; + } else if (c.y === v) { + return; + } + c.y = v; } } +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; + const sMainPos = mainPos; + const sAlignCode = alignCode; + 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; + mainPos = sMainPos; + alignCode = sAlignCode; + } +} + +function layout(node: ElementNode): boolean { const children = node.children; const numChildren = children.length; @@ -150,6 +296,12 @@ export default function (node: ElementNode): boolean { const paddingCrossEnd = isRow ? paddingBottom : paddingRight; const nodePaddingTotal = paddingStart + paddingEnd; + 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); + ensureCapacity(numChildren); let n = 0; @@ -202,13 +354,20 @@ export default function (node: ElementNode): boolean { // 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. + // (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) { + 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; @@ -256,6 +415,15 @@ export default function (node: ElementNode): boolean { growFactor[k] = grow; shrinkFactor[k] = flexShrink || 0; orderKey[k] = flexOrder || 0; + const alignSelf = c.alignSelf || align; + alignCode[k] = + alignSelf === 'flexStart' + ? ALIGN_START + : alignSelf === 'center' + ? ALIGN_CENTER + : alignSelf === 'flexEnd' + ? ALIGN_END + : ALIGN_NONE; } if (n === 0) { @@ -300,13 +468,8 @@ export default function (node: ElementNode): boolean { (isRow ? node.minHeight : node.minWidth) || 0, 0, ); - const flexWrap = node.flexWrap; - const isWrapReverse = flexWrap === 'wrap-reverse'; - // B10: wrap-reverse wraps too. - const wrapping = flexWrap === 'wrap' || isWrapReverse; const gap = node.gap || 0; const justify = node.justifyContent || 'flexStart'; - const align = node.alignItems || (flexWrap ? 'flexStart' : undefined); let containerUpdated = false; let sumOfFlexBaseSizesWithMargins = 0; @@ -384,17 +547,15 @@ export default function (node: ElementNode): boolean { const c = children[childIndex[k]!] as ElementNode; if ((flag & GROWN) !== 0) { const size = mainSize[k]!; - if (size !== mainRead[k]) setSize(c, isRow, size); + writeSize(c, isRow, mainRead[k]!, size); c._flexBase = ownSize[k]; c._flexGrown = size; } else if ((flag & SHRUNK) !== 0) { - const size = mainSize[k]!; - if (size !== mainRead[k]) setSize(c, isRow, size); + writeSize(c, isRow, mainRead[k]!, mainSize[k]!); 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 !== mainRead[k]) setSize(c, isRow, size); + writeSize(c, isRow, mainRead[k]!, ownSize[k]!); c._flexGrown = undefined; } } @@ -422,171 +583,149 @@ export default function (node: ElementNode): boolean { if (size > maxHeight) maxHeight = size; } const newHeight = maxHeight || nodeHeight; - if (newHeight !== nodeHeight) { + if (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; + // Main-axis positions go to mainPos; one loop below writes them with the + // cross-axis ones. + const wrapped = justify === 'flexStart' && wrapping; + let placed = true; let currentPos = paddingStart; - if (justify === 'flexStart') { - if (wrapping) { - const lineSize = crossSize[order[0]!]!; - const crossGap = isRow ? (node.columnGap ?? gap) : (node.rowGap ?? gap); - let line = paddingCrossStart; - - for (let p = 0; p < n; p++) { - const k = order[p]!; - if ( - currentPos + totalMain[k]! > containerSize && - currentPos > paddingStart - ) { - currentPos = paddingStart; - line += lineSize + crossGap; - } - setPos( - children[childIndex[k]!] as ElementNode, - isRow, - currentPos + marginStart[k]!, - ); - currentPos += totalMain[k]! + gap; - lineStart[k] = line; - } - - // 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, - ); - } - - const finalCrossSize = line + lineSize + paddingCrossEnd; - if (isRow) { - const height = node.height; - if (height !== finalCrossSize) { - node.preFlexheight = height; - node.height = finalCrossSize; - containerUpdated = true; - } - } else { - const width = node.width; - if (width !== finalCrossSize) { - node.preFlexwidth = width; - node.width = finalCrossSize; - containerUpdated = true; - } - } - } else { - 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); - } + let line = paddingCrossStart; // wrap: the start of the last line + let lineSize = 0; + if (wrapped) { + lineSize = crossSize[order[0]!]!; + const crossGap = isRow ? (node.columnGap ?? gap) : (node.rowGap ?? gap); + for (let p = 0; p < n; p++) { + const k = order[p]!; + if ( + currentPos + totalMain[k]! > containerSize && + currentPos > paddingStart + ) { + currentPos = paddingStart; + line += lineSize + crossGap; } + mainPos[k] = currentPos + marginStart[k]!; + currentPos += totalMain[k]! + gap; + lineStart[k] = line; } - - // Update container size - if (node.flexBoundary !== 'fixed' && !wrapping) { - let calculatedSize = currentPos - gap + paddingEnd; - const minSize = (isRow ? node.minWidth : node.minHeight) || 0; - if (calculatedSize < minSize) { - calculatedSize = minSize; - } - if (calculatedSize !== (nodeMain || 0)) { - if (isRow) { - node.preFlexwidth = containerSize; - } else { - node.preFlexheight = containerSize; - } - setSize(node, isRow, calculatedSize); - return true; - } + } else if (justify === 'flexStart') { + for (let p = 0; p < n; p++) { + const k = order[p]!; + mainPos[k] = currentPos + marginStart[k]!; + currentPos += totalMain[k]! + gap; } } else if (justify === 'flexEnd') { currentPos = containerSize - paddingEnd; 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]!); + mainPos[k] = 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 - - paddingStart - - paddingEnd - - (totalItemSize + gap * (n - 1))) / - 2 + - paddingStart; + } else if ( + justify === 'center' || + justify === 'spaceBetween' || + justify === 'spaceAround' || + justify === 'spaceEvenly' + ) { + let space = gap; + if (justify === 'center') { + // B6: centred inside the padded box. + currentPos = + (containerSize - + paddingStart - + paddingEnd - + (totalItemSize + gap * (n - 1))) / + 2 + + paddingStart; + } else if (justify === 'spaceBetween') { + space = + n > 1 + ? (containerSize - totalItemSize - nodePaddingTotal) / (n - 1) + : 0; + } else if (justify === 'spaceAround') { + space = (containerSize - totalItemSize - nodePaddingTotal) / n; + currentPos = paddingStart + space / 2; + } else { + space = (containerSize - totalItemSize - nodePaddingTotal) / (n + 1); + currentPos = space + paddingStart; + } 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); - } + mainPos[k] = currentPos + marginStart[k]!; + currentPos += totalMain[k]! + space; } - } else if (justify === 'spaceBetween') { - const spaceBetween = - n > 1 ? (containerSize - totalItemSize - nodePaddingTotal) / (n - 1) : 0; - currentPos = paddingStart; + } else { + placed = false; // an unknown justifyContent places nothing + } + + if (placed) { + // Cross axis. Wrapped: from each item's line start (B9: also when the + // container has no cross size, then against the line; B10: lines + // mirrored for wrap-reverse), center and flexEnd against the cross + // size less its padding (B7), as before 1.7. Otherwise from the cross + // padding, only when the container had a cross size. + const alignAll = wrapped || crossAlign; + const alignSize = wrapped && !crossAlign ? lineSize : crossBox; 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); + setPos(c, isRow, mainPos[k]!); + const a = alignCode[k]!; + if (alignAll && a !== ALIGN_NONE) { + const start = wrapped + ? isWrapReverse + ? line + paddingCrossStart - lineStart[k]! + : lineStart[k]! + : paddingCrossStart; + setPos( + c, + !isRow, + a === ALIGN_START + ? start + marginCrossStart[k]! + : a === ALIGN_CENTER + ? start + (alignSize - crossSize[k]!) / 2 + marginCrossStart[k]! + : start + alignSize - crossSize[k]! - marginCrossEnd[k]!, + ); } } - } else if (justify === 'spaceAround') { - const spaceAround = (containerSize - totalItemSize - nodePaddingTotal) / n; - currentPos = paddingStart + spaceAround / 2; - 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); + } + + if (wrapped) { + const finalCrossSize = line + lineSize + paddingCrossEnd; + if (isRow) { + const height = node.height; + if (writeSize(node, false, height, finalCrossSize)) { + node.preFlexheight = height; + containerUpdated = true; + } + } else { + const width = node.width; + if (writeSize(node, true, width, finalCrossSize)) { + node.preFlexwidth = width; + containerUpdated = true; } } - } else if (justify === 'spaceEvenly') { - const spaceEvenly = - (containerSize - totalItemSize - nodePaddingTotal) / (n + 1); - currentPos = spaceEvenly + paddingStart; - 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); + } else if (justify === 'flexStart' && node.flexBoundary !== 'fixed') { + // Update container size + let calculatedSize = currentPos - gap + paddingEnd; + const minSize = (isRow ? node.minWidth : node.minHeight) || 0; + if (calculatedSize < minSize) { + calculatedSize = minSize; + } + if (writeSize(node, isRow, nodeMain || 0, calculatedSize)) { + if (isRow) { + node.preFlexwidth = containerSize; + } else { + node.preFlexheight = containerSize; } + return true; } } diff --git a/tests/contract-flex.test.tsx b/tests/contract-flex.test.tsx index f4d2a466..9e36263c 100644 --- a/tests/contract-flex.test.tsx +++ b/tests/contract-flex.test.tsx @@ -800,7 +800,10 @@ const cases: FlexCase[] = [ 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. + // 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: 0, w: 100, h: 50 }, { x: 110, y: 0, w: 100, h: 50 }, @@ -838,6 +841,30 @@ const cases: FlexCase[] = [ ]), }, + // --- 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 }, + ]), + // flex.ts (default build until 1.7) ignored flexBasis: x 0 and 50, w 110. + }, + // --- flexOrder ------------------------------------------------------------ { name: 'flexOrder sorts items; a missing flexOrder counts as 0', @@ -1042,6 +1069,51 @@ describe('contract: flex props, details', () => { 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); + }, + }); + 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, + ]); + }); + // 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', () => { @@ -1348,100 +1420,72 @@ describe('contract: flex through the renderer', () => { 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 }> = - []; - let row!: lng.ElementNode; - let second!: lng.ElementNode; - const dispose = renderer.render(() => ( - - - - - )); - await waitForUpdate(); - expect(calls).toHaveLength(1); - expect(calls[0]!.self).toBe(row); - expect(calls[0]!.args).toEqual([row]); - expect(calls[0]!.secondX).toBe(60); - dispose(); - }); - - it('onLayout: fires again when a child is added or removed, and on updateLayout() (synchronously)', async () => { - const [show, setShow] = s.createSignal(true); - let count = 0; + 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 last!: lng.ElementNode; + let moving!: lng.ElementNode; const dispose = renderer.render(() => ( - void count++}> - - - - + + + )); await waitForUpdate(); - expect(count).toBe(1); - expect(last.x).toBe(50); + expect(moving.x).toBe(50); + setTransition({ x: { duration: 1000 } }); + const animate = vi.spyOn(moving, 'animate'); - setShow(false); - await waitForUpdate(); - expect(count).toBe(2); - expect(last.x).toBe(0); - expect(row.width).toBe(60); - - row.updateLayout(); - expect(count).toBe(3); - dispose(); - }); + 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 }, + ]); - it('onLayout: fires on a non-flex view with children; never on a view without children', async () => { - let withKids = 0; - let withoutKids = 0; - const dispose = renderer.render(() => ( - - void withKids++}> - - - void withoutKids++} /> - - )); - await waitForUpdate(); - expect(withKids).toBe(1); - expect(withoutKids).toBe(0); + row.updateLayout(); // nothing moved since: no write, no restart + expect(animate).toHaveBeenCalledTimes(2); dispose(); }); - it('onLayout: a truthy return value queues the parent layout; a falsy one does not', async () => { - let parentCount = 0; - let returnValue = false; - let child!: lng.ElementNode; + 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(() => ( - void parentCount++}> - returnValue}> - - + + + )); await waitForUpdate(); - const afterRender = parentCount; - expect(afterRender).toBeGreaterThanOrEqual(1); - - child.updateLayout(); - await waitForUpdate(); - expect(parentCount).toBe(afterRender); + expect(grow.width).toBe(230); + setTransition({ width: { duration: 1000 } }); + const animate = vi.spyOn(grow, 'animate'); - returnValue = true; - child.updateLayout(); - await waitForUpdate(); - expect(parentCount).toBe(afterRender + 1); + 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(); }); From f8cd3b4d7cd186a7e45fa0584a6f69baf254d1c4 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:25:32 -0400 Subject: [PATCH 06/34] fix(layout): onLayout after a flexGrow container's children; a robust delete flush Review fixes for the layout queue and B11: - A flexGrow container lays out its grown flex children again, then (if one resized) itself once more, all in the same updateLayout, and calls onLayout once, after that: the app sees the final layout, as the second of the two calls before 1.7 did. The first call, made before the children were laid out again, is gone. - Delete flush: an entry is cleared (and its _queueDelete reset) before destroy(), and cleared entries are skipped, so an onDestroy that throws no longer makes every later post-mutation run throw before layout and focus. enqueueDelete always asks for the run. - B11 reads the margin array too (marginRight || margin[1], as flex does). - Doc comments: flexShrink/flexBasis are no longer "NEW flex layout" only. Tests: the container's single onLayout after its children (spaceBetween and content-fitting children), the margin array for `contain`, a deeper container queued while a shallower one runs (one post-mutation run, another sweep), `loaded` on a text removed from its container, and a throwing onDestroy. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 85131514ae8547984dd1f5978953f18d451a79cf) --- src/core/elementNode.ts | 67 ++++++++-------- tests/contract-flex.test.tsx | 47 ++++++++++++ tests/contract-text.test.tsx | 15 ++++ tests/layoutQueue.test.tsx | 144 +++++++++++++++++++++++++++++++++++ 4 files changed, 243 insertions(+), 30 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 86d22654..1ce37090 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -16,7 +16,7 @@ import { type DollarString, } from './intrinsicTypes.js'; import States, { type NodeStates } from './states.js'; -import calculateFlex from './flexLayout.js'; +import calculateFlex, { getArrayValue } from './flexLayout.js'; import { log, isArray, @@ -92,9 +92,7 @@ export function enqueueDelete(node: ElementNode, n: number): void { if (node._queueDelete === undefined) { node._queueDelete = n; elementDeleteQueue[elementDeleteCount++] = node; - if (elementDeleteCount === 1) { - schedulePostMutation(); - } + schedulePostMutation(); } else { node._queueDelete += n; } @@ -126,15 +124,18 @@ function runPostMutation() { postMutationInFrame = false; // Phase 1: delete-flush (the count is read every time: a destroy can - // queue more) + // 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]!; + const el = elementDeleteQueue[i]; elementDeleteQueue[i] = undefined; - if ((el._queueDelete ?? 0) < 0) { + if (el === undefined) continue; + const queued = el._queueDelete ?? 0; + el._queueDelete = undefined; + if (queued < 0) { el.destroy(); } - el._queueDelete = undefined; } elementDeleteCount = 0; } @@ -1648,24 +1649,12 @@ export class ElementNode { return; } - const flexChanged = isFlex && calculateFlex(this); - 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). - const parent = this.parent; - if ((flexChanged || onLayoutChanged) && parent && parent._requiresLayout) { - queueLayout(parent); - } + let flexChanged = isFlex && calculateFlex(this); - if (this._containsFlexGrow === true) { + if (isFlex && this._containsFlexGrow === true) { // This pass grew or shrank its children: lay out the flex ones again, // directly, so they do not queue this container back through their - // own size. Run this container again only if one of them resized. + // 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]!; @@ -1677,11 +1666,24 @@ export class ElementNode { } } } - if (childResized) { - queueLayout(this); - } else { - this._containsFlexGrow = null; + 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). + const parent = this.parent; + if ((flexChanged || onLayoutChanged) && parent && parent._requiresLayout) { + queueLayout(parent); } } @@ -1890,15 +1892,20 @@ export class ElementNode { textProps.maxLines = textProps.maxLines ?? 99; } - // B11: margins live on the ElementNode, not in the renderer props. + // 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! - (node.marginRight || 0); + parentWidth - + textProps.x! - + (node.marginRight || getArrayValue(node.margin, 1)); } if (textProps.contain === 'both' && !textProps.maxHeight) { textProps.maxHeight = - parentHeight - textProps.y! - (node.marginBottom || 0); + 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; diff --git a/tests/contract-flex.test.tsx b/tests/contract-flex.test.tsx index 9e36263c..e3028eac 100644 --- a/tests/contract-flex.test.tsx +++ b/tests/contract-flex.test.tsx @@ -1420,6 +1420,53 @@ describe('contract: flex through the renderer', () => { 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('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< diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index c788725e..9df1fc60 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -155,6 +155,21 @@ describe('contract: text props reach the renderer node (el.lng)', () => { dispose(); }); + // 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; diff --git a/tests/layoutQueue.test.tsx b/tests/layoutQueue.test.tsx index b85e6685..8a877186 100644 --- a/tests/layoutQueue.test.tsx +++ b/tests/layoutQueue.test.tsx @@ -227,6 +227,150 @@ describe('layout queue', () => { }); }); +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 a text removed from its container does not throw, and the container stays laid out', async () => { + mockTextMeasure(); + const [show, setShow] = s.createSignal(true); + let t!: lng.ElementNode; + let last!: lng.ElementNode; + const dispose = renderer.render(() => ( + + + Hello + + + + )); + 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: 'text', + 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(); From 186e59e90492d3385ab5c2470afa23eb76e003d7 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:36:17 -0400 Subject: [PATCH 07/34] perf(flex): keep the transition-aware writers inline 57bb69a sent a node with any transition through out-of-line writers that took their value from a typed array. Tiles with a scale transition (the bench's virtual-grid) went through them for every position, and they allocated about 5.3 KB per press there. setPos and writeSize now decide in place: the transition check reads `c.transition` first, and the double is only boxed on the write path. Same semantics; the tests are unchanged. Bench alloc mode, arm C on renderer faf4b9f, bytes per op charged to the flex function: virtual-grid 5,344 -> below the top 30 sites, virtual-row 1,797 -> 1,492, text-details-panel 1,774 -> 1,761. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 89a54f0e89be38789473b60eb1f254becfbfa945) --- src/core/flexLayout.ts | 80 +++++++++++------------------------------- 1 file changed, 20 insertions(+), 60 deletions(-) diff --git a/src/core/flexLayout.ts b/src/core/flexLayout.ts index 5085e15b..7d205805 100644 --- a/src/core/flexLayout.ts +++ b/src/core/flexLayout.ts @@ -113,15 +113,11 @@ function setSize(c: ElementNode, isWidth: boolean, v: number): void { } } -// Hands a value to the transition paths below without passing the double as -// an argument: a second boxed use of it in the small, inlined writers would -// make TurboFan box it on every call, transition or not. -const handoff = new Float64Array(2); - /** * Writes a size the engine computed, unless `current` (read from the node) - * is already `v`. Returns whether it wrote. A node with a transition takes - * writeSizeAnimated. + * 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. `v` is only boxed on the write path. */ function writeSize( c: ElementNode, @@ -129,72 +125,36 @@ function writeSize( current: number, v: number, ): boolean { - if (c.transition) { - handoff[0] = current; - handoff[1] = v; - return writeSizeAnimated(c, isWidth); - } - if (current === v) { + 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; } - setSize(c, isWidth, v); - return true; -} - -/** - * With a transition, the current value is the animated one, not the target: - * write unless it is the new value and that is also what this engine last - * wrote. Reads current and new value from `handoff`. - */ -function writeSizeAnimated(c: ElementNode, isWidth: boolean): boolean { - const current = handoff[0]!; - const v = handoff[1]!; - if (isWidth) { - if (animates(c, 'w', 'width')) { - if (current === v && c._flexW === v) return false; + if (animated) { + if (isWidth) { c._flexW = v; - } else if (current === v) { - return false; + } else { + c._flexH = v; } - } else if (animates(c, 'h', 'height')) { - if (current === v && c._flexH === v) return false; - c._flexH = v; - } else if (current === v) { - return false; } 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 (c.transition) { - handoff[1] = v; - setPosAnimated(c, isX); - } else if (isX) { - if (c.x !== v) c.x = v; - } else if (c.y !== v) { - c.y = v; - } -} - -/** setPos for a node with a transition (see writeSizeAnimated). */ -function setPosAnimated(c: ElementNode, isX: boolean): void { - const v = handoff[1]!; if (isX) { - if (animates(c, 'x', 'x')) { - if (c.x === v && c._flexX === v) return; - c._flexX = v; - } else if (c.x === v) { - return; - } + 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 { - if (animates(c, 'y', 'y')) { - if (c.y === v && c._flexY === v) return; - c._flexY = v; - } else if (c.y === v) { - return; - } + 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; } } From eb568ecfb3575eb6de8db7e482d43dbc3321bd07 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:51:25 -0400 Subject: [PATCH 08/34] fix(flex): a steady relayout of a grown auto-sizing child writes nothing A grown child that is itself a flex container sizing to its content was shrunk to its content and grown back on every relayout of its parent (widths 40, 300, 40, 300 over two relayouts, plus two extra passes each): every pass that grew set `_containsFlexGrow`, so updateLayout laid the child out again. The flag is now set only when the pass changed a child's size; a relayout that changes none writes nothing and runs no extra pass. The flexGrow record is written only when it changes. The size writers are called only when `current !== v` or the node has a transition, so the common no-write case passes no doubles to a call. contract-flex.test.tsx: restores the four Phase 1 onLayout contract tests that 8513151 dropped by mistake (verbatim from 01d5fa1), and pins two consecutive relayouts of the grown, content-sized child (no width write, no pass of the child). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 08d7647c851605c062c434d7db321253750b11ae) --- src/core/elementNode.ts | 2 +- src/core/flexLayout.ts | 67 +++++++++++++---- tests/contract-flex.test.tsx | 142 +++++++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 15 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 1ce37090..6d18f787 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -1652,7 +1652,7 @@ export class ElementNode { let flexChanged = isFlex && calculateFlex(this); if (isFlex && this._containsFlexGrow === true) { - // This pass grew or shrank its children: lay out the flex ones again, + // 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; diff --git a/src/core/flexLayout.ts b/src/core/flexLayout.ts index 7d205805..db30cdef 100644 --- a/src/core/flexLayout.ts +++ b/src/core/flexLayout.ts @@ -117,7 +117,8 @@ function setSize(c: ElementNode, isWidth: boolean, v: number): void { * 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. `v` is only boxed on the write path. + * 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, @@ -458,7 +459,6 @@ function layout(node: ElementNode): boolean { } } sizeWork = true; - node._containsFlexGrow = node._containsFlexGrow ? null : true; } else if (availableSpace < 0 && totalFlexShrink > 0) { // Flex Shrink Phase let totalScaledShrinkFactor = 0; @@ -491,12 +491,14 @@ function layout(node: ElementNode): boolean { } } } - 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]!; @@ -505,21 +507,45 @@ function layout(node: ElementNode): boolean { continue; } const c = children[childIndex[k]!] as ElementNode; + const read = mainRead[k]!; if ((flag & GROWN) !== 0) { const size = mainSize[k]!; - writeSize(c, isRow, mainRead[k]!, size); - c._flexBase = ownSize[k]; - c._flexGrown = size; + 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) { - writeSize(c, isRow, mainRead[k]!, mainSize[k]!); + 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. - writeSize(c, isRow, mainRead[k]!, ownSize[k]!); + 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 ( @@ -543,7 +569,10 @@ function layout(node: ElementNode): boolean { if (size > maxHeight) maxHeight = size; } const newHeight = maxHeight || nodeHeight; - if (writeSize(node, false, nodeHeight, newHeight)) { + if ( + (newHeight !== nodeHeight || node.transition) && + writeSize(node, false, nodeHeight, newHeight) + ) { containerUpdated = true; containerCrossSize = newHeight; } @@ -661,13 +690,19 @@ function layout(node: ElementNode): boolean { const finalCrossSize = line + lineSize + paddingCrossEnd; if (isRow) { const height = node.height; - if (writeSize(node, false, height, finalCrossSize)) { + if ( + (height !== finalCrossSize || node.transition) && + writeSize(node, false, height, finalCrossSize) + ) { node.preFlexheight = height; containerUpdated = true; } } else { const width = node.width; - if (writeSize(node, true, width, finalCrossSize)) { + if ( + (width !== finalCrossSize || node.transition) && + writeSize(node, true, width, finalCrossSize) + ) { node.preFlexwidth = width; containerUpdated = true; } @@ -679,7 +714,11 @@ function layout(node: ElementNode): boolean { if (calculatedSize < minSize) { calculatedSize = minSize; } - if (writeSize(node, isRow, nodeMain || 0, calculatedSize)) { + const current = nodeMain || 0; + if ( + (calculatedSize !== current || node.transition) && + writeSize(node, isRow, current, calculatedSize) + ) { if (isRow) { node.preFlexwidth = containerSize; } else { diff --git a/tests/contract-flex.test.tsx b/tests/contract-flex.test.tsx index e3028eac..6e9fd2e5 100644 --- a/tests/contract-flex.test.tsx +++ b/tests/contract-flex.test.tsx @@ -1467,6 +1467,51 @@ describe('contract: flex through the renderer', () => { 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< @@ -1536,6 +1581,103 @@ describe('contract: flex through the renderer', () => { 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 }> = + []; + let row!: lng.ElementNode; + let second!: lng.ElementNode; + const dispose = renderer.render(() => ( + + + + + )); + await waitForUpdate(); + expect(calls).toHaveLength(1); + expect(calls[0]!.self).toBe(row); + expect(calls[0]!.args).toEqual([row]); + expect(calls[0]!.secondX).toBe(60); + dispose(); + }); + + it('onLayout: fires again when a child is added or removed, and on updateLayout() (synchronously)', async () => { + const [show, setShow] = s.createSignal(true); + let count = 0; + let row!: lng.ElementNode; + let last!: lng.ElementNode; + const dispose = renderer.render(() => ( + void count++}> + + + + + + )); + await waitForUpdate(); + expect(count).toBe(1); + expect(last.x).toBe(50); + + setShow(false); + await waitForUpdate(); + expect(count).toBe(2); + expect(last.x).toBe(0); + expect(row.width).toBe(60); + + row.updateLayout(); + expect(count).toBe(3); + dispose(); + }); + + it('onLayout: fires on a non-flex view with children; never on a view without children', async () => { + let withKids = 0; + let withoutKids = 0; + const dispose = renderer.render(() => ( + + void withKids++}> + + + void withoutKids++} /> + + )); + await waitForUpdate(); + expect(withKids).toBe(1); + expect(withoutKids).toBe(0); + dispose(); + }); + + it('onLayout: a truthy return value queues the parent layout; a falsy one does not', async () => { + let parentCount = 0; + let returnValue = false; + let child!: lng.ElementNode; + const dispose = renderer.render(() => ( + void parentCount++}> + returnValue}> + + + + )); + await waitForUpdate(); + const afterRender = parentCount; + expect(afterRender).toBeGreaterThanOrEqual(1); + + child.updateLayout(); + await waitForUpdate(); + expect(parentCount).toBe(afterRender); + + returnValue = true; + child.updateLayout(); + await waitForUpdate(); + expect(parentCount).toBe(afterRender + 1); + dispose(); + }); + it('relayout: a reactive width change on a flex child does NOT reflow the parent; updateLayout() does', async () => { const [w, setW] = s.createSignal(50); let row!: lng.ElementNode; From 2f46fd9032c4b2ce7a669d58c86a0f30319adb20 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 21:00:56 -0400 Subject: [PATCH 09/34] perf(flex): write positions in the per-justify loops again 57bb69a moved every position write into one loop over a scratch array (and resolved alignment into codes). In the browser that charged more boxing to the pass in text-details-panel (1,490 -> about 1,770 B per op) than the earlier shape, so the per-justify loops and alignCross of 01d5fa1 are back, with the transition-aware setPos. The container size writes keep their inline `current !== v || transition` test. Bench alloc mode, arm C, renderer 6392ce4, bytes per op charged to the flex pass (layout + alignCross): text-details-panel 1,496 (L2 1,490), virtual-row 1,842 (L2 1,896), virtual-grid below the top 30 sites. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a69c3b655b11802a9eaf8b8227aad26d7b16061a) --- src/core/flexLayout.ts | 312 ++++++++++++++++++++++------------------- 1 file changed, 167 insertions(+), 145 deletions(-) diff --git a/src/core/flexLayout.ts b/src/core/flexLayout.ts index db30cdef..8fe5bdc4 100644 --- a/src/core/flexLayout.ts +++ b/src/core/flexLayout.ts @@ -17,12 +17,6 @@ const FROM_RECORD = 1; // the main size came from the flexGrow record (B8) const GROWN = 2; const SHRUNK = 4; -/** A child's resolved `alignSelf || alignItems`. */ -const ALIGN_NONE = 0; -const ALIGN_START = 1; -const ALIGN_CENTER = 2; -const ALIGN_END = 3; - let capacity = 0; let childIndex = new Int32Array(0); // slot -> index in node.children let order = new Int32Array(0); // layout position -> slot @@ -40,8 +34,6 @@ let growFactor = new Float64Array(0); let shrinkFactor = new Float64Array(0); let orderKey = new Float64Array(0); let lineStart = new Float64Array(0); -let mainPos = new Float64Array(0); -let alignCode = new Uint8Array(0); function ensureCapacity(n: number): void { if (n <= capacity) { @@ -68,8 +60,6 @@ function ensureCapacity(n: number): void { shrinkFactor = new Float64Array(c); orderKey = new Float64Array(c); lineStart = new Float64Array(c); - mainPos = new Float64Array(c); - alignCode = new Uint8Array(c); } /** A `padding`/`margin` side from a number or a 2-4 value array. */ @@ -160,6 +150,32 @@ function setPos(c: ElementNode, isX: boolean, v: number): void { } } +/** + * 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; /** @@ -201,8 +217,6 @@ function nestedLayout(node: ElementNode): boolean { const sShrinkFactor = shrinkFactor; const sOrderKey = orderKey; const sLineStart = lineStart; - const sMainPos = mainPos; - const sAlignCode = alignCode; capacity = 0; passDepth++; try { @@ -226,8 +240,6 @@ function nestedLayout(node: ElementNode): boolean { shrinkFactor = sShrinkFactor; orderKey = sOrderKey; lineStart = sLineStart; - mainPos = sMainPos; - alignCode = sAlignCode; } } @@ -376,15 +388,6 @@ function layout(node: ElementNode): boolean { growFactor[k] = grow; shrinkFactor[k] = flexShrink || 0; orderKey[k] = flexOrder || 0; - const alignSelf = c.alignSelf || align; - alignCode[k] = - alignSelf === 'flexStart' - ? ALIGN_START - : alignSelf === 'center' - ? ALIGN_CENTER - : alignSelf === 'flexEnd' - ? ALIGN_END - : ALIGN_NONE; } if (n === 0) { @@ -581,150 +584,169 @@ function layout(node: ElementNode): boolean { // B7: center and flexEnd align inside the padded box, not the full size. const crossBox = containerCrossSize - paddingCrossStart - paddingCrossEnd; - // Main-axis positions go to mainPos; one loop below writes them with the - // cross-axis ones. - const wrapped = justify === 'flexStart' && wrapping; - let placed = true; let currentPos = paddingStart; - let line = paddingCrossStart; // wrap: the start of the last line - let lineSize = 0; - if (wrapped) { - lineSize = crossSize[order[0]!]!; - const crossGap = isRow ? (node.columnGap ?? gap) : (node.rowGap ?? gap); - for (let p = 0; p < n; p++) { - const k = order[p]!; + if (justify === 'flexStart') { + if (wrapping) { + const lineSize = crossSize[order[0]!]!; + const crossGap = isRow ? (node.columnGap ?? gap) : (node.rowGap ?? gap); + let line = paddingCrossStart; + + for (let p = 0; p < n; p++) { + const k = order[p]!; + if ( + currentPos + totalMain[k]! > containerSize && + currentPos > paddingStart + ) { + currentPos = paddingStart; + line += lineSize + crossGap; + } + setPos( + children[childIndex[k]!] as ElementNode, + isRow, + currentPos + marginStart[k]!, + ); + currentPos += totalMain[k]! + gap; + lineStart[k] = line; + } + + // 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, + ); + } + + 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 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' && !wrapping) { + let calculatedSize = currentPos - gap + paddingEnd; + const minSize = (isRow ? node.minWidth : node.minHeight) || 0; + if (calculatedSize < minSize) { + calculatedSize = minSize; + } + const current = nodeMain || 0; if ( - currentPos + totalMain[k]! > containerSize && - currentPos > paddingStart + (calculatedSize !== current || node.transition) && + writeSize(node, isRow, current, calculatedSize) ) { - currentPos = paddingStart; - line += lineSize + crossGap; + if (isRow) { + node.preFlexwidth = containerSize; + } else { + node.preFlexheight = containerSize; + } + return true; } - mainPos[k] = currentPos + marginStart[k]!; - currentPos += totalMain[k]! + gap; - lineStart[k] = line; - } - } else if (justify === 'flexStart') { - for (let p = 0; p < n; p++) { - const k = order[p]!; - mainPos[k] = currentPos + marginStart[k]!; - currentPos += totalMain[k]! + gap; } } else if (justify === 'flexEnd') { currentPos = containerSize - paddingEnd; for (let p = n - 1; p >= 0; p--) { const k = order[p]!; - mainPos[k] = currentPos - mainSize[k]! - marginEnd[k]!; + 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' || - justify === 'spaceBetween' || - justify === 'spaceAround' || - justify === 'spaceEvenly' - ) { - let space = gap; - if (justify === 'center') { - // B6: centred inside the padded box. - currentPos = - (containerSize - - paddingStart - - paddingEnd - - (totalItemSize + gap * (n - 1))) / - 2 + - paddingStart; - } else if (justify === 'spaceBetween') { - space = - n > 1 - ? (containerSize - totalItemSize - nodePaddingTotal) / (n - 1) - : 0; - } else if (justify === 'spaceAround') { - space = (containerSize - totalItemSize - nodePaddingTotal) / n; - currentPos = paddingStart + space / 2; - } else { - space = (containerSize - totalItemSize - nodePaddingTotal) / (n + 1); - currentPos = space + paddingStart; - } + } else if (justify === 'center') { + // B6: centred inside the padded box. + currentPos = + (containerSize - + paddingStart - + paddingEnd - + (totalItemSize + gap * (n - 1))) / + 2 + + paddingStart; for (let p = 0; p < n; p++) { const k = order[p]!; - mainPos[k] = currentPos + marginStart[k]!; - currentPos += totalMain[k]! + space; + 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 { - placed = false; // an unknown justifyContent places nothing - } - - if (placed) { - // Cross axis. Wrapped: from each item's line start (B9: also when the - // container has no cross size, then against the line; B10: lines - // mirrored for wrap-reverse), center and flexEnd against the cross - // size less its padding (B7), as before 1.7. Otherwise from the cross - // padding, only when the container had a cross size. - const alignAll = wrapped || crossAlign; - const alignSize = wrapped && !crossAlign ? lineSize : crossBox; + } else if (justify === 'spaceBetween') { + const spaceBetween = + n > 1 ? (containerSize - totalItemSize - nodePaddingTotal) / (n - 1) : 0; + currentPos = paddingStart; for (let p = 0; p < n; p++) { const k = order[p]!; const c = children[childIndex[k]!] as ElementNode; - setPos(c, isRow, mainPos[k]!); - const a = alignCode[k]!; - if (alignAll && a !== ALIGN_NONE) { - const start = wrapped - ? isWrapReverse - ? line + paddingCrossStart - lineStart[k]! - : lineStart[k]! - : paddingCrossStart; - setPos( - c, - !isRow, - a === ALIGN_START - ? start + marginCrossStart[k]! - : a === ALIGN_CENTER - ? start + (alignSize - crossSize[k]!) / 2 + marginCrossStart[k]! - : start + alignSize - crossSize[k]! - marginCrossEnd[k]!, - ); + setPos(c, isRow, currentPos + marginStart[k]!); + currentPos += totalMain[k]! + spaceBetween; + if (crossAlign) { + alignCross(c, k, isRow, align, paddingCrossStart, crossBox); } } - } - - if (wrapped) { - 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 if (justify === 'spaceAround') { + const spaceAround = (containerSize - totalItemSize - nodePaddingTotal) / n; + currentPos = paddingStart + spaceAround / 2; + 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 === 'flexStart' && node.flexBoundary !== 'fixed') { - // Update container size - let calculatedSize = currentPos - gap + paddingEnd; - const minSize = (isRow ? node.minWidth : node.minHeight) || 0; - if (calculatedSize < minSize) { - calculatedSize = minSize; - } - const current = nodeMain || 0; - if ( - (calculatedSize !== current || node.transition) && - writeSize(node, isRow, current, calculatedSize) - ) { - if (isRow) { - node.preFlexwidth = containerSize; - } else { - node.preFlexheight = containerSize; + } else if (justify === 'spaceEvenly') { + const spaceEvenly = + (containerSize - totalItemSize - nodePaddingTotal) / (n + 1); + currentPos = spaceEvenly + paddingStart; + 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); } - return true; } } From aecd3cc123491f152f0b8a358cef269455642364 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:00:38 -0400 Subject: [PATCH 10/34] fix(nodes): never write unknown names to a renderer v2 handle (B20) Text-only props (fontSize, lineHeight, maxWidth, text, contain, ...) and fontFamily (through fontWeight) written to an element that is not a became own fields of its renderer v2 handle. They now stay on the ElementNode (`_textProps`, read back through the same accessors); a still forwards them to its renderer node. absX, absY and destroyed leave the forwarded setter list: they are getter-only on v2, where a write threw; the ElementNode ignores the write and keeps the getters. The new WebGL test also writes every forwarded prop on a rendered node and checks that the handle gets it under its own name. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 7d4065852b21fa77e9820f329f3ee006c4853af5) --- src/core/elementNode.ts | 134 +++++++++++++++++----- tests/webgl/handleFields.test.tsx | 180 ++++++++++++++++++++++++++++++ 2 files changed, 289 insertions(+), 25 deletions(-) create mode 100644 tests/webgl/handleFields.test.tsx diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 6d18f787..d2be7d55 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -388,6 +388,9 @@ function getPropertyAlias(name: string) { return name; } +// Forwarded to the renderer node (lng[key] = v). Only the renderer's props: +// on a @solidtv/renderer 2.0 node any other name becomes a field of its +// own. fontStretch, the DOM renderer's alone, has an accessor below. const LightningRendererNumberProps = [ 'alpha', 'color', @@ -400,8 +403,6 @@ const LightningRendererNumberProps = [ 'colorBl', 'colorBr', 'h', - 'fontSize', - 'lineHeight', 'mount', 'mountX', 'mountY', @@ -422,49 +423,46 @@ const LightningRendererNumberProps = [ ]; const LightningRendererNonAnimatingProps = [ - 'absX', - 'absY', 'atlasGroup', 'autosize', 'clipping', - 'contain', 'componentName', 'componentLocation', 'data', - 'destroyed', - 'forceLoad', - 'fontStretch', - 'fontStyle', - 'group', 'ignoreParentAlpha', 'imageType', + 'placeholderColor', + 'srcHeight', + 'srcWidth', + 'srcX', + 'srcY', + 'texture', + 'textureOptions', +]; + +// Text only: forwarded on a ``, kept on the ElementNode elsewhere. +const TextNumberProps = ['fontSize', 'lineHeight']; + +const TextNonAnimatingProps = [ + 'contain', + 'forceLoad', + 'fontStyle', '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', ]; +// Read-only on the renderer node: a write would throw there (B20). +const ReadOnlyProps = ['absX', 'absY', 'destroyed']; + declare global { interface HTMLElement { /** Assigned for development, to quickly get ElementNode from selected HTMLElement */ @@ -523,6 +521,8 @@ 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; _theme?: Styles; _lastAnyKeyPressTime?: number; _type: 'element' | 'textNode'; @@ -1023,6 +1023,7 @@ export class ElementNode { this._requiresLayout = false; this._focusGen = 0; this._layoutQueued = false; + this._textProps = undefined; } get effects(): StyleEffects | undefined { @@ -1148,9 +1149,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 @@ -2068,6 +2074,35 @@ export class ElementNode { } } +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; +} + for (const key of LightningRendererNumberProps) { Object.defineProperty(ElementNode.prototype, key, { get(): number { @@ -2090,6 +2125,55 @@ for (const key of LightningRendererNonAnimatingProps) { }); } +for (const key of TextNumberProps) { + Object.defineProperty(ElementNode.prototype, key, { + get(this: ElementNode): unknown { + return textPropsOf(this)[key]; + }, + set(this: ElementNode, v: number) { + if (this._type === NodeType.TextNode) { + this._sendToLightningAnimatable(key, v); + } else { + textPropsFor(this)[key] = v; + } + }, + }); +} + +for (const key of TextNonAnimatingProps) { + Object.defineProperty(ElementNode.prototype, key, { + get(this: ElementNode): unknown { + return textPropsOf(this)[key]; + }, + set(this: ElementNode, v: unknown) { + textPropsFor(this)[key] = v; + }, + }); +} + +for (const key of ReadOnlyProps) { + Object.defineProperty(ElementNode.prototype, key, { + get(): unknown { + return this.lng[key]; + }, + set(_v: unknown) {}, + }); +} + +// 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 { set(this: ElementNode, value: T) { diff --git a/tests/webgl/handleFields.test.tsx b/tests/webgl/handleFields.test.tsx new file mode 100644 index 00000000..3de10a56 --- /dev/null +++ b/tests/webgl/handleFields.test.tsx @@ -0,0 +1,180 @@ +/** + * 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(); +}); From 4499e2afc245370456a78237f5fab62ff7f7b5f3 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:17:38 -0400 Subject: [PATCH 11/34] perf(nodes): one accessor per forwarded prop, with a constant name (design 3.6.6) The forwarded props' getters and setters were made in loops, so each shared one body (`this.lng[key]`, `this.lng[key] = v`): one inline cache saw every prop name, a megamorphic keyed access, and into renderer v2's prototype accessors a call V8 does not inline. They are written out, one per prop, each loading or storing one constant name (no `new Function`, which a TV app's CSP may forbid). An animatable setter stores directly unless the node has a `transition`; only then does `_sendToLightningAnimatable` run, and it returns whether the write became an animation. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d33c789938e0b7ced27c207086bcb4ce344834a8) --- src/core/elementNode.ts | 796 ++++++++++++++++++++++++++++++++-------- 1 file changed, 644 insertions(+), 152 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index d2be7d55..91813c1b 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -388,81 +388,6 @@ function getPropertyAlias(name: string) { return name; } -// Forwarded to the renderer node (lng[key] = v). Only the renderer's props: -// on a @solidtv/renderer 2.0 node any other name becomes a field of its -// own. fontStretch, the DOM renderer's alone, has an accessor below. -const LightningRendererNumberProps = [ - 'alpha', - 'color', - 'colorTop', - 'colorRight', - 'colorLeft', - 'colorBottom', - 'colorTl', - 'colorTr', - 'colorBl', - 'colorBr', - 'h', - 'mount', - 'mountX', - 'mountY', - 'pivot', - 'pivotX', - 'pivotY', - 'rotation', - 'scale', - 'scaleX', - 'scaleY', - 'w', - 'worldX', - 'worldY', - 'x', - 'y', - 'zIndex', - 'zIndexLocked', -]; - -const LightningRendererNonAnimatingProps = [ - 'atlasGroup', - 'autosize', - 'clipping', - 'componentName', - 'componentLocation', - 'data', - 'ignoreParentAlpha', - 'imageType', - 'placeholderColor', - 'srcHeight', - 'srcWidth', - 'srcX', - 'srcY', - 'texture', - 'textureOptions', -]; - -// Text only: forwarded on a ``, kept on the ElementNode elsewhere. -const TextNumberProps = ['fontSize', 'lineHeight']; - -const TextNonAnimatingProps = [ - 'contain', - 'forceLoad', - 'fontStyle', - 'letterSpacing', - 'maxHeight', - 'maxLines', - 'maxWidth', - 'offsetY', - 'overflowSuffix', - 'text', - 'textAlign', - 'verticalAlign', - 'wordBreak', - 'wordWrap', -]; - -// Read-only on the renderer node: a write would throw there (B20). -const ReadOnlyProps = ['absX', 'absY', 'destroyed']; - declare global { interface HTMLElement { /** Assigned for development, to quickly get ElementNode from selected HTMLElement */ @@ -1249,45 +1174,47 @@ 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]; + const setting = own || transition[getPropertyAlias(name)]; + 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 || {}, + ); + this._fireAnimationEvents(name, value, animationSettings); + return true; } _fireAnimationEvents( @@ -2074,6 +2001,22 @@ export class ElementNode { } } +// 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' +> & { lng: Record }; + const NO_TEXT_PROPS: Readonly> = Object.freeze({}); /** @@ -2103,62 +2046,611 @@ function textPropsOf(node: ElementNode): Readonly> { return own === undefined ? NO_TEXT_PROPS : own; } -for (const key of LightningRendererNumberProps) { - Object.defineProperty(ElementNode.prototype, key, { - get(): number { - return this.lng[key]; +/** 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: ElementNode, v: number) { - this._sendToLightningAnimatable(key, v); + set(this: Forwarding, v: number) { + if ( + this.transition === undefined || + !this._sendToLightningAnimatable('alpha', v) + ) { + this.lng.alpha = v; + } }, - }); -} - -for (const key of LightningRendererNonAnimatingProps) { - Object.defineProperty(ElementNode.prototype, key, { - get(): unknown { - return this.lng[key]; + }, + color: { + get(this: Forwarding) { + return this.lng.color; }, - set(v: unknown) { - this.lng[key] = v; + set(this: Forwarding, v: number) { + if ( + this.transition === undefined || + !this._sendToLightningAnimatable('color', v) + ) { + this.lng.color = v; + } }, - }); -} - -for (const key of TextNumberProps) { - Object.defineProperty(ElementNode.prototype, key, { - get(this: ElementNode): unknown { - return textPropsOf(this)[key]; + }, + 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; + } + }, + }, + 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; + } + }, + }, + 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) { - if (this._type === NodeType.TextNode) { - this._sendToLightningAnimatable(key, v); - } else { - textPropsFor(this)[key] = v; + if ( + this._type !== NodeType.TextNode || + this.transition === undefined || + !this._sendToLightningAnimatable('fontSize', v) + ) { + textPropsFor(this).fontSize = v; } }, - }); -} - -for (const key of TextNonAnimatingProps) { - Object.defineProperty(ElementNode.prototype, key, { - get(this: ElementNode): unknown { - return textPropsOf(this)[key]; + }, + lineHeight: { + get(this: ElementNode) { + return textPropsOf(this).lineHeight; + }, + set(this: ElementNode, v: number) { + if ( + this._type !== NodeType.TextNode || + this.transition === undefined || + !this._sendToLightningAnimatable('lineHeight', v) + ) { + textPropsFor(this).lineHeight = v; + } + }, + }, + // 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)[key] = v; + textPropsFor(this).contain = v; }, - }); -} - -for (const key of ReadOnlyProps) { - Object.defineProperty(ElementNode.prototype, key, { - get(): unknown { - return this.lng[key]; + }, + forceLoad: { + get(this: ElementNode) { + return textPropsOf(this).forceLoad; }, - set(_v: unknown) {}, - }); -} + 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; + }, + }, + maxHeight: { + get(this: ElementNode) { + return textPropsOf(this).maxHeight; + }, + set(this: ElementNode, v: unknown) { + textPropsFor(this).maxHeight = v; + }, + }, + maxLines: { + get(this: ElementNode) { + return textPropsOf(this).maxLines; + }, + set(this: ElementNode, v: unknown) { + textPropsFor(this).maxLines = v; + }, + }, + maxWidth: { + get(this: ElementNode) { + return textPropsOf(this).maxWidth; + }, + set(this: ElementNode, v: unknown) { + textPropsFor(this).maxWidth = v; + }, + }, + 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; + }, + }, + text: { + get(this: ElementNode) { + return textPropsOf(this).text; + }, + set(this: ElementNode, v: unknown) { + textPropsFor(this).text = v; + }, + }, + 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; + }, + }, + // 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. From 03e7ac1248b9e8ca0dda50c3e014b11d36a043fc Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 19:32:24 -0400 Subject: [PATCH 12/34] perf(nodes): inline the w/h transition alias in _sendToLightningAnimatable With the setters no longer calling it, getPropertyAlias had one call site, and terser (default compress options) inlined it there as an IIFE: a closure allocated on every animated write (733 B per press in virtual-row). The alias is written inline instead. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a2666f2e73be249f93f0b8453e30f17df3543053) --- src/core/elementNode.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 91813c1b..9eb90fef 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -382,12 +382,6 @@ export function convertToShader( ) as IRendererShader; } -function getPropertyAlias(name: string) { - if (name === 'w') return 'width'; - if (name === 'h') return 'height'; - return name; -} - declare global { interface HTMLElement { /** Assigned for development, to quickly get ElementNode from selected HTMLElement */ @@ -1188,7 +1182,16 @@ export class ElementNode { let animationSettings: AnimationSettings | undefined; if (transition !== true) { const own = transition[name]; - const setting = own || transition[getPropertyAlias(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; } From c4775a949274cf04ae861877cca1510e220d742a Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:11:57 -0400 Subject: [PATCH 13/34] test(nodes): each animatable setter animates under its own name With `transition` on a rendered node, every animatable setter (the 25 node props, and fontSize/lineHeight on a ) must hand renderer v2's animateProp its own name and the value, on its own handle, and not store the value itself. animateProp is stubbed on Node.prototype. Passes on the loop-made accessors (d342c37) and the written-out ones; a setter passing another prop's name fails it. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ff1ad120bd1b48295f9c3eafc5ae9cdc3fbb47f3) --- tests/webgl/handleFields.test.tsx | 159 +++++++++++++++++++++--------- 1 file changed, 113 insertions(+), 46 deletions(-) diff --git a/tests/webgl/handleFields.test.tsx b/tests/webgl/handleFields.test.tsx index 3de10a56..92fff226 100644 --- a/tests/webgl/handleFields.test.tsx +++ b/tests/webgl/handleFields.test.tsx @@ -15,29 +15,32 @@ 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 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; @@ -57,29 +60,32 @@ v.test('text-only props written to a rendered reach its handle', () => { 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(); -}); +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 @@ -178,3 +184,64 @@ v.test('every forwarded prop reaches the handle under its own name', () => { 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(); + } + }, +); From 422fa909d7ebd007679135aafba37fde39c8b368 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:13:56 -0400 Subject: [PATCH 14/34] bench: an accessor micro-benchmark on real renderer v2 handles bench/micro/accessors.test.tsx times 1.6 M reads and 400 k writes through ElementNode's forwarded-prop accessors on 100 rendered views, in the browser setup of vitest.webgl.config.ts (bench/micro/vitest.config.ts): npx vitest run --config=bench/micro/vitest.config.ts --reporter=verbose Neither `npx vitest run` (excludes bench/) nor `pnpm test:webgl` (only tests/webgl) runs it. M4 Pro, Chromium 141: loop-made accessors (d342c37) about 16 ms read / 15 ms write, written out about 1.1 / 1.5 ms. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 71fb38b6e3632420a2e5703d8681e1cc5861b003) --- bench/micro/accessors.test.tsx | 80 ++++++++++++++++++++++++++++++++++ bench/micro/vitest.config.ts | 17 ++++++++ 2 files changed, 97 insertions(+) create mode 100644 bench/micro/accessors.test.tsx create mode 100644 bench/micro/vitest.config.ts 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'], + }, +}; From b3c1a180210b6b75d9c738f8037d0f632ec6413f Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:42:20 -0400 Subject: [PATCH 15/34] feat(dom-renderer): insertBefore, as renderer v2's Node.insertBefore DOMNode.insertBefore(child, before) makes `child` a child of the node before `before` (null, or a node that is not a child, appends; a child moves; a node placed before itself stays). It reorders the child's div among the parent's divs, the DOM renderer's paint order among equal z-index, and its place in the parent's `children` set. Typed on IRendererNodeShaded. Solid uses it next for B19. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit d5db836b4a90570c8e7ccb8604bc9ca3be715db6) --- src/core/dom-renderer/domRenderer.ts | 36 +++++++++++++++++++++++ src/core/dom-renderer/domRendererTypes.ts | 2 ++ 2 files changed, 38 insertions(+) diff --git a/src/core/dom-renderer/domRenderer.ts b/src/core/dom-renderer/domRenderer.ts index 5f735e24..dffcc43a 100644 --- a/src/core/dom-renderer/domRenderer.ts +++ b/src/core/dom-renderer/domRenderer.ts @@ -1430,6 +1430,42 @@ 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. 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) return; + const anchor = + before instanceof DOMNode && before.props.parent === this ? 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: re-add the anchor and what follows it. + const after: DOMNode[] = []; + let found = false; + for (const c of children) { + if (c === anchor) found = true; + if (found) after.push(c); + } + for (const c of after) children.delete(c); + children.add(child); + for (const c of after) children.add(c); + this.div.insertBefore(child.div, anchor.div); + } + this.markChildrenBoundsDirty(); + } + public markChildrenBoundsDirty() { for (const child of this.children) { child.boundsDirty = true; diff --git a/src/core/dom-renderer/domRendererTypes.ts b/src/core/dom-renderer/domRendererTypes.ts index b7cd9872..32b8b35d 100644 --- a/src/core/dom-renderer/domRendererTypes.ts +++ b/src/core/dom-renderer/domRendererTypes.ts @@ -80,6 +80,8 @@ export interface IRendererNodeShaded extends EventEmitter { ) => lng.IAnimationController; get absX(): number; get absY(): number; + /** Renderer v2's `Node.insertBefore` (draw order follows Solid's children). */ + insertBefore(child: IRendererNode, before: IRendererNode | null): void; } /** Based on {@link lng.INodeProps} */ From 62ad0d4f17ac66da0d576c03d34bdfda552a622f Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:42:31 -0400 Subject: [PATCH 16/34] fix(nodes): draw order follows children (B19); a child list without scans from the front Renderer v2 draws siblings in its child order (among equal zIndex), but insertChild never moved a renderer node: a node inserted before an anchor (a between siblings, a adding in the middle) was drawn after its later siblings, and a same-parent move (a reorder) not at all. - insertChild places a rendered child with the renderer's insertBefore (renderer R4) before the renderer node of its next rendered sibling, and skips a same-parent move that leaves it there; solidOpts.insertNode places a node that render() just created (render appends it). - insertChild, removeChild and getNextSibling find a node from the end (Solid appends and removes at the tail most often), checking the first child first, so Solid's cleanChildren (remove the first child until none is left) is O(n); inserts and removes no longer allocate (no splice, no rest array). - removeChild clears the child's parent, so a re-insert does not pay a full miss; insertNode now tells a re-insert by a parent or a pending delete, and replaceText on a detached text node only sets its text. Tests: tests/webgl/drawOrder.test.tsx (renderer v2 children order) and tests/drawOrder.test.tsx (DOM renderer div and child-set order, the child list, a preserved node re-inserted, replaceText on a removed node). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f611469416e80bea6e8d68464afe881ca35b9a9b) --- src/core/elementNode.ts | 153 +++++++++++++++++------- src/solidOpts.ts | 36 ++++-- tests/drawOrder.test.tsx | 209 +++++++++++++++++++++++++++++++++ tests/webgl/drawOrder.test.tsx | 133 +++++++++++++++++++++ 4 files changed, 480 insertions(+), 51 deletions(-) create mode 100644 tests/drawOrder.test.tsx create mode 100644 tests/webgl/drawOrder.test.tsx diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 9eb90fef..d11e7094 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -188,23 +188,6 @@ function queueLayout(node: ElementNode): void { schedulePostMutation(); } -/** - * 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. - */ -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]!; - } - arr.pop(); - } - return index; -} - function runLayoutQueue(): void { // Start from the deepest bucket there is, so entries a run that threw left // behind are not stranded. @@ -1100,44 +1083,79 @@ export class ElementNode { node: ElementNode | ElementText | TextNode, beforeNode?: ElementNode | ElementText | TextNode | null, ) { + const children = this.children; + const prevParent = node.parent; + // The renderer node of a rendered element is placed among its siblings + // in `children` order (B19: renderer v2 draws siblings in that order). + 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; // 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; + if (prevParent !== undefined) { + if (drawn && prevParent === this) { + drawnBefore = nextDrawn(children, lastIndexOf(children, node) + 1); } + prevParent.removeChild(node); } - node.parent = this; + // 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; + } - 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; - } + // 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 || 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) { + const children = this.children; + const index = lastIndexOf(children, node); + if (index > -1) { + removeAt(children, index); if (isElementNode(node) && node.onRemove) { node.onRemove.call(node, node); } + // Out of the tree: a re-insert finds no parent to remove it from. + node.parent = undefined; if (this.requiresLayout()) { queueLayout(this); @@ -2004,6 +2022,59 @@ export class ElementNode { } } +/** + * 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 diff --git a/src/solidOpts.ts b/src/solidOpts.ts index 1a8bf366..70823794 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 removed node has no parent (removeChild clears it): no text to update. + if (parent !== undefined) { + parent.text = parent.getText(); + } }, setProperty(node: ElementNode, name: string, value: any): void { node[name] = value; @@ -30,14 +31,24 @@ export default { insertNode(parent: ElementNode, node: SolidNode, anchor: SolidNode): void { log('INSERT: ', parent, node, anchor); - const prevParent = node.parent; + // Inserted before: in a parent now, or removed with its delete still + // pending (a removed node has no parent; removeNode counted -1 in + // _queueDelete). A preserved node never inserted has 0 there. + const queued = node instanceof ElementNode ? node._queueDelete : undefined; + const reinserted = + node.parent !== undefined || (queued !== undefined && queued < 0); parent.insertChild(node, anchor); 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) { + if (reinserted) { enqueueDelete(node, 1); } } else if (isElementText(parent)) { @@ -67,11 +78,16 @@ 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; + if (parent === undefined) { + 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/drawOrder.test.tsx b/tests/drawOrder.test.tsx new file mode 100644 index 00000000..ae8e3b11 --- /dev/null +++ b/tests/drawOrder.test.tsx @@ -0,0 +1,209 @@ +/** + * 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 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(); + }); +}); + +v.describe('child list', () => { + v.test('removeChild takes the child out and clears its parent', () => { + 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).toBeUndefined(); + v.expect(a.parent).toBe(parent); + + // Not a child: nothing changes. + parent.removeChild(b); + v.expect(ids(parent)).toEqual(['a', 'c']); + + parent.removeChild(a); + parent.removeChild(c); + v.expect(ids(parent)).toEqual([]); + parent.insertChild(b); + v.expect(ids(parent)).toEqual(['b']); + v.expect(b.parent).toBe(parent); + }); + + 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); + + setShow(false); + await tick(); + v.expect(el.parent).toBeUndefined(); + setShow(true); + await tick(); + v.expect(el.parent).toBeDefined(); + v.expect(el.preserve).toBe(true); + v.expect(destroyed).toBe(0); + dispose(); + }, + ); +}); diff --git a/tests/webgl/drawOrder.test.tsx b/tests/webgl/drawOrder.test.tsx new file mode 100644 index 00000000..364a868d --- /dev/null +++ b/tests/webgl/drawOrder.test.tsx @@ -0,0 +1,133 @@ +/** + * 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(); +}); From 2b9e85e062124f369740a5609d4cb0011d63ef3e Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 20:48:31 -0400 Subject: [PATCH 17/34] docs(nodes): the zIndex caveat of draw order in insertChild Renderer v2 keeps siblings sorted by zIndex; when an anchor's zIndex is not the child's, the child goes to the nearest sorted place, so among equal-zIndex siblings its order can differ from `children`. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1c74a6d779554437b5b81793139f18e3ba3a47c9) --- src/core/elementNode.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index d11e7094..c6306f27 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -1087,6 +1087,9 @@ export class ElementNode { const prevParent = node.parent; // 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. From 1013ecd6f1a2715d04b400c189a850c400bed9b1 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 21:04:56 -0400 Subject: [PATCH 18/34] fix(nodes): a child inserted before itself stays in place (B19) Solid universal's swap of adjacent items calls insertNode(parent, y, getNextSibling(x)), which for neighbours is y itself. insertChild took y out first, so the anchor was no longer a child and y was appended: [head, a, x, y, b, tail] swapped to [a, y, x, b] gave [head, a, x, b, tail, y], and the renderers followed. A node placed before itself now stays (DOM semantics): the anchor becomes its next sibling, and the drawn-sibling check skips the renderer call. Also fixes the stale comment on the removal. Tests: the adjacent swap with a later sibling (DOM and WebGL), and a spy on the parent's insertBefore across no-op moves (none) and a real one (one call). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1b0acbe6057d4f492ec80c9bc111ec94be4369e7) --- src/core/elementNode.ts | 12 +++++-- tests/drawOrder.test.tsx | 63 ++++++++++++++++++++++++++++++++++ tests/webgl/drawOrder.test.tsx | 25 ++++++++++++++ 3 files changed, 98 insertions(+), 2 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index c6306f27..6d76872c 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -1094,8 +1094,16 @@ export class ElementNode { // 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; - // 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 + // 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 + ? 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) { if (drawn && prevParent === this) { drawnBefore = nextDrawn(children, lastIndexOf(children, node) + 1); diff --git a/tests/drawOrder.test.tsx b/tests/drawOrder.test.tsx index ae8e3b11..2e53e79b 100644 --- a/tests/drawOrder.test.tsx +++ b/tests/drawOrder.test.tsx @@ -137,6 +137,69 @@ v.describe('B19: the DOM renderer draws children in children order', () => { 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.describe('child list', () => { diff --git a/tests/webgl/drawOrder.test.tsx b/tests/webgl/drawOrder.test.tsx index 364a868d..e3e9213b 100644 --- a/tests/webgl/drawOrder.test.tsx +++ b/tests/webgl/drawOrder.test.tsx @@ -131,3 +131,28 @@ v.test('insertChild(node, before) between rendered parents', () => { 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(); + }, +); From 9cdf64ec098f9fa380960d58e8efc780c34b71c3 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 21:05:23 -0400 Subject: [PATCH 19/34] fix(nodes): render() reparents moved-in children in children order (B19) An unrendered parent that got already-rendered children (moved in) and new ones reparented all the rendered ones right after createNode, then rendered the new ones, which append: [n1, moved, n2] drew as [moved, n1, n2]. The reparent now happens in the ordered child loop, just before each child's render(). Also covers the re-keyed _hasRenderedChildren (a rendered node moved into an unrendered parent that renders later). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 7240927e78a09dea32f334b9dcb2111e4e35b5a7) --- src/core/elementNode.ts | 17 +++++++---------- tests/drawOrder.test.tsx | 30 ++++++++++++++++++++++++++++++ tests/webgl/drawOrder.test.tsx | 29 +++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 10 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 6d76872c..6f3a932f 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -1965,16 +1965,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; @@ -2013,12 +2003,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(); } } diff --git a/tests/drawOrder.test.tsx b/tests/drawOrder.test.tsx index 2e53e79b..7e7faa5c 100644 --- a/tests/drawOrder.test.tsx +++ b/tests/drawOrder.test.tsx @@ -200,6 +200,36 @@ v.describe('B19: the DOM renderer draws children in children order', () => { } }, ); + + 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(); + }, + ); }); v.describe('child list', () => { diff --git a/tests/webgl/drawOrder.test.tsx b/tests/webgl/drawOrder.test.tsx index e3e9213b..b1264fe8 100644 --- a/tests/webgl/drawOrder.test.tsx +++ b/tests/webgl/drawOrder.test.tsx @@ -156,3 +156,32 @@ v.test( 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(); + }, +); From 86f33fa8538b51a49da1b3f236a6c726623d0ad5 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 21:05:50 -0400 Subject: [PATCH 20/34] fix(dom-renderer): insertBefore leaves destroyed nodes alone, no array per move As renderer v2's Node.insertBefore: a destroyed parent or child does nothing (it re-appended a destroyed child's div), and a destroyed anchor appends (its div is no longer the parent's, so div.insertBefore threw). The anchored move reorders the children Set in place instead of collecting the anchor and its followers in an array. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a4fa11bf12331f63211844a11548007f16f43e50) --- src/core/dom-renderer/domRenderer.ts | 43 +++++++++++++++++++--------- tests/drawOrder.test.tsx | 29 +++++++++++++++++++ 2 files changed, 59 insertions(+), 13 deletions(-) diff --git a/src/core/dom-renderer/domRenderer.ts b/src/core/dom-renderer/domRenderer.ts index dffcc43a..1fb86d0a 100644 --- a/src/core/dom-renderer/domRenderer.ts +++ b/src/core/dom-renderer/domRenderer.ts @@ -1433,14 +1433,26 @@ export class DOMNode extends EventEmitter implements IRendererNode { /** * 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. The div order is - * the paint order among equal z-index, as v2's sibling order is its draw - * order. + * 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) return; + if ( + !(child instanceof DOMNode) || + child === before || + !elMap.has(this) || + !elMap.has(child) + ) { + return; + } const anchor = - before instanceof DOMNode && before.props.parent === this ? before : null; + 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; @@ -1451,16 +1463,21 @@ export class DOMNode extends EventEmitter implements IRendererNode { children.add(child); this.div.appendChild(child.div); } else { - // A Set keeps insertion order: re-add the anchor and what follows it. - const after: DOMNode[] = []; - let found = false; + // 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) found = true; - if (found) after.push(c); + if (c === anchor) moving = true; + if (moving) { + children.delete(c); + children.add(c); + } + if (c === last) break; } - for (const c of after) children.delete(c); - children.add(child); - for (const c of after) children.add(c); this.div.insertBefore(child.div, anchor.div); } this.markChildrenBoundsDirty(); diff --git a/tests/drawOrder.test.tsx b/tests/drawOrder.test.tsx index 7e7faa5c..87a5030e 100644 --- a/tests/drawOrder.test.tsx +++ b/tests/drawOrder.test.tsx @@ -230,6 +230,35 @@ v.describe('B19: the DOM renderer draws children in children order', () => { 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', () => { From 402e4af56e312bd75138e50d42e61097fb23df12 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 21:06:17 -0400 Subject: [PATCH 21/34] fix(primitives): a removed Row/Column scrolls without its parent removeChild now clears a removed node's parent, and withScrolling's first scroll read `componentRef.parent!.clipping`: a Row or Column that is itself a removed root, with focus still stranded in it, threw on its first key press. The clipping end offset is skipped without a parent. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e6d6a96db7fd49691fbf81655f713fc04f60dac3) --- src/primitives/utils/withScrolling.ts | 5 +++-- tests/drawOrder.test.tsx | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/primitives/utils/withScrolling.ts b/src/primitives/utils/withScrolling.ts index 09b7b9f8..5930485e 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 removed Row/Column has no parent (removeChild clears it). + 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/tests/drawOrder.test.tsx b/tests/drawOrder.test.tsx index 87a5030e..d89a1fa6 100644 --- a/tests/drawOrder.test.tsx +++ b/tests/drawOrder.test.tsx @@ -7,6 +7,7 @@ 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'; @@ -328,4 +329,24 @@ v.describe('child list', () => { dispose(); }, ); + + // A Row that is itself a removed root, with focus still in it, takes its + // first scroll: its parent is gone (removeChild clears it). + v.test('a removed Row scrolls without its parent', () => { + let host!: ElementNode; + let row!: ElementNode; + const dispose = renderer.render(() => ( + + + + + + + + )); + host.removeChild(row); + v.expect(row.parent).toBeUndefined(); + v.expect(() => scrollRow(1, row, undefined, 0)).not.toThrow(); + dispose(); + }); }); From fd6c3bbf2b1384d190e46c0e4785e802a292cecb Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:43:16 -0400 Subject: [PATCH 22/34] fix(nodes): a removed node keeps its parent link, as in 1.6 f611469 (N2) made removeChild clear the removed node's `parent`. The demo port found that this changes focus semantics: when a focused element's subtree is removed and nothing re-focuses, 1.6 keeps building focus paths and bubbling keys and events up the stale parent chain, so a key on a removed card's Row still reached the live Column (demo #/complexflex); with the link cleared, the chain ended at the removed Row. Removed nodes keep `parent` again. The re-insert fast path stays without it: removeChild marks an element `_detached` (cleared by insertChild), so a removed element re-inserted is not looked for in its old parent's children (no full-scan miss), a same-parent re-insert is always placed in the renderer, and getNextSibling answers undefined at once. insertNode is back to 1.6's "had a parent" re-insert test. New contract test (contract-focus, "a removed focused subtree"): keys from inside a removed subtree reach its former ancestors' handlers. It passes on a `git archive` export of 71c170f (1.6.4, renderer 1.9.3) and failed on 1672798. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 7bd7fbad35ea8bf11676b57077df68e0ce962794) --- src/core/elementNode.ts | 29 +++++++++--- src/primitives/utils/withScrolling.ts | 2 +- src/solidOpts.ts | 17 ++++--- tests/contract-focus.test.tsx | 47 ++++++++++++++++++ tests/drawOrder.test.tsx | 68 ++++++++++++++++----------- 5 files changed, 119 insertions(+), 44 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 6f3a932f..ff7ead87 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -425,6 +425,12 @@ export interface ElementNode extends RendererNode, FocusNode { _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'; @@ -926,6 +932,7 @@ export class ElementNode { this._focusGen = 0; this._layoutQueued = false; this._textProps = undefined; + this._detached = false; } get effects(): StyleEffects | undefined { @@ -1085,6 +1092,9 @@ export class ElementNode { ) { 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 @@ -1098,18 +1108,22 @@ export class ElementNode { // adjacent items asks for this (insertNode(parent, y, nextSibling(x))). if (beforeNode === node) { beforeNode = - prevParent === this + 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) { + 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) { @@ -1136,7 +1150,7 @@ export class ElementNode { // renderer write is skipped. (node as ElementNode)._parent = this; const next = nextDrawn(children, index + 1); - if (prevParent !== this || next !== drawnBefore) { + if (prevParent !== this || detached || next !== drawnBefore) { (this.lng as INode).insertBefore( (node as ElementNode).lng as INode, next === null ? null : (next.lng as INode), @@ -1162,11 +1176,12 @@ export class ElementNode { const index = lastIndexOf(children, node); if (index > -1) { removeAt(children, index); - if (isElementNode(node) && node.onRemove) { - node.onRemove.call(node, node); + if (isElementNode(node)) { + node._detached = true; + if (node.onRemove) { + node.onRemove.call(node, node); + } } - // Out of the tree: a re-insert finds no parent to remove it from. - node.parent = undefined; if (this.requiresLayout()) { queueLayout(this); diff --git a/src/primitives/utils/withScrolling.ts b/src/primitives/utils/withScrolling.ts index 5930485e..c7781e44 100644 --- a/src/primitives/utils/withScrolling.ts +++ b/src/primitives/utils/withScrolling.ts @@ -93,7 +93,7 @@ export function withScrolling(isRow: boolean): Scroller { let endOffset = componentRef.endOffset; let screenOffset = componentRef._screenOffset; if (screenOffset === undefined) { - // A removed Row/Column has no parent (removeChild clears it). + // A Row/Column with no parent (a root) has no clipping parent. const p = componentRef.parent; if (p !== undefined && p !== null && p.clipping) { endOffset = diff --git a/src/solidOpts.ts b/src/solidOpts.ts index 70823794..c76925ed 100644 --- a/src/solidOpts.ts +++ b/src/solidOpts.ts @@ -20,7 +20,7 @@ export default { log('Replace Text: ', node, value); node.text = value; const parent = node.parent; - // A removed node has no parent (removeChild clears it): no text to update. + // A text node never inserted has no parent. if (parent !== undefined) { parent.text = parent.getText(); } @@ -31,12 +31,7 @@ export default { insertNode(parent: ElementNode, node: SolidNode, anchor: SolidNode): void { log('INSERT: ', parent, node, anchor); - // Inserted before: in a parent now, or removed with its delete still - // pending (a removed node has no parent; removeNode counted -1 in - // _queueDelete). A preserved node never inserted has 0 there. - const queued = node instanceof ElementNode ? node._queueDelete : undefined; - const reinserted = - node.parent !== undefined || (queued !== undefined && queued < 0); + const prevParent = node.parent; parent.insertChild(node, anchor); if (node instanceof ElementNode) { @@ -48,7 +43,7 @@ export default { parent._drawInOrder(node); } } - if (reinserted) { + if (prevParent !== undefined) { enqueueDelete(node, 1); } } else if (isElementText(parent)) { @@ -79,7 +74,11 @@ export default { }, getNextSibling(node: SolidNode): SolidNode | undefined { const parent = node.parent; - if (parent === undefined) { + // 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. 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/drawOrder.test.tsx b/tests/drawOrder.test.tsx index d89a1fa6..a324bd71 100644 --- a/tests/drawOrder.test.tsx +++ b/tests/drawOrder.test.tsx @@ -263,31 +263,43 @@ v.describe('B19: the DOM renderer draws children in children order', () => { }); v.describe('child list', () => { - v.test('removeChild takes the child out and clears its parent', () => { - 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]; + // 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).toBeUndefined(); - v.expect(a.parent).toBe(parent); + 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']); + // Not a child: nothing changes. + parent.removeChild(b); + v.expect(ids(parent)).toEqual(['a', 'c']); - parent.removeChild(a); - parent.removeChild(c); - v.expect(ids(parent)).toEqual([]); - parent.insertChild(b); - v.expect(ids(parent)).toEqual(['b']); - v.expect(b.parent).toBe(parent); - }); + // 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'); @@ -318,12 +330,14 @@ v.describe('child list', () => { await tick(); v.expect(el.preserve).toBe(true); + const host = el.parent!; setShow(false); await tick(); - v.expect(el.parent).toBeUndefined(); + v.expect(host.children).not.toContain(el); + v.expect(el.parent).toBe(host); setShow(true); await tick(); - v.expect(el.parent).toBeDefined(); + v.expect(host.children).toContain(el); v.expect(el.preserve).toBe(true); v.expect(destroyed).toBe(0); dispose(); @@ -331,8 +345,8 @@ v.describe('child list', () => { ); // A Row that is itself a removed root, with focus still in it, takes its - // first scroll: its parent is gone (removeChild clears it). - v.test('a removed Row scrolls without its parent', () => { + // 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(() => ( @@ -345,7 +359,7 @@ v.describe('child list', () => { )); host.removeChild(row); - v.expect(row.parent).toBeUndefined(); + v.expect(row.parent).toBe(host); v.expect(() => scrollRow(1, row, undefined, 0)).not.toThrow(); dispose(); }); From eae956892089a124e7f0dd99734862fd5ec7ef68 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:43:45 -0400 Subject: [PATCH 23/34] fix(nodes): a removed node does not lay out its old parent With the parent link kept (as in 1.6), the layout queue must not treat a removed node as attached: its `loaded` handler no longer queues its old parent, a removed container whose layout changed its size no longer queues its old parent, and its depth in the layout queue counts its own tree only (it ends at the removed node). Removed-but-alive nodes are Preserve and KeepAlive roots, and nodes an app removes itself; 1.6 laid out the old parent synchronously from a removed node's load. Tests (jsdom, failed with the parent link back and without this): a removed autosize view's load, and a removed flex container's resize, leave the old parent's onLayout count alone. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b571b998bc8df1119ad847884d0cf6c6e3ad1736) --- src/core/elementNode.ts | 12 ++++++--- tests/drawOrder.test.tsx | 58 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index ff7ead87..775d3dd2 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -160,8 +160,13 @@ function runPostMutation() { 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 p = node.parent; p !== undefined && p !== null; p = p.parent) { + 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) { @@ -1383,7 +1388,7 @@ export class ElementNode { width = w; height = h; const parent = this.parent; - if (parent !== undefined && parent !== null) { + if (parent !== undefined && parent !== null && !this._detached) { enqueueLayout(parent); schedulePostMutationInFrame(); } @@ -1661,7 +1666,8 @@ export class ElementNode { // A container whose size changed queues its parent (one with nothing to // lay out would do nothing). - const parent = this.parent; + // 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); } diff --git a/tests/drawOrder.test.tsx b/tests/drawOrder.test.tsx index a324bd71..075777c9 100644 --- a/tests/drawOrder.test.tsx +++ b/tests/drawOrder.test.tsx @@ -363,4 +363,62 @@ v.describe('child list', () => { 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(); + }, + ); }); From efccb45b2e312977bbbf92cbf5d8f9c27c26a6a4 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 21:28:31 -0400 Subject: [PATCH 24/34] feat(text): Solid measures flex text with TextNode.measure() (T1) A text whose parent lays out (flex or onLayout) is sized by the renderer's synchronous measure() in Solid's post-mutation pass, before the parent's flex and before the frame, instead of by the walk and a persistent `loaded` listener. A text change in a flex container now costs one walk per drawn frame, no `loaded` event when the app has no listener, and one flex pass per container whose size changed. - render() queues a new flex text to be measured (after its onEvent listeners are on, so an app's `loaded` hears the layout measure() makes); _layoutOnLoad stays for autosize nodes only. - _textLayoutDirty(), the one helper, is called by the accessors of the props the layout reads: text, fontFamily/fontWeight (_writeFontFamily), fontSize, lineHeight, letterSpacing, maxWidth/w(width), maxHeight/h (height), maxLines, wordBreak, overflowSuffix. It queues the text; the layout phase measures the queue and queues the parent only when the size flex reads (maxWidth || w, maxHeight || h) changed. A text with both max sizes is not measured (flex reads those). - updateLayout() measures due or never-measured text children before its pass (a direct updateLayout(), a container that lays out only now). - Texts flex sizes (flexGrow, flexShrink, minWidth) are measured again after each sweep, so their container runs again; capped at 16 sweeps. - measure() false (no font description): the text hears `loaded` once (a shared listener, run in the frame), and loadFonts() tells when a font loaded (internal src/core/fontLoaded.ts), for texts no walk visits (5.2: text under a hidden or out-of-bounds ancestor is laid out too). - Development only: a warning when a walk's layout changes the size of a text Solid measures (a layout prop written on el.lng). - DOM renderer: DOMText.measure() (getBoundingClientRect while document.fonts.check says the font is loaded, else false) and DOMNode.destroyed; both in domRendererTypes. Tests: WebGL walks per drawn frame 1 and one pass per container for text changes, `loaded` heard once by a listener, eager layout under alpha 0 and out of bounds, culled text whose font loads later, flex-written text widths settle; jsdom: measured in the post-mutation microtask, direct updateLayout(), unchanged size lays nothing out, every font prop, the font-not-loaded wait. layoutQueue's `loaded` cases use an autosize view. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit bcf31d226aa6f6c6df2dc3d980bf62c7f724f514) --- src/core/dom-renderer/domRenderer.ts | 41 +++ src/core/dom-renderer/domRendererTypes.ts | 8 + src/core/elementNode.ts | 347 ++++++++++++++++++++-- src/core/fontLoaded.ts | 19 ++ src/core/lightningInit.ts | 8 +- tests/contract-text.test.tsx | 252 +++++++++++++++- tests/layoutQueue.test.tsx | 37 +-- tests/webgl/flex-text.test.tsx | 337 +++++++++++++++++++-- 8 files changed, 992 insertions(+), 57 deletions(-) create mode 100644 src/core/fontLoaded.ts diff --git a/src/core/dom-renderer/domRenderer.ts b/src/core/dom-renderer/domRenderer.ts index 1fb86d0a..46059bb5 100644 --- a/src/core/dom-renderer/domRenderer.ts +++ b/src/core/dom-renderer/domRenderer.ts @@ -1158,6 +1158,32 @@ function updateDOMTextSize(node: DOMText, emitLoaded = true): void { } } +/** + * 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(props: IRendererTextNodeProps): 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; + } + try { + return fonts.check( + `${props.fontStyle} ${props.fontWeight} ${props.fontSize}px "${props.fontFamily}"`, + ); + } catch { + return true; + } +} + function updateDOMTextMeasurements() { textNodesToMeasure.forEach((node) => updateDOMTextSize(node)); textNodesToMeasure.clear(); @@ -1955,6 +1981,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.props)) { + return false; + } + updateDOMTextSize(this, false); + return true; + } + get text() { return this.props.text; } diff --git a/src/core/dom-renderer/domRendererTypes.ts b/src/core/dom-renderer/domRendererTypes.ts index 32b8b35d..cb2af74f 100644 --- a/src/core/dom-renderer/domRendererTypes.ts +++ b/src/core/dom-renderer/domRendererTypes.ts @@ -80,6 +80,8 @@ 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; } @@ -117,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 775d3dd2..3644d153 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -48,6 +48,7 @@ import { FocusNode, } from './focusManager.js'; import { initClickInspector } from './clickInspector.js'; +import { onFontLoaded } from './fontLoaded.js'; import { IRendererNode, @@ -63,7 +64,9 @@ import { // 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 @@ -88,6 +91,25 @@ 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; +// Re-measures in one layout phase before the rest waits for the next run: +// 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; @@ -141,6 +163,9 @@ function runPostMutation() { } // Phase 2: layout + if (fontWaitingDue === true) { + measureFontWaiting(); + } runLayoutQueue(); // Phase 3: focus. setFocus() may have evaluated forwardFocus pre-render @@ -194,9 +219,11 @@ function queueLayout(node: ElementNode): void { } 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; @@ -214,9 +241,126 @@ function runLayoutQueue(): void { 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 (isDev && textMeasureCount > 0) { + console.warn( + '[solid] Text sizes did not settle in ' + + MAX_TEXT_SWEEPS + + ' layout passes (a flex size that depends on a text that flex sizes); the rest waits for the next change.', + ); } } +/** + * 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 measureQueuedTexts(): void { + for (let i = 0; i < textMeasureCount; i++) { + const t = textMeasureQueue[i]!; + textMeasureQueue[i] = undefined; + 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); + } + } + 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; + 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); + } + } + // 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; +} + +/** + * 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; + + constructor() { + this.due = false; + this.waiting = false; + this.w = NaN; + this.h = NaN; + } +} + +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; @@ -416,6 +560,12 @@ export interface ElementNode extends RendererNode, FocusNode { _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. */ @@ -938,6 +1088,7 @@ export class ElementNode { this._layoutQueued = false; this._textProps = undefined; this._detached = false; + this._text = undefined; } get effects(): StyleEffects | undefined { @@ -1080,15 +1231,16 @@ 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( @@ -1376,9 +1528,10 @@ export class ElementNode { } _layoutOnLoad() { - // The size the parent's last layout saw: a load that leaves it unchanged - // needs no layout. Until Solid measures text itself, this is how a text - // size reaches flex: queue the parent and run the pass in the frame. + // 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', () => { @@ -1395,6 +1548,123 @@ export class ElementNode { }); } + /** + * @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.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 text prop written on el.lng, or animated there, 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); + fontWaiting.push(this); + } + getText(this: ElementText) { const len = this.children.length; if (len === 1) return this.children[0]!.text; @@ -1634,6 +1904,19 @@ export class ElementNode { 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(); + } + } + } + let flexChanged = isFlex && calculateFlex(this); if (isFlex && this._containsFlexGrow === true) { @@ -1917,11 +2200,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) { @@ -2013,6 +2294,19 @@ 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 (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) { @@ -2117,7 +2411,7 @@ function nextDrawn( // then `_sendToLightningAnimatable` may animate instead. type Forwarding = Pick< ElementNode, - 'transition' | '_sendToLightningAnimatable' + 'transition' | '_sendToLightningAnimatable' | '_type' | '_textLayoutDirty' > & { lng: Record }; const NO_TEXT_PROPS: Readonly> = Object.freeze({}); @@ -2295,6 +2589,10 @@ Object.defineProperties(ElementNode.prototype, { ) { this.lng.h = v; } + // On a text, the max height (renderer v2), which its layout reads. + if (this._type === NodeType.TextNode) { + this._textLayoutDirty(); + } }, }, mount: { @@ -2438,6 +2736,10 @@ Object.defineProperties(ElementNode.prototype, { ) { this.lng.w = v; } + // On a text, the max width (renderer v2), which its layout reads. + if (this._type === NodeType.TextNode) { + this._textLayoutDirty(); + } }, }, x: { @@ -2492,6 +2794,7 @@ Object.defineProperties(ElementNode.prototype, { ) { textPropsFor(this).fontSize = v; } + this._textLayoutDirty(); }, }, lineHeight: { @@ -2506,6 +2809,7 @@ Object.defineProperties(ElementNode.prototype, { ) { textPropsFor(this).lineHeight = v; } + this._textLayoutDirty(); }, }, // Not animated @@ -2660,6 +2964,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).letterSpacing = v; + this._textLayoutDirty(); }, }, maxHeight: { @@ -2668,6 +2973,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).maxHeight = v; + this._textLayoutDirty(); }, }, maxLines: { @@ -2676,6 +2982,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).maxLines = v; + this._textLayoutDirty(); }, }, maxWidth: { @@ -2684,6 +2991,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).maxWidth = v; + this._textLayoutDirty(); }, }, offsetY: { @@ -2700,6 +3008,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).overflowSuffix = v; + this._textLayoutDirty(); }, }, text: { @@ -2708,6 +3017,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).text = v; + this._textLayoutDirty(); }, }, textAlign: { @@ -2732,6 +3042,7 @@ Object.defineProperties(ElementNode.prototype, { }, set(this: ElementNode, v: unknown) { textPropsFor(this).wordBreak = v; + this._textLayoutDirty(); }, }, // Read-only on the renderer node: a write would throw there (B20) diff --git a/src/core/fontLoaded.ts b/src/core/fontLoaded.ts new file mode 100644 index 00000000..58985c77 --- /dev/null +++ b/src/core/fontLoaded.ts @@ -0,0 +1,19 @@ +// 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(); + } +} diff --git a/src/core/lightningInit.ts b/src/core/lightningInit.ts index 6a7e9cc4..33930549 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 { fontLoaded } from './fontLoaded.js'; import { FontLoadOptions } from './intrinsicTypes.js'; export type SdfFontType = 'ssdf' | 'msdf'; @@ -129,7 +130,12 @@ 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`). + return renderer.stage + .loadFont('sdf', font as lng.FontLoadOptions) + .then(fontLoaded); } // DOM — Web if ('fontUrl' in font && enableDomRenderer) { diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index 9df1fc60..06d9cbc7 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'; @@ -640,7 +643,20 @@ describe('contract: text in a flex container (DOM renderer)', () => { 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( @@ -679,8 +695,14 @@ 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; fontsReady(); await waitForUpdate(); await nextTask(); @@ -691,6 +713,7 @@ describe('contract: text in a flex container (DOM renderer)', () => { expect(row.height).toBe(50); expect(count).toBe(2); } finally { + fontSet.check = savedCheck; fontsReady(); fonts.ready = savedReady; await waitForUpdate(); @@ -851,3 +874,226 @@ describe('contract: text in a flex container (DOM renderer)', () => { dispose(); }); }); + +/** + * 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('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()} + + + )); + 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(); + }); +}); diff --git a/tests/layoutQueue.test.tsx b/tests/layoutQueue.test.tsx index 8a877186..4769ebd6 100644 --- a/tests/layoutQueue.test.tsx +++ b/tests/layoutQueue.test.tsx @@ -4,9 +4,13 @@ * 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 (the text fallback until - * Solid measures text itself) also asks the renderer to run it inside the - * frame, between its walks. + * 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. @@ -177,13 +181,12 @@ describe('layout queue', () => { }); it('a loaded event that reports an unchanged size does not lay the container out again', async () => { - mockTextMeasure(); let count = 0; let t!: lng.ElementNode; let last!: lng.ElementNode; const dispose = renderer.render(() => ( void count++}> - Hello + )); @@ -192,7 +195,7 @@ describe('layout queue', () => { count = 0; emitter(t).emit('loaded', { - type: 'text', + type: 'texture', dimensions: { w: 50, h: 20 }, }); await settle(); @@ -201,13 +204,12 @@ describe('layout queue', () => { }); it('a loaded event that reports a new size lays the container out in the post-mutation pass', async () => { - mockTextMeasure(); let count = 0; let t!: lng.ElementNode; let last!: lng.ElementNode; const dispose = renderer.render(() => ( void count++}> - Hello + )); @@ -216,7 +218,7 @@ describe('layout queue', () => { t.lng.w = 80; emitter(t).emit('loaded', { - type: 'text', + type: 'texture', dimensions: { w: 80, h: 20 }, }); expect(count).toBe(0); // not synchronously @@ -288,15 +290,14 @@ describe('layout queue: more cases', () => { dispose(); }); - it('a loaded event on a text removed from its container does not throw, and the container stays laid out', async () => { - mockTextMeasure(); + 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(() => ( - Hello + @@ -310,7 +311,7 @@ describe('layout queue: more cases', () => { t.lng.w = 90; expect(() => emitter(t).emit('loaded', { - type: 'text', + type: 'texture', dimensions: { w: 90, h: 20 }, }), ).not.toThrow(); @@ -383,17 +384,19 @@ describe('post-mutation scheduling', () => { let last!: lng.ElementNode; const dispose = renderer.render(() => ( - Hello + Hi + )); await settle(); - expect(last.x).toBe(60); + 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: 'text', + type: 'texture', dimensions: { w: 80, h: 20 }, }); expect(reprocess).toHaveBeenCalledTimes(1); @@ -401,7 +404,7 @@ describe('post-mutation scheduling', () => { // The renderer runs the callback between its walks: the layout lands // in the same frame. reprocess.mock.calls[0]![0](); - expect(last.x).toBe(90); + expect(last.x).toBe(120); // 20 + 10 + 80 + 10 dispose(); } finally { if (saved === undefined) { diff --git a/tests/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index 45f30d59..ea652596 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 @@ -25,10 +26,11 @@ * 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'; @@ -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,267 @@ 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(); + } + }, +); From f83dd8a085e0b65776049883d02fca0b31c5168f Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:10:44 -0400 Subject: [PATCH 25/34] fix(dom-renderer): `loaded` tells a size measure() already took (T1 review) DOMText.measure() writes the new size without emitting; the renderer's own re-measure then found the size unchanged and emitted nothing, so an app's onEvent.loaded on a flex text heard only the first size (Marquee's text width went stale). The re-measure now emits when the size differs from the one `loaded` last told (loadedW/loadedH). The jsdom fonts mock reports status 'loaded', as a browser does once its fonts are in: the re-measure runs on a timer then, after Solid's microtask, which is the order that lost the event. Two contract tests wait for that timer; the font-not-loaded test sets status 'loading' while it holds `ready`. New contract test: a flex text's onEvent.loaded hears a text change (RED before: [{50,20}] only). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f2c8bf8f3ada742211d3e94eaebcf0c038ffee3c) --- src/core/dom-renderer/domRenderer.ts | 16 +++++++++- tests/contract-text.test.tsx | 44 +++++++++++++++++++++++++++- tests/setup.ts | 3 ++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/core/dom-renderer/domRenderer.ts b/src/core/dom-renderer/domRenderer.ts index 46059bb5..8df828f5 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,6 +1162,8 @@ 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; } @@ -1962,6 +1973,9 @@ 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; constructor( stage: IRendererStage, diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index 06d9cbc7..cbcfe039 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -591,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); @@ -630,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); @@ -673,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; @@ -703,6 +710,7 @@ describe('contract: text in a flex container (DOM renderer)', () => { spy.mockRestore(); mockTextMeasure(); fontSet.check = savedCheck; + fonts.status = 'loaded'; fontsReady(); await waitForUpdate(); await nextTask(); @@ -714,6 +722,7 @@ describe('contract: text in a flex container (DOM renderer)', () => { expect(count).toBe(2); } finally { fontSet.check = savedCheck; + fonts.status = 'loaded'; fontsReady(); fonts.ready = savedReady; await waitForUpdate(); @@ -1096,4 +1105,37 @@ describe('contract: Solid measures text before flex (1.7, stream T)', () => { 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(); + }); }); 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', }; } From 6d0a7b2c01a5f34012b198d66c7b26ba481d76fb Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:11:34 -0400 Subject: [PATCH 26/34] fix(text): T1 review minors (queue safety, sweep cap, contain, DOM fonts, waiting list) - measureQueuedTexts skips an entry a run that threw cleared (the count was not reset): later runs no longer throw on `undefined._text`. - At the 16-sweep cap the remaining texts are dropped (measured again at their next change): the writes of a layout that never settles had scheduled another run, which started over in a microtask loop. - `contain` writes mark the text due: the DOM renderer sizes a text by it (on renderer v2 the measure finds nothing to lay out). - DOM builds keep a `loaded` listener per measured text that lays the container out when the size changed since Solid saw it: a web font that loads after the text was measured (document.fonts.check is true for a family no face names). isFontLoaded caches the CSS font on the text. - The font-waiting list is swept of destroyed texts when it doubles; a loadFonts() font that fails runs the same pass (fontFailed rethrows). Tests: the sweep cap (17 passes, one warning, later runs lay out; it hung the worker before), a throwing measure (2 errors before), contain, a DOM re-measure at a new size, and a font loaded with renderer.loadFont alone (the texts' `loaded`, no loadFonts hook). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f2983202310d4e2c157205ed1c83c5d4c58e2814) --- src/core/dom-renderer/domRenderer.ts | 20 ++++-- src/core/elementNode.ts | 92 +++++++++++++++++++++++--- src/core/fontLoaded.ts | 10 +++ src/core/lightningInit.ts | 7 +- tests/contract-text.test.tsx | 48 ++++++++++++++ tests/layoutQueue.test.tsx | 99 ++++++++++++++++++++++++++++ tests/webgl/flex-text.test.tsx | 32 +++++++++ 7 files changed, 291 insertions(+), 17 deletions(-) diff --git a/src/core/dom-renderer/domRenderer.ts b/src/core/dom-renderer/domRenderer.ts index 8df828f5..4d55544d 100644 --- a/src/core/dom-renderer/domRenderer.ts +++ b/src/core/dom-renderer/domRenderer.ts @@ -1174,7 +1174,7 @@ function updateDOMTextSize(node: DOMText, emitLoaded = true): void { * 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(props: IRendererTextNodeProps): boolean { +function isFontLoaded(node: DOMText): boolean { if (typeof document === 'undefined') { return true; } @@ -1186,10 +1186,14 @@ function isFontLoaded(props: IRendererTextNodeProps): boolean { ) { 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( - `${props.fontStyle} ${props.fontWeight} ${props.fontSize}px "${props.fontFamily}"`, - ); + return fonts.check(font); } catch { return true; } @@ -1976,6 +1980,8 @@ class DOMText extends DOMNode { /** 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, @@ -2003,7 +2009,7 @@ class DOMText extends DOMNode { * destroyed node too. */ measure(): boolean { - if (!elMap.has(this) || !isFontLoaded(this.props)) { + if (!elMap.has(this) || !isFontLoaded(this)) { return false; } updateDOMTextSize(this, false); @@ -2025,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); } @@ -2034,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); } @@ -2043,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); } @@ -2052,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/elementNode.ts b/src/core/elementNode.ts index 3644d153..d4e7ffdd 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -105,7 +105,10 @@ let textMeasureCount = 0; // set fontWaitingDue; the layout phase then measures them. const fontWaiting: ElementNode[] = []; let fontWaitingDue = false; -// Re-measures in one layout phase before the rest waits for the next run: +// 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). +let fontWaitingSweepAt = 64; +// 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; @@ -248,12 +251,24 @@ function runLayoutQueue(): void { measureQueuedTexts(); } } - if (isDev && textMeasureCount > 0) { - console.warn( - '[solid] Text sizes did not settle in ' + - MAX_TEXT_SWEEPS + - ' layout passes (a flex size that depends on a text that flex sizes); the rest waits for the next change.', - ); + 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.', + ); + } } } @@ -264,8 +279,12 @@ function runLayoutQueue(): void { */ function measureQueuedTexts(): void { for (let i = 0; i < textMeasureCount; i++) { - const t = textMeasureQueue[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; @@ -332,6 +351,19 @@ function measureFontWaiting(): void { 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; +} + /** * 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 @@ -1662,9 +1694,38 @@ export class ElementNode { _waitForFont(m: TextMeasure): void { m.waiting = true; (this.lng as IRendererTextNode).on('loaded', fontWaitHeard); + if (fontWaiting.length >= fontWaitingSweepAt) { + sweepFontWaiting(); + } fontWaiting.push(this); } + /** + * @internal After a layout Solid did not make (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; @@ -2299,7 +2360,17 @@ export class ElementNode { // 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 (isDev) { + 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.lng as IRendererTextNode).on('loaded', () => { + if (node._textSizeChanged() === true) { + enqueueLayout(node._parent!); + schedulePostMutationInFrame(); + } + }); + } else if (isDev) { (node.lng as IRendererTextNode).on('loaded', () => node._warnUnmeasuredLayout(), ); @@ -2940,6 +3011,9 @@ Object.defineProperties(ElementNode.prototype, { }, 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: { diff --git a/src/core/fontLoaded.ts b/src/core/fontLoaded.ts index 58985c77..cd1336ce 100644 --- a/src/core/fontLoaded.ts +++ b/src/core/fontLoaded.ts @@ -17,3 +17,13 @@ export function fontLoaded(): void { 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 33930549..69f1193b 100644 --- a/src/core/lightningInit.ts +++ b/src/core/lightningInit.ts @@ -3,7 +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 { fontLoaded } from './fontLoaded.js'; +import { fontFailed, fontLoaded } from './fontLoaded.js'; import { FontLoadOptions } from './intrinsicTypes.js'; export type SdfFontType = 'ssdf' | 'msdf'; @@ -132,10 +132,11 @@ function attachFonts(fonts: 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`). + // 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); + .then(fontLoaded, fontFailed); } // DOM — Web if ('fontUrl' in font && enableDomRenderer) { diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index cbcfe039..3885211b 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -1138,4 +1138,52 @@ describe('contract: Solid measures text before flex (1.7, stream T)', () => { ]); 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/layoutQueue.test.tsx b/tests/layoutQueue.test.tsx index 4769ebd6..519946ff 100644 --- a/tests/layoutQueue.test.tsx +++ b/tests/layoutQueue.test.tsx @@ -415,3 +415,102 @@ describe('post-mutation scheduling', () => { } }); }); + +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 last!: lng.ElementNode; + const dispose = renderer.render(() => ( + { + passes++; + // 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'); + dispose(); + 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/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index ea652596..de891d21 100644 --- a/tests/webgl/flex-text.test.tsx +++ b/tests/webgl/flex-text.test.tsx @@ -953,3 +953,35 @@ v.test( } }, ); + +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(); + }, +); From d6c19e8a4d93c392cbafdaaf927c40721bafe087 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:12:14 -0400 Subject: [PATCH 27/34] fix(text): a text layout prop's transition or animate() relays out its container (T1 review) T1 measured a text when its fontSize/lineHeight/width/height was written, but with a `transition` the write starts an animation: the measure saw the old size and the walk's layouts of the animated values reached nobody, so the container kept the old size while the text grew (sibling at 80.44 under a 140.88-wide text; 1.6: 150.88). While an animation of a text's layout props runs (started by _sendToLightningAnimatable or animate(), the controller kept on the text's TextMeasure record), the text hears `loaded` through one shared listener; the layout phase, in that frame, lays out the parent of each animating text whose size changed, and drops the texts whose animations stopped (they stop listening). Two walks per frame only while it animates, as in 1.6; a later text change walks once again. The list is swept of stopped or destroyed texts when it doubles. The development warning skips animating texts and names the cause it reports (a layout prop written or animated on el.lng). WebGL test: fontSize 30 -> 60 with a 600 ms transition, the sibling never overlaps the text in any frame (37 frames, 37 flex passes) and ends at 149.02 (139.02 + 10); a later text change walks once. RED before: the sibling stayed at 79.51. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9d8716a5dc691a434ea5fe9879ba967e66fb74d1) --- src/core/elementNode.ts | 172 +++++++++++++++++++++++++++++++-- tests/webgl/flex-text.test.tsx | 66 +++++++++++++ 2 files changed, 229 insertions(+), 9 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index d4e7ffdd..70e84db6 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -105,9 +105,18 @@ let textMeasureCount = 0; // 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). +// Texts whose layout props animate (a `transition`, or animate()): the walk +// lays out each animated value, so each hears `loaded` (a shared listener) +// while its animations run, and the layout phase, in the frame, lays out the +// parent of one whose size changed (1.6's result: two walks per frame while +// it animates). `animatingTextsDue`: one of them heard `loaded`. +const animatingTexts: ElementNode[] = []; +let animatingTextsDue = false; +// Lengths at which the two lists are next swept of texts that no longer +// wait: destroyed (nothing else takes them off while their font never +// loads), or whose animation stopped with no layout to tell. let fontWaitingSweepAt = 64; +let animatingSweepAt = 64; // 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. @@ -169,6 +178,9 @@ function runPostMutation() { if (fontWaitingDue === true) { measureFontWaiting(); } + if (animatingTextsDue === true) { + measureAnimatingTexts(); + } runLayoutQueue(); // Phase 3: focus. setFocus() may have evaluated forwardFocus pre-render @@ -364,6 +376,65 @@ function sweepFontWaiting(): void { fontWaitingSweepAt = kept * 2 > 64 ? kept * 2 : 64; } +/** `loaded` on an animating text (`_textLayoutAnimated`); shared by all. */ +function animatingTextHeard(): void { + animatingTextsDue = true; + schedulePostMutationInFrame(); +} + +/** + * The animating texts after a walk laid one out: the parent of each whose + * size changed is queued; one whose animations all stopped (or that was + * destroyed) stops listening and leaves the list. + */ +function measureAnimatingTexts(): void { + animatingTextsDue = false; + let kept = 0; + for (let i = 0; i < animatingTexts.length; i++) { + const t = animatingTexts[i]!; + if (t.destroyed !== true) { + if (t._textSizeChanged() === true) { + enqueueLayout(t._parent!); + } + if (t._textAnimating() === true) { + animatingTexts[kept++] = t; + continue; + } + } + t._stopTextAnimating(); + } + animatingTexts.length = kept; +} + +/** Drops the texts whose animations stopped without a layout to tell. */ +function sweepAnimating(): void { + let kept = 0; + for (let i = 0; i < animatingTexts.length; i++) { + const t = animatingTexts[i]!; + if (t.destroyed !== true && t._textAnimating() === true) { + animatingTexts[kept++] = t; + } else { + t._stopTextAnimating(); + } + } + animatingTexts.length = kept; + animatingSweepAt = 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 @@ -377,12 +448,18 @@ class TextMeasure { /** Width and height, as flex reads them, when last measured; NaN before. */ w: number; h: number; + /** In `animatingTexts`, listening to `loaded` (`_textLayoutAnimated`). */ + animating: boolean; + /** The animations of its layout props; null until it has had one. */ + animations: IAnimationController[] | null; constructor() { this.due = false; this.waiting = false; this.w = NaN; this.h = NaN; + this.animating = false; + this.animations = null; } } @@ -1444,11 +1521,21 @@ export class ElementNode { return true; } - (this.lng as INode).animateProp( + const controller = (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(controller); + } this._fireAnimationEvents(name, value, animationSettings); return true; } @@ -1478,10 +1565,14 @@ 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)) { + this._textLayoutAnimated(controller); + } + return controller; } chain(props: Partial, animationSettings?: AnimationSettings) { @@ -1670,6 +1761,7 @@ export class ElementNode { m === undefined || m.due === true || m.waiting === true || + m.animating === true || m.w !== m.w || this._parent === undefined || this._parent._requiresLayout !== true @@ -1679,7 +1771,7 @@ export class ElementNode { 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 text prop written on el.lng, or animated there, instead of on the element): its container keeps the old size.', + '[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, ); } @@ -1701,10 +1793,72 @@ export class ElementNode { } /** - * @internal After a layout Solid did not make (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. + * @internal An animation of a prop this text's layout reads started + * (`_sendToLightningAnimatable`, `animate()`): while it runs, each layout + * the walk makes of an animated value is heard (`loaded`), and its + * container laid out again in that frame, as 1.6's `loaded` listener did. + */ + _textLayoutAnimated(controller: IAnimationController): void { + if (this.rendered !== true) { + return; + } + const parent = this._parent; + if (parent === undefined || parent._requiresLayout !== true) { + return; + } + let m = this._text; + if (m === undefined) { + m = new TextMeasure(); + this._text = m; + } + let list = m.animations; + if (list === null) { + list = []; + m.animations = list; + } + if (list.indexOf(controller) === -1) { + list.push(controller); + } + if (m.animating === false) { + m.animating = true; + (this.lng as IRendererTextNode).on('loaded', animatingTextHeard); + if (animatingTexts.length >= animatingSweepAt) { + sweepAnimating(); + } + animatingTexts.push(this); + } + } + + /** + * @internal Whether an animation of this text's layout props has not + * stopped (running, scheduled or paused); drops the stopped ones. + */ + _textAnimating(): boolean { + const list = this._text!.animations!; + let kept = 0; + for (let i = 0; i < list.length; i++) { + const c = list[i]!; + if (c.state !== 'stopped') { + list[kept++] = c; + } + } + list.length = kept; + return kept > 0; + } + + /** @internal Stops hearing the animated layouts (`_textLayoutAnimated`). */ + _stopTextAnimating(): void { + const m = this._text!; + m.animating = false; + m.animations!.length = 0; + (this.lng as IRendererTextNode).off('loaded', animatingTextHeard); + } + + /** + * @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; diff --git a/tests/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index de891d21..7cd84d55 100644 --- a/tests/webgl/flex-text.test.tsx +++ b/tests/webgl/flex-text.test.tsx @@ -954,6 +954,72 @@ v.test( }, ); +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; + 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 () => { From d4931a81ca6cd558ea23a8012ca95022674adfdb Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:35:05 -0400 Subject: [PATCH 28/34] fix(text): never sweep the font-waiting list while it is being measured (T1 review 2) measureFontWaiting walks the list by index up to its starting length; a text whose font is still missing is appended again through _waitForFont, which swept the list once it reached its sweep length. The sweep moved entries under the loop: texts dropped off the list while still waiting (nothing measured them again until their next write), others were read twice, and reading past the compacted end threw (the rest of that post-mutation run, layout and focus, was skipped). _waitForFont now sweeps only outside measureFontWaiting (a flag, reset in a finally); the loop's own tail shift already drops what it measured. Tests (jsdom, document.fonts.check per family, fontLoaded() as loadFonts calls it, the DOM renderer's own re-measure held): 120 texts alternating two families, 100 alternating, 100 then 20; one family loads, then the other. Each alone was RED: texts still waiting after their font loaded, and a TypeError reading '_text' for 100 + 20. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f51c63c2e7f8bd07a3e77bc134bcac87eea86996) --- src/core/elementNode.ts | 55 +++++++++------ tests/layoutQueue.test.tsx | 135 +++++++++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+), 21 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index 70e84db6..e37bdf30 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -117,6 +117,9 @@ let animatingTextsDue = false; // loads), or whose animation stopped with no layout to tell. let fontWaitingSweepAt = 64; let animatingSweepAt = 64; +// Set while measureFontWaiting walks fontWaiting: _waitForFont appends to +// it then, and must not sweep it under the loop. +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. @@ -333,27 +336,34 @@ function fontWaitHeard(): void { function measureFontWaiting(): void { fontWaitingDue = false; const n = fontWaiting.length; - 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); + // 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; @@ -1786,7 +1796,10 @@ export class ElementNode { _waitForFont(m: TextMeasure): void { m.waiting = true; (this.lng as IRendererTextNode).on('loaded', fontWaitHeard); - if (fontWaiting.length >= fontWaitingSweepAt) { + if ( + measuringFontWaiting === false && + fontWaiting.length >= fontWaitingSweepAt + ) { sweepFontWaiting(); } fontWaiting.push(this); diff --git a/tests/layoutQueue.test.tsx b/tests/layoutQueue.test.tsx index 519946ff..c2beb763 100644 --- a/tests/layoutQueue.test.tsx +++ b/tests/layoutQueue.test.tsx @@ -19,6 +19,8 @@ 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'; +// Internal (not re-exported): what loadFonts() calls when a font loaded. +import { fontLoaded } from '../src/core/fontLoaded.js'; const CHAR_W = 10; const LINE_H = 20; @@ -514,3 +516,136 @@ describe('text measurement in the layout phase', () => { dispose(); }); }); + +describe('texts that wait for their font', () => { + /** + * `document.fonts.check` per family: a text waits (measure() false) while + * its family is not in `loaded`. Returns the families' set and a restore. + */ + 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]!); + }; + // Fonts loading: the DOM renderer's own re-measure waits for `ready`, + // so only Solid's font-loaded pass (fontLoaded) measures the texts. + 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; + }, + }; + } + + /** Whether Solid still waits for the font of each text. */ + const waiting = (texts: lng.ElementNode[]) => + texts.map( + (t) => + (t as unknown as { _text?: { waiting: boolean } })._text?.waiting === + true, + ); + + /** 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; + }, + }; + } + + function renderTexts(families: string[]) { + const texts: lng.ElementNode[] = []; + const dispose = renderer.render(() => ( + + + {(family, i) => ( + + (texts[i()] = el)} fontFamily={family}> + Hello + + + )} + + + )); + return { texts, dispose }; + } + + // Many texts wait (an app that renders before loadFonts() resolves), in + // two families; one family loads while the other is still missing: the + // texts of the missing one wait again while the list is being measured. + // Before fix round 2 the list was swept of the measured ones meanwhile + // (once it reached its sweep length, which grows with the list, so each + // case shows it when run alone). + // + // The list is module state, kept between tests: the cases assert the + // outcome, whatever the sweep length is when they start. + 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')), + ], + ]; + 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(); + try { + const { texts, dispose } = renderTexts(families); + await settle(); + expect(texts.length).toBe(families.length); + expect(waiting(texts).every((w) => w)).toBe(true); + + fonts.loaded.add('FA'); + fontLoaded(); + await settle(); + expect(caught.errors).toEqual([]); + expect(waiting(texts)).toEqual(families.map((f) => f === 'FB')); + + fonts.loaded.add('FB'); + fontLoaded(); + await settle(); + expect(caught.errors).toEqual([]); + expect(waiting(texts).some((w) => w)).toBe(false); + dispose(); + } finally { + caught.restore(); + fonts.restore(); + } + }); + } +}); From 28f1b34578f384c91f4a8a805768ff679a362aa4 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:35:38 -0400 Subject: [PATCH 29/34] fix(text): a text Solid animated hears its layouts for its lifetime (T1 review 2) Round 1 tracked the controllers of a text's layout-prop animations and stopped listening once they were all 'stopped'. A renderer Animation is 'stopped' until start() and again when it finishes, and el.animate() hands the controller to the app: one started after the text's next layout, or started again after it finished, animated with nobody listening, so the sibling stayed put while the text grew (1.6's persistent listener handled both). Once Solid has animated a prop a text's layout reads through the element (a `transition`, el.animate(), chain()), the text keeps one `loaded` listener for its lifetime (`_listenTextLoaded`, a closure made once per text, also used by every measured text in DOM builds): a layout at a size Solid did not measure lays the container out in that frame; a layout Solid measured changes nothing and asks for no second walk. The module list, the controller tracking and their sweeps are gone: nothing but the renderer node holds the listener, so a destroyed text (mid-animation too) is not retained (review 2, minor 3). DOM renderer: `destroyed` is true for the descendants of a destroyed node too, as renderer v2 destroys the subtree (the font-waiting sweep reads it). WebGL tests: el.animate() started again after it finished, and started after the text laid out again; RED before (sibling at 79.51; 67.42 under a 124.84-wide text). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 44a15a383157b36fb75524601a7e82679e7fd7fe) --- src/core/elementNode.ts | 163 +++++++++------------------------ tests/webgl/flex-text.test.tsx | 61 ++++++++++++ 2 files changed, 103 insertions(+), 121 deletions(-) diff --git a/src/core/elementNode.ts b/src/core/elementNode.ts index e37bdf30..219eb598 100644 --- a/src/core/elementNode.ts +++ b/src/core/elementNode.ts @@ -105,20 +105,10 @@ let textMeasureCount = 0; // set fontWaitingDue; the layout phase then measures them. const fontWaiting: ElementNode[] = []; let fontWaitingDue = false; -// Texts whose layout props animate (a `transition`, or animate()): the walk -// lays out each animated value, so each hears `loaded` (a shared listener) -// while its animations run, and the layout phase, in the frame, lays out the -// parent of one whose size changed (1.6's result: two walks per frame while -// it animates). `animatingTextsDue`: one of them heard `loaded`. -const animatingTexts: ElementNode[] = []; -let animatingTextsDue = false; -// Lengths at which the two lists are next swept of texts that no longer -// wait: destroyed (nothing else takes them off while their font never -// loads), or whose animation stopped with no layout to tell. +// 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 animatingSweepAt = 64; -// Set while measureFontWaiting walks fontWaiting: _waitForFont appends to -// it then, and must not sweep it under the loop. 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 @@ -181,9 +171,6 @@ function runPostMutation() { if (fontWaitingDue === true) { measureFontWaiting(); } - if (animatingTextsDue === true) { - measureAnimatingTexts(); - } runLayoutQueue(); // Phase 3: focus. setFocus() may have evaluated forwardFocus pre-render @@ -386,51 +373,6 @@ function sweepFontWaiting(): void { fontWaitingSweepAt = kept * 2 > 64 ? kept * 2 : 64; } -/** `loaded` on an animating text (`_textLayoutAnimated`); shared by all. */ -function animatingTextHeard(): void { - animatingTextsDue = true; - schedulePostMutationInFrame(); -} - -/** - * The animating texts after a walk laid one out: the parent of each whose - * size changed is queued; one whose animations all stopped (or that was - * destroyed) stops listening and leaves the list. - */ -function measureAnimatingTexts(): void { - animatingTextsDue = false; - let kept = 0; - for (let i = 0; i < animatingTexts.length; i++) { - const t = animatingTexts[i]!; - if (t.destroyed !== true) { - if (t._textSizeChanged() === true) { - enqueueLayout(t._parent!); - } - if (t._textAnimating() === true) { - animatingTexts[kept++] = t; - continue; - } - } - t._stopTextAnimating(); - } - animatingTexts.length = kept; -} - -/** Drops the texts whose animations stopped without a layout to tell. */ -function sweepAnimating(): void { - let kept = 0; - for (let i = 0; i < animatingTexts.length; i++) { - const t = animatingTexts[i]!; - if (t.destroyed !== true && t._textAnimating() === true) { - animatingTexts[kept++] = t; - } else { - t._stopTextAnimating(); - } - } - animatingTexts.length = kept; - animatingSweepAt = kept * 2 > 64 ? kept * 2 : 64; -} - /** The props a text's layout reads that an animation can change. */ function animatesTextLayout(props: Partial): boolean { return ( @@ -458,18 +400,18 @@ class TextMeasure { /** Width and height, as flex reads them, when last measured; NaN before. */ w: number; h: number; - /** In `animatingTexts`, listening to `loaded` (`_textLayoutAnimated`). */ - animating: boolean; - /** The animations of its layout props; null until it has had one. */ - animations: IAnimationController[] | null; + /** + * 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.animating = false; - this.animations = null; + this.listening = false; } } @@ -1531,7 +1473,7 @@ export class ElementNode { return true; } - const controller = (this.lng as INode).animateProp( + (this.lng as INode).animateProp( name, value, animationSettings || this.animationSettings || {}, @@ -1544,7 +1486,7 @@ export class ElementNode { name === 'w' || name === 'h') ) { - this._textLayoutAnimated(controller); + this._textLayoutAnimated(); } this._fireAnimationEvents(name, value, animationSettings); return true; @@ -1580,7 +1522,9 @@ export class ElementNode { animationSettings || this.animationSettings || {}, ); if (this._type === NodeType.TextNode && animatesTextLayout(props)) { - this._textLayoutAnimated(controller); + // Started now or later, again or not at all: the text hears its + // layouts from now on (`_listenTextLoaded`). + this._textLayoutAnimated(); } return controller; } @@ -1771,7 +1715,7 @@ export class ElementNode { m === undefined || m.due === true || m.waiting === true || - m.animating === true || + m.listening === true || m.w !== m.w || this._parent === undefined || this._parent._requiresLayout !== true @@ -1806,12 +1750,14 @@ export class ElementNode { } /** - * @internal An animation of a prop this text's layout reads started - * (`_sendToLightningAnimatable`, `animate()`): while it runs, each layout - * the walk makes of an animated value is heard (`loaded`), and its - * container laid out again in that frame, as 1.6's `loaded` listener did. + * @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(controller: IAnimationController): void { + _textLayoutAnimated(): void { if (this.rendered !== true) { return; } @@ -1819,52 +1765,32 @@ export class ElementNode { 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; } - let list = m.animations; - if (list === null) { - list = []; - m.animations = list; - } - if (list.indexOf(controller) === -1) { - list.push(controller); - } - if (m.animating === false) { - m.animating = true; - (this.lng as IRendererTextNode).on('loaded', animatingTextHeard); - if (animatingTexts.length >= animatingSweepAt) { - sweepAnimating(); - } - animatingTexts.push(this); + if (m.listening === true) { + return; } - } - - /** - * @internal Whether an animation of this text's layout props has not - * stopped (running, scheduled or paused); drops the stopped ones. - */ - _textAnimating(): boolean { - const list = this._text!.animations!; - let kept = 0; - for (let i = 0; i < list.length; i++) { - const c = list[i]!; - if (c.state !== 'stopped') { - list[kept++] = c; + m.listening = true; + (this.lng as IRendererTextNode).on('loaded', () => { + if (this._textSizeChanged() === true) { + enqueueLayout(this._parent!); + schedulePostMutationInFrame(); } - } - list.length = kept; - return kept > 0; - } - - /** @internal Stops hearing the animated layouts (`_textLayoutAnimated`). */ - _stopTextAnimating(): void { - const m = this._text!; - m.animating = false; - m.animations!.length = 0; - (this.lng as IRendererTextNode).off('loaded', animatingTextHeard); + }); } /** @@ -2531,12 +2457,7 @@ export class ElementNode { // 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.lng as IRendererTextNode).on('loaded', () => { - if (node._textSizeChanged() === true) { - enqueueLayout(node._parent!); - schedulePostMutationInFrame(); - } - }); + node._listenTextLoaded(); } else if (isDev) { (node.lng as IRendererTextNode).on('loaded', () => node._warnUnmeasuredLayout(), diff --git a/tests/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index 7cd84d55..e1f30839 100644 --- a/tests/webgl/flex-text.test.tsx +++ b/tests/webgl/flex-text.test.tsx @@ -1051,3 +1051,64 @@ v.test( 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(); + }, +); From 173f8c0034250bdd10c8032553f52e2f419a3247 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Sat, 3 Oct 2026 22:53:25 -0400 Subject: [PATCH 30/34] test(text): font-waiting cases in a module instance of their own (T1 review 3) The three font-waiting regression cases ran in layoutQueue.test.tsx on the shared module instance (vitest isolate: false). The 16-sweep test before them left its never-settling onLayout running; its text writes scheduled the DOM renderer's re-measure timer, which flushed the new cases' texts and woke the waiting list during render, growing its sweep length past what the mixed pass reached: with the guard removed the cases still passed in a file or suite run. - tests/fontWaiting.test.ts: each case imports a fresh @solidtv/solid (vi.resetModules) with its own DOM renderer, builds its tree with that instance's ElementNode (no JSX: the JSX runtime is the shared one), and asserts the precondition that no waiting text heard `loaded` before fontLoaded(). With the _waitForFont guard removed, all three fail in the file run and in the full suite (the 100 + 20 case with a TypeError); with it, they pass. - The 16-sweep test stops its loop and lets the DOM re-measure timer run before and after disposing its container. - Two test type fixes (tests/tsconfig.json) in contract-text and flex-text. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 5a47510c24992a334e9529334889c0474b8d643e) --- tests/contract-text.test.tsx | 4 +- tests/fontWaiting.test.ts | 178 +++++++++++++++++++++++++++++++++ tests/layoutQueue.test.tsx | 143 ++------------------------ tests/webgl/flex-text.test.tsx | 2 +- 4 files changed, 189 insertions(+), 138 deletions(-) create mode 100644 tests/fontWaiting.test.ts diff --git a/tests/contract-text.test.tsx b/tests/contract-text.test.tsx index 3885211b..e04e9c65 100644 --- a/tests/contract-text.test.tsx +++ b/tests/contract-text.test.tsx @@ -1115,8 +1115,8 @@ describe('contract: Solid measures text before flex (1.7, stream T)', () => { 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 index c2beb763..a8d9f485 100644 --- a/tests/layoutQueue.test.tsx +++ b/tests/layoutQueue.test.tsx @@ -19,8 +19,6 @@ 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'; -// Internal (not re-exported): what loadFonts() calls when a font loaded. -import { fontLoaded } from '../src/core/fontLoaded.js'; const CHAR_W = 10; const LINE_H = 20; @@ -425,6 +423,7 @@ describe('text measurement in the layout phase', () => { let passes = 0; let t!: lng.ElementNode; let toggle = false; + let looping = true; let last!: lng.ElementNode; const dispose = renderer.render(() => ( { gap={10} onLayout={() => { 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'; @@ -448,7 +448,13 @@ describe('text measurement in the layout phase', () => { 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. @@ -516,136 +522,3 @@ describe('text measurement in the layout phase', () => { dispose(); }); }); - -describe('texts that wait for their font', () => { - /** - * `document.fonts.check` per family: a text waits (measure() false) while - * its family is not in `loaded`. Returns the families' set and a restore. - */ - 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]!); - }; - // Fonts loading: the DOM renderer's own re-measure waits for `ready`, - // so only Solid's font-loaded pass (fontLoaded) measures the texts. - 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; - }, - }; - } - - /** Whether Solid still waits for the font of each text. */ - const waiting = (texts: lng.ElementNode[]) => - texts.map( - (t) => - (t as unknown as { _text?: { waiting: boolean } })._text?.waiting === - true, - ); - - /** 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; - }, - }; - } - - function renderTexts(families: string[]) { - const texts: lng.ElementNode[] = []; - const dispose = renderer.render(() => ( - - - {(family, i) => ( - - (texts[i()] = el)} fontFamily={family}> - Hello - - - )} - - - )); - return { texts, dispose }; - } - - // Many texts wait (an app that renders before loadFonts() resolves), in - // two families; one family loads while the other is still missing: the - // texts of the missing one wait again while the list is being measured. - // Before fix round 2 the list was swept of the measured ones meanwhile - // (once it reached its sweep length, which grows with the list, so each - // case shows it when run alone). - // - // The list is module state, kept between tests: the cases assert the - // outcome, whatever the sweep length is when they start. - 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')), - ], - ]; - 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(); - try { - const { texts, dispose } = renderTexts(families); - await settle(); - expect(texts.length).toBe(families.length); - expect(waiting(texts).every((w) => w)).toBe(true); - - fonts.loaded.add('FA'); - fontLoaded(); - await settle(); - expect(caught.errors).toEqual([]); - expect(waiting(texts)).toEqual(families.map((f) => f === 'FB')); - - fonts.loaded.add('FB'); - fontLoaded(); - await settle(); - expect(caught.errors).toEqual([]); - expect(waiting(texts).some((w) => w)).toBe(false); - dispose(); - } finally { - caught.restore(); - fonts.restore(); - } - }); - } -}); diff --git a/tests/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index e1f30839..4cbf6bb5 100644 --- a/tests/webgl/flex-text.test.tsx +++ b/tests/webgl/flex-text.test.tsx @@ -982,7 +982,7 @@ v.test( const overlaps: number[][] = []; const sampled: number[] = []; const sample = () => { - const w = t.lng.w; + const w = t.lng.w as number; sampled.push(w); if (after.x < w + 10 - 0.001) { overlaps.push([w, after.x]); From 4449ed142ef6d1f8914cbae941a6b2a72f8c1dfc Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Thu, 19 Nov 2026 14:59:13 -0500 Subject: [PATCH 31/34] docs(layout): one flex engine; VITE_USE_NEW_FLEX is ignored From 46ba87e on the 1.8 branch (the layout.md part only), with the version and the migration pointer adjusted for main. Co-Authored-By: Claude Opus 5.5 --- docs/flow/layout.md | 38 ++++++++++++++++---------------------- 1 file changed, 16 insertions(+), 22 deletions(-) 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: ![Flex Grow](../images/flexGrow-multiple.png) -### 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 From ebb6baf672466e1d0464783cffd751f0993b2372 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Thu, 19 Nov 2026 15:00:09 -0500 Subject: [PATCH 32/34] test(childList): a child inserted before itself stays in place (B19) main's child-list test pinned the 1.6 result (appended). Stream N's B19 fix keeps the node where it is, as DOM insertBefore does, so Solid's adjacent-item swap no longer sends the item to the end. Co-Authored-By: Claude Opus 5.5 --- tests/childList.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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', () => { From 4d437e1ccf88e6255cc1108aeac1fa70aeb09e02 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Thu, 19 Nov 2026 15:01:51 -0500 Subject: [PATCH 33/34] test(webgl): flex-text imports renderer for the walk counts Lost while merging stream T's version of the test with main's. Co-Authored-By: Claude Opus 5.5 --- tests/webgl/flex-text.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/webgl/flex-text.test.tsx b/tests/webgl/flex-text.test.tsx index 4cbf6bb5..ff8cf139 100644 --- a/tests/webgl/flex-text.test.tsx +++ b/tests/webgl/flex-text.test.tsx @@ -35,7 +35,7 @@ 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( From 3370fe679398867b179273d0df4490d6ff94e9b6 Mon Sep 17 00:00:00 2001 From: Chris Lorenzo Date: Fri, 20 Nov 2026 10:03:35 -0500 Subject: [PATCH 34/34] test(virtual): hand the DOM animation loop to the rAF stub before the first press The "animations on" tests of VirtualRow and VirtualGrid stub requestAnimationFrame and then give each press four setTimeout(0) turns. Animations are on by default, so an earlier test's scroll transitions can leave the DOM renderer's loop with animationFrameRequested set and a jsdom frame up to ~16 ms away. Until that frame runs the loop requests no other, the stub is never called, and the press's transition does not move: CI saw y stay at 40 on the first ArrowDown. With isolate: false it depends on the file order (reproduced with `--maxWorkers=1 --sequence.shuffle.files --sequence.seed=3`, and seed 4 for the VirtualRow test). Both tests now wait one jsdom frame after stubbing. A leftover frame runs first and its next request goes to the stub. The race was already on main; this branch's test set changed the order that exposed it. Co-Authored-By: Claude Opus 5.5 --- tests/contract-virtual-grid.test.tsx | 6 ++++++ tests/contract-virtual.test.tsx | 6 ++++++ 2 files changed, 12 insertions(+) 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