-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdom.mjs
More file actions
313 lines (257 loc) · 9.86 KB
/
dom.mjs
File metadata and controls
313 lines (257 loc) · 9.86 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
/* global document*/
import * as l from './lang.mjs'
import * as o from './obj.mjs'
export function isEvent(val) {return typeof Event === `function` && l.isInst(val, Event)}
export function reqEvent(val) {return l.req(val, isEvent)}
export function optEvent(val) {return l.opt(val, isEvent)}
export function isChildNode(val) {return l.isObj(val) && `parentNode` in val}
export function reqChildNode(val) {return l.req(val, isChildNode)}
export function optChildNode(val) {return l.opt(val, isChildNode)}
export function isParentNode(val) {return l.isObj(val) && `childNodes` in val}
export function reqParentNode(val) {return l.req(val, isParentNode)}
export function optParentNode(val) {return l.opt(val, isParentNode)}
// See `dom_shim.mjs` → `Node`.
export function isNode(val) {return l.isObj(val) && `nodeType` in val}
export function reqNode(val) {return l.req(val, isNode)}
export function optNode(val) {return l.opt(val, isNode)}
// See `dom_shim.mjs` → `Node.ELEMENT_NODE`.
export function isElement(val) {return l.isObj(val) && val.nodeType === 1}
export function reqElement(val) {return l.req(val, isElement)}
export function optElement(val) {return l.opt(val, isElement)}
export function isBlob(val) {return typeof Blob === `function` && l.isInst(val, Blob)}
export function reqBlob(val) {return l.req(val, isBlob)}
export function optBlob(val) {return l.opt(val, isBlob)}
export function isFile(val) {return typeof File === `function` && l.isInst(val, File)}
export function reqFile(val) {return l.req(val, isFile)}
export function optFile(val) {return l.opt(val, isFile)}
export function eventKill(val) {
if (!optEvent(val)) return val
val.preventDefault()
return eventStop(val)
}
export function eventStop(val) {
if (!optEvent(val)) return val
val.stopPropagation()
val.stopImmediatePropagation()
return val
}
export function isEventModified(val) {
return !!(optEvent(val) && (val.altKey || val.ctrlKey || val.metaKey || val.shiftKey))
}
export function eventDispatch({src, type, data}) {
src.dispatchEvent(new CustomEvent(l.reqStr(type), {detail: data}))
}
export function eventListen({src, type, han, opt}) {
l.reqObj(src).addEventListener(l.reqStr(type), l.reqComp(han), l.optRec(opt))
return function deinit() {src.removeEventListener(type, han, opt)}
}
export class ListenRef extends l.WeakRef {
constructor({self, src, type, fun, opt}) {
super(self)
this.src = new l.WeakRef(src)
this.type = l.reqStr(type)
this.fun = l.reqFun(fun)
this.opt = l.optRec(opt)
REG_DEINIT.register(self, this)
}
handleEvent(eve) {
const self = this.deref()
if (self) this.fun.call(self, eve)
else this.deinit()
}
init() {
this.deinit()
this.src.deref().addEventListener(this.type, this, this.opt)
return this
}
deinit() {this.src.deref()?.removeEventListener(this.type, this, this.opt)}
[l.DISPOSE]() {this.deinit()}
}
const REG_DEINIT = new l.FinalizationRegistry(function finalizeDeinit(val) {
if (l.isFun(val)) val()
else val.deinit()
})
export function nodeShow(val) {if (optNode(val) && val.hidden) val.hidden = false}
export function nodeHide(val) {if (optNode(val) && !val.hidden) val.hidden = true}
export function nodeRemove(val) {if (optNode(val)) val.remove()}
export function nodeSel(val, sel) {return val.querySelector(l.reqStr(sel))}
export function nodeSelAll(val, sel) {return val.querySelectorAll(l.reqStr(sel))}
export function isConnected(val) {return isNode(val) && val.isConnected}
export function isDisconnected(val) {return isNode(val) && !val.isConnected}
export function copyToClipboard(src) {
if (!(src = l.render(src))) return
const prev = document.activeElement
const next = document.createElement(`textarea`)
next.value = src
document.body.append(next)
try {
next.focus()
selectText(next)
document.execCommand(`copy`)
}
finally {
next.remove()
prev?.focus?.()
}
}
export function selectText(val) {
if (!optElement(val)) return
if (l.hasMeth(val, `select`)) {
val.select()
}
else if (l.hasMeth(val, `setSelectionRange`)) {
val.setSelectionRange(0, l.laxStr(val.value).length)
}
}
export function ancestor(tar, cls) {return findAncestor(tar, clsTest(cls))}
function clsTest(cls) {
l.reqFun(cls)
return function test(val) {return l.isInst(val, cls)}
}
export function findAncestor(tar, fun) {
l.reqFun(fun)
while (l.isSome(tar)) {
if (fun(tar)) return tar
if (!isChildNode(tar)) break
tar = tar.parentNode
}
return undefined
}
/*
Implementation note. In a native DOM environment, we could transparently use
`.querySelector` when the given class is registered through `dom_reg.mjs` and
has `.localName` and `.customName` defined as static properties. You would
expect `.querySelector` to perform better. However, in testing, it seems to
perform worse than our approach.
*/
export function descendant(src, cls) {return findDescendant(src, clsTest(cls))}
export function findDescendant(val, fun) {
for (val of findDescendants(val, fun)) return val
return undefined
}
export function descendants(tar, cls) {return findDescendants(tar, clsTest(cls))}
export function* findDescendants(val, fun) {
l.reqFun(fun)
if (l.isNil(val)) return
if (fun(val)) yield val
if (!isParentNode(val)) return
val = val.childNodes
if (val) for (val of val) yield* findDescendants(val, fun)
}
export function findNextSibling(tar, fun) {
l.reqFun(fun)
while (l.isSome((tar = l.get(tar, `nextSibling`)))) {
if (fun(tar)) return tar
}
return undefined
}
export function nextSibling(tar, cls) {return findNextSibling(tar, clsTest(cls))}
export function findPrevSibling(tar, fun) {
l.reqFun(fun)
while (l.isSome((tar = l.get(tar, `previousSibling`)))) {
if (fun(tar)) return tar
}
return undefined
}
export function prevSibling(tar, cls) {return findPrevSibling(tar, clsTest(cls))}
/*
Takes a DOM node class and returns a subclass with various shortcuts for DOM
inspection and manipulation.
*/
export function MixNode(cls) {return MixinNode.get(cls)}
export class MixinNode extends o.Mixin {
static make(cls) {
return class MixinNode extends cls {
anc(cls) {return ancestor(this, cls)}
findAnc(fun) {return findAncestor(this, fun)}
desc(cls) {return descendant(this, cls)}
findDesc(fun) {return findDescendant(this, fun)}
descs(cls) {return descendants(this, cls)}
findDescs(fun) {return findDescendants(this, fun)}
}
}
}
// Should match `dom_shim.mjs`.
export const PARENT_NODE = Symbol.for(`parentNode`)
/*
Short for "mixin: child". Supports establishing child-to-parent relations.
Implementation note. This uses the `get parentNode` and `set parentNode`
properties for compatibility with native DOM classes and our own DOM shim.
In addition to properties, we provide methods, because:
- Methods are easier to override. Subclasses may override `.setParent` to add a
type assertion. To correctly override `set parentNode`, a subclass must also
explicitly define `get parentNode`, which takes more code and ends up more
error-prone.
- Methods may return `this`, which is convenient for chaining.
*/
export function MixChild(cls) {return MixinChild.get(cls)}
export class MixinChild extends o.Mixin {
static make(cls) {
const desc = o.descIn(cls.prototype, `parentNode`)
if (!desc || !desc.get) {
return class ChildClsBase extends cls {
get parentNode() {return this[PARENT_NODE]}
set parentNode(val) {this[PARENT_NODE] = val}
getParent() {return this.parentNode}
setParent(val) {return (this.parentNode = val), this}
}
}
if (desc.set) {
return class ChildClsOnlyMethods extends cls {
getParent() {return this.parentNode}
setParent(val) {return (this.parentNode = val), this}
}
}
/*
Native DOM classes operate in this mode. They define `.parentNode` getter
without setter. DOM tree operations set this property magically, bypassing
JS operations. We must prioritize the native getter over our property to
ensure that when the element is attached to the DOM, the native parent
takes priority over the grafted one.
*/
return class ChildClsCompat extends cls {
get parentNode() {return super.parentNode ?? this[PARENT_NODE]}
set parentNode(val) {this[PARENT_NODE] = val}
getParent() {return this.parentNode}
setParent(val) {return (this.parentNode = val), this}
}
}
}
/*
Short for "mixin: child with constructor". Variant of `MixChild` that
automatically calls `.setParent` in the constructor if at least one argument
was provided. Convenient for code that heavily relies on child-to-parent
relations, which are particularly important when working with custom DOM
elements and using our `prax.mjs` and/or `dom_shim.mjs`.
Important note. Normally, DOM nodes establish child-to-parent relations when
children are attached to parents. With this mixin, the child-to-parent
relationship is established at construction time, via the first argument
provided to the constructor, and before the child is attached to the parent.
This allows children to immediately traverse the ancestor chain to
access "contextual" data available on ancestors. Note that this establishes
only child-to-parent relations, not parent-to-child. The latter become
available only after attaching the newly initialized children to the parent,
which is out of scope for this mixin.
*/
export function MixChildCon(cls) {return MixinChildCon.get(cls)}
export class MixinChildCon extends o.Mixin {
static make(cls) {
return class ChildCon extends MixChild(cls) {
constructor(...src) {
super()
if (src.length) this.setParent(...src)
}
}
}
}
export class ChildDiff extends WeakSet {
apply(tar, src) {
reqNode(tar)
src = new Set(l.optSeq(src))
for (const val of tar.childNodes) {
if (this.has(val) && !src.has(val)) val.remove()
}
for (const val of src) this.add(val)
tar.append(...src)
}
}