/
dom.ts
363 lines (343 loc) · 10.4 KB
/
dom.ts
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
import {
isArray as isa,
isNotStringAndIterable as isi,
isString as iss,
} from "@thi.ng/checks";
import { css, formatPrefixes, SVG_TAGS } from "@thi.ng/hiccup";
import { XML_SVG } from "@thi.ng/prefixes";
import type { HDOMImplementation, HDOMOpts } from "./api";
const isArray = isa;
const isNotStringAndIterable = isi;
const isString = iss;
const maybeInitElement = <T>(el: T, tree: any) =>
tree.__init && tree.__init.apply(tree.__this, [el, ...tree.__args]);
/**
* See {@link HDOMImplementation} interface for further details.
*
* @param opts - hdom config options
* @param parent - DOM element
* @param tree - component tree
* @param insert - child index
*/
export const createTree = <T>(
opts: Partial<HDOMOpts>,
impl: HDOMImplementation<T>,
parent: T,
tree: any,
insert?: number,
init = true
): any => {
if (isArray(tree)) {
const tag = tree[0];
if (typeof tag === "function") {
return createTree(
opts,
impl,
parent,
tag.apply(null, [opts.ctx, ...tree.slice(1)]),
insert
);
}
const attribs = tree[1];
if (attribs.__impl) {
return (<HDOMImplementation<any>>attribs.__impl).createTree(
opts,
parent,
tree,
insert,
init
);
}
const el = impl.createElement(parent, tag, attribs, insert);
if (tree.length > 2) {
const n = tree.length;
for (let i = 2; i < n; i++) {
createTree(opts, impl, el, tree[i], undefined, init);
}
}
init && maybeInitElement<T>(el, tree);
return el;
}
if (isNotStringAndIterable(tree)) {
const res = [];
for (let t of tree) {
res.push(createTree(opts, impl, parent, t, insert, init));
}
return res;
}
if (tree == null) {
return parent;
}
return impl.createTextElement(parent, tree);
};
/**
* See {@link HDOMImplementation} interface for further details.
*
* @param opts - hdom config options
* @param parent - DOM element
* @param tree - component tree
* @param index - child index
*/
export const hydrateTree = <T>(
opts: Partial<HDOMOpts>,
impl: HDOMImplementation<any>,
parent: T,
tree: any,
index = 0
) => {
if (isArray(tree)) {
const el = impl.getChild(parent, index);
if (typeof tree[0] === "function") {
hydrateTree(
opts,
impl,
parent,
tree[0].apply(null, [opts.ctx, ...tree.slice(1)]),
index
);
}
const attribs = tree[1];
if (attribs.__impl) {
return (<HDOMImplementation<any>>attribs.__impl).hydrateTree(
opts,
parent,
tree,
index
);
}
maybeInitElement(el, tree);
for (let a in attribs) {
a[0] === "o" && a[1] === "n" && impl.setAttrib(el, a, attribs[a]);
}
for (let n = tree.length, i = 2; i < n; i++) {
hydrateTree(opts, impl, el, tree[i], i - 2);
}
} else if (isNotStringAndIterable(tree)) {
for (let t of tree) {
hydrateTree(opts, impl, parent, t, index);
index++;
}
}
};
/**
* Creates a new DOM element of type `tag` with optional `attribs`. If
* `parent` is not `null`, the new element will be inserted as child at
* given `insert` index. If `insert` is missing, the element will be
* appended to the `parent`'s list of children. Returns new DOM node.
*
* If `tag` is a known SVG element name, the new element will be created
* with the proper SVG XML namespace.
*
* @param parent - DOM element
* @param tag - component tree
* @param attribs - attributes
* @param insert - child index
*/
export const createElement = (
parent: Element,
tag: string,
attribs?: any,
insert?: number
) => {
const el = SVG_TAGS[tag]
? document.createElementNS(XML_SVG, tag)
: document.createElement(tag);
attribs && setAttribs(el, attribs);
return addChild(parent, el, insert);
};
export const createTextElement = (
parent: Element,
content: string,
insert?: number
) => addChild(parent, document.createTextNode(content), insert);
export const addChild = (parent: Element, child: Node, insert?: number) =>
parent
? insert === undefined
? parent.appendChild(child)
: parent.insertBefore(child, parent.children[insert])
: child;
export const getChild = (parent: Element, child: number) =>
parent.children[child];
export const replaceChild = (
opts: Partial<HDOMOpts>,
impl: HDOMImplementation<any>,
parent: Element,
child: number,
tree: any,
init = true
) => (
impl.removeChild(parent, child),
impl.createTree(opts, parent, tree, child, init)
);
export const cloneWithNewAttribs = (el: Element, attribs: any) => {
const res = <Element>el.cloneNode(true);
setAttribs(res, attribs);
el.parentNode!.replaceChild(res, el);
return res;
};
export const setContent = (el: Element, body: any) => (el.textContent = body);
export const setAttribs = (el: Element, attribs: any) => {
for (let k in attribs) {
setAttrib(el, k, attribs[k], attribs);
}
return el;
};
/**
* Sets a single attribute on given element. If attrib name is NOT an
* event name (prefix: "on") and its value is a function, it is called
* with given `attribs` object (usually the full attrib object passed to
* {@link setAttribs}) and the function's return value is used as the actual
* attrib value.
*
* Special rules apply for certain attributes:
*
* - "style": delegated to {@link setStyle}
* - "value": delegated to {@link updateValueAttrib}
* - attrib IDs starting with "on" are treated as event listeners
*
* If the given (or computed) attrib value is `false` or `undefined` the
* attrib is removed from the element.
*
* @param el - DOM element
* @param id - attribute name
* @param val - attribute value
* @param attribs - object of all attribs
*/
export const setAttrib = (el: Element, id: string, val: any, attribs?: any) => {
if (id.startsWith("__")) return;
const isListener = id[0] === "o" && id[1] === "n";
if (!isListener && typeof val === "function") {
val = val(attribs);
}
if (val !== undefined && val !== false) {
switch (id) {
case "style":
setStyle(el, val);
break;
case "value":
updateValueAttrib(<HTMLInputElement>el, val);
break;
case "prefix":
el.setAttribute(id, isString(val) ? val : formatPrefixes(val));
break;
case "accesskey":
(<any>el).accessKey = val;
break;
case "contenteditable":
(<any>el).contentEditable = val;
break;
case "tabindex":
(<any>el).tabIndex = val;
break;
case "align":
case "autocapitalize":
case "checked":
case "dir":
case "draggable":
case "hidden":
case "id":
case "lang":
case "namespaceURI":
case "scrollTop":
case "scrollLeft":
case "title":
// TODO add more properties / enumerated attribs?
(<any>el)[id] = val;
break;
default:
isListener
? setListener(el, id.substr(2), val)
: el.setAttribute(id, val === true ? "" : val);
}
} else {
(<any>el)[id] != null ? ((<any>el)[id] = null) : el.removeAttribute(id);
}
return el;
};
/**
* Updates an element's `value` property. For form elements it too
* ensures the edit cursor retains its position.
*
* @param el - DOM element
* @param value - value
*/
export const updateValueAttrib = (el: HTMLInputElement, value: any) => {
let ev;
switch (el.type) {
case "text":
case "textarea":
case "password":
case "search":
case "number":
case "email":
case "url":
case "tel":
case "date":
case "datetime-local":
case "time":
case "week":
case "month":
if ((ev = el.value) !== undefined && typeof value === "string") {
const off =
value.length - (ev.length - (el.selectionStart || 0));
el.value = value;
el.selectionStart = el.selectionEnd = off;
break;
}
default:
el.value = value;
}
};
export const removeAttribs = (el: Element, attribs: string[], prev: any) => {
for (let i = attribs.length; --i >= 0; ) {
const a = attribs[i];
if (a[0] === "o" && a[1] === "n") {
removeListener(el, a.substr(2), prev[a]);
} else {
el.hasAttribute(a) ? el.removeAttribute(a) : ((<any>el)[a] = null);
}
}
};
export const setStyle = (el: Element, styles: any) => (
el.setAttribute("style", css(styles)), el
);
/**
* Adds event listener (possibly with options).
*
* @param el - DOM element
* @param id - event name (w/o `on` prefix)
* @param listener -
*/
export const setListener = (
el: Element,
id: string,
listener:
| string
| EventListener
| [EventListener, boolean | AddEventListenerOptions]
) =>
isString(listener)
? el.setAttribute("on" + id, listener)
: isArray(listener)
? el.addEventListener(id, ...listener)
: el.addEventListener(id, listener);
/**
* Removes event listener (possibly with options).
*
* @param el - DOM element
* @param id - event name (w/o `on` prefix)
* @param listener -
*/
export const removeListener = (
el: Element,
id: string,
listener: EventListener | [EventListener, boolean | AddEventListenerOptions]
) =>
isArray(listener)
? el.removeEventListener(id, ...listener)
: el.removeEventListener(id, listener);
export const clearDOM = (el: Element) => (el.innerHTML = "");
export const removeChild = (parent: Element, childIdx: number) => {
const n = parent.children[childIdx];
n !== undefined && parent.removeChild(n);
};