Skip to content

Commit

Permalink
Merge pull request #1 from schnogz/feature/add-nonce-support
Browse files Browse the repository at this point in the history
feat(nonce): add nonce support to style tag attributes
  • Loading branch information
Andrew Schneider authored Apr 8, 2022
2 parents 0ebaf9f + f6d8ef1 commit c1e90fe
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,6 @@ dist

# TernJS port file
.tern-port

# IntelliJ
.idea/
20 changes: 17 additions & 3 deletions packages/core/src/sheet.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { getNonce } from './utility/getNonce'

/** @typedef {import('./sheet').RuleGroup} RuleGroup */
/** @typedef {import('./sheet').RuleGroupNames} RuleGroupNames */
/** @typedef {import('./sheet').SheetGroup} SheetGroup */
Expand Down Expand Up @@ -137,8 +139,20 @@ export const createSheet = (/** @type {DocumentOrShadowRoot} */ root) => {
})
}

const createSheet = () => {
if (!root) {
return createCSSMediaRule('', 'text/css')
}
const styleEl = document.createElement('style')
const nonce = getNonce()
if (nonce) {
styleEl.setAttribute('nonce', nonce)
}
return (root.head || root).appendChild(styleEl).sheet
}

groupSheet = {
sheet: root ? (root.head || root).appendChild(document.createElement('style')).sheet : createCSSMediaRule('', 'text/css'),
sheet: createSheet(),
rules: {},
reset,
toString,
Expand Down Expand Up @@ -187,9 +201,9 @@ const addApplyToGroup = (/** @type {RuleGroup} */ group) => {
/** Pending rules for injection */
const $pr = Symbol()

/**
/**
* When a stitches component is extending some other random react component,
* it’s gonna create a react component (Injector) using this function and then render it after the children,
* it’s gonna create a react component (Injector) using this function and then render it after the children,
* this way, we would force the styles of the wrapper to be injected after the wrapped component
*/
export const createRulesInjectionDeferrer = (globalSheet) => {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/utility/getNonce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const getNonce = () => {
if (typeof window.__webpack_nonce__ !== 'undefined') return window.__webpack_nonce__
if (typeof window.nonce !== 'undefined') return window.nonce
return null
}

0 comments on commit c1e90fe

Please sign in to comment.