Files
openchamber/packages/ui/src/contexts/theme-embedded-bootstrap.ts
T

57 lines
1.5 KiB
TypeScript
Raw Normal View History

import { isEmbeddedSessionChat } from '@/components/layout/contextPanelEmbeddedChat';
2026-07-26 20:33:04 +08:00
import type { Theme } from '@/types/theme';
import { isValidTheme } from './theme-validation';
type ThemeBootstrapWindow = Window & {
__openchamberEmbeddedThemeBootstrap?: unknown;
};
2026-06-16 23:33:29 +03:00
export const readEmbeddedThemeSearchParams = (): URLSearchParams | null => {
if (!isEmbeddedSessionChat()) {
2026-06-16 23:33:29 +03:00
return null;
}
return new URLSearchParams(window.location.search);
2026-06-16 23:33:29 +03:00
};
2026-07-26 20:33:04 +08:00
export const publishEmbeddedThemeBootstrap = (theme: Theme): void => {
if (typeof window === 'undefined') {
return;
}
(window as ThemeBootstrapWindow).__openchamberEmbeddedThemeBootstrap = theme;
};
export const readEmbeddedThemeBootstrap = (): Theme | null => {
if (!isEmbeddedSessionChat()) {
return null;
}
try {
const parent = window.parent as ThemeBootstrapWindow;
if (parent === window) {
return null;
}
return isValidTheme(parent.__openchamberEmbeddedThemeBootstrap)
? parent.__openchamberEmbeddedThemeBootstrap
: null;
} catch {
return null;
}
};
2026-06-16 23:33:29 +03:00
const getSystemPreference = (): boolean => {
if (typeof window === 'undefined') {
return true;
}
return window.matchMedia('(prefers-color-scheme: dark)').matches;
};
export const getInitialSystemPreference = (): boolean => {
const embeddedParams = readEmbeddedThemeSearchParams();
const embeddedVariant = embeddedParams?.get('themeVariant');
if (embeddedVariant === 'dark' || embeddedVariant === 'light') {
return embeddedVariant === 'dark';
}
return getSystemPreference();
};