From 5d2115477368174464cd464c104d47ccbe20bf9d Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 17 Nov 2026 17:21:13 +0800 Subject: [PATCH 1/3] fix(web-ui): center session status and trailing controls in sidebar rows --- .../sections/sessions/SessionStatusIndicator.scss | 5 +++++ .../NavPanel/sections/sessions/SessionsSection.scss | 3 +++ .../sections/sessions/SessionsSectionLayout.test.ts | 3 +++ .../workspaces/AssistantSessionHistory.scss | 8 ++++++-- .../workspaces/WorkspaceListSectionLayout.test.ts | 13 +++++++++++++ 5 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionStatusIndicator.scss b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionStatusIndicator.scss index 54c02093d6..246b4569b8 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionStatusIndicator.scss +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionStatusIndicator.scss @@ -5,6 +5,11 @@ inline-size: var(--openbitfun-space-5); block-size: var(--openbitfun-space-5); + > [data-openbitfun-component='icon'] { + display: block; + vertical-align: middle; + } + &[data-status='running'] > [data-openbitfun-component='icon'] { animation: session-status-running 1.4s linear infinite; } diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss index 90a2d29bf4..a42054ae23 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss @@ -255,6 +255,8 @@ &__inline-item-trailing { display: grid; flex: 0 0 var(--openbitfun-space-5); + grid-template-rows: minmax(0, 1fr); + place-content: center; place-items: center; inline-size: var(--openbitfun-space-5); block-size: var(--openbitfun-space-5); @@ -262,6 +264,7 @@ &__inline-item-status { grid-area: 1 / 1; + line-height: 0; pointer-events: none; .openbitfun-nav-panel__inline-item:hover &, diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSectionLayout.test.ts b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSectionLayout.test.ts index 734d7293af..83fdce5371 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSectionLayout.test.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSectionLayout.test.ts @@ -59,7 +59,10 @@ describe('SessionsSection layout styles', () => { const trailingBlock = extractInlineItemBlock(stylesheet, 'trailing'); expect(trailingBlock).toContain('display: grid;'); expect(trailingBlock).toContain('flex: 0 0 var(--openbitfun-space-5);'); + expect(trailingBlock).toContain('grid-template-rows: minmax(0, 1fr);'); + expect(trailingBlock).toContain('place-content: center;'); const statusBlock = extractInlineItemBlock(stylesheet, 'status'); + expect(statusBlock).toContain('line-height: 0;'); expect(statusBlock).toContain('grid-area: 1 / 1;'); expect(statusBlock).not.toContain('margin-inline-end'); expect(statusBlock).toContain('.openbitfun-nav-panel__inline-item:hover &'); diff --git a/src/web-ui/src/app/components/NavPanel/sections/workspaces/AssistantSessionHistory.scss b/src/web-ui/src/app/components/NavPanel/sections/workspaces/AssistantSessionHistory.scss index be625e7cbe..289fc7cdff 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/workspaces/AssistantSessionHistory.scss +++ b/src/web-ui/src/app/components/NavPanel/sections/workspaces/AssistantSessionHistory.scss @@ -5,11 +5,15 @@ } .openbitfun-nav-panel__inline-item-trailing { - // Reserve both actions even while hidden, so their intrinsic width cannot - // push the status icon outside the row's clipped boundary. + // Reserve both actions on both axes even while hidden, so the xs default + // icon button neither clips the status icon nor overflows the 20px trailing + // track downward. flex-basis: calc(var(--openbitfun-control-icon-button-xs-size) + var(--openbitfun-space-5)); inline-size: calc(var(--openbitfun-control-icon-button-xs-size) + var(--openbitfun-space-5)); + block-size: var(--openbitfun-control-icon-button-xs-size); grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(0, 1fr); + align-content: center; justify-items: end; } } diff --git a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSectionLayout.test.ts b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSectionLayout.test.ts index 641049b146..de2366d46d 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSectionLayout.test.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSectionLayout.test.ts @@ -322,4 +322,17 @@ describe('WorkspaceListSection layout styles', () => { expect(assistant).not.toContain('AssistantSessionHistoryDialog'); expect(assistant).toContain('handleOpenLatestAssistantSession'); }); + + it('centers assistant history trailing status and action controls on the block axis', () => { + const assistantHistoryStyles = readFileSync( + fileURLToPath(new URL('./AssistantSessionHistory.scss', import.meta.url)), + 'utf8', + ).replace(/\r\n/g, '\n'); + const trailing = extractBlock(assistantHistoryStyles, '.openbitfun-nav-panel__inline-item-trailing'); + + expect(trailing).toContain('block-size: var(--openbitfun-control-icon-button-xs-size);'); + expect(trailing).toContain('grid-template-rows: minmax(0, 1fr);'); + expect(trailing).toContain('align-content: center;'); + expect(trailing).toContain('justify-items: end;'); + }); }); From 6784dc6f6893023e10f7613c5cce1a80795dfed7 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 17 Nov 2026 17:21:13 +0800 Subject: [PATCH 2/3] fix(web-ui): stabilize backdrop and masked transcript compositing --- .../flow-chat/composer/ChatComposer.meta.ts | 1 - .../composer/ChatComposer.module.css | 7 ++-- .../src/generated/chat-styles.css | 7 ++-- src/shared/miniapp-chrome/generated/theme.css | 1 - src/web-ui/src/app/layout/AppLayout.scss | 1 + src/web-ui/src/app/styles/visual-skin.scss | 4 +++ .../components/modern/FlowChatHeader.scss | 36 +++++++++++++------ .../VirtualMessageList.edgeFade.test.ts | 10 ++++++ .../components/modern/VirtualMessageList.scss | 5 +++ .../AppearanceBackgroundMedia.test.tsx | 8 +++++ .../visual-skin/video-backdrop.test.ts | 17 +++++++++ 11 files changed, 81 insertions(+), 16 deletions(-) diff --git a/design-system/packages/ui/src/flow-chat/composer/ChatComposer.meta.ts b/design-system/packages/ui/src/flow-chat/composer/ChatComposer.meta.ts index 3dc973e0d3..722ffdd053 100644 --- a/design-system/packages/ui/src/flow-chat/composer/ChatComposer.meta.ts +++ b/design-system/packages/ui/src/flow-chat/composer/ChatComposer.meta.ts @@ -20,7 +20,6 @@ export const chatComposerMeta = { "border.width.default", "color.composer.border", "color.composer.contextBackground", - "control.composer.contextBlur", "control.composer.surfaceRadius", "control.composer.surfacePadding", "control.composer.surfaceGap", diff --git a/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css b/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css index 7e5d0f14a4..4d7730ce2e 100644 --- a/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css +++ b/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css @@ -12,8 +12,11 @@ .root[data-has-context="true"] { background: var(--openbitfun-color-composer-context-background); - backdrop-filter: blur(var(--openbitfun-control-composer-context-blur)); - -webkit-backdrop-filter: blur(var(--openbitfun-control-composer-context-blur)); + /* A transparent composer must not blur a rectangular patch of the shared + wallpaper. The patch becomes especially visible while reading older + messages and looks like an unintended shadow beside the input. */ + backdrop-filter: none; + -webkit-backdrop-filter: none; } .context { diff --git a/src/apps/miniapp-shell/src/generated/chat-styles.css b/src/apps/miniapp-shell/src/generated/chat-styles.css index 84401c61c3..18b3fa7579 100644 --- a/src/apps/miniapp-shell/src/generated/chat-styles.css +++ b/src/apps/miniapp-shell/src/generated/chat-styles.css @@ -327,8 +327,11 @@ .miniapp-ChatComposer-root[data-has-context="true"] { background: var(--openbitfun-color-composer-context-background); - backdrop-filter: blur(var(--openbitfun-control-composer-context-blur)); - -webkit-backdrop-filter: blur(var(--openbitfun-control-composer-context-blur)); + /* A transparent composer must not blur a rectangular patch of the shared + wallpaper. The patch becomes especially visible while reading older + messages and looks like an unintended shadow beside the input. */ + backdrop-filter: none; + -webkit-backdrop-filter: none; } .miniapp-ChatComposer-context { diff --git a/src/shared/miniapp-chrome/generated/theme.css b/src/shared/miniapp-chrome/generated/theme.css index 1bce133a40..e8e784995b 100644 --- a/src/shared/miniapp-chrome/generated/theme.css +++ b/src/shared/miniapp-chrome/generated/theme.css @@ -10,7 +10,6 @@ --openbitfun-control-chat-composer-compact-padding-inline: 8px; --openbitfun-control-chat-composer-compact-track-height: 24px; --openbitfun-control-chat-composer-control-height: 24px; - --openbitfun-control-composer-context-blur: 10px; --openbitfun-control-composer-surface-gap: 12px; --openbitfun-control-composer-surface-padding: 8px; --openbitfun-control-composer-surface-radius: 16px; diff --git a/src/web-ui/src/app/layout/AppLayout.scss b/src/web-ui/src/app/layout/AppLayout.scss index 66ca3c49b2..8340b9025b 100644 --- a/src/web-ui/src/app/layout/AppLayout.scss +++ b/src/web-ui/src/app/layout/AppLayout.scss @@ -157,6 +157,7 @@ html[data-openbitfun-native-material='sidebar'] body { overflow: hidden; background-repeat: no-repeat; pointer-events: none; + transform: translateZ(0); } .openbitfun-appearance-background-media__video { diff --git a/src/web-ui/src/app/styles/visual-skin.scss b/src/web-ui/src/app/styles/visual-skin.scss index 6318914cc3..aca67cc4b0 100644 --- a/src/web-ui/src/app/styles/visual-skin.scss +++ b/src/web-ui/src/app/styles/visual-skin.scss @@ -44,6 +44,10 @@ overflow: hidden; border-radius: inherit; pointer-events: none; + // Keep the backdrop in a stable composited layer while masked transcript + // rows reveal hover controls. Otherwise WebKit can re-composite the video + // and its scrim together for a frame, briefly darkening the whole shell. + transform: translateZ(0); &::before, &::after { diff --git a/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.scss b/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.scss index 235b5a5bfe..56c88395cc 100644 --- a/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.scss +++ b/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.scss @@ -109,10 +109,18 @@ height: 4px; border-radius: 999px; background: var(--openbitfun-color-status-success-emphasis); - box-shadow: - 0 0 0 1px var(--openbitfun-color-surface-raised), - 0 0 0 0 color-mix(in srgb, var(--openbitfun-color-status-success-emphasis) 42%, transparent); + box-shadow: 0 0 0 1px var(--openbitfun-color-surface-raised); animation: flowchat-header-session-overview-pulse 1.45s ease-out infinite; + + &::after { + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + background: inherit; + pointer-events: none; + animation: flowchat-header-session-overview-halo 1.45s ease-out infinite; + } } @keyframes flowchat-header-session-overview-pulse { @@ -120,22 +128,30 @@ 100% { transform: scale(1); opacity: 0.9; - box-shadow: - 0 0 0 1px var(--openbitfun-color-surface-raised), - 0 0 0 0 color-mix(in srgb, var(--openbitfun-color-status-success-emphasis) 40%, transparent); } 50% { transform: scale(1.22); opacity: 1; - box-shadow: - 0 0 0 1px var(--openbitfun-color-surface-raised), - 0 0 0 5px color-mix(in srgb, var(--openbitfun-color-status-success-emphasis) 0%, transparent); + } + } + + @keyframes flowchat-header-session-overview-halo { + 0% { + transform: scale(1); + opacity: 0.42; + } + + 50%, + 100% { + transform: scale(3.5); + opacity: 0; } } @media (prefers-reduced-motion: reduce) { - &__session-overview-status-dot { + &__session-overview-status-dot, + &__session-overview-status-dot::after { animation: none; } } diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.edgeFade.test.ts b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.edgeFade.test.ts index a576a11af1..a3739f9a72 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.edgeFade.test.ts +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.edgeFade.test.ts @@ -68,6 +68,16 @@ describe('FlowChat transcript edge fade', () => { expect(stylesheet).not.toContain('backdrop-filter'); }); + it('keeps the animated transcript mask on a stable compositing path without trapping fixed descendants', () => { + const stylesheet = readSource('./VirtualMessageList.scss'); + const scroller = stylesheet.match(/&__scroller\s*\{[\s\S]*?\n\s{2}\}/)?.[0]; + + expect(scroller).toBeDefined(); + expect(scroller).toContain('will-change: opacity;'); + expect(scroller).not.toMatch(/(?:^|\s)transform\s*:/); + expect(scroller).not.toContain('will-change: transform'); + }); + it('removes the mask in forced-colors mode', () => { const stylesheet = readSource('./VirtualMessageList.scss'); const forcedColors = stylesheet.slice(stylesheet.indexOf('@media (forced-colors: active)')); diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss index b5308f1fff..bcbc741dcd 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss @@ -92,6 +92,11 @@ // fits. Overflow restores these defaults without changing layout geometry. -webkit-mask-size: 100% 100%; mask-size: 100% 100%; + // Runtime status spinners, hover controls, and streaming rows continuously + // invalidate this masked subtree. Keep its offscreen surface alive via + // opacity will-change (never `transform`, which traps non-portaled + // `position: fixed` views such as expanded GenUI maps inside the scroller). + will-change: opacity; } // At the actual scroll start there is no content entering from above, so diff --git a/src/web-ui/src/infrastructure/appearance/runtime/AppearanceBackgroundMedia.test.tsx b/src/web-ui/src/infrastructure/appearance/runtime/AppearanceBackgroundMedia.test.tsx index b4748b3723..8e71666fd4 100644 --- a/src/web-ui/src/infrastructure/appearance/runtime/AppearanceBackgroundMedia.test.tsx +++ b/src/web-ui/src/infrastructure/appearance/runtime/AppearanceBackgroundMedia.test.tsx @@ -1,5 +1,7 @@ // @vitest-environment jsdom +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; import { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { renderToStaticMarkup } from 'react-dom/server'; @@ -72,6 +74,12 @@ describe('AppearanceBackgroundMedia', () => { expect(html).toContain('data-media-ready="false"'); }); + it('keeps the appearance video backdrop on a dedicated composited layer', () => { + const styles = readFileSync(resolve('src/app/layout/AppLayout.scss'), 'utf8'); + const layerRule = styles.match(/\.openbitfun-appearance-background-media\s*\{[^}]*\}/)?.[0]; + expect(layerRule).toContain('transform: translateZ(0);'); + }); + it('keeps the poster visible until a video frame is presented and hides the video again when suspended', async () => { const releaseRevision = vi.fn(); const retainRevision = vi.fn(() => releaseRevision); diff --git a/src/web-ui/src/infrastructure/visual-skin/video-backdrop.test.ts b/src/web-ui/src/infrastructure/visual-skin/video-backdrop.test.ts index 333efe6676..1e77330e62 100644 --- a/src/web-ui/src/infrastructure/visual-skin/video-backdrop.test.ts +++ b/src/web-ui/src/infrastructure/visual-skin/video-backdrop.test.ts @@ -1,4 +1,7 @@ // @vitest-environment jsdom +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { compile } from 'sass'; import JSZip from 'jszip'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { VisualSkinRuntime } from './runtime'; @@ -86,6 +89,20 @@ describe('mp4 backdrop', () => { expect(document.querySelector('main')!.getAttribute('data-openbitfun-skin-artwork')).toBe('true'); }); + it('keeps the video paint plane composited while transcript hover controls change', () => { + const styles = compile(resolve('src/app/styles/visual-skin.scss')).css; + const plane = styles.match(/> \[data-openbitfun-skin-paint\]\s*\{[^}]*transform: translateZ\(0\);[^}]*\}/)?.[0]; + expect(plane).toContain('transform: translateZ(0)'); + }); + + it('does not blur a rectangular wallpaper patch behind the composer', () => { + const source = readFileSync(resolve('../../design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css'), 'utf8'); + const contextRule = source.match(/\.root\[data-has-context="true"\]\s*\{[^}]*\}/)?.[0]; + expect(contextRule).toContain('backdrop-filter: none'); + expect(contextRule).toContain('-webkit-backdrop-filter: none'); + expect(contextRule).not.toContain('blur('); + }); + it('keeps the same player across repaints, swaps mode-specific videos, and cleans up on deactivate', async () => { const modeSkin = await parser.parse(await zipWith({ manifest, From 77236cf6164551ea2b85570f7458d9edb62fa6e7 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 17 Nov 2026 17:21:13 +0800 Subject: [PATCH 3/3] perf(visual-skin): avoid full-DOM rescans and style recompiles on scroll --- .../visual-skin/runtime.regression.test.ts | 58 +++++ .../src/infrastructure/visual-skin/runtime.ts | 222 +++++++++++++----- 2 files changed, 222 insertions(+), 58 deletions(-) diff --git a/src/web-ui/src/infrastructure/visual-skin/runtime.regression.test.ts b/src/web-ui/src/infrastructure/visual-skin/runtime.regression.test.ts index 428cad7379..383bd57209 100644 --- a/src/web-ui/src/infrastructure/visual-skin/runtime.regression.test.ts +++ b/src/web-ui/src/infrastructure/visual-skin/runtime.regression.test.ts @@ -426,6 +426,64 @@ describe('interaction refresh work', () => { expect(entry(runtime, 'components[0].slots.root')?.status).toBe('unresolved'); } finally { query.mockRestore(); } }); + + it('skips DOM rescans, style recompiles, and projection reports during virtualized transcript scrolling without watchers', async () => { + const storage = new TestStorage(), skin = source('a'); + skin.assets = { art: { mimeType: 'image/svg+xml', source: { kind: 'data', data: 'data:image/svg+xml;base64,PHN2Zy8+' } } }; + skin.surfaces = [{ surface: 'shell', backgroundAssetId: 'art' }, { surface: 'chat', backgroundSource: 'shell', baseOpacity: 0.3 }]; + skin.components = [ + { component: 'navigation-panel', slots: { root: { assetId: 'art', backgroundPosition: '15% 25%' } } }, + { component: 'icon-button', tokens: { 'color.content.primary': '#444444' } }, + ]; + await install(storage, skin); + document.body.innerHTML = '
'; + const runtime = new VisualSkinRuntime(storage); runtimes.push(runtime); + await runtime.activate('a'); await tick(); + const scroller = document.getElementById('scroller')!; + const style = document.querySelector('style[data-openbitfun-skin-runtime]')!; + const initialCss = style.textContent; + const snapshots: number[] = []; + const unsubscribe = runtime.subscribe(() => snapshots.push(1)); + const query = vi.spyOn(document, 'querySelectorAll'); + try { + for (let i = 0; i < 12; i++) { + const row = document.createElement('div'); + row.setAttribute('data-openbitfun-component', 'virtual-item'); + row.setAttribute('data-openbitfun-part', 'root'); + row.innerHTML = '
'; + scroller.append(row); + row.dispatchEvent(new Event('pointerover', { bubbles: true })); + if (scroller.childElementCount > 4) scroller.firstElementChild?.remove(); + } + await tick(); + expect(query).not.toHaveBeenCalled(); + expect(style.textContent).toBe(initialCss); + expect(snapshots).toHaveLength(0); + + // Subscribing a visible projection watcher later reconciles current DOM state on demand. + const stopWatching = runtime.watchProjection(() => true); + await tick(); + expect(entry(runtime, 'components[1]')?.message).toContain('4 mounted component(s)'); + stopWatching(); + } finally { unsubscribe(); query.mockRestore(); } + }); + + it('recompiles part rules when a child part mounts inside an already-mounted component owner', async () => { + const storage = new TestStorage(), skin = source('a'); + skin.assets = { art: { mimeType: 'image/svg+xml', source: { kind: 'data', data: 'data:image/svg+xml;base64,PHN2Zy8+' } } }; + skin.components = [{ component: 'button', slots: { 'leading-icon': { assetId: 'art', backgroundPosition: '25% 75%' } } }]; + await install(storage, skin); + document.body.innerHTML = ''; + const runtime = new VisualSkinRuntime(storage); runtimes.push(runtime); + await runtime.activate('a'); await tick(); + const wrap = document.querySelector('#owner > span')!; + const icon = document.createElement('span'); + icon.id = 'late-icon'; + icon.setAttribute('data-openbitfun-part', 'leading-icon'); + wrap.append(icon); + await tick(); + expect(paintPosition('late-icon')).toBe('25% 75%'); + }); }); describe('current mode diagnostics', () => { diff --git a/src/web-ui/src/infrastructure/visual-skin/runtime.ts b/src/web-ui/src/infrastructure/visual-skin/runtime.ts index 05c5429d21..50fb9bef55 100644 --- a/src/web-ui/src/infrastructure/visual-skin/runtime.ts +++ b/src/web-ui/src/infrastructure/visual-skin/runtime.ts @@ -31,6 +31,35 @@ const SAFE_BACKGROUND_POSITION = /^(?:center|top|bottom|left|right|[-+]?\d{1,3}( const DEFAULT_SCRIM_OPACITY = 0; const PAINT_ATTRIBUTES = ['data-openbitfun-paint-layer', 'data-openbitfun-edge-layer', 'data-openbitfun-component', 'data-openbitfun-product-component', 'data-openbitfun-scene', 'data-openbitfun-surface', 'data-openbitfun-skin-slot', 'data-openbitfun-part', 'data-openbitfun-product-part']; const PAINT_TARGET_SELECTOR = PAINT_ATTRIBUTES.map(name => `[${name}]`).join(','); +const SURFACE_MUTATION_SELECTOR = `[data-openbitfun-surface],[${SURFACE_ATTRIBUTE}],[${PAINT_PLANE_ATTRIBUTE}]`; +const OBSERVED_STATE_ATTRIBUTES = ['data-disabled', 'data-invalid', 'data-selected', 'data-openbitfun-state', 'aria-selected', 'aria-pressed', 'aria-current', 'aria-disabled', 'aria-checked', 'aria-expanded', 'aria-invalid', 'aria-readonly', 'aria-required', 'aria-busy', 'disabled', 'checked', 'open', 'readonly', 'required']; +const INTERACTION_DIAGNOSTIC_EVENTS = ['pointerover', 'pointerout', 'pointerdown', 'pointerup', 'focusin', 'focusout', 'change', 'input', 'keydown', 'keyup', 'reset'] as const; + +function hasPartSlotRules(slots: VisualSkinStateRecipe['slots']): boolean { + return Object.values(slots ?? {}).some(Boolean); +} + +function dynamicPartOwnerSelector(skin: StoredVisualSkin, mode: VisualSkinMode): string { + const selectors: string[] = []; + for (const recipe of skin.components ?? []) { + if (!SAFE_IDENTIFIER.test(recipe.component)) continue; + const hasSlots = hasPartSlotRules(recipe.slots) + || Object.entries(recipe.states ?? {}).some(([state, stateRecipe]) => Boolean(stateRecipe && SAFE_STATE.test(state) && hasPartSlotRules(stateRecipe.slots))); + if (!hasSlots) continue; + const id = cssEscape(recipe.component); + selectors.push(`[data-openbitfun-component="${id}"]`, `[data-openbitfun-product-component="${id}"]`, `[data-openbitfun-scene="${id}"]`); + } + for (const { surface } of resolveSkinSurfaces(skin, mode).selected) { + if (!SAFE_IDENTIFIER.test(surface.surface) || !isVisualSkinSurfaceId(surface.surface)) continue; + const hasSlots = Object.entries(surface.states ?? {}).some(([state, stateRecipe]) => Boolean(stateRecipe && SAFE_STATE.test(state) && hasPartSlotRules(stateRecipe.slots))); + if (hasSlots) selectors.push(`[data-openbitfun-surface="${cssEscape(surface.surface)}"]`); + } + return selectors.join(','); +} + +function subtreeTouchesSelector(node: Node, selector: string): boolean { + return node instanceof Element && (node.matches(selector) || node.querySelector(selector) !== null); +} function cssEscape(value: string): string { @@ -377,8 +406,13 @@ export class VisualSkinRuntime { private initializePromise: Promise | null = null; private mutationObserver: MutationObserver | null = null; private projectionObserver: MutationObserver | null = null; + private skinObserversAttached = false; + private interactionListenersAttached = false; + private disposed = false; private projectionRefreshQueued = false; - private paintRefreshNeeded = false; + private surfaceRefreshNeeded = false; + private styleRefreshNeeded = false; + private modeRefreshNeeded = false; private appliedSkin: StoredVisualSkin | null = null; private readonly partImages = new VisualSkinImageResources(); @@ -390,6 +424,13 @@ export class VisualSkinRuntime { this.partImages.retain([this.appliedSkin, this.snapshot.activeSkin]); } + private hasVisibleProjectionWatcher(): boolean { + for (const isVisible of this.projectionWatchers) { + if (isVisible()) return true; + } + return false; + } + constructor(storage: VisualSkinStorage = createVisualSkinStorage()) { this.storage = storage; } @@ -410,8 +451,12 @@ export class VisualSkinRuntime { /** Interactive diagnostics are opt-in; CSS already owns live state paint. */ watchProjection = (isVisible: () => boolean = () => true): (() => void) => { this.projectionWatchers.add(isVisible); - this.queueRefresh(false); - return () => { this.projectionWatchers.delete(isVisible); }; + this.syncObservers(); + this.queueRefresh({ diagnose: true }); + return () => { + this.projectionWatchers.delete(isVisible); + this.syncObservers(); + }; }; async importPackage(source: ArrayBuffer): Promise { @@ -439,19 +484,13 @@ export class VisualSkinRuntime { if (!skin) throw new Error(`Visual skin is not installed: ${id}`); this.setSnapshot({ status: 'applying', error: undefined }); try { - this.appliedSkin = skin; - document.documentElement.setAttribute(ACTIVE_ID_ATTRIBUTE, skin.manifest.id); - this.syncSurfaceMarkers(skin); - this.replaceStyle(this.skinCss(skin)); + this.applyDisplayedSkin(skin); this.setSnapshot({ previewSkinId: skin.manifest.id, projection: createProjectionReport(skin), status: 'previewing', error: undefined }); this.collectPartImages(); } catch (error) { const restore = this.snapshot.activeSkin; if (restore) { - this.appliedSkin = restore; - document.documentElement.setAttribute(ACTIVE_ID_ATTRIBUTE, restore.manifest.id); - this.syncSurfaceMarkers(restore); - this.replaceStyle(this.skinCss(restore)); + this.applyDisplayedSkin(restore); } else { this.clearAppliedSkin(); } @@ -470,14 +509,19 @@ export class VisualSkinRuntime { this.collectPartImages(); } - private restoreDisplay(skin: StoredVisualSkin | null): void { - if (!skin) { this.clearAppliedSkin(); return; } + private applyDisplayedSkin(skin: StoredVisualSkin): void { this.appliedSkin = skin; + this.syncObservers(); document.documentElement.setAttribute(ACTIVE_ID_ATTRIBUTE, skin.manifest.id); this.syncSurfaceMarkers(skin); this.replaceStyle(this.skinCss(skin)); } + private restoreDisplay(skin: StoredVisualSkin | null): void { + if (!skin) { this.clearAppliedSkin(); return; } + this.applyDisplayedSkin(skin); + } + private async applySelection(id: string | null): Promise { const before = this.snapshot; const previousSkin = this.appliedSkin; @@ -501,10 +545,7 @@ export class VisualSkinRuntime { await this.storage.setSelection(before.activeSkinId); this.clearAppliedSkin(); if (previousSkin) { - this.appliedSkin = previousSkin; - document.documentElement.setAttribute(ACTIVE_ID_ATTRIBUTE, previousSkin.manifest.id); - this.syncSurfaceMarkers(previousSkin); - this.replaceStyle(this.skinCss(previousSkin)); + this.applyDisplayedSkin(previousSkin); } } this.setSnapshot({ ...before, error: message }); @@ -552,72 +593,136 @@ export class VisualSkinRuntime { if (selection) await this.storage.setSelection(null); this.setSnapshot({ initialized: true, status: 'ready', activeSkinId: null, activeSkin: null, previewSkinId: null, projection: null }); } - this.mutationObserver = new MutationObserver(() => this.queueRefresh(true)); + this.syncObservers(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + this.setSnapshot({ initialized: true, status: 'degraded', error: message }); + } + } + + private handleBodyMutations = (records: MutationRecord[]): void => { + const skin = this.appliedSkin; + if (!skin) return; + let surfaces = false; + let styles = false; + let diagnose = false; + let partSelector: string | null = null; + const getPartSelector = (): string => { + if (partSelector === null) partSelector = dynamicPartOwnerSelector(skin, currentMode()); + return partSelector; + }; + + for (const record of records) { + if (record.type === 'attributes') { + diagnose = true; + const attr = record.attributeName!; + if (attr === 'data-openbitfun-surface') surfaces = true; + if (PAINT_ATTRIBUTES.includes(attr) && getPartSelector()) styles = true; + continue; + } + for (const node of [...record.addedNodes, ...record.removedNodes]) { + if (!(node instanceof Element)) continue; + if (!surfaces && subtreeTouchesSelector(node, SURFACE_MUTATION_SELECTOR)) { + surfaces = true; + diagnose = true; + } + if (!styles) { + const selector = getPartSelector(); + if (selector && ( + subtreeTouchesSelector(node, selector) + || (record.target instanceof Element && record.target.closest(selector) !== null && subtreeTouchesSelector(node, PAINT_TARGET_SELECTOR)) + )) { + styles = true; + diagnose = true; + } + } + if (!diagnose && this.projectionWatchers.size > 0 && subtreeTouchesSelector(node, PAINT_TARGET_SELECTOR)) { + diagnose = true; + } + } + } + if (surfaces || styles || diagnose) { + this.queueRefresh({ surfaces, styles, diagnose }); + } + }; + + private syncObservers(): void { + const shouldObserveSkin = !this.disposed && this.appliedSkin !== null && typeof document !== 'undefined'; + if (shouldObserveSkin && !this.skinObserversAttached) { + this.mutationObserver ??= new MutationObserver(() => this.queueRefresh({ mode: true, surfaces: true, styles: true })); this.mutationObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-color-scheme', 'data-contrast'] }); document.addEventListener('visibilitychange', this.syncVideoPlayback); if (document.body) { - this.projectionObserver = new MutationObserver(records => { - let repaint = false, diagnose = false; - for (const record of records) { - if (record.type === 'attributes') { - diagnose = true; - if (PAINT_ATTRIBUTES.includes(record.attributeName!)) repaint = true; - } else if ([...record.addedNodes, ...record.removedNodes].some(node => node instanceof Element && (node.matches(PAINT_TARGET_SELECTOR) || node.querySelector(PAINT_TARGET_SELECTOR)))) { - repaint = true; - } - } - if (repaint || diagnose) this.queueRefresh(repaint); - }); + this.projectionObserver ??= new MutationObserver(this.handleBodyMutations); this.projectionObserver.observe(document.body, { attributes: true, - attributeFilter: [...PAINT_ATTRIBUTES, 'data-disabled', 'data-invalid', 'data-selected', 'data-openbitfun-state', 'aria-selected', 'aria-pressed', 'aria-current', 'aria-disabled', 'aria-checked', 'aria-expanded', 'aria-invalid', 'aria-readonly', 'aria-required', 'aria-busy', 'disabled', 'checked', 'open', 'readonly', 'required'], - childList: true, subtree: true, + attributeFilter: [...PAINT_ATTRIBUTES, ...OBSERVED_STATE_ATTRIBUTES], + childList: true, + subtree: true, }); - for (const name of ['pointerover', 'pointerout', 'pointerdown', 'pointerup', 'focusin', 'focusout', 'change', 'input', 'keydown', 'keyup', 'reset']) { - document.body.addEventListener(name, this.queueProjectionRefresh, true); - } } - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.setSnapshot({ initialized: true, status: 'degraded', error: message }); + this.skinObserversAttached = true; + } else if (!shouldObserveSkin && this.skinObserversAttached) { + this.mutationObserver?.disconnect(); + this.projectionObserver?.disconnect(); + document.removeEventListener('visibilitychange', this.syncVideoPlayback); + this.skinObserversAttached = false; + } + + const shouldObserveInteractions = shouldObserveSkin && this.projectionWatchers.size > 0 && Boolean(document.body); + if (shouldObserveInteractions && !this.interactionListenersAttached) { + for (const name of INTERACTION_DIAGNOSTIC_EVENTS) { + document.body.addEventListener(name, this.queueProjectionRefresh, true); + } + this.interactionListenersAttached = true; + } else if (!shouldObserveInteractions && this.interactionListenersAttached) { + for (const name of INTERACTION_DIAGNOSTIC_EVENTS) { + document.body?.removeEventListener(name, this.queueProjectionRefresh, true); + } + this.interactionListenersAttached = false; } } private queueProjectionRefresh = (): void => { - this.queueRefresh(false); + this.queueRefresh({ diagnose: true }); }; - private queueRefresh(repaint: boolean): void { - if (!repaint && ![...this.projectionWatchers].some(isVisible => isVisible())) return; - this.paintRefreshNeeded ||= repaint; + private queueRefresh(options: { mode?: boolean; surfaces?: boolean; styles?: boolean; diagnose?: boolean }): void { + const watchDiagnostics = Boolean((options.mode || options.diagnose) && (options.mode || this.hasVisibleProjectionWatcher())); + const surfaces = Boolean(options.surfaces); + const styles = Boolean(options.styles); + if (!surfaces && !styles && !watchDiagnostics) return; + this.surfaceRefreshNeeded ||= surfaces; + this.styleRefreshNeeded ||= styles; + this.modeRefreshNeeded ||= Boolean(options.mode); if (this.projectionRefreshQueued || !this.appliedSkin) return; this.projectionRefreshQueued = true; queueMicrotask(() => { this.projectionRefreshQueued = false; - const repaint = this.paintRefreshNeeded; - this.paintRefreshNeeded = false; + const refreshSurfaces = this.surfaceRefreshNeeded; + const refreshStyles = this.styleRefreshNeeded; + const refreshMode = this.modeRefreshNeeded; + this.surfaceRefreshNeeded = false; + this.styleRefreshNeeded = false; + this.modeRefreshNeeded = false; if (!this.appliedSkin) return; - // Native CSS selectors own interactive paint. State changes update only - // diagnostics; ownership/mode changes are the only reasons to recompile. - if (repaint) { - this.syncSurfaceMarkers(this.appliedSkin); - this.replaceStyle(this.skinCss(this.appliedSkin)); + // Native CSS selectors own interactive paint. Reconcile only the exact + // surface markers, part-slot CSS, or opt-in diagnostics that changed. + if (refreshSurfaces) this.syncSurfaceMarkers(this.appliedSkin); + if (refreshStyles) this.replaceStyle(this.skinCss(this.appliedSkin)); + if (refreshMode || this.hasVisibleProjectionWatcher()) { + const projection = createProjectionReport(this.appliedSkin); + if (JSON.stringify(projection) !== JSON.stringify(this.snapshot.projection)) this.setSnapshot({ projection }); } - const projection = createProjectionReport(this.appliedSkin); - if (JSON.stringify(projection) !== JSON.stringify(this.snapshot.projection)) this.setSnapshot({ projection }); }); } dispose(): void { - this.mutationObserver?.disconnect(); - this.projectionObserver?.disconnect(); - document.removeEventListener('visibilitychange', this.syncVideoPlayback); - for (const name of ['pointerover', 'pointerout', 'pointerdown', 'pointerup', 'focusin', 'focusout', 'change', 'input', 'keydown', 'keyup', 'reset']) { - document.body?.removeEventListener(name, this.queueProjectionRefresh, true); - } + this.disposed = true; + this.projectionWatchers.clear(); this.clearAppliedSkin(); + this.syncObservers(); this.partImages.retain([]); - this.projectionWatchers.clear(); this.listeners.clear(); } @@ -647,6 +752,7 @@ export class VisualSkinRuntime { document.querySelectorAll(`video[${VIDEO_ATTRIBUTE}]`).forEach(teardownSkinVideo); document.documentElement.removeAttribute(ACTIVE_ID_ATTRIBUTE); this.appliedSkin = null; + this.syncObservers(); } private syncSurfaceMarkers(skin: StoredVisualSkin | null): void {