forked from tw-in-js/twind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
82 lines (68 loc) · 2.11 KB
/
index.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* [[include:src/shim/README.md]]
*
* @packageDocumentation
* @module twind/shim
*/
import type { Configuration } from 'twind'
import { setup as setupTW, createObserver } from 'twind/observe'
export * from 'twind'
/**
* Options for {@link setup}.
*/
export interface ShimConfiguration extends Configuration {
/**
* The root element to shim (default: `document.documentElement`).
*/
target?: HTMLElement
}
if (typeof document !== 'undefined' && typeof addEventListener == 'function') {
// eslint-disable-next-line no-var
var onload = () => {
const script = document.querySelector('script[type="twind-config"]')
setup(script ? JSON.parse(script.innerHTML) : {})
}
if (document.readyState === 'loading') {
// Loading hasn't finished yet
addEventListener('DOMContentLoaded', onload)
} else {
// `DOMContentLoaded` has already fired
// invoke on next tick to allow other setup methods to run
// eslint-disable-next-line no-var
var timeoutRef = setTimeout(onload)
}
}
const observer = createObserver()
/**
* Stop shimming/observing all nodes.
*/
export const disconnect = (): void => {
if (onload) {
// Removing the callbacks ensures that the setup is called only once
// either programmatically from userland or by DOMContentLoaded/setTimeout
removeEventListener('DOMContentLoaded', onload)
clearTimeout(timeoutRef)
}
observer.disconnect()
}
/**
* Configure the default {@link tw} and starts {@link observe | observing} the
* {@link ShimConfiguration.target | target element} (default: `document.documentElement`).
*
* You do not need to call this method. As an alternativ you can provide a
* `<script type="twind-config">...</script>` element within the document.
* The content must be valid JSON and all {@link twind.setup | twind setup options}
* (including hash) are supported.
*/
export const setup = ({
target = document.documentElement,
...config
}: ShimConfiguration = {}): void => {
if (Object.keys(config).length) {
setupTW(config)
}
// Remove event listeners
disconnect()
observer.observe(target)
target.hidden = false
}