-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
209 lines (174 loc) · 5.58 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import getConfig from "./lib/config.js";
import getParser, { hasVariant } from "./lib/parser.js";
import keyframes from "./lib/keyframes.js";
import { preflight as preflightStyles, variables } from "./lib/styles.js";
import { theme } from "./lib/selector.js";
const onObserve = (process, filterClasses, append) => mutations => {
let styles = [...new Set(
mutations
.filter(t => t.type === 'attributes')
.map(i => (i.target.classList.value || "").split(' '))
.flat()
.filter(a => {
return filterClasses(a)
})
)]
.map(process)
.filter(Boolean);
styles = [...styles, ...[...new Set(
mutations
.filter(f => {
return f.type === 'childList' && f.addedNodes.length && f.addedNodes[0].classList
})
.map(i => {
let c = [];
const node = i.addedNodes[0]
const all = node.getElementsByTagName('*');
for (var i = -1, l = all.length; ++i < l;) {
c.push((all[i].classList.value ||'').split(' '));
}
return [...c.flat(), ...(node.classList.value || '').split(' ')];
})
.flat()
)
]
.filter(filterClasses)
.map(process)
.filter(Boolean)
];
append(styles);
}
const getInitialClasses = (process) => [...new Set(
[...document.querySelectorAll("*")]
.map(i => i.classList.value.split(' '))
.flat()
)]
.map(process)
.filter(Boolean);
const observeClasses = (observer, container) => observer.observe(
container,
{
subtree: true,
attributes: true,
childList: true,
}
);
function mergeUserConfig(config, userConfig) {
if (!userConfig || !userConfig.theme) return config;
const configTheme = theme(config.theme);
if (userConfig.theme.extend) {
for (const key in userConfig.theme.extend) {
config.theme[key] = typeof config.theme[key] === 'function'
? {
...config.theme[key](configTheme),
...userConfig.theme.extend[key],
} : {
...config.theme[key],
...userConfig.theme.extend[key],
};
}
}
return {
...config,
theme: Object.keys(config.theme).reduce((acc, cur) => ({
...acc,
[cur]: userConfig.theme[cur] || config.theme[cur]
}), {})
};
}
function appendCssToEl(css, el) {
if (!css) return;
if (el.styleSheet) {
el.styleSheet.cssText = css;
} else {
el.appendChild(document.createTextNode(css));
}
}
let headlong;
export function init({
container = document.querySelector('body'),
classes: userClasses = new Set(),
config: userConfig = {},
preflight = true,
} = {}) {
if (headlong) return headlong;
if (!(userClasses instanceof Set)) {
throw new Error('Classes must be instance of Set');
}
const classes = new Set(userClasses);
const s = document.createElement('style');
s.setAttribute('type', 'text/css');
document.head.appendChild(s);
const med = document.createElement('style');
med.setAttribute('type', 'text/css');
document.head.appendChild(med);
function appendStyleMedia(css) {
appendCssToEl(css, med);
}
function appendStyle(css) {
appendCssToEl(css, s);
}
function append(styles) {
appendStyle(styles.filter(s => !s.includes('@media')).join('\n'));
appendStyleMedia(styles.filter(s => s.includes('@media')).join('\n'));
}
const filterClasses = i => Boolean(i) && !classes.has(i) && typeof i === "string";
const configMerged = mergeUserConfig(getConfig(), userConfig);
const parse = getParser(configMerged);
const process = c => {
const css = parse(c);
if (css) {
classes.add(c);
}
return css;
}
const initialStyles = getInitialClasses(process, filterClasses);
appendStyle(
(preflight ? preflightStyles : "")
+ variables(configMerged)
+ keyframes
);
append(initialStyles);
const classObserver = new MutationObserver(onObserve(process, filterClasses, append));
observeClasses(classObserver, container);
function output() { // TODO: what output options do we need?
return {
classes: new Set(classes),
styles: `<style>${s.innerText}${med.innerText}</style>`.replace(/\n/, '')
};
}
headlong = {
unsubscribe: () => {
console.log('Headlong generated styles', output());
classObserver.disconnect();
headlong = null;
return output();
},
parse,
config: configMerged,
output,
apply: (selector, classList) => {
const arr = classList.split(' ');
const noVariantStyles = arr
.filter(s => !hasVariant(s))
.map(c => parse(c, true))
.filter(Boolean)
.join('') || '';
appendStyle(`${selector} { ${noVariantStyles} }`);
// Facing the same problem with @apply variant:class like Tailwind 1.x.
// Got to group all uninque variant groups, capture their styles separately,
// then apply variant groups on selector argument (which can be tricky if we allow arbitrary selector)
// so keeping it simple for now.
// apply('#mySelector', 'sm:text-red-500 text-green-500 dark:sm:text-yellow-500')
// should resolve to
// #mySelector { --tw-text-opacity: 1; color: rgba(239,68,68, var(--tw-text-opacity)); }
// @media (min-width: 640px) { #mySelector { --tw-text-opacity: 1; color: rgba(239,68,68, var(--tw-text-opacity)); } }
// @media (min-width: 640px) { .mode-dark #mySelector { --tw-text-opacity: 1; color: rgba(245,158,11, var(--tw-text-opacity)); } }
// const variantStyles = arr.filter(hasVariant).map(c => parse(c).replace(c.split(":").pop(), selector));
// append(variantStyles);
return `${selector} { ${noVariantStyles} }`;
}
};
return headlong;
}
export default init;