-
Notifications
You must be signed in to change notification settings - Fork 0
/
preqompile.js
122 lines (71 loc) · 2.15 KB
/
preqompile.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
/*
# Preqompile
## version 1.1.1
Preqompile is a JS-in-CSS runtime that interprets the same containerQuery syntax as Qompile.
### Usage
To preview the result of adding a 'Qompile' stylesheet to an HTML document include a link to the `preqompile.js` file in your HTML document like this:
```
<script src=preqompile.js></script>
```
### Info
- website: https://github.com/tomhodgins/qompile
- author: Tommy Hodgins
- license: MIT
*/
function containerQuery(selector, test, stylesheet) {
var tag = document.querySelectorAll(selector)
var style = ''
var count = 0
for (var i=0; i<tag.length; i++) {
var attr = (selector+test).replace(/\W+/g, '')
if (test(tag[i])) {
var css = stylesheet.replace(/:self|\$this/g, '[data-' + attr + '="' + count + '"]')
tag[i].setAttribute('data-' + attr, count)
style += css
count++
}
}
return style
}
// Interpolate JS from inside <style> and <link> tags with ${}
var JSinCSS = {}
JSinCSS.load = function() {
document.querySelectorAll('style').forEach(tag => {
if (tag.getAttribute('data-populated') == null) {
tag.setAttribute('data-populated', true)
JSinCSS.process(tag.innerHTML)
}
})
document.querySelectorAll('link').forEach(tag => {
if (tag.href
&& tag.rel == 'stylesheet'
&& tag.getAttribute('data-populated') == null) {
tag.setAttribute('data-populated', true)
;(() => {
var xhr = new XMLHttpRequest
xhr.open('GET', tag.href, true)
xhr.send(null)
xhr.onload = function() {
JSinCSS.process(xhr.responseText)
}
})()
}
})
}
JSinCSS.process = function(stylesheet) {
if (stylesheet) {
var events = ['resize', 'input', 'click']
var css = new Function('return `' + stylesheet + '`')
var style = document.createElement('style')
style.setAttribute('data-populated', true)
style.innerHTML = css()
document.head.appendChild(style)
events.forEach(event => {
window.addEventListener(event, e => {
style.innerHTML = css()
})
})
style.innerHTML = css()
}
}
window.addEventListener('load', JSinCSS.load)