forked from vercel/styled-jsx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstyle.js
More file actions
60 lines (52 loc) · 1.64 KB
/
Copy pathstyle.js
File metadata and controls
60 lines (52 loc) · 1.64 KB
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
import React, { useLayoutEffect, useRef } from 'react'
import { useStyleRegistry, createStyleRegistry } from './stylesheet-registry'
import { computeId } from './lib/hash'
// Opt-into the new `useInsertionEffect` API in React 18, fallback to `useLayoutEffect`.
// https://github.com/reactwg/react-18/discussions/110
const useInsertionEffect = React.useInsertionEffect || useLayoutEffect
const defaultRegistry =
typeof window !== 'undefined' ? createStyleRegistry() : undefined
export default function JSXStyle(props) {
const registry = defaultRegistry ? defaultRegistry : useStyleRegistry()
const insertionEffectCalled = useRef(false)
// `registry` might not exist while server-side rendering
if (!registry) {
return null
}
if (typeof window === 'undefined') {
registry.add(props)
return null
}
useInsertionEffect(() => {
// ReactDOM removes all DOM during hydration in certain cases
if (!document.head) {
return
}
registry.add(props)
insertionEffectCalled.current = true
return () => {
insertionEffectCalled.current = false
registry.remove(props)
}
}, [props.id, String(props.dynamic)])
useLayoutEffect(() => {
if (!document.head || insertionEffectCalled.current) {
return
}
registry.add(props)
return () => {
registry.remove(props)
}
// props.children can be string[], will be striped since id is identical
}, [props.id, String(props.dynamic)])
return null
}
JSXStyle.dynamic = info => {
return info
.map(tagInfo => {
const baseId = tagInfo[0]
const props = tagInfo[1]
return computeId(baseId, props)
})
.join(' ')
}