-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
useStyle.js
61 lines (46 loc) · 1.9 KB
/
useStyle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { useContext, useEffect, useRef, useState } from 'react';
import PrimeReact, { PrimeReactContext } from '../api/Api';
import { DomHandler } from '../utils/Utils';
let _id = 0;
export const useStyle = (css, options = {}) => {
const [isLoaded, setIsLoaded] = useState(false);
const styleRef = useRef(null);
const context = useContext(PrimeReactContext);
const defaultDocument = DomHandler.isClient() ? window.document : undefined;
const { document = defaultDocument, manual = false, name = `style_${++_id}`, id = undefined, media = undefined } = options;
const update = (newCSS) => {
isLoaded && css !== newCSS && (styleRef.current.textContent = newCSS);
};
const load = () => {
if (!document || isLoaded) return;
styleRef.current = document.querySelector(`style[data-primereact-style-id="${name}"]`) || document.getElementById(id) || document.createElement('style');
if (!styleRef.current.isConnected) {
styleRef.current.type = 'text/css';
id && (styleRef.current.id = id);
media && (styleRef.current.media = media);
DomHandler.addNonce(styleRef.current, (context && context.nonce) || PrimeReact.nonce);
document.head.appendChild(styleRef.current);
name && styleRef.current.setAttribute('data-primereact-style-id', name);
}
styleRef.current.textContent = css;
setIsLoaded(true);
};
const unload = () => {
if (!document || !styleRef.current) return;
DomHandler.removeInlineStyle(styleRef.current);
setIsLoaded(false);
};
useEffect(() => {
if (!manual) load();
// return () => {if (!manual) unload()}; /* @todo */
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [manual]);
return {
id,
name,
update,
unload,
load,
isLoaded
};
};