Skip to content

Commit

Permalink
[@mantine/core] Fix nonce attribute not being set on <style /> ta…
Browse files Browse the repository at this point in the history
…g generated in color scheme switching script
  • Loading branch information
rtivital committed May 10, 2024
1 parent 2f61697 commit 0976f8a
Showing 1 changed file with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { useCallback, useContext, useEffect, useRef } from 'react';
import { useColorScheme } from '@mantine/hooks';
import { MantineContext } from '../Mantine.context';
import { MantineContext, useMantineStyleNonce } from '../Mantine.context';
import { MantineColorScheme } from '../theme.types';

function disableTransition() {
function disableTransition(nonce: string | undefined) {
const style = document.createElement('style');
style.setAttribute('data-mantine-styles', 'inline');
style.innerHTML = '*, *::before, *::after {transition: none !important;}';
style.setAttribute('data-mantine-disable-transition', 'true');
nonce && style.setAttribute('nonce', nonce);

document.head.appendChild(style);
const clear = () =>
document
Expand All @@ -19,14 +22,16 @@ export function useMantineColorScheme({ keepTransitions }: { keepTransitions?: b
const clearStylesRef = useRef<() => void>();
const timeoutRef = useRef<number>();
const ctx = useContext(MantineContext);
const nonce = useMantineStyleNonce();
const nonceValue = useRef(nonce?.());

if (!ctx) {
throw new Error('[@mantine/core] MantineProvider was not found in tree');
}

const setColorScheme = (value: MantineColorScheme) => {
ctx.setColorScheme(value);
clearStylesRef.current = keepTransitions ? () => {} : disableTransition();
clearStylesRef.current = keepTransitions ? () => {} : disableTransition(nonceValue.current);
window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => {
clearStylesRef.current?.();
Expand All @@ -35,7 +40,7 @@ export function useMantineColorScheme({ keepTransitions }: { keepTransitions?: b

const clearColorScheme = () => {
ctx.clearColorScheme();
clearStylesRef.current = keepTransitions ? () => {} : disableTransition();
clearStylesRef.current = keepTransitions ? () => {} : disableTransition(nonceValue.current);
window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => {
clearStylesRef.current?.();
Expand Down

0 comments on commit 0976f8a

Please sign in to comment.