From d9c3b5ba793d58252bc5a5553537c3adea678f85 Mon Sep 17 00:00:00 2001 From: Suresh Kumar Gangumalla Date: Tue, 7 Apr 2026 14:24:14 +0530 Subject: [PATCH 01/34] Added `hoverable` config property Component's hoverable configuration property will alter holder node `interactive` flag Signed-off-by: Suresh Kumar Gangumalla --- index.d.ts | 10 +++++++++- src/engines/L3/element.test.js | 24 ++++++++++++++++++++++++ src/lib/codegenerator/generator.js | 4 +++- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/index.d.ts b/index.d.ts index ef8a22f3..ef2782e3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -687,6 +687,14 @@ declare module '@lightningjs/blits' { * Watchers for changes to state variables, props or computed properties */ watch?: W & ComponentContext + /** + * Whether the component's holder node is interactive for mouse hit-testing. + * When set to `false`, the renderer skips this component's node during + * `getNodeFromPosition()`, allowing pointer events to pass through to + * the node underneath (e.g. a tile behind a focus ring overlay). + * Defaults to `true`. + */ + hoverable?: boolean } export interface RouterHooks { @@ -1353,7 +1361,7 @@ declare module '@lightningjs/blits' { M extends Methods, C extends Computed, W extends Watch>(name: string, config: ComponentConfig) : ComponentFactory - /** + /** * Blits Launch */ Launch(App: ComponentFactory, target: HTMLElement | String, settings?: Settings) : void diff --git a/src/engines/L3/element.test.js b/src/engines/L3/element.test.js index 09e8e59b..df8a598c 100644 --- a/src/engines/L3/element.test.js +++ b/src/engines/L3/element.test.js @@ -1255,3 +1255,27 @@ test('Element - Set maxheight property', (assert) => { assert.equal(el.props.props['contain'], 'height', 'maxheight should set contain to height') assert.end() }) + +test('Element - holder true sets interactive to true', (assert) => { + assert.capture(renderer, 'createNode', () => new EventEmitter()) + const el = element({ parent: { node: { w: 1920, h: 1080 } } }, {}) + el.populate({ parent: { node: new EventEmitter() }, holder: true }) + assert.equal( + el.props.props['interactive'], + true, + 'interactive should be true when holder is true' + ) + assert.end() +}) + +test('Element - holder false sets interactive to false', (assert) => { + assert.capture(renderer, 'createNode', () => new EventEmitter()) + const el = element({ parent: { node: { w: 1920, h: 1080 } } }, {}) + el.populate({ parent: { node: new EventEmitter() }, holder: false }) + assert.equal( + el.props.props['interactive'], + false, + 'interactive should be false when holder is false (hoverable: false)' + ) + assert.end() +}) diff --git a/src/lib/codegenerator/generator.js b/src/lib/codegenerator/generator.js index f8ab03bc..3b3755c9 100644 --- a/src/lib/codegenerator/generator.js +++ b/src/lib/codegenerator/generator.js @@ -187,7 +187,9 @@ const generateElementCode = function ( } if (options.holder) { - renderCode.push(`elementConfigs[${counter}]['holder'] = true`) + renderCode.push( + `elementConfigs[${counter}]['holder'] = cmps[${counter}] === undefined || cmps[${counter}][Symbol.for('config')].hoverable !== false` + ) } Object.keys(templateObject).forEach((key) => { From baba0ec5a80836559c57a193f1bb8ccc8ef1a826 Mon Sep 17 00:00:00 2001 From: Suresh Kumar Gangumalla Date: Wed, 15 Apr 2026 18:10:11 +0530 Subject: [PATCH 02/34] Marking component as non-interactive based on hover/unhover if component does not registered hover/unhover hooks in component configuation then that component subjected to non interactive by setting `interactive` on holder node to false. Signed-off-by: Suresh Kumar Gangumalla --- index.d.ts | 9 +------- src/engines/L3/element.js | 11 +++++++++- src/engines/L3/element.test.js | 33 +++++++++++++++++++++++------- src/lib/codegenerator/generator.js | 4 +--- src/lib/hooks.js | 4 ++++ 5 files changed, 42 insertions(+), 19 deletions(-) diff --git a/index.d.ts b/index.d.ts index ef2782e3..e9ddc41e 100644 --- a/index.d.ts +++ b/index.d.ts @@ -687,14 +687,7 @@ declare module '@lightningjs/blits' { * Watchers for changes to state variables, props or computed properties */ watch?: W & ComponentContext - /** - * Whether the component's holder node is interactive for mouse hit-testing. - * When set to `false`, the renderer skips this component's node during - * `getNodeFromPosition()`, allowing pointer events to pass through to - * the node underneath (e.g. a tile behind a focus ring overlay). - * Defaults to `true`. - */ - hoverable?: boolean + } export interface RouterHooks { diff --git a/src/engines/L3/element.js b/src/engines/L3/element.js index 1f2ef3e3..3ed0348a 100644 --- a/src/engines/L3/element.js +++ b/src/engines/L3/element.js @@ -23,6 +23,7 @@ import { Log } from '../../lib/log.js' import symbols from '../../lib/symbols.js' import Settings from '../../settings.js' import shaders from '../../lib/shaders/shaders.js' +import { hasHook } from '../../lib/hooks.js' const holderComponentMap = new WeakMap() @@ -528,7 +529,15 @@ const propsTransformer = { } }, set holder(v) { - this.props['interactive'] = v + const identifier = + this.element && this.element.component + ? this.element.component[symbols.identifier] + : undefined + if (identifier !== undefined) { + this.props['interactive'] = hasHook('hover', identifier) || hasHook('unhover', identifier) + } else { + this.props['interactive'] = v + } }, } diff --git a/src/engines/L3/element.test.js b/src/engines/L3/element.test.js index df8a598c..3f917341 100644 --- a/src/engines/L3/element.test.js +++ b/src/engines/L3/element.test.js @@ -23,6 +23,7 @@ import { initLog } from '../../lib/log.js' import symbols from '../../lib/symbols.js' import sinon from 'sinon' import shaders from '../../lib/shaders/shaders.js' // Changed from './shaderLoader.js' +import { registerHooks } from '../../lib/hooks.js' initLog() @@ -1256,26 +1257,44 @@ test('Element - Set maxheight property', (assert) => { assert.end() }) -test('Element - holder true sets interactive to true', (assert) => { +test('Element - holder true sets interactive to true when component has hover hook', (assert) => { assert.capture(renderer, 'createNode', () => new EventEmitter()) - const el = element({ parent: { node: { w: 1920, h: 1080 } } }, {}) + const component = { [symbols.identifier]: 'test-hover-1' } + registerHooks({ hover: () => {} }, component[symbols.identifier]) + const el = element({ parent: { node: { w: 1920, h: 1080 } } }, component) el.populate({ parent: { node: new EventEmitter() }, holder: true }) assert.equal( el.props.props['interactive'], true, - 'interactive should be true when holder is true' + 'interactive should be true when component has hover hook' ) assert.end() }) -test('Element - holder false sets interactive to false', (assert) => { +test('Element - holder true sets interactive to true when component has unhover hook', (assert) => { assert.capture(renderer, 'createNode', () => new EventEmitter()) - const el = element({ parent: { node: { w: 1920, h: 1080 } } }, {}) - el.populate({ parent: { node: new EventEmitter() }, holder: false }) + const component = { [symbols.identifier]: 'test-unhover-1' } + registerHooks({ unhover: () => {} }, component[symbols.identifier]) + const el = element({ parent: { node: { w: 1920, h: 1080 } } }, component) + el.populate({ parent: { node: new EventEmitter() }, holder: true }) + assert.equal( + el.props.props['interactive'], + true, + 'interactive should be true when component has unhover hook' + ) + assert.end() +}) + +test('Element - holder true sets interactive to false when component has no hover/unhover hooks', (assert) => { + assert.capture(renderer, 'createNode', () => new EventEmitter()) + const component = { [symbols.identifier]: 'test-no-hooks-1' } + registerHooks({}, component[symbols.identifier]) + const el = element({ parent: { node: { w: 1920, h: 1080 } } }, component) + el.populate({ parent: { node: new EventEmitter() }, holder: true }) assert.equal( el.props.props['interactive'], false, - 'interactive should be false when holder is false (hoverable: false)' + 'interactive should be false when component has no hover/unhover hooks' ) assert.end() }) diff --git a/src/lib/codegenerator/generator.js b/src/lib/codegenerator/generator.js index 3b3755c9..f8ab03bc 100644 --- a/src/lib/codegenerator/generator.js +++ b/src/lib/codegenerator/generator.js @@ -187,9 +187,7 @@ const generateElementCode = function ( } if (options.holder) { - renderCode.push( - `elementConfigs[${counter}]['holder'] = cmps[${counter}] === undefined || cmps[${counter}][Symbol.for('config')].hoverable !== false` - ) + renderCode.push(`elementConfigs[${counter}]['holder'] = true`) } Object.keys(templateObject).forEach((key) => { diff --git a/src/lib/hooks.js b/src/lib/hooks.js index f0a18c80..1f8e439e 100644 --- a/src/lib/hooks.js +++ b/src/lib/hooks.js @@ -57,3 +57,7 @@ export const registerHooks = (hooks = {}, identifier) => { if (typeof hooks[hook] === 'function') cbs[identifier][hook] = hooks[hook] }) } + +export const hasHook = (hook, identifier) => { + return !!(cbs[identifier] && cbs[identifier][hook]) +} From 6fdcd57149b24aadd8ac7f407ea6170c7e49d4cc Mon Sep 17 00:00:00 2001 From: Suresh Kumar Gangumalla Date: Thu, 16 Apr 2026 11:29:20 +0530 Subject: [PATCH 03/34] Addressed review comments Signed-off-by: Suresh Kumar Gangumalla --- src/engines/L3/element.js | 11 ++--------- src/lib/hooks.js | 2 +- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/src/engines/L3/element.js b/src/engines/L3/element.js index 3ed0348a..be3f2fbf 100644 --- a/src/engines/L3/element.js +++ b/src/engines/L3/element.js @@ -529,15 +529,8 @@ const propsTransformer = { } }, set holder(v) { - const identifier = - this.element && this.element.component - ? this.element.component[symbols.identifier] - : undefined - if (identifier !== undefined) { - this.props['interactive'] = hasHook('hover', identifier) || hasHook('unhover', identifier) - } else { - this.props['interactive'] = v - } + const identifier = this.element.component[symbols.identifier] + this.props['interactive'] = hasHook('hover', identifier) || hasHook('unhover', identifier) }, } diff --git a/src/lib/hooks.js b/src/lib/hooks.js index 1f8e439e..5bb45cf0 100644 --- a/src/lib/hooks.js +++ b/src/lib/hooks.js @@ -59,5 +59,5 @@ export const registerHooks = (hooks = {}, identifier) => { } export const hasHook = (hook, identifier) => { - return !!(cbs[identifier] && cbs[identifier][hook]) + return cbs[identifier] !== undefined && hook in cbs[identifier] } From a7bbec4a0b9698c5cea2206cf21bd2d79d7f0e24 Mon Sep 17 00:00:00 2001 From: Suresh Kumar Gangumalla Date: Thu, 23 Apr 2026 17:12:49 +0530 Subject: [PATCH 04/34] Detecting $isHovered from template Detecting $isHovered from template and checking whether component holder node should be interactive or not based on $isHovered or hover/unhover hooks. Signed-off-by: Suresh Kumar Gangumalla --- src/application.js | 1 + src/component.js | 10 ++++++++++ src/engines/L3/element.js | 4 +--- src/lib/codegenerator/generator.js | 7 +++++-- src/lib/precompiler/precompiler.js | 2 +- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/application.js b/src/application.js index a10651d7..d6cf74f2 100644 --- a/src/application.js +++ b/src/application.js @@ -165,6 +165,7 @@ const Application = (config) => { if (node === null) { currentComponent = undefined + currentNode = null Hover.clear() return } diff --git a/src/component.js b/src/component.js index 1999ff2a..022b7c31 100644 --- a/src/component.js +++ b/src/component.js @@ -499,6 +499,16 @@ const Component = (name = required('name'), config = required('config')) => { // To determine whether dynamic component is actual Blits component or not factory[symbols.isComponent] = true + // Getter to determine if the component needs interactive hover support + Object.defineProperty(factory, 'needsInteractive', { + get() { + return ( + (config.hooks && !!(config.hooks.hover || config.hooks.unhover)) || + !!(config.code && config.code.usesHoverState) + ) + }, + }) + return factory } diff --git a/src/engines/L3/element.js b/src/engines/L3/element.js index be3f2fbf..1f2ef3e3 100644 --- a/src/engines/L3/element.js +++ b/src/engines/L3/element.js @@ -23,7 +23,6 @@ import { Log } from '../../lib/log.js' import symbols from '../../lib/symbols.js' import Settings from '../../settings.js' import shaders from '../../lib/shaders/shaders.js' -import { hasHook } from '../../lib/hooks.js' const holderComponentMap = new WeakMap() @@ -529,8 +528,7 @@ const propsTransformer = { } }, set holder(v) { - const identifier = this.element.component[symbols.identifier] - this.props['interactive'] = hasHook('hover', identifier) || hasHook('unhover', identifier) + this.props['interactive'] = v }, } diff --git a/src/lib/codegenerator/generator.js b/src/lib/codegenerator/generator.js index f8ab03bc..d54eb37c 100644 --- a/src/lib/codegenerator/generator.js +++ b/src/lib/codegenerator/generator.js @@ -87,6 +87,8 @@ export default function (templateObject = { children: [] }, devMode = false) { }, skips} `) + const renderCodeString = ctx.renderCode.join('\n') + return { render: new Function( 'parent', @@ -96,7 +98,7 @@ export default function (templateObject = { children: [] }, devMode = false) { 'effect', 'getRaw', 'Log', - ctx.renderCode.join('\n') + renderCodeString ), effects: ctx.effectsCode.map( (code) => @@ -112,6 +114,7 @@ export default function (templateObject = { children: [] }, devMode = false) { ) ), context: ctx.context, + usesHoverState: renderCodeString.includes('.$isHovered'), } } @@ -187,7 +190,7 @@ const generateElementCode = function ( } if (options.holder) { - renderCode.push(`elementConfigs[${counter}]['holder'] = true`) + renderCode.push(`elementConfigs[${counter}]['holder'] = cmps[${counter}].needsInteractive`) } Object.keys(templateObject).forEach((key) => { diff --git a/src/lib/precompiler/precompiler.js b/src/lib/precompiler/precompiler.js index 7552b20f..d11d511c 100644 --- a/src/lib/precompiler/precompiler.js +++ b/src/lib/precompiler/precompiler.js @@ -55,7 +55,7 @@ export default (source, filePath, mode) => { // Insert the code in the component using the 'code' key, replacing the template key const replacement = `/* eslint-disable no-unused-vars */ \ncode: { render: ${code.render.toString()}, effects: [${code.effects.map( (fn) => fn.toString() - )}], context: {}}` + )}], context: {}, usesHoverState: ${code.usesHoverState}}` // MagicString tracks all changes automatically, no offset needed s.overwrite(templateStartIndex, templateEndIndex, replacement) From cde97bf91acee32dba2702d7450178b7eb8f6eac Mon Sep 17 00:00:00 2001 From: Suresh Kumar Gangumalla Date: Fri, 24 Apr 2026 17:35:02 +0530 Subject: [PATCH 05/34] Handled $isHovered and this.$isHovered from template and from JS layer detecting whether any component holding reference to $isHovered then marking that component's holder node as interactive otherwise non-interactive For router page components, holder node will be created by router not code-generator like regular children component's inside a page component. Router page components are two types, lazy import and normal direct import. We can't alter (even we have alter also renderer doesn't remove/add it from hierarchy pattern) any node interactivity once it created so for normal import we can invoke needsInteractity function in component's factory which will return whether component's holder node need to be marked interactive or not based on folliwng conditions 1. Existance of hover/unhover hook in component config 2. Existance of $isHovered in template which will be inspected at pre-compile or run time compilation 3. Existance of this.$isHovered in JS layer of component This step is challening, in users opted for pre-compilation, it will be like finding existance of this.$isHovered in a source code If not, we will loop through all JS layer functions and stringy then look for this.$isHovered. So, finally dynamic imported router page component's holder node always interactive. Signed-off-by: Suresh Kumar Gangumalla --- index.d.ts | 4 +++- src/engines/L3/element.test.js | 31 ++++++------------------- src/lib/codegenerator/generator.test.js | 24 +++++++++---------- src/lib/precompiler/precompiler.js | 23 +++++++++++++++++- src/router/router.js | 7 ++++-- 5 files changed, 49 insertions(+), 40 deletions(-) diff --git a/index.d.ts b/index.d.ts index e9ddc41e..ffe605d3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -905,7 +905,9 @@ declare module '@lightningjs/blits' { } } - type ComponentFactory = () => void + type ComponentFactory = (() => void) & { + needsInteractive?: boolean + } // Launch Related diff --git a/src/engines/L3/element.test.js b/src/engines/L3/element.test.js index 3f917341..ef39ffaa 100644 --- a/src/engines/L3/element.test.js +++ b/src/engines/L3/element.test.js @@ -23,7 +23,6 @@ import { initLog } from '../../lib/log.js' import symbols from '../../lib/symbols.js' import sinon from 'sinon' import shaders from '../../lib/shaders/shaders.js' // Changed from './shaderLoader.js' -import { registerHooks } from '../../lib/hooks.js' initLog() @@ -1257,44 +1256,28 @@ test('Element - Set maxheight property', (assert) => { assert.end() }) -test('Element - holder true sets interactive to true when component has hover hook', (assert) => { +test('Element - holder sets interactive to the passed value (true)', (assert) => { assert.capture(renderer, 'createNode', () => new EventEmitter()) - const component = { [symbols.identifier]: 'test-hover-1' } - registerHooks({ hover: () => {} }, component[symbols.identifier]) + const component = {} const el = element({ parent: { node: { w: 1920, h: 1080 } } }, component) el.populate({ parent: { node: new EventEmitter() }, holder: true }) assert.equal( el.props.props['interactive'], true, - 'interactive should be true when component has hover hook' + 'interactive should be true when holder value is true' ) assert.end() }) -test('Element - holder true sets interactive to true when component has unhover hook', (assert) => { +test('Element - holder sets interactive to the passed value (false)', (assert) => { assert.capture(renderer, 'createNode', () => new EventEmitter()) - const component = { [symbols.identifier]: 'test-unhover-1' } - registerHooks({ unhover: () => {} }, component[symbols.identifier]) + const component = {} const el = element({ parent: { node: { w: 1920, h: 1080 } } }, component) - el.populate({ parent: { node: new EventEmitter() }, holder: true }) - assert.equal( - el.props.props['interactive'], - true, - 'interactive should be true when component has unhover hook' - ) - assert.end() -}) - -test('Element - holder true sets interactive to false when component has no hover/unhover hooks', (assert) => { - assert.capture(renderer, 'createNode', () => new EventEmitter()) - const component = { [symbols.identifier]: 'test-no-hooks-1' } - registerHooks({}, component[symbols.identifier]) - const el = element({ parent: { node: { w: 1920, h: 1080 } } }, component) - el.populate({ parent: { node: new EventEmitter() }, holder: true }) + el.populate({ parent: { node: new EventEmitter() }, holder: false }) assert.equal( el.props.props['interactive'], false, - 'interactive should be false when component has no hover/unhover hooks' + 'interactive should be false when holder value is false' ) assert.end() }) diff --git a/src/lib/codegenerator/generator.test.js b/src/lib/codegenerator/generator.test.js index e5cbfecf..23dfac2f 100644 --- a/src/lib/codegenerator/generator.test.js +++ b/src/lib/codegenerator/generator.test.js @@ -1542,7 +1542,7 @@ test('Generate code for a template with custom components', (assert) => { elementConfigs[1] = {} elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive skips[1] = [] if (typeof cmps[1] !== 'undefined' && cmps[1][Symbol.for('config')].props !== undefined) { let props = cmps[1][Symbol.for('config')].props @@ -1591,7 +1591,7 @@ test('Generate code for a template with custom components', (assert) => { elementConfigs[3] = {} elms[3] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[3]['holder'] = true + elementConfigs[3]['holder'] = cmps[3].needsInteractive skips[3] = [] if (typeof cmps[3] !== 'undefined' && cmps[3][Symbol.for('config')].props !== undefined) { let props = cmps[3][Symbol.for('config')].props @@ -1730,7 +1730,7 @@ test('Generate code for a template with an unregistered custom component', (asse parent = elms[0] elementConfigs[1] = {} elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive skips[1] = [] if (typeof cmps[1] !== 'undefined' && cmps[1][Symbol.for('config')].props !== undefined) { let props = cmps[1][Symbol.for('config')].props @@ -1775,7 +1775,7 @@ test('Generate code for a template with an unregistered custom component', (asse parent = elms[0] elementConfigs[3] = {} elms[3] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[3]['holder'] = true + elementConfigs[3]['holder'] = cmps[3].needsInteractive skips[3] = [] if (typeof cmps[3] !== 'undefined' && cmps[3][Symbol.for('config')].props !== undefined) { let props = cmps[3][Symbol.for('config')].props @@ -1913,7 +1913,7 @@ test('Generate code for a template with custom components with arguments', (asse parent = elms[0] elementConfigs[1] = {} elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive elementConfigs[1]['x'] = 10 skips[1] = [] if(typeof cmps[1] !== 'undefined' && cmps[1][Symbol.for('config')].props !== undefined) { @@ -1960,7 +1960,7 @@ test('Generate code for a template with custom components with arguments', (asse parent = elms[0] elementConfigs[3] = {} elms[3] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[3]['holder'] = true + elementConfigs[3]['holder'] = cmps[3].needsInteractive elementConfigs[3]['x'] = 100 elementConfigs[3]['img'] = component.img skips[3] = [] @@ -2107,7 +2107,7 @@ test('Generate code for a template with custom components with argument value as elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive elementConfigs[1]['x'] = 1000 elementConfigs[1]['y'] = 100 elementConfigs[1]['h'] = parent.node.h * (45 / 100) @@ -2262,7 +2262,7 @@ test('Generate code for a template with custom components with reactive props', parent = elms[0] elementConfigs[1] = {} elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive elementConfigs[1]['x'] = 10 elementConfigs[1]['img'] = component.image skips[1] = [] @@ -2316,7 +2316,7 @@ test('Generate code for a template with custom components with reactive props', parent = elms[0] elementConfigs[3] = {} elms[3] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[3]['holder'] = true + elementConfigs[3]['holder'] = cmps[3].needsInteractive elementConfigs[3]['x'] = 100 elementConfigs[3]['img'] = component.image skips[3] = [] @@ -2592,7 +2592,7 @@ test('Generate code for a template with slot content', (assert) => { elementConfigs[1] = {} elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive elementConfigs[1]['w'] = 1920 elementConfigs[1]['h'] = 1080 skips[1] = [] @@ -2781,7 +2781,7 @@ test('Generate code for a template with slot content, using a named slot', (asse elementConfigs[1] = {} elms[1] = this.element({ parent: parent || 'root' }, inSlot === true ? slotComponent : component) - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive elementConfigs[1]['w'] = 1920 elementConfigs[1]['h'] = 1080 skips[1] = [] @@ -4411,7 +4411,7 @@ test('Generate code for a template with a simple for-loop on a Component with a if(elms[1][scope.key] === undefined) { elms[1][scope.key] = this.element({parent: parent || 'root'}, inSlot === true ? slotComponent : component) } - elementConfigs[1]['holder'] = true + elementConfigs[1]['holder'] = cmps[1].needsInteractive skips[1] = [] if(typeof cmps[1] !== 'undefined' && cmps[1][Symbol.for('config')].props !== undefined) { // attributes that are a prop should be removed from element config (even if it's a know element prop) diff --git a/src/lib/precompiler/precompiler.js b/src/lib/precompiler/precompiler.js index d11d511c..1605bf21 100644 --- a/src/lib/precompiler/precompiler.js +++ b/src/lib/precompiler/precompiler.js @@ -31,6 +31,11 @@ export default (source, filePath, mode) => { // Use MagicString to track changes const s = new MagicString(source) + // Find component definition start positions for scoping JS-layer checks + const componentStarts = [...source.matchAll(/(?:Blits\.)?(?:Component|Application)\s*\(/g)] + .map((m) => m.index) + .sort((a, b) => a - b) + for (const template of templates) { if (template[2]) { const templateContent = template[2] @@ -52,10 +57,26 @@ export default (source, filePath, mode) => { // Generate the code const code = generator.call({ components: {} }, parsed, mode === 'development') + // Determine the component scope containing this template + let scopeStart = 0 + let scopeEnd = source.length + for (let i = 0; i < componentStarts.length; i++) { + if (componentStarts[i] <= templateStartIndex) { + scopeStart = componentStarts[i] + scopeEnd = i + 1 < componentStarts.length ? componentStarts[i + 1] : source.length + } + } + const componentScope = source.slice(scopeStart, scopeEnd) + + // Derive usesHoverState from both template ($$isHovered) and JS layer (this.$isHovered) + const usesHoverState = + code.usesHoverState || + componentScope.replace(templateContent, '').includes('this.$isHovered') + // Insert the code in the component using the 'code' key, replacing the template key const replacement = `/* eslint-disable no-unused-vars */ \ncode: { render: ${code.render.toString()}, effects: [${code.effects.map( (fn) => fn.toString() - )}], context: {}, usesHoverState: ${code.usesHoverState}}` + )}], context: {}, usesHoverState: ${usesHoverState}}` // MagicString tracks all changes automatically, no offset needed s.overwrite(templateStartIndex, templateEndIndex, replacement) diff --git a/src/router/router.js b/src/router/router.js index 436ef4ce..9d2393be 100644 --- a/src/router/router.js +++ b/src/router/router.js @@ -42,7 +42,7 @@ import Settings from '../settings.js' * @property {Object} hooks - The hooks of the route * @property {Object} transition - The transition of the route * @property {Object} announce - The announce of the route - * @property {(options: Object, parentEl: BlitsElement, parentComponent: BlitsComponent, rootComponent?: BlitsComponent) => BlitsComponent} component - The component factory of the route + * @property {BlitsComponentFactory} component - The component factory of the route (or a lazy import function) * * @typedef {Object} Hash * @property {string} path - The path of the hash @@ -427,8 +427,11 @@ export const navigate = async function () { if (!view) { // create a holder element for the new view + // for lazy imports needsInteractive is undefined, default to true + const needsInteractive = + route.component.needsInteractive !== undefined ? route.component.needsInteractive : true holder = stage.element({ parent: this[symbols.children][0] }) - holder.populate({}) + holder.populate({ holder: needsInteractive }) holder.set('w', '100%') holder.set('h', '100%') From 0e08352b82db60b5d61ff93e302a1c4d1d88ee4d Mon Sep 17 00:00:00 2001 From: Ugur Aslan Date: Tue, 28 Apr 2026 12:46:30 +0200 Subject: [PATCH 06/34] fix: improve precompiler hover state detection --- src/lib/precompiler/precompiler.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/lib/precompiler/precompiler.js b/src/lib/precompiler/precompiler.js index 1605bf21..1aed01a2 100644 --- a/src/lib/precompiler/precompiler.js +++ b/src/lib/precompiler/precompiler.js @@ -32,7 +32,7 @@ export default (source, filePath, mode) => { const s = new MagicString(source) // Find component definition start positions for scoping JS-layer checks - const componentStarts = [...source.matchAll(/(?:Blits\.)?(?:Component|Application)\s*\(/g)] + const componentStarts = [...source.matchAll(/Blits\.(Component|Application)\s*\(/g)] .map((m) => m.index) .sort((a, b) => a - b) @@ -69,9 +69,11 @@ export default (source, filePath, mode) => { const componentScope = source.slice(scopeStart, scopeEnd) // Derive usesHoverState from both template ($$isHovered) and JS layer (this.$isHovered) - const usesHoverState = - code.usesHoverState || - componentScope.replace(templateContent, '').includes('this.$isHovered') + // Strip comments before checking to avoid false positives from commented-out code + const strippedScope = componentScope + .replace(/\/\/[^\n]*/g, '') + .replace(/\/\*[\s\S]*?\*\//g, '') + const usesHoverState = code.usesHoverState || strippedScope.includes('this.$isHovered') // Insert the code in the component using the 'code' key, replacing the template key const replacement = `/* eslint-disable no-unused-vars */ \ncode: { render: ${code.render.toString()}, effects: [${code.effects.map( From 12264e3ad27ba882e55464e7b70f48c3cfe61ae8 Mon Sep 17 00:00:00 2001 From: Michiel van der Geest Date: Mon, 26 Oct 2026 15:06:00 +0100 Subject: [PATCH 07/34] Added support for / fixed using computed props in forloops (fully reactive). --- src/component/setup/computed.js | 3 +- src/lib/reactivity/effect.js | 34 +++- src/lib/reactivity/effect.test.js | 109 +++++++++++- src/lib/reactivity/forLoopReactivity.test.js | 164 +++++++++++++++++++ 4 files changed, 306 insertions(+), 4 deletions(-) create mode 100644 src/lib/reactivity/forLoopReactivity.test.js diff --git a/src/component/setup/computed.js b/src/component/setup/computed.js index 4d9a831b..a0bc079e 100644 --- a/src/component/setup/computed.js +++ b/src/component/setup/computed.js @@ -18,6 +18,7 @@ import { Log } from '../../lib/log.js' import symbols from '../../lib/symbols.js' +import { trackComputed } from '../../lib/reactivity/effect.js' export default (component, computeds) => { component[symbols.computedKeys] = [] @@ -40,7 +41,7 @@ export default (component, computeds) => { component[symbols.computedKeys].push(computed) Object.defineProperty(component, computed, { get() { - return computeds[computed].apply(this) + return trackComputed(computeds[computed], this) }, }) } diff --git a/src/lib/reactivity/effect.js b/src/lib/reactivity/effect.js index 4d8a606f..11cb68c2 100644 --- a/src/lib/reactivity/effect.js +++ b/src/lib/reactivity/effect.js @@ -33,10 +33,40 @@ export const resumeTracking = () => { const objectMap = new WeakMap() const effectDependenciesMap = new WeakMap() +const computedEffects = new WeakMap() + +export const trackComputed = (getter, component) => { + if (currentEffect === null || currentKey === null || pauseCounter > 0) { + return getter.call(component) + } + + const previousEffect = currentEffect + const previousKey = currentKey + let computedEffect = computedEffects.get(previousEffect) + if (computedEffect === undefined) { + // Only computed dependencies need a runner that restores tracking on updates. + computedEffect = (force) => effect(previousEffect, previousKey, force) + computedEffects.set(previousEffect, computedEffect) + } + currentEffect = computedEffect + currentKey = null + try { + return getter.call(component) + } finally { + currentEffect = previousEffect + currentKey = previousKey + } +} export const removeEffects = (effectsToRemove) => { for (let i = 0; i < effectsToRemove.length; i++) { const effect = effectsToRemove[i] + const computedEffect = computedEffects.get(effect) + if (computedEffect !== undefined) { + // Computed dependencies subscribe the runner itself, so unsubscribe it separately. + removeEffects([computedEffect]) + computedEffects.delete(effect) + } const dependencies = effectDependenciesMap.get(effect) if (dependencies === undefined) continue for (let j = 0; j < dependencies.length; j++) { @@ -92,7 +122,7 @@ export const trigger = (target, key, force = false) => { } } -export const effect = (effectFn, key = null) => { +export const effect = (effectFn, key = null, force) => { const previousEffect = currentEffect const previousKey = currentKey @@ -100,7 +130,7 @@ export const effect = (effectFn, key = null) => { currentKey = key try { - effectFn() + effectFn(force) } finally { currentEffect = previousEffect currentKey = previousKey diff --git a/src/lib/reactivity/effect.test.js b/src/lib/reactivity/effect.test.js index 87677880..ac91f8ae 100644 --- a/src/lib/reactivity/effect.test.js +++ b/src/lib/reactivity/effect.test.js @@ -16,7 +16,15 @@ */ import test from 'tape' -import { trigger, track, effect, pauseTracking, resumeTracking } from './effect.js' +import { + trigger, + track, + effect, + pauseTracking, + resumeTracking, + removeEffects, + trackComputed, +} from './effect.js' test('Trigger - type', (assert) => { const expected = 'function' @@ -133,3 +141,102 @@ test('Effect - Restores the enclosing effect when a nested effect throws', (asse assert.equal(outerEffectRuns, 2, 'Enclosing effect should keep tracking after the nested error') assert.end() }) + +test('Computed tracking restores filters, discovers dependencies, and cleans up its runner', (assert) => { + const target = {} + let ready = false + let runs = 0 + let lastForce + const getter = function () { + track(target, 'ready') + if (ready) track(target, 'cards') + return this.value + } + const component = { value: 42 } + const render = (force) => { + runs++ + lastForce = force + assert.equal(trackComputed(getter, component), 42, 'Getter preserves its receiver and result') + track(target, 'childOnly') + track(target, 'range') + } + effect(render, ['visibleCards', 'range']) + trigger(target, 'childOnly') + assert.equal(runs, 1, 'Reads after the getter remain filtered') + + ready = true + trigger(target, 'ready', true) + assert.equal(runs, 2, 'Computed dependencies trigger the effect') + assert.equal(lastForce, true, 'Computed runner forwards the force flag') + trigger(target, 'cards') + assert.equal(runs, 3, 'Dependencies first read on an update are tracked') + trigger(target, 'childOnly') + assert.equal(runs, 3, 'Update tracking also excludes child-only reads') + trigger(target, 'range') + assert.equal(runs, 4, 'The original filtered dependencies remain active') + + removeEffects([render]) + trigger(target, 'ready') + trigger(target, 'cards') + trigger(target, 'range') + assert.equal(runs, 4, 'Cleanup removes both computed and direct subscriptions') + assert.end() +}) + +test('Nested and throwing computed getters restore the outer tracking filter', (assert) => { + const target = {} + let runs = 0 + const inner = () => { + track(target, 'inner') + return 42 + } + const outer = () => { + const value = trackComputed(inner) + track(target, 'outer') + return value + } + const throwing = () => { + throw new Error('Computed failed') + } + const render = () => { + runs++ + assert.equal(trackComputed(outer), 42, 'Nested getter returns its result') + assert.throws(() => trackComputed(throwing), /Computed failed/, 'Getter errors propagate') + track(target, 'unrelated') + } + effect(render, ['computed']) + trigger(target, 'inner') + trigger(target, 'outer') + assert.equal(runs, 3, 'Both nested and outer dependencies trigger one execution each') + trigger(target, 'unrelated') + assert.equal(runs, 3, 'The original filter is restored even after an error') + removeEffects([render]) + trigger(target, 'inner') + trigger(target, 'outer') + assert.equal(runs, 3, 'Nested computed subscriptions are cleaned up') + assert.end() +}) + +test('Computed tracking respects paused tracking and reads outside effects', (assert) => { + const target = {} + let runs = 0 + const getter = () => { + track(target, 'cards') + return [] + } + const render = () => { + runs++ + pauseTracking() + try { + trackComputed(getter) + } finally { + resumeTracking() + } + } + effect(render, ['computed']) + trackComputed(getter) + trigger(target, 'cards') + assert.equal(runs, 1, 'Paused and non-effect reads do not subscribe') + removeEffects([render]) + assert.end() +}) diff --git a/src/lib/reactivity/forLoopReactivity.test.js b/src/lib/reactivity/forLoopReactivity.test.js new file mode 100644 index 00000000..165b51df --- /dev/null +++ b/src/lib/reactivity/forLoopReactivity.test.js @@ -0,0 +1,164 @@ +/* + * Copyright 2026 Comcast Cable Communications Management, LLC + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +import test from 'tape' +import Component from '../../component.js' +import symbols from '../symbols.js' +import { renderComponent } from '../../testing/index.js' + +const cards = [{ id: 'one' }, { id: 'two' }] +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) +const Card = Component('LoopCard', { template: '' }) +const keys = (fixture) => Object.keys(fixture.component[symbols.children][2] || {}).sort() +const createList = (source, config) => + renderComponent( + Component('LoopList', { + template: ``, + components: { LoopCard: Card }, + ...config, + }), + { props: config.props } + ) + +const computedCards = { + visibleCards() { + return this.cards.filter(() => true) + }, +} + +const checkUpdates = async (assert, fixture, setCards) => { + try { + assert.deepEqual(keys(fixture), [], 'Initially empty') + await settle() + setCards({ cards }) + assert.deepEqual(keys(fixture), ['one', 'two'], 'Array replacement creates children') + fixture.component.cards.push({ id: 'three' }) + assert.deepEqual(keys(fixture), ['one', 'three', 'two'], 'Push creates another child') + setCards({ cards: [] }) + assert.deepEqual(keys(fixture), [], 'Clearing removes children') + fixture.component.cards.push(...cards) + assert.deepEqual(keys(fixture), ['one', 'two'], 'Push into an empty array creates children') + } finally { + fixture.destroy() + } + assert.end() +} + +test(':for updates an initially empty state array', (assert) => { + const fixture = createList('cards', { state: () => ({ cards: [] }) }) + return checkUpdates(assert, fixture, fixture.setState) +}) + +test(':for updates an initially empty prop array', (assert) => { + const fixture = createList('cards', { props: { cards: [] } }) + return checkUpdates(assert, fixture, fixture.setProps) +}) + +test(':for updates a computed array derived from initially empty state', (assert) => { + const fixture = createList('visibleCards', { + state: () => ({ cards: [] }), + computed: computedCards, + }) + return checkUpdates(assert, fixture, fixture.setState) +}) + +test(':for updates a computed array derived from an initially empty prop', (assert) => { + const fixture = createList('visibleCards', { + props: { cards: [] }, + computed: computedCards, + }) + return checkUpdates(assert, fixture, fixture.setProps) +}) + +test(':for tracks dependencies discovered by a conditional computed', (assert) => { + const fixture = createList('visibleCards', { + state: () => ({ cards, show: false }), + computed: { + visibleCards() { + return this.show ? this.cards : [] + }, + }, + }) + try { + assert.deepEqual(keys(fixture), [], 'Initially hidden') + fixture.component.show = true + assert.deepEqual(keys(fixture), ['one', 'two'], 'Changing the condition creates children') + fixture.component.cards = [{ id: 'three' }] + assert.deepEqual(keys(fixture), ['three'], 'Newly discovered dependency remains reactive') + fixture.component.show = false + assert.deepEqual(keys(fixture), [], 'Changing the condition removes children') + } finally { + fixture.destroy() + } + assert.end() +}) + +test(':for renders an initially populated computed array', (assert) => { + const fixture = createList('visibleCards', { + state: () => ({ cards }), + computed: { + visibleCards() { + return this.cards.filter(() => true) + }, + }, + }) + try { + assert.deepEqual(keys(fixture), ['one', 'two'], 'Computed children render at mount') + fixture.component.cards = [] + assert.deepEqual(keys(fixture), [], 'Clearing removes the initial children') + } finally { + fixture.destroy() + } + assert.end() +}) + +test(':for preserves range tracking, filtering, and cleanup with chained computeds', (assert) => { + let runs = 0 + const fixture = renderComponent( + Component('ComputedLoopRange', { + template: ``, + state: () => ({ cards: [], to: 1, x: 0 }), + computed: { + loadedCards() { + return this.cards + }, + visibleCards() { + runs++ + return this.loadedCards.filter(() => true) + }, + }, + }) + ) + const component = fixture.component + const renderedKeys = () => Object.keys(component[symbols.children][1] || {}).sort() + try { + component.cards = cards + assert.deepEqual(renderedKeys(), ['one'], 'Range limits the computed collection') + assert.equal(runs, 2, 'One evaluation at mount and one on update') + component.x = 10 + assert.equal(runs, 2, 'Loop body reads do not subscribe the loop') + component.to = 2 + assert.deepEqual(renderedKeys(), ['one', 'two'], 'Range changes update the loop') + assert.equal(runs, 3, 'Range update evaluates once') + } finally { + fixture.destroy() + } + component.cards = [{ id: 'three' }] + assert.equal(runs, 3, 'Destroy unsubscribes computed dependencies') + assert.end() +}) From 773b1dd95c184b7ef06afb5270c6a0885abc6a93 Mon Sep 17 00:00:00 2001 From: Michiel van der Geest Date: Tue, 27 Oct 2026 10:01:07 +0100 Subject: [PATCH 08/34] Added benchmark for measuring component creation. --- benchmarks/README.md | 11 ++- benchmarks/benchmarks.js | 15 ++++ benchmarks/compare.js | 2 + benchmarks/runner.js | 10 ++- benchmarks/src/App.js | 51 ++++++++++++ benchmarks/src/Benchmark.js | 82 ------------------- .../src/benchmarks/ComponentCreation.js | 67 +++++++++++++++ benchmarks/src/benchmarks/ElementCreation.js | 55 +++++++++++++ benchmarks/src/main.js | 9 +- 9 files changed, 213 insertions(+), 89 deletions(-) create mode 100644 benchmarks/benchmarks.js create mode 100644 benchmarks/src/App.js delete mode 100644 benchmarks/src/Benchmark.js create mode 100644 benchmarks/src/benchmarks/ComponentCreation.js create mode 100644 benchmarks/src/benchmarks/ElementCreation.js diff --git a/benchmarks/README.md b/benchmarks/README.md index 3084b081..3000adc5 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,6 +1,6 @@ -# Element generation benchmark +# Benchmarks -One workload: clear a keyed loop and generate Elements again. Data creation and clearing happen outside the measured generation time. The default run uses 1,000 Elements, five warmups, and 20 measured samples. Each sample verifies the number of live rendered Elements. +Two independently selectable workloads clear a keyed loop and create it again: `element-creation` (the default) creates Elements with text; `component-creation` creates component instances with matching rectangles, text, dimensions, and alternating colors. Each item receives its text and color as props, adding a component boundary around the same content. Data creation and clearing happen outside the measured generation time. The default run uses 1,000 items, five warmups, and 20 measured samples. Each sample verifies the number of live Elements or component instances. Install dependencies in this folder with `npm install` and install Chromium with `npx playwright install chromium`. @@ -8,6 +8,7 @@ From the repository root: ```sh npm run bench +npm run bench -- --benchmark component-creation npm run bench -- --size 100 --samples 5 --warmup 2 npm run bench -- --headed npm run bench -- --output results/benchmark.json @@ -15,12 +16,16 @@ npm run bench:serve npm run bench:compare -- --base master ``` +Each CLI invocation runs only the selected benchmark in a fresh Chromium launch. Use `--benchmark element-creation` or `--benchmark component-creation` with `bench`, `bench:profile`, or `bench:compare`. In the browser, changing the `benchmark` query parameter and navigating launches a fresh application. Warmups and samples run within that launch. + +To add a workload, create a CamelCase definition in `src/benchmarks/` and register it in `benchmarks.js`. Each entry exports a `title` and a default `Blits.Component` with its template, state, and `setup`, `measure`, and `verify` methods under `methods`. The shared application renders the selected component and calls those methods on its instance, preserving Blits autocomplete and type inference within the workload. The application lifecycle, keyboard trigger, timing loop, reporting, and launch configuration are shared. + Relative `--output` paths resolve from the `benchmarks/` directory, so the example saves to `benchmarks/results/benchmark.json`. For browser inspection, open the URL printed by `bench:serve` and press **Enter**. The loop is cleared and recreated on every repetition, and the final sample stays visible. Results are logged in the browser console. Options can be supplied in the URL: ```text -http://localhost:5173/?size=1000&warmup=5&samples=20 +http://localhost:5173/?benchmark=element-creation&size=1000&warmup=5&samples=20 ``` Browser and CLI runs use the same workload. The CLI applies a 20x Chromium CPU slowdown; manual browser runs use the browser's current CPU settings. Use DevTools CPU throttling for a manual slowdown. diff --git a/benchmarks/benchmarks.js b/benchmarks/benchmarks.js new file mode 100644 index 00000000..cfa2508e --- /dev/null +++ b/benchmarks/benchmarks.js @@ -0,0 +1,15 @@ +export const benchmarks = { + 'element-creation': () => import('./src/benchmarks/ElementCreation.js'), + 'component-creation': () => import('./src/benchmarks/ComponentCreation.js'), +} + +export const defaultBenchmark = 'element-creation' + +export const validateBenchmark = (name) => { + if (!Object.hasOwn(benchmarks, name)) { + throw new Error( + `Unknown benchmark: ${name}. Choose from: ${Object.keys(benchmarks).join(', ')}` + ) + } + return name +} diff --git a/benchmarks/compare.js b/benchmarks/compare.js index 0e28d314..9a3d0ba3 100644 --- a/benchmarks/compare.js +++ b/benchmarks/compare.js @@ -5,6 +5,7 @@ import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { buildBenchmark, measureBenchmark, writeReport } from './runner.js' import { comparePairs, formatComparison } from './comparison.js' +import { defaultBenchmark, validateBenchmark } from './benchmarks.js' import { validateOptions } from './src/benchmark-utils.js' const root = fileURLToPath(new URL('..', import.meta.url)) @@ -68,6 +69,7 @@ const run = async () => { const output = value('--output', 'results/comparison.json') const pairCount = Number(value('--pairs', 2)) const options = { + benchmark: validateBenchmark(value('--benchmark', defaultBenchmark)), size: Number(value('--size', 1000)), warmup: Number(value('--warmup', 5)), samples: Number(value('--samples', 20)), diff --git a/benchmarks/runner.js b/benchmarks/runner.js index 58db2463..b9f4cd83 100644 --- a/benchmarks/runner.js +++ b/benchmarks/runner.js @@ -4,6 +4,7 @@ import { dirname, resolve } from 'node:path' import { build, preview } from 'vite' import { chromium } from 'playwright' import { formatSummary } from './summary.js' +import { defaultBenchmark, validateBenchmark } from './benchmarks.js' import viteConfig from './vite.config.js' const benchmarkRoot = fileURLToPath(new URL('.', import.meta.url)) @@ -38,6 +39,7 @@ export const buildBenchmark = async (sourceRoot, outDir) => { } export const measureBenchmark = async (config, options, headed = false) => { + const benchmark = validateBenchmark(options.benchmark ?? defaultBenchmark) const server = await preview({ ...config, preview: { host: '127.0.0.1', port: 0 }, @@ -51,12 +53,15 @@ export const measureBenchmark = async (config, options, headed = false) => { page.on('pageerror', (error) => console.error(error)) const client = await page.context().newCDPSession(page) await client.send('Emulation.setCPUThrottlingRate', { rate: 20 }) - const url = server.resolvedUrls.local[0] - await page.goto(config.mode === 'development' ? `${url}?profile` : url) + const url = new URL(server.resolvedUrls.local[0]) + url.searchParams.set('benchmark', benchmark) + if (config.mode === 'development') url.searchParams.set('profile', '') + await page.goto(url.href) await page.waitForFunction(() => window.__BLITS_BENCH__?.ready === true) const results = await page.evaluate((options) => window.__BLITS_BENCH__.run(options), options) return { ...results, + benchmark, cpuSlowdown: 20, browserVersion: browser.version(), mode: config.mode, @@ -93,6 +98,7 @@ const run = async () => { return index === -1 ? fallback : args[index + 1] } const options = { + benchmark: validateBenchmark(value('--benchmark', defaultBenchmark)), size: Number(value('--size', 1000)), samples: Number(value('--samples', 20)), warmup: Number(value('--warmup', 5)), diff --git a/benchmarks/src/App.js b/benchmarks/src/App.js new file mode 100644 index 00000000..efff63db --- /dev/null +++ b/benchmarks/src/App.js @@ -0,0 +1,51 @@ +import Blits from '@lightningjs/blits' +import { updateIdle, runBenchmark, getManualOptions } from './benchmark-utils.js' + +export default (component, title) => + Blits.Application({ + components: { Workload: component }, + template: ` + + + + `, + state() { + return { benchmarkRunning: false } + }, + input: { + async enter(event) { + if (event.repeat || this.benchmarkRunning || !this.runBenchmark) return + event.preventDefault() + try { + await this.runBenchmark(getManualOptions()) + } catch (error) { + console.error(error) + } + }, + }, + hooks: { + idle(idle) { + updateIdle(idle) + }, + ready() { + const workload = this.$select('workload') + const run = async (options = {}) => { + if (this.benchmarkRunning) return + this.benchmarkRunning = true + try { + return await runBenchmark({ + ...options, + title, + setup: workload.setup.bind(workload), + measure: workload.measure.bind(workload), + verify: workload.verify.bind(workload), + }) + } finally { + this.benchmarkRunning = false + } + } + this.runBenchmark = run + window.__BLITS_BENCH__ = { ready: true, run } + }, + }, + }) diff --git a/benchmarks/src/Benchmark.js b/benchmarks/src/Benchmark.js deleted file mode 100644 index 0d8d1fec..00000000 --- a/benchmarks/src/Benchmark.js +++ /dev/null @@ -1,82 +0,0 @@ -import Blits from '@lightningjs/blits' -import symbols from '@lightningjs/blits/symbols' -import { untilIdle, updateIdle, runBenchmark, getManualOptions } from './benchmark-utils.js' - -const columns = 34 - -export default Blits.Application({ - template: ` - - - - - - `, - state() { - return { items: [], benchmarkRunning: false } - }, - input: { - async enter(event) { - if (event.repeat || this.benchmarkRunning || !this.runBenchmark) return - event.preventDefault() - try { - await this.runBenchmark(getManualOptions()) - } catch (error) { - console.error(error) - } - }, - }, - hooks: { - idle(idle) { - updateIdle(idle) - }, - ready() { - const run = async (options = {}) => { - if (this.benchmarkRunning) return - this.benchmarkRunning = true - try { - return await runBenchmark({ - ...options, - title: 'Element generation benchmark', - setup: async ({ size }) => { - if (this.items.length > 0) { - await untilIdle(() => { - this.items = [] - }) - } else { - await untilIdle() - } - // Prepare data outside timing; each assignment starts from an empty loop. - return Array.from({ length: size }, (_, item) => ({ - id: `item-${item}`, - x: (item % columns) * 55, - y: Math.floor(item / columns) * 34, - color: item % 2 === 0 ? '#334155' : '#475569', - })) - }, - measure: async (items) => { - let start - let generationSyncMs - await untilIdle(() => { - start = performance.now() - this.items = items - generationSyncMs = performance.now() - start - }) - return { generationSyncMs, totalToIdleMs: performance.now() - start } - }, - verify: ({ size }) => { - const rendered = Object.values(this[symbols.children][1] || {}) - if (rendered.length !== size || rendered.some((element) => element.eol === true)) { - throw new Error(`Expected ${size} live Elements, found ${rendered.length}`) - } - }, - }) - } finally { - this.benchmarkRunning = false - } - } - this.runBenchmark = run - window.__BLITS_BENCH__ = { ready: true, run } - }, - }, -}) diff --git a/benchmarks/src/benchmarks/ComponentCreation.js b/benchmarks/src/benchmarks/ComponentCreation.js new file mode 100644 index 00000000..e89ac5f4 --- /dev/null +++ b/benchmarks/src/benchmarks/ComponentCreation.js @@ -0,0 +1,67 @@ +import Blits from '@lightningjs/blits' +import symbols from '@lightningjs/blits/symbols' +import { untilIdle } from '../benchmark-utils.js' + +const columns = 34 + +// Match the element benchmark content, adding only the component boundary. +const Item = Blits.Component('ComponentCreationItem', { + props: ['content', 'color'], + template: ` + + + + `, +}) + +export const title = 'Component generation benchmark' + +export default Blits.Component('ComponentCreation', { + components: { Item }, + template: ` + + + +`, + state() { + return { items: [] } + }, + + methods: { + async setup({ size }) { + if (this.items.length > 0) { + await untilIdle(() => { + this.items = [] + }) + } else { + await untilIdle() + } + // Prepare data outside timing; each assignment starts from an empty loop. + return Array.from({ length: size }, (_, item) => ({ + id: `item-${item}`, + x: (item % columns) * 55, + y: Math.floor(item / columns) * 34, + color: item % 2 === 0 ? '#334155' : '#475569', + })) + }, + async measure(items) { + let start + let generationSyncMs + await untilIdle(() => { + start = performance.now() + this.items = items + generationSyncMs = performance.now() - start + }) + return { generationSyncMs, totalToIdleMs: performance.now() - start } + }, + verify({ size }) { + const rendered = Object.values(this[symbols.children][2] || {}) + if ( + rendered.length !== size || + rendered.some((component) => component.$componentId === undefined || component.eol === true) + ) { + throw new Error(`Expected ${size} live components, found ${rendered.length}`) + } + }, + }, +}) diff --git a/benchmarks/src/benchmarks/ElementCreation.js b/benchmarks/src/benchmarks/ElementCreation.js new file mode 100644 index 00000000..bd735bf8 --- /dev/null +++ b/benchmarks/src/benchmarks/ElementCreation.js @@ -0,0 +1,55 @@ +import Blits from '@lightningjs/blits' +import symbols from '@lightningjs/blits/symbols' +import { untilIdle } from '../benchmark-utils.js' + +const columns = 34 + +export const title = 'Element generation benchmark' + +export default Blits.Component('ElementCreation', { + template: ` + + + + + +`, + state() { + return { items: [] } + }, + + methods: { + async setup({ size }) { + if (this.items.length > 0) { + await untilIdle(() => { + this.items = [] + }) + } else { + await untilIdle() + } + // Prepare data outside timing; each assignment starts from an empty loop. + return Array.from({ length: size }, (_, item) => ({ + id: `item-${item}`, + x: (item % columns) * 55, + y: Math.floor(item / columns) * 34, + color: item % 2 === 0 ? '#334155' : '#475569', + })) + }, + async measure(items) { + let start + let generationSyncMs + await untilIdle(() => { + start = performance.now() + this.items = items + generationSyncMs = performance.now() - start + }) + return { generationSyncMs, totalToIdleMs: performance.now() - start } + }, + verify({ size }) { + const rendered = Object.values(this[symbols.children][1] || {}) + if (rendered.length !== size || rendered.some((element) => element.eol === true)) { + throw new Error(`Expected ${size} live Elements, found ${rendered.length}`) + } + }, + }, +}) diff --git a/benchmarks/src/main.js b/benchmarks/src/main.js index 22766726..e66e0bdc 100644 --- a/benchmarks/src/main.js +++ b/benchmarks/src/main.js @@ -1,10 +1,15 @@ import Blits from '@lightningjs/blits' import profiler from '@lightningjs/blits/profiler' -import Benchmark from './Benchmark.js' +import createBenchmark from './App.js' +import { benchmarks, defaultBenchmark, validateBenchmark } from '../benchmarks.js' const query = new URLSearchParams(window.location.search) +const name = validateBenchmark(query.get('benchmark') ?? defaultBenchmark) +const { default: benchmark, title } = await benchmarks[name]() + if (query.has('profile')) profiler.start({ frames: false }) -Blits.Launch(Benchmark, 'app', { + +Blits.Launch(createBenchmark(benchmark, title), 'app', { w: 1920, h: 1080, debugLevel: 0, From a57d94b8309709fd290d9068bd6d2dea149699b4 Mon Sep 17 00:00:00 2001 From: Michiel van der Geest Date: Tue, 27 Oct 2026 10:10:35 +0100 Subject: [PATCH 09/34] Added --all option to run all benchmarks. --- benchmarks/README.md | 3 ++- benchmarks/runner.js | 28 +++++++++++++++++++++--- benchmarks/suite.js | 14 ++++++++++++ benchmarks/suite.test.js | 46 ++++++++++++++++++++++++++++++++++++++++ benchmarks/summary.js | 19 +++++++++++++++++ 5 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 benchmarks/suite.js create mode 100644 benchmarks/suite.test.js diff --git a/benchmarks/README.md b/benchmarks/README.md index 3000adc5..42f96116 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -8,6 +8,7 @@ From the repository root: ```sh npm run bench +npm run bench -- --all --output results/benchmarks.json npm run bench -- --benchmark component-creation npm run bench -- --size 100 --samples 5 --warmup 2 npm run bench -- --headed @@ -16,7 +17,7 @@ npm run bench:serve npm run bench:compare -- --base master ``` -Each CLI invocation runs only the selected benchmark in a fresh Chromium launch. Use `--benchmark element-creation` or `--benchmark component-creation` with `bench`, `bench:profile`, or `bench:compare`. In the browser, changing the `benchmark` query parameter and navigating launches a fresh application. Warmups and samples run within that launch. +By default, each CLI invocation runs only the selected benchmark in a fresh Chromium launch. With `--all`, the local runner builds once and runs every registered benchmark sequentially, launching fresh Chromium with its own warmups for each workload. The same size, warmup, and sample options apply to every workload. The console shows an overview and per-benchmark summaries; `--output` saves one JSON object with `status` and a `benchmarks` array containing each complete report and its raw samples. If a benchmark fails, the suite stops, includes the error alongside completed results, writes the report, and exits with a nonzero status. Later benchmarks are omitted. `--all` and `--benchmark` cannot be combined. `--all` also works with `bench:profile`; comparison runs do not support it yet. Use `--benchmark element-creation` or `--benchmark component-creation` with `bench`, `bench:profile`, or `bench:compare`. In the browser, changing the `benchmark` query parameter and navigating launches a fresh application. Warmups and samples run within that launch. To add a workload, create a CamelCase definition in `src/benchmarks/` and register it in `benchmarks.js`. Each entry exports a `title` and a default `Blits.Component` with its template, state, and `setup`, `measure`, and `verify` methods under `methods`. The shared application renders the selected component and calls those methods on its instance, preserving Blits autocomplete and type inference within the workload. The application lifecycle, keyboard trigger, timing loop, reporting, and launch configuration are shared. diff --git a/benchmarks/runner.js b/benchmarks/runner.js index b9f4cd83..1a75b523 100644 --- a/benchmarks/runner.js +++ b/benchmarks/runner.js @@ -3,8 +3,10 @@ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { build, preview } from 'vite' import { chromium } from 'playwright' -import { formatSummary } from './summary.js' -import { defaultBenchmark, validateBenchmark } from './benchmarks.js' +import { runSuite } from './suite.js' +import { validateOptions } from './src/benchmark-utils.js' +import { formatSummary, formatSuiteSummary } from './summary.js' +import { benchmarks, defaultBenchmark, validateBenchmark } from './benchmarks.js' import viteConfig from './vite.config.js' const benchmarkRoot = fileURLToPath(new URL('.', import.meta.url)) @@ -93,9 +95,17 @@ const run = async () => { const args = process.argv.slice(2) const profile = args.includes('--profile') const headed = args.includes('--headed') + const all = args.includes('--all') + if (all && args.includes('--benchmark')) { + throw new Error('Use either --all or --benchmark, not both') + } const value = (name, fallback) => { const index = args.indexOf(name) - return index === -1 ? fallback : args[index + 1] + if (index === -1) return fallback + if (!args[index + 1] || args[index + 1].startsWith('--')) { + throw new Error(`${name} requires a value`) + } + return args[index + 1] } const options = { benchmark: validateBenchmark(value('--benchmark', defaultBenchmark)), @@ -103,6 +113,7 @@ const run = async () => { samples: Number(value('--samples', 20)), warmup: Number(value('--warmup', 5)), } + validateOptions(options) const output = value('--output', undefined) if (args.includes('--output') && (!output || output.startsWith('--'))) { throw new Error('--output requires a file path') @@ -112,6 +123,17 @@ const run = async () => { mode: profile ? 'development' : 'production', } await build(config) + if (all) { + const report = await runSuite(Object.keys(benchmarks), (benchmark) => + measureBenchmark(config, { ...options, benchmark }, headed) + ) + report.commit = process.env.GITHUB_SHA + const summary = formatSuiteSummary(report) + console.log(summary) + await writeReport(report, output, summary) + if (report.status === 'failed') process.exitCode = 1 + return + } const report = await measureBenchmark(config, options, headed) report.commit = process.env.GITHUB_SHA await writeReport(report, output, formatSummary(report)) diff --git a/benchmarks/suite.js b/benchmarks/suite.js new file mode 100644 index 00000000..9205db3f --- /dev/null +++ b/benchmarks/suite.js @@ -0,0 +1,14 @@ +export const runSuite = async (names, measure) => { + const report = { status: 'completed', benchmarks: [] } + for (const benchmark of names) { + console.log(`Running ${benchmark}…`) + try { + report.benchmarks.push(await measure(benchmark)) + } catch (error) { + report.status = 'failed' + report.benchmarks.push({ benchmark, error: error.message }) + break + } + } + return report +} diff --git a/benchmarks/suite.test.js b/benchmarks/suite.test.js new file mode 100644 index 00000000..dca3757b --- /dev/null +++ b/benchmarks/suite.test.js @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { runSuite } from './suite.js' +import { formatSuiteSummary } from './summary.js' + +test('runs benchmarks sequentially and retains complete results in registry order', async () => { + const events = [] + const reports = {} + const report = await runSuite(['first', 'second'], async (benchmark) => { + events.push(`start ${benchmark}`) + await new Promise((resolve) => setImmediate(resolve)) + events.push(`end ${benchmark}`) + reports[benchmark] = { benchmark, results: [{ generationSyncMs: 1, totalToIdleMs: 2 }] } + return reports[benchmark] + }) + assert.deepEqual(events, ['start first', 'end first', 'start second', 'end second']) + assert.equal(report.status, 'completed') + assert.deepEqual(report.benchmarks, [reports.first, reports.second]) +}) + +test('stops on failure and retains completed reports and the failing benchmark', async () => { + const calls = [] + const report = await runSuite(['first', 'second', 'third'], async (benchmark) => { + calls.push(benchmark) + if (benchmark === 'second') throw new Error('Renderer timed out') + return { benchmark, results: [] } + }) + assert.deepEqual(calls, ['first', 'second']) + assert.deepEqual(report, { + status: 'failed', + benchmarks: [ + { benchmark: 'first', results: [] }, + { benchmark: 'second', error: 'Renderer timed out' }, + ], + }) +}) + +test('suite summary exposes failures without formatting them as timings', () => { + const summary = formatSuiteSummary({ + status: 'failed', + benchmarks: [{ benchmark: 'second', error: 'Renderer timed out' }], + }) + assert.match(summary, /Status: failed/) + assert.match(summary, /\| second \| failed \| failed \|/) + assert.match(summary, /Renderer timed out/) +}) diff --git a/benchmarks/summary.js b/benchmarks/summary.js index df494f5a..44d6554a 100644 --- a/benchmarks/summary.js +++ b/benchmarks/summary.js @@ -26,3 +26,22 @@ export const formatSummary = (report) => { '', ].join('\n') } + +export const formatSuiteSummary = (report) => + [ + '# Benchmark suite', + '', + `Status: ${report.status}`, + '', + '| Benchmark | Median generation (ms) | Median time to idle (ms) |', + '| --- | ---: | ---: |', + ...report.benchmarks.map((result) => + result.error + ? `| ${result.benchmark} | failed | failed |` + : `| ${result.benchmark} | ${result.medianGenerationSyncMs.toFixed(2)} | ${result.medianTotalToIdleMs.toFixed(2)} |` + ), + '', + ...report.benchmarks.map((result) => + result.error ? `## ${result.benchmark}: failed\n\n${result.error}\n` : formatSummary(result) + ), + ].join('\n') From da91f4cff74d2d913750a997b70ac8d12146ec9f Mon Sep 17 00:00:00 2001 From: Michiel van der Geest Date: Tue, 27 Oct 2026 10:25:38 +0100 Subject: [PATCH 10/34] Updated GH workflow runner of benchmarks to handle all benchmarks. --- .github/scripts/publish-benchmark.cjs | 132 +++++++++++++-------- .github/scripts/publish-benchmark.test.cjs | 120 ++++++++++++++++++- .github/workflows/run-benchmarks.yml | 12 +- benchmarks/README.md | 21 +++- benchmarks/compare.js | 56 +++++---- benchmarks/comparison.js | 47 +++++++- benchmarks/comparison.test.js | 36 +++++- benchmarks/runner.js | 2 + benchmarks/src/main.js | 37 +++--- benchmarks/src/support.js | 14 +++ benchmarks/support.test.js | 33 ++++++ 11 files changed, 416 insertions(+), 94 deletions(-) create mode 100644 benchmarks/src/support.js create mode 100644 benchmarks/support.test.js diff --git a/.github/scripts/publish-benchmark.cjs b/.github/scripts/publish-benchmark.cjs index 84f0d475..5cd9bc15 100644 --- a/.github/scripts/publish-benchmark.cjs +++ b/.github/scripts/publish-benchmark.cjs @@ -4,7 +4,13 @@ const marker = '' const branch = 'benchmark-reports' module.exports = async ({ github, context, core }) => { - const { comparePairs, formatComparison } = await import('../../benchmarks/comparison.js') + const { + comparePairs, + formatComparison, + formatComparisonSuite, + formatComparisonOverview, + unsupportedReasons, + } = await import('../../benchmarks/comparison.js') const repo = context.repo const run = context.payload.workflow_run let pulls = run.pull_requests @@ -32,57 +38,79 @@ module.exports = async ({ github, context, core }) => { return } - // Artifacts are untrusted data. Validate numeric inputs and escape display text. - const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 && value <= 100_000 - if ( - !positiveInteger(report.size) || - !positiveInteger(report.samples) || - !Number.isSafeInteger(report.warmup) || - report.warmup < 0 || - report.warmup > 100_000 || - !Array.isArray(report.pairs) || - !report.pairs.length || - report.pairs.length > 100 - ) { - throw new Error('Invalid benchmark configuration') + const reports = Object.hasOwn(report, 'benchmarks') ? report.benchmarks : [report] + if (!Array.isArray(reports) || reports.length < 1 || reports.length > 100) { + throw new Error('Invalid benchmark suite') } - for (const pair of report.pairs) { + for (const result of reports) { if ( - !Array.isArray(pair.order) || - pair.order.length !== 2 || - [...pair.order].sort().join(',') !== 'base,candidate' + result.base?.commit !== report.base.commit || + result.candidate?.commit !== report.candidate.commit ) { - throw new Error('Invalid benchmark execution order') + throw new Error('Benchmark commit identities do not match the suite') } - for (const name of ['base', 'candidate']) { - for (const metric of ['medianGenerationSyncMs', 'medianTotalToIdleMs']) { - if (!Number.isFinite(pair[name]?.[metric]) || pair[name][metric] < 0) { - throw new Error('Invalid benchmark timing') + // Artifacts are untrusted data. Validate numeric inputs and escape display text. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 && value <= 100_000 + if ( + !positiveInteger(result.size) || + !positiveInteger(result.samples) || + !Number.isSafeInteger(result.warmup) || + result.warmup < 0 || + result.warmup > 100_000 || + !Array.isArray(result.pairs) || + !result.pairs.length || + result.pairs.length > 100 + ) { + throw new Error('Invalid benchmark configuration') + } + for (const pair of result.pairs) { + if ( + !Array.isArray(pair.order) || + pair.order.length !== 2 || + [...pair.order].sort().join(',') !== 'base,candidate' + ) { + throw new Error('Invalid benchmark execution order') + } + for (const name of ['base', 'candidate']) { + if (name === 'base' && pair.base?.status === 'unsupported') { + if (typeof pair.base.reason !== 'string' || !pair.base.reason.trim()) { + throw new Error('Invalid unsupported baseline reason') + } + continue + } + if (pair[name]?.status === 'unsupported') throw new Error('Candidate benchmark unsupported') + for (const metric of ['medianGenerationSyncMs', 'medianTotalToIdleMs']) { + if (!Number.isFinite(pair[name]?.[metric]) || pair[name][metric] < 0) { + throw new Error('Invalid benchmark timing') + } } } } - } - const text = (value) => - String(value) - .slice(0, 120) - .replace(/[\\`*_[\]<>|#\r\n]/g, ' ') - report.title = text(report.title) - report.browserVersion = text(report.browserVersion) - report.cpuSlowdown = 20 - report.candidate.dirty = false - report.comparison = comparePairs(report.pairs) - if ( - report.comparison.some( - (row) => - !Number.isFinite(row.differenceMs) || - (row.changePercent !== null && !Number.isFinite(row.changePercent)) - ) - ) { - throw new Error('Invalid benchmark comparison') + const text = (value) => + String(value) + .slice(0, 120) + .replace(/[\\`*_[\]<>|#\r\n]/g, ' ') + for (const pair of result.pairs) { + if (pair.base.status === 'unsupported') pair.base.reason = text(pair.base.reason) + } + result.title = text(result.title) + result.browserVersion = text(result.browserVersion) + result.cpuSlowdown = 20 + result.candidate.dirty = false + result.comparison = comparePairs(result.pairs) + if ( + result.comparison.some( + (row) => + (row.differenceMs !== null && !Number.isFinite(row.differenceMs)) || + (row.changePercent !== null && !Number.isFinite(row.changePercent)) + ) + ) { + throw new Error('Invalid benchmark comparison') + } } const path = `runs/${run.id}-${run.run_attempt || 1}` - const markdown = `${formatComparison(report)}\n[JSON data](comparison.json) · [Workflow run](${run.html_url})\n` + const markdown = `${Object.hasOwn(report, 'benchmarks') ? formatComparisonSuite(report) : formatComparison(report)}\n[JSON data](comparison.json) · [Workflow run](${run.html_url})\n` let parent let baseTree try { @@ -124,18 +152,22 @@ module.exports = async ({ github, context, core }) => { } const url = `${context.serverUrl}/${repo.owner}/${repo.repo}/blob/${commit.sha}/${path}/report.md` - const change = (metric) => { - const value = report.comparison.find((row) => row.metric === metric).changePercent - return value === null ? 'n/a' : `${value > 0 ? '+' : ''}${value.toFixed(2)}%` - } const body = [ marker, '### Benchmark comparison', '', - '| Timing | Change |', - '| --- | ---: |', - `| Synchronous generation | ${change('medianGenerationSyncMs')} |`, - `| Total time to idle | ${change('medianTotalToIdleMs')} |`, + formatComparisonOverview(reports), + '', + ...reports.map( + (result) => + `${result.title}: ${result.pairs.length} pairs, ${result.warmup} warmups and ${result.samples} samples per run.` + ), + '', + ...reports.flatMap((result) => + unsupportedReasons(result).map( + (reason) => `${result.title}: N/A — unsupported by baseline: ${reason}` + ) + ), '', 'Negative means faster. Informational results; small changes can be measurement noise.', '', diff --git a/.github/scripts/publish-benchmark.test.cjs b/.github/scripts/publish-benchmark.test.cjs index dc40e792..cc8f7387 100644 --- a/.github/scripts/publish-benchmark.test.cjs +++ b/.github/scripts/publish-benchmark.test.cjs @@ -19,7 +19,13 @@ after(async () => { await rm(directory, { recursive: true, force: true }) }) -const fixture = async ({ existing = false, stale = false, invalid = false } = {}) => { +const fixture = async ({ + existing = false, + stale = false, + invalid = false, + suite = false, + mutate, +} = {}) => { const calls = [] const report = { title: 'Element generation benchmark', @@ -38,7 +44,22 @@ const fixture = async ({ existing = false, stale = false, invalid = false } = {} ], comparison: [{ changePercent: 999 }], // Recomputed rather than trusted. } - await writeFile('benchmark-data/comparison.json', JSON.stringify(report)) + const data = suite + ? { + base: report.base, + candidate: report.candidate, + benchmarks: [ + { ...report, benchmark: 'element-creation' }, + { + ...structuredClone(report), + benchmark: 'component-creation', + title: 'Component generation benchmark', + }, + ], + } + : report + mutate?.(data) + await writeFile('benchmark-data/comparison.json', JSON.stringify(data)) const method = (name, data) => async (args) => { calls.push({ name, args }) return { data } @@ -137,3 +158,98 @@ test('skips stale results and rejects invalid timings before publication', async await assert.rejects(publish(invalid), /Invalid benchmark timing/) assert.ok(!invalid.calls.some((call) => call.name === 'createTree')) }) + +test('publishes every benchmark with individual comparisons and run configuration', async () => { + const mock = await fixture({ suite: true }) + await publish(mock) + const body = mock.calls.find((call) => call.name === 'createComment').args.body + assert.match(body, /Benchmark \| Generation change \| Time to idle change/) + assert.match(body, /Element generation benchmark \| -20\.00% \| \+10\.00%/) + assert.match(body, /Component generation benchmark \| -20\.00% \| \+10\.00%/) + assert.match(body, /1 pairs, 5 warmups and 20 samples/) + const tree = mock.calls.find((call) => call.name === 'createTree').args.tree + assert.match(tree[0].content, /## Element generation benchmark: comparison/) + assert.match(tree[0].content, /## Component generation benchmark: comparison/) + const saved = JSON.parse(tree[1].content) + assert.equal(saved.benchmarks.length, 2) + assert.equal(saved.benchmarks[1].comparison[0].changePercent, -20) +}) + +test('rejects invalid suite entries before writing reports or comments', async () => { + for (const [mutate, expected] of [ + [ + (report) => { + report.benchmarks = [] + }, + /Invalid benchmark suite/, + ], + [ + (report) => { + report.benchmarks[1].pairs[0].candidate.medianTotalToIdleMs = -1 + }, + /Invalid benchmark timing/, + ], + [ + (report) => { + report.benchmarks[1].candidate.commit = 'different' + }, + /commit identities/, + ], + ]) { + const mock = await fixture({ suite: true, mutate }) + await assert.rejects(publish(mock), expected) + assert.ok( + !mock.calls.some((call) => + ['createTree', 'createComment', 'updateComment'].includes(call.name) + ) + ) + } +}) + +test('escapes suite titles before rendering comment tables and report sections', async () => { + const mock = await fixture({ + suite: true, + mutate: (report) => { + report.benchmarks[1].title = '