Skip to content

Commit

Permalink
chore: nonce support function to save perf (#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ committed Mar 27, 2023
1 parent 9141fc9 commit 44a7118
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 21 deletions.
8 changes: 5 additions & 3 deletions src/hooks/useStyleRegister.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ export default function useStyleRegister(
path: string[];
hashId?: string;
layer?: string;
nonce?: string;
nonce?: string | (() => string);
},
styleFn: () => CSSInterpolation,
) {
Expand Down Expand Up @@ -385,8 +385,10 @@ export default function useStyleRegister(
attachTo: container,
};

if (nonce) {
mergedCSSConfig.csp = { nonce };
const nonceStr = typeof nonce === 'function' ? nonce() : nonce;

if (nonceStr) {
mergedCSSConfig.csp = { nonce: nonceStr };
}

const style = updateCSS(styleStr, styleId, mergedCSSConfig);
Expand Down
43 changes: 25 additions & 18 deletions tests/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -411,24 +411,31 @@ describe('csssinjs', () => {
expect(container.querySelectorAll('style')).toHaveLength(1);
});

it('nonce', () => {
const NonceBox = () => {
useStyleRegister(
{ theme, token: {}, path: ['.nonce'], nonce: 'bamboo' },
() => [],
);

return <div />;
};

render(
<StyleProvider cache={createCache()}>
<NonceBox />
</StyleProvider>,
);
describe('nonce', () => {
function test(name: string, nonce: string | (() => string)) {
it(name, () => {
const NonceBox = () => {
useStyleRegister(
{ theme, token: {}, path: ['.nonce'], nonce },
() => [],
);

return <div />;
};

render(
<StyleProvider cache={createCache()}>
<NonceBox />
</StyleProvider>,
);

const styles = Array.from(document.head.querySelectorAll('style'));
expect(styles).toHaveLength(1);
expect(styles[0].nonce).toBe('bamboo');
});
}

const styles = Array.from(document.head.querySelectorAll('style'));
expect(styles).toHaveLength(1);
expect(styles[0].nonce).toBe('bamboo');
test('string', 'bamboo');
test('function', () => 'bamboo');
});
});

0 comments on commit 44a7118

Please sign in to comment.