Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Allow controlling Frosted theme with CustomEvents #42

Merged
merged 7 commits into from
Dec 11, 2023
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
26 changes: 25 additions & 1 deletion packages/frosted-ui/src/theme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as React from 'react';
import { getMatchingGrayColor, themePropDefs } from './theme-options';

import type { ThemeOptions } from './theme-options';
import { WithThemeEvents } from './use-theme-events';

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
Expand Down Expand Up @@ -126,7 +127,10 @@ const ThemeRoot = React.forwardRef<ThemeImplElement, ThemeRootProps>(
return (
<>
{appearance !== 'inherit' && (
<ExplicitRootAppearanceScript appearance={appearance} />
<>
<ExplicitRootAppearanceScript appearance={appearance} />
<SyncRootElementAppearance appearance={appearance} />
</>
)}

{hasBackground && (
Expand Down Expand Up @@ -169,6 +173,25 @@ body { background-color: var(--color-page-background); }
);
ThemeRoot.displayName = 'ThemeRoot';

function SyncRootElementAppearance({
appearance,
}: {
appearance: Exclude<ThemeOptions['appearance'], 'inherit'>;
}) {
React.useEffect(() => {
try {
document.documentElement.style.colorScheme = appearance;
const cl = document.documentElement.classList;
const opposite = appearance === 'light' ? 'dark' : 'light';
if (cl.contains(opposite)) cl.remove(opposite);
if (!cl.contains(appearance)) cl.add(appearance);
} catch {
/* ignore errors */
}
}, [appearance]);
return null;
}

type ThemeImplElement = React.ElementRef<'div'>;
interface ThemeImplProps extends ThemeImplPublicProps, ThemeImplPrivateProps {}
interface ThemeImplPublicProps
Expand Down Expand Up @@ -259,6 +282,7 @@ const ThemeImpl = React.forwardRef<ThemeImplElement, ThemeImplProps>(
],
)}
>
{isRoot && <WithThemeEvents />}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

<Comp
data-is-root-theme={isRoot ? 'true' : 'false'}
data-accent-color={accentColor}
Expand Down
125 changes: 125 additions & 0 deletions packages/frosted-ui/src/use-theme-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
'use client';

import React, { FC, useEffect } from 'react';
import { useThemeContext } from './theme';
import { ThemeOptions, themePropDefs } from './theme-options';

function validateThemeColor<
K extends Exclude<keyof typeof themePropDefs, 'hasBackground'>,
>(
key: K,
value: unknown,
): value is (typeof themePropDefs)[K]['values'][number] {
const validValues = themePropDefs[key].values;
return validValues.includes(value as never);
}

function validateThemeOptions(detail: unknown) {
if (typeof detail !== 'object' || !detail) return {};

const ret: Partial<ThemeOptions> = {};

const keysToCheck: readonly (keyof ThemeOptions)[] = [
'accentColor',
'appearance',
'dangerColor',
'grayColor',
'infoColor',
'successColor',
'warningColor',
];

for (const key of keysToCheck) {
if (!(key in detail)) continue;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (!validateThemeColor(key, (detail as any)[key])) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
console.warn(`Invalid value for ${key}: ${(detail as any)[key]}`);
continue;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ret[key] = (detail as any)[key];
}

return ret;
}

export function useThemeEvents() {
const {
accentColor,
appearance,
dangerColor,
grayColor,
infoColor,
successColor,
warningColor,
onAccentColorChange,
onAppearanceChange,
onDangerColorChange,
onGrayColorChange,
onInfoColorChange,
onSuccessColorChange,
onWarningColorChange,
} = useThemeContext();

// Emit an event when the component is mounted.
// Listen for theme changes from the outside.
useEffect(() => {
const listener = (e: Event) => {
if (e instanceof CustomEvent) {
const d = validateThemeOptions(e.detail);
if (d.appearance) onAppearanceChange(d.appearance);
if (d.accentColor) onAccentColorChange(d.accentColor);
if (d.grayColor) onGrayColorChange(d.grayColor);
if (d.infoColor) onInfoColorChange(d.infoColor);
if (d.successColor) onSuccessColorChange(d.successColor);
if (d.warningColor) onWarningColorChange(d.warningColor);
if (d.dangerColor) onDangerColorChange(d.dangerColor);
}
};
document.documentElement.addEventListener('frosted-ui:set-theme', listener);

// Let external code know that the component is mounted.
const event = new CustomEvent('frosted-ui:mounted');
document.documentElement.dispatchEvent(event);

return () => {
document.documentElement.removeEventListener(
'frosted-ui:set-theme',
listener,
);
const event = new CustomEvent('frosted-ui:unmounted');
document.documentElement.dispatchEvent(event);
};
}, []);

// Emit an event when the theme is changed.
React.useEffect(() => {
const event = new CustomEvent('frosted-ui:on-theme-change', {
detail: {
appearance,
accentColor,
grayColor,
infoColor,
successColor,
warningColor,
dangerColor,
},
});
document.documentElement.dispatchEvent(event);
}, [
appearance,
accentColor,
grayColor,
infoColor,
successColor,
warningColor,
dangerColor,
]);
}

export const WithThemeEvents: FC = () => {
useThemeEvents();
return null;
};
2 changes: 1 addition & 1 deletion packages/frosted-ui/tsconfig-cjs.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"extends": "./tsconfig-base.json",
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist/cjs",
"module": "CommonJS"
Expand Down
2 changes: 1 addition & 1 deletion packages/frosted-ui/tsconfig-esm.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"extends": "./tsconfig-base.json",
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist/esm",
"module": "ES2020"
Expand Down