Skip to content

Commit 274a3f9

Browse files
authored
Merge pull request #3746 from wgqqqqq/wgq/genui-appearance-theme
fix(genui): follow OpenBitFun Appearance theme
2 parents c4f0be9 + 65ec5aa commit 274a3f9

8 files changed

Lines changed: 98 additions & 57 deletions

File tree

‎src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.test.tsx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,21 @@ describe('GenUI HTML documents', () => {
88
expect(GENUI_HTML_RUNTIME).toEqual(genUICatalog.htmlRuntime);
99
});
1010

11+
it('passes the active Appearance mode into the isolated document', () => {
12+
const result = sanitizeGenUIHtmlSource(
13+
{ kind: 'html-document', html: '<main>Theme aware</main>' },
14+
undefined,
15+
':root{color-scheme:dark;--openbitfun-color-content-primary:#f3f3f5}',
16+
false,
17+
false,
18+
false,
19+
'dark',
20+
);
21+
expect(result.document).toContain('<html data-openbitfun-appearance-mode="dark">');
22+
expect(result.document).toContain('color-scheme:dark');
23+
expect(result.document).toContain('--openbitfun-color-content-primary:#f3f3f5');
24+
});
25+
1126
it('keeps HTML/SVG content while removing active and unsafe host paths', () => {
1227
const result = sanitizeGenUIHtmlSource({
1328
kind: 'html-document',

‎src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.tsx‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { useMemo } from 'react';
22
import { useEffect, useRef } from 'react';
3+
import { useColorScheme } from './components/openui/scheme';
34
import { genUICatalog, type GenUIDesignSpec } from './genUIContract';
45
import type { GenUIHtmlDocumentSource } from './genUITypes';
56

@@ -220,7 +221,7 @@ function inspectionBootstrap(): string {
220221
* retained in the source record but are deliberately disabled by this static
221222
* renderer until a host has negotiated the controlled bridge capability.
222223
*/
223-
export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec, hostStyleResourceCss = '', scriptEnabled = false, inspectionEnabled = false, inlineScriptEnabled = false): GenUIHtmlSanitizeResult {
224+
export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec, hostStyleResourceCss = '', scriptEnabled = false, inspectionEnabled = false, inlineScriptEnabled = false, colorScheme: 'light' | 'dark' = 'light'): GenUIHtmlSanitizeResult {
224225
const diagnostics: string[] = [];
225226
const allowControlledScript = scriptEnabled && !inspectionEnabled;
226227
const scriptNonce = allowControlledScript || inspectionEnabled ? createCspNonce() : undefined;
@@ -307,7 +308,7 @@ export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specifi
307308
}
308309
if (scriptNonce) policy.setAttribute('content', `default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; script-src 'nonce-${scriptNonce}'`);
309310
return {
310-
document: `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${parsed.head.innerHTML}</head><body>${parsed.body.innerHTML}</body></html>`,
311+
document: `<!doctype html><html data-openbitfun-appearance-mode="${colorScheme}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${parsed.head.innerHTML}</head><body>${parsed.body.innerHTML}</body></html>`,
311312
diagnostics,
312313
};
313314
}
@@ -346,8 +347,10 @@ export default function GenUIHtmlDocument({ source, specification, designSpecId,
346347
inspection?: GenUIHtmlInspection;
347348
}) {
348349
const frameRef = useRef<HTMLIFrameElement>(null);
350+
const themeRef = useRef<HTMLDivElement>(null);
351+
const colorScheme = useColorScheme(themeRef);
349352
const hostStyleResourceCss = useMemo(() => {
350-
if (!specification?.styleResources.length || typeof document === 'undefined') return '';
353+
if (typeof document === 'undefined') return '';
351354
const computed = getComputedStyle(document.documentElement);
352355
const tokens: string[] = [];
353356
for (let index = 0; index < computed.length; index++) {
@@ -358,14 +361,11 @@ export default function GenUIHtmlDocument({ source, specification, designSpecId,
358361
// into the opaque document's inline stylesheet.
359362
if (value && !/[{};]/.test(value)) tokens.push(`${name}:${value};`);
360363
}
361-
const base = tokens.length
362-
? `:root{${tokens.join('')}}html,body{margin:0;min-height:100%;color:var(--openbitfun-color-content-primary);background:var(--openbitfun-color-surface-canvas);font-family:var(--openbitfun-type-body-md-font-family);font-size:var(--openbitfun-type-body-md-font-size);line-height:var(--openbitfun-type-body-md-line-height);}`
363-
: '';
364-
return base;
365-
}, [specification]);
364+
return `:root{color-scheme:${colorScheme};${tokens.join('')}}html,body{margin:0;min-height:100%;color:var(--openbitfun-color-content-primary);background:var(--openbitfun-color-surface-canvas);font-family:var(--openbitfun-type-body-md-font-family);font-size:var(--openbitfun-type-body-md-font-size);line-height:var(--openbitfun-type-body-md-line-height);}`;
365+
}, [colorScheme]);
366366
const inspectionEnabled = Boolean(inspection);
367367
const canRunScript = Boolean(scriptEnabled && bridge && source.script?.trim() && !inspectionEnabled);
368-
const sanitized = useMemo(() => sanitizeGenUIHtmlSource(source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled, false), [source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled]);
368+
const sanitized = useMemo(() => sanitizeGenUIHtmlSource(source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled, false, colorScheme), [source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled, colorScheme]);
369369
useEffect(() => {
370370
if (!canRunScript || !bridge) return;
371371
const frame = frameRef.current;
@@ -485,7 +485,7 @@ export default function GenUIHtmlDocument({ source, specification, designSpecId,
485485
window.clearInterval(retryTimer);
486486
};
487487
}, [inspection]);
488-
return <div className="gen-ui-html-document" data-gen-ui-html-document="true" data-gen-ui-source-kind={source.kind} data-gen-ui-sanitize-diagnostics={sanitized.diagnostics.length}>
488+
return <div ref={themeRef} className="gen-ui-html-document" data-gen-ui-html-document="true" data-gen-ui-source-kind={source.kind} data-gen-ui-sanitize-diagnostics={sanitized.diagnostics.length}>
489489
<iframe
490490
title="Generated HTML document"
491491
className="gen-ui-html-document__frame"

‎src/web-ui/src/tools/generative-ui/components/map/MapView.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'maplibre-gl/dist/maplibre-gl.css';
22

33
import { useEffect, useMemo, useRef, useState } from 'react';
4+
import { useColorScheme } from '../openui/scheme';
45
import type { GeoJSONSource, Map as MapLibreMap, Marker } from 'maplibre-gl';
56
import type { GenUIComponentProps } from '../../genUILibrary';
67
import type { GenUIAsyncExecuteOptions, GenUIAsyncRuntime } from '../../genUIAsyncCapabilities';
@@ -223,6 +224,7 @@ export default function MapView({ view, emit, asyncRuntime, isStreaming }: Pick<
223224
const [group, setGroup] = useState('all');
224225
const [infoOpen, setInfoOpen] = useState(false);
225226
const containerRef = useRef<HTMLDivElement>(null);
227+
const dark = useColorScheme(containerRef) === 'dark';
226228
const surfaceRef = useRef<HTMLDivElement>(null);
227229
const mapRef = useRef<MapLibreMap | null>(null);
228230
const markersRef = useRef(new Map<string, { marker: Marker; element: HTMLDivElement; pin: HTMLSpanElement; label: HTMLSpanElement }>());
@@ -232,7 +234,6 @@ export default function MapView({ view, emit, asyncRuntime, isStreaming }: Pick<
232234
const userMovedRef = useRef(false);
233235
const anchoredRef = useRef(false);
234236
const styledDarkRef = useRef(false);
235-
const dark = typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: dark)').matches;
236237
const darkRef = useRef(dark);
237238
darkRef.current = dark;
238239
const maxHeight = Math.min(MAX_HEIGHT, Math.max(200, typeof view.props.height === 'number' ? view.props.height : 400));

‎src/web-ui/src/tools/generative-ui/components/openui/components.css‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@
134134
.iui-button-soft:not(:disabled):hover, :is(.iui-button-outline, .iui-button-ghost):not(:disabled):active { background: var(--iui-pressed); }
135135
.iui-button-solid.iui-button-danger { background: var(--iui-danger); color: #fff; }
136136
.iui-button-solid.iui-button-success { background: var(--iui-success); color: #fff; }
137-
:is(:root[data-openui-theme="dark"], [data-theme="dark"]) .iui-button-solid:is(.iui-button-danger, .iui-button-success) { color: #121212; }
137+
:is(:root[data-openbitfun-appearance-mode="dark"], [data-openbitfun-appearance-mode="dark"]) .iui-button-solid:is(.iui-button-danger, .iui-button-success) { color: var(--iui-canvas); }
138138
.iui-button-solid:is(.iui-button-danger, .iui-button-success):not(:disabled):hover { filter: brightness(1.08); }
139139
:is(.iui-button-outline, .iui-button-soft, .iui-button-ghost).iui-button-danger { color: var(--iui-danger); }
140140
:is(.iui-button-outline, .iui-button-soft, .iui-button-ghost).iui-button-success { color: var(--iui-success); }
@@ -168,7 +168,7 @@
168168
/* Rows in a list keep still: the wash alone shows hover and press. */
169169
.iui-pressable:has(> .iui-row):not([aria-disabled="true"]):is(:hover, :active) { transform: none; }
170170
.iui-pressable.is-selected:not(:has(> .iui-row))::before { content: ""; position: absolute; top: 8px; right: 8px; z-index: 1; width: 18px; height: 18px; border-radius: 50%; background: var(--iui-ink) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none' stroke='white' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2.5 6.2l2.3 2.3 4.7-5'/%3E%3C/svg%3E") center / 12px no-repeat; }
171-
:root[data-openui-theme="dark"] .iui-pressable.is-selected:not(:has(> .iui-row))::before, [data-theme="dark"] .iui-pressable.is-selected:not(:has(> .iui-row))::before { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none' stroke='%23171717' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2.5 6.2l2.3 2.3 4.7-5'/%3E%3C/svg%3E"); }
171+
:is(:root[data-openbitfun-appearance-mode="dark"], [data-openbitfun-appearance-mode="dark"]) .iui-pressable.is-selected:not(:has(> .iui-row))::before { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none' stroke='%23171717' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2.5 6.2l2.3 2.3 4.7-5'/%3E%3C/svg%3E"); }
172172
.iui-pressable[aria-disabled="true"] { cursor: default; }
173173
.iui-pressable:focus-visible { outline: 2px solid var(--iui-focus); outline-offset: 2px; }
174174

@@ -179,15 +179,15 @@
179179
.iui-input:focus, .iui-input:focus-visible { border-color: var(--iui-focus); box-shadow: 0 0 0 2px color-mix(in srgb, var(--iui-focus) 18%, transparent); outline: none; }
180180
.iui-textarea { min-height: 96px; resize: vertical; }
181181
.iui-select { appearance: none; padding-right: 38px; cursor: pointer; background: var(--iui-canvas) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23676767' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E") no-repeat right 12px center / 16px; }
182-
:is(:root[data-openui-theme="dark"], [data-theme="dark"]) .iui-select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23ababab' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E"); }
182+
:is(:root[data-openbitfun-appearance-mode="dark"], [data-openbitfun-appearance-mode="dark"]) .iui-select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23ababab' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E"); }
183183
.iui-date::-webkit-calendar-picker-indicator { opacity: .55; cursor: pointer; }
184184

185185
.iui-segmented { display: inline-flex; align-self: flex-start; gap: 2px; max-width: 100%; padding: 3px; overflow-x: auto; border-radius: 999px; background: var(--iui-surface); scrollbar-width: none; }
186186
.iui-segmented.iui-block { display: flex; }
187187
.iui-segmented > button { flex: 1 0 auto; padding: 6px 14px; border: 0; border-radius: 999px; background: transparent; color: var(--iui-muted); font-size: 13px; line-height: 1.4; white-space: nowrap; cursor: pointer; transition: background .2s, color .2s; }
188188
.iui-segmented > button:hover:not(.is-selected) { color: var(--iui-ink); }
189189
.iui-segmented > button.is-selected { background: var(--iui-canvas); color: var(--iui-ink); font-weight: 560; box-shadow: var(--iui-shadow-sm), 0 0 0 1px var(--iui-border); }
190-
:root[data-openui-theme="dark"] .iui-segmented > button.is-selected, [data-theme="dark"] .iui-segmented > button.is-selected { background: var(--iui-surface-strong); }
190+
:is(:root[data-openbitfun-appearance-mode="dark"], [data-openbitfun-appearance-mode="dark"]) .iui-segmented > button.is-selected { background: var(--iui-surface-strong); }
191191

192192
/* Range: a 24px pill track with an 18px thumb inside a 40px hit area. */
193193
.iui-slider { display: flex; flex-direction: column; min-width: 0; }

‎src/web-ui/src/tools/generative-ui/components/openui/map/map.css‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/web-ui/src/tools/generative-ui/components/openui/scheme.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { useEffect, useState, type RefObject } from "react";
44

5-
/** "dark" when the element sits inside data-theme="dark" (its used color-scheme), else "light". */
5+
/** Read the active host color-scheme and refresh when its Appearance mode changes. */
66
export function useColorScheme(ref: RefObject<HTMLElement | null>): "light" | "dark" {
77
const [scheme, setScheme] = useState<"light" | "dark">("light");
88
useEffect(() => {
@@ -11,9 +11,9 @@ export function useColorScheme(ref: RefObject<HTMLElement | null>): "light" | "d
1111
setScheme(value.trim() === "dark" ? "dark" : "light");
1212
};
1313
read();
14-
// Theme switches flip a data-theme attribute somewhere above us.
14+
// Appearance switches the mode on the document root.
1515
const observer = new MutationObserver(read);
16-
observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ["data-theme"] });
16+
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-openbitfun-appearance-mode", "data-theme"] });
1717
return () => observer.disconnect();
1818
}, [ref]);
1919
return scheme;

0 commit comments

Comments
 (0)