-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvarwind.js
353 lines (268 loc) · 9.78 KB
/
varwind.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
window.VARWIND_DEFAULT_PROPERTY_ALIASES = {
'p': 'padding',
'pl': 'padding-left',
'pr': 'padding-right',
'pt': 'padding-top',
'pb': 'padding-bottom',
'px':['padding-left', 'padding-right'],
'py': ['padding-top', 'padding-bottom'],
'm': 'margin',
'ml': 'margin-left',
'mr': 'margin-right',
'mt': 'margin-top',
'mb': 'margin-bottom',
'mx': ['margin-left', 'margin-right'],
'my': ['margin-top', 'margin-bottom'],
'd': 'display',
'bg': 'background',
}
window.VARWIND_EXTRA_PROPERTY_ALIASES = {}
window.VARWIND_DEFAULT_PREFIX_ALIASES = {
'after': '::after',
'before': '::before',
'odd': ':nth-child(odd)',
'even': ':nth-child(even)',
}
window.VARWIND_EXTRA_PREFIX_ALIASES = {}
// [value] ->> @media [value] { ... }
window.VARWIND_DEFAULT_MEDIA_QUERIES = {
'sm': '(min-width: 640px)',
'md': '(min-width: 768px)',
'lg': '(min-width: 1024px)',
'xl': '(min-width: 1280px)',
}
window.VARWIND_EXTRA_MEDIA_QUERIES = {}
const ATTRIBUTE_NAME = 'x-css-vars';
let classNameCounter = 0;
function generateClassName() {
return `${ATTRIBUTE_NAME}-${classNameCounter++}`;
}
function processAttributeValue(value) {
const allUtitlities = value.split(' ').map((v) => v.trim()).filter((v) => v !== '');
const parsedStyleDefinitions = [];
let hasMediaQuery = false;
for(const utility of allUtitlities){
const utilityParts = utility.split(':');
let mediaQuery = undefined;
let prefix = undefined;
let value = undefined;
if(utilityParts.length > 3){
console.error('Invalid tailvars class', utility);
return;
}
for(let index = 0; index < utilityParts.length; index++){
const part = utilityParts[index];
if (index === utilityParts.length - 1) {
value = part;
} else if (part.startsWith('@')) {
hasMediaQuery = true;
mediaQuery = part;
} else {
prefix = part;
}
}
parsedStyleDefinitions.push({ mediaQuery: mediaQuery || null, prefix: prefix || null, value });
}
return parsedStyleDefinitions;
}
function resolveCssValue(value){
const maybeSplittedVar = value.split('--');
if(maybeSplittedVar.length == 2){
const [propertyOrAlias, value] = maybeSplittedVar;
const property = resolveAlias(propertyOrAlias);
if(property instanceof Array){
return property.map((p) => ({p, v: `var(--${value})`}))
}
return [{p: property, v: `var(--${value})`}]
}
const maybeSplittedLiteral = value.split('-[');
if(maybeSplittedLiteral.length == 2){
const [propertyOrAlias, rawValue] = maybeSplittedLiteral;
const value = rawValue.slice(0, -1); // strip last character ']'
const property = resolveAlias(propertyOrAlias);
if(property instanceof Array){
return property.map((p) => ({p, v: value}))
}
return [{p: property, v: value}]
}
console.error('Invalid tailvars value', value);
return [];
}
const NOT_SET_KEY = '__null';
function createTreeForMediaQuery(parsedStyleDefinitions) {
const tree = {};
for(const { mediaQuery, prefix, value } of parsedStyleDefinitions){
const mediaKey = mediaQuery || NOT_SET_KEY;
const prefixKey = prefix || NOT_SET_KEY;
if (tree[mediaKey] === undefined) {
tree[mediaKey] = {};
}
if(tree[mediaKey][prefixKey] === undefined){
tree[mediaKey][prefixKey] = [];
}
for(const item of resolveCssValue(value)){
tree[mediaKey][prefixKey].push(item);
}
}
return tree;
}
function resolveMediaQuery(mediaQueryRaw){
const mediaQuery = mediaQueryRaw.slice(1); // strip '@'
return window.VARWIND_EXTRA_MEDIA_QUERIES[mediaQuery] ||
window.VARWIND_DEFAULT_MEDIA_QUERIES[mediaQuery] ||
mediaQuery;
}
function resolvePrefix(prefix){
return window.VARWIND_EXTRA_PREFIX_ALIASES[prefix] ||
window.VARWIND_DEFAULT_PREFIX_ALIASES[prefix] ||
`:${prefix}`;
}
function resolveAlias(alias){
return window.VARWIND_EXTRA_PROPERTY_ALIASES[alias] ||
window.VARWIND_DEFAULT_PROPERTY_ALIASES[alias] ||
alias;
}
const attrStringToClassName = new Map();
const initialSylesAdded = new Set();
function applyStyles(targetElements){
for(const element of targetElements){
// determine classname
const attributeValue = element.getAttribute(ATTRIBUTE_NAME);
if(attrStringToClassName.has(attributeValue)){
const generatedClassName = attrStringToClassName.get(attributeValue);
element.classList.add(generatedClassName);
return;
}
const generatedClassName = generateClassName();
attrStringToClassName.set(attributeValue, generatedClassName);
const parsedStyleDefinitions = processAttributeValue(attributeValue);
const mediaQueryTree = createTreeForMediaQuery(parsedStyleDefinitions);
let moreSpecificClassContent = '';
let leastSpecificClassContent = '';
const styles = {};
for(const mediaQuery of Object.keys(mediaQueryTree)){
const mediaQueryStyles = mediaQueryTree[mediaQuery];
for(const prefix of Object.keys(mediaQueryStyles)){
const styleDefinitions = mediaQueryStyles[prefix];
let currentClassContent = "";
if(mediaQuery === NOT_SET_KEY && prefix === NOT_SET_KEY){
for(const {p, v} of styleDefinitions){
styles[p] = v;
}
continue;
}
if(mediaQuery !== NOT_SET_KEY){
const cssMediaQuery = resolveMediaQuery(mediaQuery);
currentClassContent += `@media ${cssMediaQuery} { \n`;
}
if(prefix !== NOT_SET_KEY){
// translate prefix to css selector
const cssPrefix = resolvePrefix(prefix);
currentClassContent += `.${generatedClassName}${cssPrefix} { \n`;
}else{
currentClassContent += `.${generatedClassName} { \n`;
}
for(const {p, v} of styleDefinitions){
currentClassContent += `${p}: ${v}; \n`;
}
currentClassContent += "}\n";
if(mediaQuery !== NOT_SET_KEY){
currentClassContent += "}";
}
if(prefix !== NOT_SET_KEY && mediaQuery === NOT_SET_KEY){
moreSpecificClassContent += currentClassContent + " ";
}else{
leastSpecificClassContent += currentClassContent + " ";
}
}
}
let prefixClassContent = "";
prefixClassContent += "\n";
prefixClassContent += `.${generatedClassName} { \n`;
for (const [key, value] of Object.entries(styles)) {
prefixClassContent += `${key}: ${value}; \n`;
}
prefixClassContent += "}\n";
const classContent = prefixClassContent + leastSpecificClassContent + moreSpecificClassContent;
// let styleElement = document.querySelector(`style.${generatedClassName}`); // TODO: probably remove
let styleElement = document.querySelector(`style.varwind-styles`);
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.classList.add('varwind-styles');
document.head.appendChild(styleElement);
}
styleElement.innerHTML += classContent;
// attach the class to the element
element.classList.add(generatedClassName);
}
}
function onStylesheetsLoaded(callback) {
const stylesheets = [...document.styleSheets];
if (stylesheets.every(sheet => sheet.cssRules !== null)) {
callback();
} else {
window.addEventListener('load', callback);
}
}
function initializeStyles() {
requestAnimationFrame(() => {
applyStyles(document.querySelectorAll(`[${ATTRIBUTE_NAME}]`));
});
}
function handleDevToolsChanges() {
const allNodes = document.querySelectorAll(`[${ATTRIBUTE_NAME}]`);
for(const node of allNodes){
const oldValue = node.getAttribute(ATTRIBUTE_NAME);
Object.defineProperty(node, ATTRIBUTE_NAME, {
get: function() {
return this.getAttribute(ATTRIBUTE_NAME);
},
set: function(newValue) {
this.setAttribute(ATTRIBUTE_NAME, newValue);
requestAnimationFrame(() => applyStyles([this]));
}
});
// Trigger the setter to apply initial styles
node[ATTRIBUTE_NAME] = oldValue;
};
}
function setupObserver(){
// Create a MutationObserver to watch for changes in the x-css-vars attribute
const observer = new MutationObserver(mutations => {
for(const mutation of mutations){
if (mutation.type === 'attributes' && mutation.attributeName === ATTRIBUTE_NAME) {
const updatedNodes = mutation.target.querySelectorAll(`[${ATTRIBUTE_NAME}]`);
applyStyles(updatedNodes);
}
}
});
observer.observe(document.body, {
attributes: true,
subtree: true,
attributeFilter: [ATTRIBUTE_NAME]
});
}
requestAnimationFrame(() => {
initializeStyles();
});
// hide the page until the styles are applied
const htmlElement = document.getElementsByTagName("html")[0];
htmlElement.style.display = 'none';
// Start observing the document with the configured parameters
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
onStylesheetsLoaded(() => {
initializeStyles();
setupObserver();
handleDevToolsChanges();
htmlElement.style.display = '';
});
});
} else {
onStylesheetsLoaded(() => {
initializeStyles();
setupObserver();
handleDevToolsChanges();
htmlElement.style.display = '';
});
}