Skip to content

Commit

Permalink
#4602: Add NONCE to inline style
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware committed Jul 12, 2023
1 parent 27a9654 commit 51918de
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
8 changes: 7 additions & 1 deletion components/lib/hooks/useStyle.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useEffect, useRef, useState } from 'react';
import PrimeReact, { PrimeReactContext } from '../api/Api';
import { DomHandler, ObjectUtils } from '../utils/Utils';

let _id = 0;

export const useStyle = (css = {}, options = {}) => {
const [isLoaded, setIsLoaded] = useState(false);

const context = React.useContext(PrimeReactContext);
const cssRef = useRef(null);
const defaultDocument = DomHandler.isClient() ? window.document : undefined;
const { document = defaultDocument, immediate = true, manual = false, name = `primereact_style_${++_id}`, media } = options;
Expand All @@ -23,6 +25,10 @@ export const useStyle = (css = {}, options = {}) => {
el.type = 'text/css';
el.setAttribute('data-pc-name', name);
if (media) el.media = media;

const nonce = (context && context.nonce) || PrimeReact.nonce;

DomHandler.addNonce(el, nonce);
document.head.appendChild(el);
}

Expand All @@ -37,7 +43,7 @@ export const useStyle = (css = {}, options = {}) => {
const node = document.querySelector(`[data-pc-name="${name}"]`);

if (node && node.isConnected) {
document.head.removeChild(node);
DomHandler.removeInlineStyle(node);
setIsLoaded(false);
}
};
Expand Down
22 changes: 13 additions & 9 deletions components/lib/utils/DomHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -981,15 +981,7 @@ export default class DomHandler {
static createInlineStyle(nonce) {
let styleElement = document.createElement('style');

try {
if (!nonce) {
nonce = process.env.REACT_APP_CSS_NONCE;
}
} catch (error) {
// NOOP
}

nonce && styleElement.setAttribute('nonce', nonce);
DomHandler.addNonce(styleElement, nonce);
document.head.appendChild(styleElement);

return styleElement;
Expand All @@ -1009,6 +1001,18 @@ export default class DomHandler {
return styleElement;
}

static addNonce(styleElement, nonce) {
try {
if (!nonce) {
nonce = process.env.REACT_APP_CSS_NONCE;
}
} catch (error) {
// NOOP
}

nonce && styleElement.setAttribute('nonce', nonce);
}

static getTargetElement(target) {
if (!target) return null;

Expand Down

0 comments on commit 51918de

Please sign in to comment.