-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstyle.js
More file actions
63 lines (57 loc) · 1.49 KB
/
style.js
File metadata and controls
63 lines (57 loc) · 1.49 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
61
62
63
import charCount from './charCount.js';
import eventManager from './eventManager.js';
import last from './last.js';
// Custom CSS classes are great.
export function newStyle(plugin = false) {
let loaded = false;
const el = document.createElement('style');
function appendStyle() {
if (el.parentElement) return;
if (plugin) el.dataset.underscriptPlugin = plugin.name;
else el.dataset.underscript = '';
document.head.append(el);
}
eventManager.on(':preload', () => {
loaded = true;
});
function add(...styles) {
const hasChildren = styles.length + el.children.length;
if (hasChildren) {
if (loaded) appendStyle();
else eventManager.once(':preload', () => appendStyle());
}
return wrapper(append(styles));
}
function append(styles = [], nodes = []) {
styles.flat().forEach((s) => {
if (charCount(s, '{') !== charCount(s, '}')) {
const logger = plugin?.logger ?? console;
logger.error('Malformed CSS (missing { or }):\n', s);
return;
}
el.append(s);
nodes.push(last(el.childNodes));
});
return nodes;
}
function wrapper(nodes = []) {
return {
remove() {
nodes.splice(0)
.forEach((node) => node.remove());
return this;
},
replace(...styles) {
return this.remove().append(styles);
},
append(...styles) {
append(styles, nodes);
return this;
},
};
}
return {
add,
};
}
export default newStyle();