-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmixin.js
217 lines (187 loc) · 7.43 KB
/
mixin.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
import { render } from "./hoquet.js";
import { _importStyleRules, normalizeStylesEntry, rendered, defineReflectedAttributes, uuid } from "./utils.js";
const _nullobj = Object.create(null);
const CONTAINER_KEY = Symbol();
const CONTAINER_PTR = Symbol();
export default ((C = HTMLElement, {
template = "",
stylesheets = [],
attributes = [],
/**
* If true, shadow DOM is initialized by the constructor.
*/
shadowy = false,
/**
* If false, subsequent calls to render will not create new DOM elements,
* only update references and reflect attributes.
*/
rerenderable = false,
/**
* If true, any element with an `id` attribute will be cached
* in the `this.$` property for easy access. Otherwise, a Proxy
* is created for `this.$` doing `container.getElementById`.
*/
cacheIDs = false //!shadowy
} = {}) => {
const isHTMLElement = HTMLElement === C || HTMLElement.isPrototypeOf(C);
if (!isHTMLElement) {
throw new Error(
"Hoquet mixin must wrap either HTMLElement or a subclass of " +
"HTMLElement."
);
}
const _reflectedAttributes = new Set([...(C.reflectedAttributes || []), ...attributes] || []);
const _observedAttributes = [...(C.observedAttributes || [])];
const _getElementById = shadowy
? function(id) { return this.shadowRoot.getElementById(id); }
: function(id) { return this.querySelector(`#${id}`); };
class A extends (C) {
constructor(...args) {
super(...args);
if (shadowy) {
if (!this.shadowRoot) {
this.attachShadow({mode:"open"});
}
this[CONTAINER_KEY] = this.shadowRoot;
} else {
const $div = document.createElement("div");
this.appendChild($div);
this[CONTAINER_KEY] = $div;
}
}
static get reflectedAttributes() {
return _reflectedAttributes;
}
/**
* By default, all `reflectedAttributes` are `observedAttributes`, but
* it's also possible to override this so that additional attributes
* can be defined that aren't reflected (e.g., if they wouldn't trigger
* immediate mutations to the DOM). Just be careful not to forget to
* include the `reflectedAttributes` in the override. E.g., this
* probably does what you want:
*
* ```
* static get observedAttributes() {
* return [
* ...super.observedAttributes, // i.e., creates `reflectedAttributes`, returns their names
* "further", "unreflected", "attributes"
* ];
* }
* ```
*
* And this is functionally equivalent to `inst.render({reflect: false})`:
*
* ```
* static get observedAttributes() {
* return [
* ...this.reflectedAttributes, // i.e., returns `attributes` without creating `reflectedAttributes`
* "ignoring", "all", "reflected", "attributes"
* ];
* }
* ```
*/
static get observedAttributes() {
defineReflectedAttributes(this);
return [..._observedAttributes, ...this.reflectedAttributes];
}
/**
* This method is required to exist, otherwise `observedAttributes`
* won't be called by the browser. However, client code can override
* (or not) as normal.
*
* Also, we don't try to determine whether `attributeChangedCallback`
* is a function or not for performance reasons.
*/
attributeChangedCallback(k, p, c) {
if (super.attributeChangedCallback) {
super.attributeChangedCallback(k, p, c);
}
}
reflect() {
for (let k of _reflectedAttributes) {
this[k] = this[k]
}
}
get template() { return template; }
get styles() { return ""; }
set [CONTAINER_KEY](value) { Object.defineProperty(this, CONTAINER_PTR, {value}); }
get [CONTAINER_KEY]() { return this[CONTAINER_PTR]; }
fragment(...sources) {
return sources.map(source => source instanceof HTMLTemplateElement
? document.importNode(source.content, true)
: source instanceof DocumentFragment || source instanceof HTMLElement
? document.importNode(source, true)
: document.createRange().createContextualFragment(render(source))
).reduce((parent, child) => {
parent.appendChild(child);
return parent;
}, document.createDocumentFragment());
}
replace(container, ...sources) {
let child;
while(child = container.firstChild)
child.remove();
container.appendChild(this.fragment(...sources));
}
get rendered() { return this.hasOwnProperty("$"); }
render(options = {}) {
const {
/**
* If true, after the template/styles have been rendered, all
* `reflectedAttributes` will be reapplied, triggering
* `attributeChangedCallback`, so that DOM changes can be made.
*/
reflect = true
} = options;
const container = this[CONTAINER_KEY];
const rendered = this.rendered;
if (!rendered || rerenderable) {
const {sheets, styles} = normalizeStylesEntry(this.styles).reduce(
(conf, source) => {
conf[
source instanceof CSSStyleSheet
? "sheets"
: "styles"
].push(source);
return conf;
},
{sheets: [], styles: []}
);
if (!this.adoptStyleSheets(...stylesheets, ...sheets)) {
[...stylesheets, ...sheets].forEach(sheet => {
styles.push(["style", Array.from(sheet.rules).map(
rule => rule.cssText
).join(" ")]);
});
this.replace(container, ...styles, this.template);
this.shadowRoot?.prepend(...Array.from(
this.shadowRoot.querySelectorAll("link[rel='stylesheet']"))
);
} else {
this.replace(container, ...styles, this.template);
}
if (!rendered) {
Object.defineProperty(this, "$", {
value: cacheIDs
? {}
: new Proxy(_nullobj, {
get: (_, k) => _getElementById.call(this, k)
})
});
}
}
if (cacheIDs) {
Array.from(container.querySelectorAll("[id]")).forEach(
el => this.$[el.id] = el
);
}
if (reflect) {
this.reflect();
}
}
adoptStyleSheets(...sources) {
return !sources.length || _importStyleRules(this[CONTAINER_KEY], sources, shadowy);
}
}
return A;
});