Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@ describe('GenUI HTML documents', () => {
expect(GENUI_HTML_RUNTIME).toEqual(genUICatalog.htmlRuntime);
});

it('passes the active Appearance mode into the isolated document', () => {
const result = sanitizeGenUIHtmlSource(
{ kind: 'html-document', html: '<main>Theme aware</main>' },
undefined,
':root{color-scheme:dark;--openbitfun-color-content-primary:#f3f3f5}',
false,
false,
false,
'dark',
);
expect(result.document).toContain('<html data-openbitfun-appearance-mode="dark">');
expect(result.document).toContain('color-scheme:dark');
expect(result.document).toContain('--openbitfun-color-content-primary:#f3f3f5');
});

it('keeps HTML/SVG content while removing active and unsafe host paths', () => {
const result = sanitizeGenUIHtmlSource({
kind: 'html-document',
Expand Down
20 changes: 10 additions & 10 deletions src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
import { useEffect, useRef } from 'react';
import { useColorScheme } from './components/openui/scheme';
import { genUICatalog, type GenUIDesignSpec } from './genUIContract';
import type { GenUIHtmlDocumentSource } from './genUITypes';

Expand Down Expand Up @@ -220,7 +221,7 @@ function inspectionBootstrap(): string {
* retained in the source record but are deliberately disabled by this static
* renderer until a host has negotiated the controlled bridge capability.
*/
export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec, hostStyleResourceCss = '', scriptEnabled = false, inspectionEnabled = false, inlineScriptEnabled = false): GenUIHtmlSanitizeResult {
export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec, hostStyleResourceCss = '', scriptEnabled = false, inspectionEnabled = false, inlineScriptEnabled = false, colorScheme: 'light' | 'dark' = 'light'): GenUIHtmlSanitizeResult {
const diagnostics: string[] = [];
const allowControlledScript = scriptEnabled && !inspectionEnabled;
const scriptNonce = allowControlledScript || inspectionEnabled ? createCspNonce() : undefined;
Expand Down Expand Up @@ -307,7 +308,7 @@ export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specifi
}
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}'`);
return {
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>`,
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>`,
diagnostics,
};
}
Expand Down Expand Up @@ -346,8 +347,10 @@ export default function GenUIHtmlDocument({ source, specification, designSpecId,
inspection?: GenUIHtmlInspection;
}) {
const frameRef = useRef<HTMLIFrameElement>(null);
const themeRef = useRef<HTMLDivElement>(null);
const colorScheme = useColorScheme(themeRef);
const hostStyleResourceCss = useMemo(() => {
if (!specification?.styleResources.length || typeof document === 'undefined') return '';
if (typeof document === 'undefined') return '';
const computed = getComputedStyle(document.documentElement);
const tokens: string[] = [];
for (let index = 0; index < computed.length; index++) {
Expand All @@ -358,14 +361,11 @@ export default function GenUIHtmlDocument({ source, specification, designSpecId,
// into the opaque document's inline stylesheet.
if (value && !/[{};]/.test(value)) tokens.push(`${name}:${value};`);
}
const base = tokens.length
? `: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);}`
: '';
return base;
}, [specification]);
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);}`;
}, [colorScheme]);
const inspectionEnabled = Boolean(inspection);
const canRunScript = Boolean(scriptEnabled && bridge && source.script?.trim() && !inspectionEnabled);
const sanitized = useMemo(() => sanitizeGenUIHtmlSource(source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled, false), [source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled]);
const sanitized = useMemo(() => sanitizeGenUIHtmlSource(source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled, false, colorScheme), [source, specification, hostStyleResourceCss, canRunScript, inspectionEnabled, colorScheme]);
useEffect(() => {
if (!canRunScript || !bridge) return;
const frame = frameRef.current;
Expand Down Expand Up @@ -485,7 +485,7 @@ export default function GenUIHtmlDocument({ source, specification, designSpecId,
window.clearInterval(retryTimer);
};
}, [inspection]);
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}>
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}>
<iframe
title="Generated HTML document"
className="gen-ui-html-document__frame"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'maplibre-gl/dist/maplibre-gl.css';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useColorScheme } from '../openui/scheme';
import type { GeoJSONSource, Map as MapLibreMap, Marker } from 'maplibre-gl';
import type { GenUIComponentProps } from '../../genUILibrary';
import type { GenUIAsyncExecuteOptions, GenUIAsyncRuntime } from '../../genUIAsyncCapabilities';
Expand Down Expand Up @@ -223,6 +224,7 @@ export default function MapView({ view, emit, asyncRuntime, isStreaming }: Pick<
const [group, setGroup] = useState('all');
const [infoOpen, setInfoOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const dark = useColorScheme(containerRef) === 'dark';
const surfaceRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<MapLibreMap | null>(null);
const markersRef = useRef(new Map<string, { marker: Marker; element: HTMLDivElement; pin: HTMLSpanElement; label: HTMLSpanElement }>());
Expand All @@ -232,7 +234,6 @@ export default function MapView({ view, emit, asyncRuntime, isStreaming }: Pick<
const userMovedRef = useRef(false);
const anchoredRef = useRef(false);
const styledDarkRef = useRef(false);
const dark = typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: dark)').matches;
const darkRef = useRef(dark);
darkRef.current = dark;
const maxHeight = Math.min(MAX_HEIGHT, Math.max(200, typeof view.props.height === 'number' ? view.props.height : 400));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
.iui-button-soft:not(:disabled):hover, :is(.iui-button-outline, .iui-button-ghost):not(:disabled):active { background: var(--iui-pressed); }
.iui-button-solid.iui-button-danger { background: var(--iui-danger); color: #fff; }
.iui-button-solid.iui-button-success { background: var(--iui-success); color: #fff; }
:is(:root[data-openui-theme="dark"], [data-theme="dark"]) .iui-button-solid:is(.iui-button-danger, .iui-button-success) { color: #121212; }
: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); }
.iui-button-solid:is(.iui-button-danger, .iui-button-success):not(:disabled):hover { filter: brightness(1.08); }
:is(.iui-button-outline, .iui-button-soft, .iui-button-ghost).iui-button-danger { color: var(--iui-danger); }
:is(.iui-button-outline, .iui-button-soft, .iui-button-ghost).iui-button-success { color: var(--iui-success); }
Expand Down Expand Up @@ -168,7 +168,7 @@
/* Rows in a list keep still: the wash alone shows hover and press. */
.iui-pressable:has(> .iui-row):not([aria-disabled="true"]):is(:hover, :active) { transform: none; }
.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; }
: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"); }
: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"); }
.iui-pressable[aria-disabled="true"] { cursor: default; }
.iui-pressable:focus-visible { outline: 2px solid var(--iui-focus); outline-offset: 2px; }

Expand All @@ -179,15 +179,15 @@
.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; }
.iui-textarea { min-height: 96px; resize: vertical; }
.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; }
: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"); }
: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"); }
.iui-date::-webkit-calendar-picker-indicator { opacity: .55; cursor: pointer; }

.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; }
.iui-segmented.iui-block { display: flex; }
.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; }
.iui-segmented > button:hover:not(.is-selected) { color: var(--iui-ink); }
.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); }
:root[data-openui-theme="dark"] .iui-segmented > button.is-selected, [data-theme="dark"] .iui-segmented > button.is-selected { background: var(--iui-surface-strong); }
:is(:root[data-openbitfun-appearance-mode="dark"], [data-openbitfun-appearance-mode="dark"]) .iui-segmented > button.is-selected { background: var(--iui-surface-strong); }

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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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

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