Skip to content

Commit

Permalink
feat: allow adding a nonce to style tag injected by ColorModeProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
ArthurWD committed Mar 4, 2024
1 parent f5c3754 commit 88ea77f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
7 changes: 6 additions & 1 deletion packages/components/src/color-mode/color-mode-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export function ColorModeProvider(props: ColorModeProviderProps) {
useSystemColorMode,
initialColorMode,
disableTransitionOnChange,
nonce,
} = {},
colorModeManager = localStorageManager,
} = props
Expand All @@ -59,7 +60,11 @@ export function ColorModeProvider(props: ColorModeProviderProps) {
)

const { getSystemTheme, setClassName, setDataset, addListener } = useMemo(
() => getColorModeUtils({ preventTransition: disableTransitionOnChange }),
() =>
getColorModeUtils({
nonce,
preventTransition: disableTransitionOnChange,
}),
[disableTransitionOnChange],
)

Expand Down
1 change: 1 addition & 0 deletions packages/components/src/color-mode/color-mode-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface ColorModeOptions {
initialColorMode?: ColorModeWithSystem
useSystemColorMode?: boolean
disableTransitionOnChange?: boolean
nonce?: string
}

export interface ColorModeContextType {
Expand Down
8 changes: 6 additions & 2 deletions packages/components/src/color-mode/color-mode.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const classNames = {
}

type UtilOptions = {
nonce?: string
preventTransition?: boolean
}

Expand All @@ -14,7 +15,9 @@ export function getColorModeUtils(options: UtilOptions = {}) {

const utils = {
setDataset: (value: ColorMode) => {
const cleanup = preventTransition ? utils.preventTransition() : undefined
const cleanup = preventTransition
? utils.preventTransition(options.nonce)
: undefined
document.documentElement.dataset.theme = value
document.documentElement.style.colorScheme = value
cleanup?.()
Expand Down Expand Up @@ -45,8 +48,9 @@ export function getColorModeUtils(options: UtilOptions = {}) {
else mql.removeEventListener("change", listener)
}
},
preventTransition() {
preventTransition(nonce?: string) {
const css = document.createElement("style")
css.nonce = nonce
css.appendChild(
document.createTextNode(
`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`,
Expand Down

0 comments on commit 88ea77f

Please sign in to comment.