-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapped-elements.js
More file actions
386 lines (343 loc) · 10.6 KB
/
wrapped-elements.js
File metadata and controls
386 lines (343 loc) · 10.6 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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
export * from './bonus.js'
/** The HTMLElement setter function in WrappedHtmlElements.
* @typedef {(value: any, ...additionalValues: any[]) => WrappedHtmlElement} SetProperty
*/
/** The e proxy record.
* @typedef {Record<keyof HTMLElementTagNameMap, WrappedHtmlElement>} ElementMap
*/
/** Todo: Also document the setters for HTMLElement properties...
* @typedef {Record<keyof HTMLElement, SetProperty>} HTMLElementPropertyMap
*/
/** Given `WrappedHtmlElements` returns the `HTMLElements`, anything else is passed through.
* @param {WrappedHtmlElement} wrappedElements
* @returns {HTMLElement[]}
*/
export function unwrap(...wrappedElements) {
return wrappedElements.map((wrapper) =>
wrapper instanceof WrappedHtmlElement ? wrapper.element : wrapper)
}
/** Returns a `WrappedHtmlElement` instance wrapped around this element. If it's already wrapped in one then it just returns that one.
* @param {HTMLElement} element
* @returns {WrappedHtmlElement}
*/
export function wrap(element) {
if (wrapperWeakMap.has(element)) {
return wrapperWeakMap.get(element)
}
return new WrappedHtmlElement(element)
}
/** Find any tagged `HTMLElements` here.
* @type {Object.<string, HTMLElement>}
* @deprecated Not needed when using tag = e.whatever() */
export let tags = {}
/** @type {WeakMap.<HTMLElement, WrappedHtmlElement>} */
const wrapperWeakMap = new WeakMap()
/** It's like an `HTMLElement` with some helper functions.
* @class
* @implements {HTMLElementPropertyMap}
*/
export class WrappedHtmlElement extends Function {
/** @type {HTMLElement} */
#element
/** @type {WrappedHtmlElement} */
#proxy
/** Store any custom data here. */
data = {}
get element() {return this.#element}
/** @param {string | HTMLElement} tagNameOrElement */
constructor(tagNameOrElement) {
super()
Object.seal() // Object.freeze()
if (tagNameOrElement instanceof HTMLElement) {
this.#element = tagNameOrElement
// do not wrap if already wrapped
if (wrapperWeakMap.has(this.#element)) {
return wrapperWeakMap.get(this.#element)
}
} else {
const split = tagNameOrElement.split(/(?=[A-Z])/) // regex to split camelCase words
if (split.length > 1) {
tagNameOrElement = split.join('-')
}
this.#element = document.createElement(tagNameOrElement.toLowerCase())
}
this.#proxy = new Proxy(this, {
get: this.#getProxy.bind(this),
set: this.#setProxy.bind(this),
apply: this.#applyProxy.bind(this),
})
wrapperWeakMap.set(this.#element, this.#proxy)
return this.#proxy
}
// for convenience I return the underlying element, use .add() if proxy is wanted for further chaining
#applyProxy(target, thisArg, args) {
this.add(...args)
return this.element
}
#getProxy(target, property, r) {
if (property == 'name') {
property = 'aliasForName'
}
if (property in this) {
if (typeof this[property] == 'function') {
return this[property].bind(this)
}
return this[property]
} else if (property in this.#element) {
return this.#getProperty(this.#element, property)
}
}
#setProxy(target, property, value, r) {
if (property in this) {
this[property] = value
} else if (property in this.#element) {
this.#element[property] = value
} else {
throw Error(`No such property: ${property}`)
}
return true
}
#getProperty(parent, property) {
const value = parent[property]
switch (typeof value) {
case 'function':
return (...args) => {
value.call(parent, ...args)
return this.#proxy
}
case 'object':
if (value !== null) {
return this.#propertyProxy(value)
}
}
// if primitive
const setOrGet = function(value) {
if (!arguments.length) {
return parent[property]
}
parent[property] = value
return this.#proxy
}
return setOrGet.bind(this)
}
#propertyProxy(parent) {
return new Proxy(() => {}, {
get: (target, property) => {
if (property in parent) {
return this.#getProperty(parent, property)
}
},
set: (target, property, value) => {
parent[property] = value
return true
},
apply: (target, thisArg, args) => {
// it's either an object or a function
if (typeof parent == 'function') {
parent(...args)
} else {
if (!args.length) {
return parent
}
if (typeof args[0] != 'object') {
throw Error(`You must supply an object with the values to set.`)
}
for (const key in args[0]) {
if (!(key in parent)) {
throw Error(`No such key ${key} in object.`)
}
const value = args[0][key]
if (typeof parent[key] == 'function') {
parent[key](...(Array.isArray(value) ? value : [value]))
} else {
parent[key] = value
}
}
}
return this.#proxy
}
})
}
/** Set or Get a property on `#element` */
#setOrGetProperty(property, value) {
if (arguments.length == 1) {
return this.#element[property]
}
this.#element[property] = value
return this.#proxy
}
/** Set or Get a attribute on `#element` */
#setOrGetAttribute(attribute, value) {
if (arguments.length == 1) {
return this.#element.getAttribute(attribute)
}
this.#element.setAttribute(attribute, value)
return this.#proxy
}
/** Shortcut for `textContent`. */
text(value) {
return this.#setOrGetProperty('textContent', ...arguments)
}
/** Shortcut for `className`. */
class(value) {
return this.#setOrGetProperty('className', ...arguments)
}
/* Shortcut for the `name` attribute. Function.name is read only; so we handle this in the proxy. */
aliasForName(value) {
return this.#setOrGetAttribute('name', ...arguments)
}
/** Shortcut for the `for` attribute. */
for(value) {
// return this.#setOrGetProperty('htmlFor', ...arguments)
return this.#setOrGetAttribute('for', ...arguments)
}
/** Shortcut for `append(...unwrap(...elements))`. @deprecated Use `add()`. */
children = this.add
/** Shortcut for `append(...unwrap(...elements))`. */
add(...elements) {
this.#element.append(...unwrap(...elements))
return this.#proxy
}
#checkShadow() {
if (!this.#element.shadowRoot) {
throw Error(`No open shadowRoot is attached to the element.`)
}
}
/** Add elements to the `shadowRoot`. */
shadowAdd(...elements) {
this.#checkShadow()
this.#element.shadowRoot.append(...unwrap(...elements))
return this.#proxy
}
/** By default adopts all from `document.adoptedStyleSheets`. */
shadowAdoptStyles(styles = [...document.adoptedStyleSheets]) {
this.#checkShadow()
this.#element.shadowRoot.adoptedStyleSheets
= Array.isArray(styles) ? styles : [styles]
return this.#proxy
}
/** Store the `HTMLElement` under `tags[title]`.
* @deprecated Not needed when using tag = e.whatever() */
tag(title, group = tags) {
group[title] = this.#element
return this.#proxy
}
/** Store the `HTMLElement` under `tags[title]` and assign an id with the sane title.
* @deprecated Not needed when using tag = e.whatever() */
tagAndId(title, group = tags) {
this.#element.id = title
group[title] = this.#element
return this.#proxy
}
/** Shortcut for `addEventListener`. */
on(type, listener, options = undefined) {
this.#element.addEventListener(type, listener, options)
return this.#proxy
}
/** Shortcut for `addEventListener` with the `once` option. */
once(type, listener, options = {once: true}) {
this.#element.addEventListener(type, listener, options)
return this.#proxy
}
/** Shortcut for `setAttribute`. */
set(attribute, value = '') {
this.#element.setAttribute(attribute, value)
return this.#proxy
}
/** Shortcut for `toggleAttribute`. */
toggle(attribute, force = undefined) {
this.#element.toggleAttribute(attribute, force)
return this.#proxy
}
/** Shortcut for `removeAttribute`. */
delete(attribute) {
this.#element.removeAttribute(attribute)
return this.#proxy
}
/** Shortcut for `getAttribute`. */
get(attribute) {
return this.#element.getAttribute(attribute)
}
/** Shortcut for `hasAttribute`. */
has(attribute) {
return this.#element.hasAttribute(attribute)
}
/** Execute this callback once added to the document (the first time). */
onceAdded(callback) {
onceAdded.set(this.#element, callback)
observeDocument()
return this.#proxy
}
}
/** Returns a new `WrappedHtmlElement` for any property you access.
* @type {ElementMap}
*/
export const e = new Proxy({}, {
get: function(target, property) {
if (property == 'text') {
return text => document.createTextNode(text || '')
}
return new WrappedHtmlElement(property)
}
})
/** If given strings then consume the specified tags out of the `tags` object (returns and removes them). If no arguments then consume all the tags.
* @param {string | object | undefined} tags
* @deprecated Not needed when using tag = e.whatever() */
export function consumeTags(...tagTitle) {
// consume all
if (!tagTitle.length) {
const result = tags
tags = {}
return result
}
// consume some
const consumed = {}
for (const title of tagTitle) {
consumed[title] = tags[title]
delete tags[title]
}
return consumed
}
/** [element, callback] */
const onceAdded = new Map()
let isObserving = false
function observeDocument() {
if (!isObserving) {
documentObserver.observe(document.body, {childList: true, subtree: true})
isObserving = true
}
}
function runCallbackIfAny(element) {
const callback = onceAdded.get(element)
if (callback) {
try {
if (typeof callback == 'function') {
const wrapped = wrap(element)
callback(wrapped)
} else {
throw Error('The onceAdded(callback) must be a function!')
}
} finally {
onceAdded.delete(element)
}
}
}
const documentObserver = new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type == 'childList') {
for (const node of mutation.addedNodes) {
if (node.nodeType == Node.ELEMENT_NODE) {
runCallbackIfAny(node)
// also check its children
for (const descendant of node.querySelectorAll('*')) {
runCallbackIfAny(descendant)
}
}
}
}
}
if (onceAdded.size == 0) {
observer.disconnect()
isObserving = false
}
})