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
7 changes: 6 additions & 1 deletion design-system/packages/ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,12 @@ or contains visible keyboard focus. Leaving the viewport hides it; scrolling
from streaming output does not reveal an unattended panel. Touch surfaces retain
visible native thumbs, and forced colors retains system accessibility colors.
Tracks stay transparent. Only color changes, so hover never changes viewport
width, overflow, or scrollbar gutters.
width, overflow, or scrollbar gutters. `DesignSystemProvider`, `ThemeRoot`, and
standalone `ScrollArea` share one document focus subscription. It reads native
`:focus-visible` after input/focus changes; streaming and scrolling do not write
focus state. This avoids applying `:has()` to every descendant of the theme root.
CSS-only consumers without these React owners keep `:focus-within` viewports
visible as a conservative keyboard-accessibility fallback.

`ScrollArea` keeps `scrollbarVisibility="auto"` as the default. `always` keeps
the thumb visible and reserves a scrolling track; `hidden` deliberately hides
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { forwardRef, useCallback, useEffect, useRef, type HTMLAttributes } from "react";
import { classNames } from "../../internal/classNames";
import { retainScrollbarFocus } from "../../internal/scrollbarFocus";
import styles from "./ScrollArea.module.css";

export type ScrollAreaOrientation = "vertical" | "horizontal" | "both";
Expand Down Expand Up @@ -31,6 +32,9 @@ export const ScrollArea = forwardRef<HTMLDivElement, ScrollAreaProps>(
...props
}, ref) {
const viewportRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (viewportRef.current) return retainScrollbarFocus(viewportRef.current.ownerDocument);
}, []);
const setViewportRef = useCallback((viewport: HTMLDivElement | null) => {
viewportRef.current = viewport;
if (typeof ref === "function") ref(viewport);
Expand Down
49 changes: 49 additions & 0 deletions design-system/packages/ui/src/internal/scrollbarFocus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const ATTRIBUTE = "data-openbitfun-focus-visible";
const documents = new WeakMap<Document, { count: number; dispose: () => void }>();

/** Share the browser's focus-visible state without a :has() on every DOM node. */
export function retainScrollbarFocus(ownerDocument: Document): () => void {
let state = documents.get(ownerDocument);
if (!state) {
const root = ownerDocument.documentElement;
const view = ownerDocument.defaultView;
const previous = root.getAttribute(ATTRIBUTE);
let frame: number | undefined;
const update = () => {
frame = undefined;
let active = ownerDocument.activeElement;
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
const value = String(!!active?.matches(":focus-visible"));
if (root.getAttribute(ATTRIBUTE) !== value) root.setAttribute(ATTRIBUTE, value);
};
const schedule = () => {
if (frame === undefined && view) frame = view.requestAnimationFrame(update);
};
// Focus can change without input; keyboard/pointer modality can change
// without moving focus. Read after the browser updates its pseudo-state.
const events = ["focusin", "focusout", "keydown", "keyup", "pointerdown", "pointerup"];
for (const event of events) ownerDocument.addEventListener(event, schedule, true);
view?.addEventListener("focus", schedule);
view?.addEventListener("blur", schedule);
update();
state = { count: 0, dispose: () => {
if (frame !== undefined) view?.cancelAnimationFrame(frame);
for (const event of events) ownerDocument.removeEventListener(event, schedule, true);
view?.removeEventListener("focus", schedule);
view?.removeEventListener("blur", schedule);
if (previous === null) root.removeAttribute(ATTRIBUTE);
else root.setAttribute(ATTRIBUTE, previous);
} };
documents.set(ownerDocument, state);
}
state.count++;
let released = false;
return () => {
if (released) return;
released = true;
if (--state.count === 0) {
state.dispose();
documents.delete(ownerDocument);
}
};
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
import { useEffect, useRef, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
import { classNames } from "../../internal/classNames";
import { retainScrollbarFocus } from "../../internal/scrollbarFocus";
import styles from "./ThemeRoot.module.css";

export type ColorScheme = "light" | "dark";
Expand Down Expand Up @@ -28,6 +29,10 @@ export function ThemeRoot({
tokenOverrides,
...props
}: ThemeRootProps) {
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (rootRef.current) return retainScrollbarFocus(rootRef.current.ownerDocument);
}, []);
const mergedStyle = {
...style,
...tokenOverrides,
Expand All @@ -36,6 +41,7 @@ export function ThemeRoot({
return (
<div
{...props}
ref={rootRef}
className={classNames(styles.root, className)}
data-openbitfun-design-system-root=""
data-color-scheme={colorScheme}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useContext, useMemo, type ReactNode } from "react";
import { useContext, useEffect, useMemo, type ReactNode } from "react";
import { retainScrollbarFocus } from "../internal/scrollbarFocus";
import { ApplicationTitleTooltips, ApplicationTitleTooltipsContext } from "./ApplicationTitleTooltips";
import type {
ColorScheme,
Expand Down Expand Up @@ -42,6 +43,7 @@ export function DesignSystemProvider({
nativeTooltipPolicy = "native",
}: DesignSystemProviderProps) {
const ownerDocument = resolvePortalTarget(portalHost)?.ownerDocument;
useEffect(() => ownerDocument && retainScrollbarFocus(ownerDocument), [ownerDocument]);
const layerStack = getOverlayLayerStack(ownerDocument);
const inheritedTitlePolicy = useContext(ApplicationTitleTooltipsContext);
const applicationTitles = inheritedTitlePolicy || nativeTooltipPolicy === "application";
Expand Down
10 changes: 6 additions & 4 deletions design-system/packages/ui/src/styles/scrollbars.css
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,17 @@
* Hide only for a primary mouse/trackpad. Touch keeps a discoverable native
* thumb, and forced colors keeps the operating system's accessibility cues.
* Keyboard focus reveals its viewport without latching ordinary mouse focus.
* A document focus flag avoids a relational selector on every descendant.
* CSS-only consumers conservatively keep focused viewports discoverable.
* Scroll events (including streaming output) do not reveal an idle viewport.
*/
@media (hover: hover) and (pointer: fine) and (forced-colors: none) {
:where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:not(:hover, :focus-visible, :has(:focus-visible), [data-openbitfun-scrollbar-visibility="always"]))::-webkit-scrollbar-thumb {
:where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:not(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"])):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *)::-webkit-scrollbar-thumb {
background: transparent;
}

@supports (scrollbar-color: transparent transparent) {
:where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:not(:hover, :focus-visible, :has(:focus-visible), [data-openbitfun-scrollbar-visibility="always"])) {
:where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:not(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"])):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *) {
scrollbar-color: transparent transparent;
}
}
Expand All @@ -66,11 +68,11 @@
/* Opt-in hover viewports release idle tracks instead of only hiding paint.
Native overflow still owns whether a track is needed when revealed. */
@media (hover: hover) and (pointer: fine) and (forced-colors: none) {
[data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible, :has(:focus-visible)) {
[data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *) {
scrollbar-width: none;
}

[data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible, :has(:focus-visible))::-webkit-scrollbar {
[data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *)::-webkit-scrollbar {
display: none;
}
}
Expand Down
17 changes: 10 additions & 7 deletions src/web-ui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -181,21 +181,21 @@

/* Keep the mounting shell from showing through or doubling the tint.
Preserve layout so startup readiness and measurements still complete. */
#root:has(+ #openbitfun-startup-overlay:not(.openbitfun-startup-overlay--exiting)) {
#root[data-startup-stage="loading"] {
visibility: hidden;
}

/* The startup mark owns the visible pixels until the handoff completes. */
#root:has(+ #openbitfun-startup-overlay) [data-startup-logo-target],
#root:has(+ #openbitfun-startup-overlay) [data-startup-reveal] {
#root[data-startup-stage] [data-startup-logo-target],
#root[data-startup-stage] [data-startup-reveal] {
opacity: 0;
}

#root:has(+ .openbitfun-startup-overlay--exiting) [data-startup-reveal] {
#root:is([data-startup-stage="exiting"], [data-startup-stage="handoff"]) [data-startup-reveal] {
animation: openbitfun-startup-content-enter 0.2s ease-out both;
}

#root:has(+ .openbitfun-startup-overlay--handoff) [data-startup-reveal] {
#root[data-startup-stage="handoff"] [data-startup-reveal] {
animation-duration: 0.24s;
animation-delay: 0.18s;
}
Expand Down Expand Up @@ -371,7 +371,7 @@

@media (prefers-reduced-motion: reduce) {
#openbitfun-startup-overlay.openbitfun-startup-overlay--exiting,
#root:has(+ .openbitfun-startup-overlay--exiting) [data-startup-reveal] {
#root:is([data-startup-stage="exiting"], [data-startup-stage="handoff"]) [data-startup-reveal] {
animation-duration: 0.12s;
animation-delay: 0s;
}
Expand Down Expand Up @@ -435,7 +435,7 @@

<body>
<script type="module" src="/src/main.tsx"></script>
<div id="root"></div>
<div id="root" data-startup-stage="loading"></div>
<div id="openbitfun-startup-overlay">
<div class="splash-screen">
<div
Expand Down Expand Up @@ -476,11 +476,13 @@
var messages = window.__OPENBITFUN_RESOLVE_BOOTSTRAP_MESSAGES__();
var locale = window.__OPENBITFUN_RESOLVE_BOOTSTRAP_LOCALE__();
var startupOverlay = document.getElementById('openbitfun-startup-overlay');
var startupRoot = document.getElementById('root');
document.documentElement.setAttribute('lang', locale);

if (isPetWindow) {
document.body.classList.add('openbitfun-pet-preload-body');
if (startupOverlay) startupOverlay.remove();
if (startupRoot) startupRoot.removeAttribute('data-startup-stage');
var root = document.getElementById('root');
if (root) {
root.innerHTML = '<div class="openbitfun-pet-preload"><div class="openbitfun-pet-preload__sprite" aria-hidden="true"></div><span class="openbitfun-sr-only"></span></div>';
Expand All @@ -493,6 +495,7 @@
if (isDesktopCardWindow) {
document.body.classList.add('openbitfun-desktop-card-preload-body');
if (startupOverlay) startupOverlay.remove();
if (startupRoot) startupRoot.removeAttribute('data-startup-stage');
return;
}

Expand Down
21 changes: 18 additions & 3 deletions src/web-ui/src/app/startup/startupOverlay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,28 @@ afterEach(() => {
});

describe('startupOverlay', () => {
it('releases startup state when the overlay has already been removed', async () => {
document.body.innerHTML = '<div id="root" data-startup-stage="loading"></div>';
await hideStartupOverlay();
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
});

it('removes the existing startup overlay when its exit animation completes', async () => {
vi.useFakeTimers();
document.body.innerHTML = '<div id="openbitfun-startup-overlay"></div>';
document.body.innerHTML = '<div id="root" data-startup-stage="loading"></div><div id="openbitfun-startup-overlay"></div>';

const hidden = hideStartupOverlay();

const overlay = document.getElementById('openbitfun-startup-overlay');
expect(overlay?.classList.contains('openbitfun-startup-overlay--exiting')).toBe(true);
expect(overlay?.getAttribute('aria-hidden')).toBe('true');
expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('exiting');

overlay?.dispatchEvent(new Event('animationend'));
await hidden;

expect(isStartupOverlayPresent()).toBe(false);
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
});

it('releases startup-control focus before hiding the exiting overlay', async () => {
Expand Down Expand Up @@ -61,7 +69,7 @@ describe('startupOverlay', () => {

it('falls back to a timer when the exit animation event is not delivered', async () => {
vi.useFakeTimers();
document.body.innerHTML = '<div id="openbitfun-startup-overlay"></div>';
document.body.innerHTML = '<div id="root" data-startup-stage="loading"></div><div id="openbitfun-startup-overlay"></div>';

const hidden = hideStartupOverlay();

Expand All @@ -72,6 +80,7 @@ describe('startupOverlay', () => {
await hidden;

expect(isStartupOverlayPresent()).toBe(false);
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
});

it('tracks elapsed time from the static overlay first paint', () => {
Expand All @@ -87,7 +96,7 @@ describe('startupOverlay', () => {
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(callback, 16));
vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id));
document.body.innerHTML = `
<div id="root"><section>
<div id="root" data-startup-stage="loading"><section>
<span data-startup-logo-target aria-hidden="true"></span>
<span data-startup-reveal>OpenBitFun</span>
</section></div>
Expand Down Expand Up @@ -120,6 +129,7 @@ describe('startupOverlay', () => {
expect(mark.style.width).toBe('119px');
expect(target.isConnected).toBe(true);
expect(overlay.classList.contains('openbitfun-startup-overlay--handoff')).toBe(true);
expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('handoff');
expect(animate).toHaveBeenCalledWith([
expect.objectContaining({ transform: 'translate(0px, 0px) scale(1, 1)' }),
expect.objectContaining({ transform: `translate(-160px, -40px) scale(${size / 119}, ${size / 119})` }),
Expand Down Expand Up @@ -147,6 +157,7 @@ describe('startupOverlay', () => {
await vi.runAllTimersAsync();
await hidden;
expect(isStartupOverlayPresent()).toBe(false);
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
});

it('restores the static mark if the WebView cannot create the animation', async () => {
Expand All @@ -167,11 +178,13 @@ describe('startupOverlay', () => {
if (reason === 'cancel') reject();
await vi.advanceTimersByTimeAsync(16);
expect(overlay.classList.contains('openbitfun-startup-overlay--handoff')).toBe(true);
expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('handoff');
expect(overlay.classList.contains('openbitfun-startup-overlay--interrupted')).toBe(true);
expect(animation.cancel).toHaveBeenCalledOnce();
overlay.dispatchEvent(new Event('animationend'));
await hidden;
expect(isStartupOverlayPresent()).toBe(false);
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
expect(vi.getTimerCount()).toBe(0);
});

Expand All @@ -181,6 +194,7 @@ describe('startupOverlay', () => {
await vi.advanceTimersByTimeAsync(520);
await hidden;
expect(isStartupOverlayPresent()).toBe(false);
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
expect(vi.getTimerCount()).toBe(0);
});

Expand All @@ -191,6 +205,7 @@ describe('startupOverlay', () => {
document.dispatchEvent(new Event('visibilitychange'));
await hidden;
expect(isStartupOverlayPresent()).toBe(false);
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
expect(animation.cancel).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
Expand Down
5 changes: 5 additions & 0 deletions src/web-ui/src/app/startup/startupOverlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ function waitForOverlayExitAnimation(overlay: HTMLElement, handoff: LogoHandoff
if (frame !== undefined) window.cancelAnimationFrame(frame);
// Remove first so cancelling a filled animation cannot flash its origin.
overlay.remove();
document.getElementById('root')?.removeAttribute('data-startup-stage');
activeHandoff?.animation.cancel();
resolve();
}
Expand Down Expand Up @@ -170,6 +171,7 @@ function waitForOverlayExitAnimation(overlay: HTMLElement, handoff: LogoHandoff
export function hideStartupOverlay(): Promise<void> {
const overlay = getOverlay();
if (!overlay) {
document.getElementById('root')?.removeAttribute('data-startup-stage');
return Promise.resolve();
}

Expand All @@ -183,6 +185,9 @@ export function hideStartupOverlay(): Promise<void> {
});
pendingExits.set(overlay, exited);
overlay.classList.add(EXIT_CLASS);
// Startup owns this state directly; a root :has() would invalidate unrelated
// transcript descendants whenever virtualized or streaming DOM changes.
document.getElementById('root')?.setAttribute('data-startup-stage', handoff ? 'handoff' : 'exiting');
// Static startup window controls can still own focus when the React shell
// becomes ready. Release that focus before hiding the overlay from the
// accessibility tree, then make the exiting surface non-interactive so it
Expand Down
6 changes: 6 additions & 0 deletions src/web-ui/src/app/startup/startupPerformanceContract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ function readSource(relativePath: string): string {
return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8').replace(/\r\n?/g, '\n');
}

it('does not make the app root a relational selector subject after startup', () => {
const html = readSource('../../../index.html');
expect(html).not.toContain('#root:has(');
expect(html).toContain('id="root" data-startup-stage="loading"');
});

function dynamicImportSpecifiers(source: string): string[] {
return Array.from(
source.matchAll(/import\(\s*(['"])(.*?)\1\s*\)/g),
Expand Down
2 changes: 2 additions & 0 deletions src/web-ui/src/app/startup/startupPreload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ describe('startup preload shell', () => {

expect(dom.window.document.body.classList.contains('openbitfun-pet-preload-body')).toBe(true);
expect(dom.window.document.getElementById('openbitfun-startup-overlay')).toBeNull();
expect(dom.window.document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
expect(dom.window.document.querySelector('.openbitfun-pet-preload__sprite')).not.toBeNull();
expect(dom.window.document.querySelector('.splash-screen__logo')).toBeNull();
expect(dom.window.document.querySelector('.openbitfun-sr-only')?.textContent).toBe('Loading companion...');
Expand All @@ -259,6 +260,7 @@ describe('startup preload shell', () => {

expect(dom.window.document.body.classList.contains('openbitfun-desktop-card-preload-body')).toBe(true);
expect(dom.window.document.getElementById('openbitfun-startup-overlay')).toBeNull();
expect(dom.window.document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
expect(dom.window.document.querySelector('.openbitfun-pet-preload')).toBeNull();
dom.window.close();
});
Expand Down
Loading
Loading