-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathdom.js
More file actions
458 lines (428 loc) · 14.9 KB
/
dom.js
File metadata and controls
458 lines (428 loc) · 14.9 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/* Utilities for DOM traversal or navigation */
import events from "./events";
import logging from "./logging";
const logger = logging.getLogger("core dom");
const DATA_PREFIX = "__patternslib__data_prefix__";
const DATA_STYLE_DISPLAY = "__patternslib__style__display";
/**
* Return an array of DOM nodes.
*
* @param {Node|NodeList|jQuery} nodes - The DOM node to start the search from.
*
* @returns {Array} - An array of DOM nodes.
*/
const toNodeArray = (nodes) => {
if (nodes.jquery || nodes instanceof NodeList) {
// jQuery or document.querySelectorAll
nodes = [...nodes];
} else if (nodes instanceof Array === false) {
nodes = [nodes];
}
return nodes;
};
/**
* Like querySelectorAll but including the element where it starts from.
* Returns an Array, not a NodeList
*
* @param {Node} el - The DOM node to start the search from.
*
* @returns {Array} - The DOM nodes found.
*/
const querySelectorAllAndMe = (el, selector) => {
if (!el) {
return [];
}
const all = [...el.querySelectorAll(selector)];
if (el.matches(selector)) {
all.unshift(el); // start element should be first.
}
return all;
};
/**
* Wrap a element with a wrapper element.
*
* The element to be wrapped will be moved into the wrapper element and the
* wrapper element is placed just before the old element was.
*
* @param {Node} el - The DOM node to wrap.
* @param {Node} wrapper - The wrapper element.
*/
const wrap = (el, wrapper) => {
// See: https://stackoverflow.com/a/13169465/1337474
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
};
/**
* Hides the element with ``display: none`` and stores the current display value.
*
* @param {Node} el - The DOM node to hide.
*/
const hide = (el) => {
if (el.style.display === "none") {
// Nothing to do.
return;
}
if (el.style.display) {
el[DATA_STYLE_DISPLAY] = el.style.display;
}
el.style.display = "none";
};
/**
* Shows element by removing ``display: none`` and restoring the display value
* to whatever it was before.
*
* @param {Node} el - The DOM node to show.
*/
const show = (el) => {
const val = el[DATA_STYLE_DISPLAY] || null;
el.style.display = val;
delete el[DATA_STYLE_DISPLAY];
};
/**
* Test, if a element is visible or not.
*
* @param {Node} el - The DOM node to test.
* @returns {Boolean} - True if the element is visible.
*/
const is_visible = (el) => {
// Check, if element is visible in DOM.
// https://stackoverflow.com/a/19808107/1337474
return el.offsetWidth > 0 && el.offsetHeight > 0;
};
/**
* Test, if a element is a input-type element.
*
* @param {Node} el - The DOM node to test.
* @returns {Boolean} - True if the element is a input-type element.
*/
const is_input = (el) => {
return el.matches("button, input, select, textarea");
};
/**
* Return all direct parents of ``el`` matching ``selector``.
* This matches against all parents but not the element itself.
* The order of elements is from the search starting point up to higher
* DOM levels.
*
* @param {Node} el - The DOM node to start the search from.
* @param {String} selector - CSS selector to match against.
* @returns {Array} - List of matching DOM nodes.
*/
const find_parents = (el, selector) => {
const ret = [];
let parent = el;
while (parent) {
parent = parent.parentNode?.closest?.(selector);
if (parent) ret.push(parent);
}
return ret;
};
/**
* Find an element in the whole DOM tree if the selector is an ID selector,
* otherwise use the given element as the starting point.
*
* @param {Node} el - The DOM node to start the search from.
* @param {String} selector - The CSS selector to search for.
*
* @returns {NodeList} - The DOM nodes found.
*
*/
const find_scoped = (el, selector) => {
// If the selector starts with an object id do a global search,
// otherwise do a local search.
return (selector.indexOf("#") === 0 ? document : el).querySelectorAll(selector);
};
/**
* Return all HTMLElement parents of el, starting from the direct parent of el.
* The document itself is excluded because it's not a real DOM node.
*
* @param {Node} el - The DOM node to start the search from.
*
* @returns {Array} - The DOM nodes found.
*/
const get_parents = (el) => {
// Return all HTMLElement parents of el, starting from the direct parent of el.
const parents = [];
let parent = el?.parentNode;
while (parent) {
parents.push(parent);
parent = parent?.parentNode;
parent = parent instanceof HTMLElement ? parent : null;
}
return parents;
};
/**
* Return the value of the first attribute found in the list of parents.
*
* @param {Node} el - The DOM element to start the acquisition search for the given attribute.
* @param {string} attribute - Name of the attribute to search for.
* @param {Boolean} include_empty - Also return empty values.
* @param {Boolean} include_all - Return a list of attribute values found in all parents.
*
* @returns {*} - Returns the value of the searched attribute or a list of all attributes.
*/
const acquire_attribute = (
el,
attribute,
include_empty = false,
include_all = false
) => {
let _el = el;
const ret = []; // array for ``include_all`` mode.
while (_el) {
const val = _el.getAttribute(attribute);
if (val || (include_empty && val === "")) {
if (!include_all) {
return val;
}
ret.push(val);
}
_el = _el.parentElement;
}
if (include_all) {
return ret;
}
};
/**
* Return a DocumentFragment from a given string.
*
* @param {String} string - The HTML structure as a string.
*
* @returns {DocumentFragment} - The DOM nodes as a DocumentFragment.
*/
const create_from_string = (string) => {
// See: https://davidwalsh.name/convert-html-stings-dom-nodes
return document.createRange().createContextualFragment(string.trim());
};
/**
* Return a CSS property value for a given DOM node.
* For length-values, relative values are converted to pixels.
* Optionally parse as pixels, if applicable.
*
* Note: The element must be attached to the body to make CSS caluclations work.
*
* @param {Node} el - DOM node.
* @param {String} property - CSS property to query on DOM node.
* @param {Boolean} [as_pixels=false] - Convert value to pixels, if applicable.
* @param {Boolean} [as_float=false] - Convert value to float, if applicable.
*
* @returns {(String|Number)} - The CSS value to return.
*/
function get_css_value(el, property, as_pixels = false, as_float = false) {
let value = window.getComputedStyle(el).getPropertyValue(property);
if (as_pixels || as_float) {
value = parseFloat(value) || 0.0;
}
if (as_pixels && !as_float) {
value = parseInt(Math.round(value), 10);
}
return value;
}
/**
* Find a scrollable element up in the DOM tree.
*
* Note: Setting the ``overflow`` shorthand property also sets the individual overflow-y and overflow-y properties.
*
* @param {Node} el - The DOM element to start the search on.
* @param {String} [direction=] - Not given: Search for any scrollable element up in the DOM tree.
* ``x``: Search for a horizontally scrollable element.
* ``y``: Search for a vertically scrollable element.
* @param {(Node|null)} [fallback=document.body] - Fallback, if no scroll container can be found.
* The default is to use document.body.
*
* @returns {Node} - Return the first scrollable element.
* If no other element could be found, document.body would be returned.
*/
const find_scroll_container = (el, direction, fallback = document.body) => {
while (el && el !== document.body) {
if (!direction || direction === "y") {
let overflow_y = get_css_value(el, "overflow-y");
if (["auto", "scroll"].includes(overflow_y)) {
return el;
}
}
if (!direction || direction === "x") {
let overflow_x = get_css_value(el, "overflow-x");
if (["auto", "scroll"].includes(overflow_x)) {
return el;
}
}
el = el.parentElement;
}
return fallback;
};
/**
* Get the horizontal scroll position.
*
* @param {Node} scroll_reference - The element to get the scroll position from.
*
* @returns {number} The horizontal scroll position.
*/
const get_scroll_x = (scroll_reference) => {
// scroll_listener == window: window.scrollX
// scroll_listener == html: html.scrollLeft == window.scrollX
// scroll_listener == DOM node: node.scrollLeft
return typeof scroll_reference.scrollLeft !== "undefined"
? scroll_reference.scrollLeft
: scroll_reference.scrollX;
};
/**
* Get the vertical scroll position.
*
* @param {Node} scroll_reference - The element to get the scroll position from.
*
* @returns {number} The vertical scroll position.
*/
const get_scroll_y = (scroll_reference) => {
// scroll_listener == window: window.scrollY
// scroll_listener == html: html.scrollTop == window.scrollY
// scroll_listener == DOM node: node.scrollTop
return typeof scroll_reference.scrollTop !== "undefined"
? scroll_reference.scrollTop
: scroll_reference.scrollY;
};
/**
* Get data stored directly on the node instance.
* We are using a prefix to make sure the data doesn't collide with other attributes.
*
* @param el {Node} - The DOM node from which we want to retrieve the data.
* @param name {String} - The name of the variable. Note - this is stored on
* the DOM node prefixed with the DATA_PREFIX.
* @param default_value {Any} - Optional default value.
* @returns {Any} - The value which is stored on the DOM node.
*/
const get_data = (el, name, default_value) => {
return el[`${DATA_PREFIX}${name}`] || default_value;
};
/**
* Set and store data directly on the node instance.
* We are using a prefix to make sure the data doesn't collide with other attributes.
*
* @param el {Node} - The DOM node which we want to store the data on.
* @param name {String} - The name of the variable. Note - this is stored on
* the DOM node prefixed with the DATA_PREFIX.
* @param value {Any} - The value we want to store on the DOM node.
*/
const set_data = (el, name, value) => {
el[`${DATA_PREFIX}${name}`] = value;
};
/**
* Delete a variable from the node instance.
* We are using a prefix to make sure the data doesn't collide with other attributes.
*
* @param el {Node} - The DOM node which we want to delete the variable from.
* @param name {String} - The name of the variable. Note - this is stored on
* the DOM node prefixed with the DATA_PREFIX.
*/
const delete_data = (el, name) => {
delete el[`${DATA_PREFIX}${name}`];
};
/**
* Simple template engine, based on JS template literal
*
* NOTE: This uses eval and would break if Content-Security-Policy does not
* allow 'unsafe-eval'.
* Because of this CSR problem the use of this method is not recommended.
*
* Please note: You cannot pass a template literal as template_string.
* JavaScript itself would try to expand it and would fail.
*
* See: https://stackoverflow.com/a/37217166/1337474
*
* @param {String} template_string - The template string as a JavaScript template literal.
* For each variable in the template you have to use ``this``.
* E.g. if you pass ``{message: "ok"}`` as template_variables, you can use it like so:
* `<h1>${this.message}</h1>`
* @param {Object} template_variables - Object literal with all the variables which should be used in the template.
*
* @returns {String} - Returns the a string as template expanded with the template_variables.
*/
const template = (template_string, template_variables = {}) => {
logger.warn(
"Using dom.template is not recommended due to a problem with Content-Security-Policy."
);
return new Function("return `" + template_string + "`;").call(template_variables);
};
/**
* Get the visible ratio of an element compared to container.
* If no container is given, the viewport is used.
*
* Note: currently only vertical ratio is supported.
*
* @param {Node} el - The element to get the visible ratio from.
* @param {Node} [container] - The container to compare the element to.
* @returns {number} - The visible ratio of the element.
* 0 means the element is not visible.
* 1 means the element is fully visible.
*/
const get_visible_ratio = (el, container) => {
if (!el) {
return 0;
}
const rect = el.getBoundingClientRect();
const container_rect =
container !== window
? container.getBoundingClientRect()
: {
top: 0,
bottom: window.innerHeight,
};
let visible_ratio = 0;
if (rect.top < container_rect.bottom && rect.bottom > container_rect.top) {
const rect_height = rect.bottom - rect.top;
const visible_height =
Math.min(rect.bottom, container_rect.bottom) -
Math.max(rect.top, container_rect.top);
visible_ratio = visible_height / rect_height;
}
return visible_ratio;
};
/**
* Get an escaped CSS selector for a given id string.
*
* id selectors should - but don't have to - start with a letter.
* If the id starts with a number or a dash, it should be escaped.
* This method does that for you.
*
* Alse see:
* - https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
* - https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape
*
* @param {String} id - The id to escape.
*
* @returns {String} - The escaped CSS selector.
*
* @example
* escape_css_id_selector("#123"); // returns "#\\31 23""
* escape_css_id_selector("#-123"); // returns "#-\\31 23"
*/
const escape_css_id = (id) => {
return `#${CSS.escape(id.split("#")[1])}`;
};
const dom = {
toNodeArray: toNodeArray,
querySelectorAllAndMe: querySelectorAllAndMe,
wrap: wrap,
hide: hide,
show: show,
find_parents: find_parents,
find_scoped: find_scoped,
get_parents: get_parents,
acquire_attribute: acquire_attribute,
is_visible: is_visible,
is_input: is_input,
create_from_string: create_from_string,
get_css_value: get_css_value,
find_scroll_container: find_scroll_container,
get_scroll_x: get_scroll_x,
get_scroll_y: get_scroll_y,
get_data: get_data,
set_data: set_data,
delete_data: delete_data,
template: template,
get_visible_ratio: get_visible_ratio,
escape_css_id: escape_css_id,
add_event_listener: events.add_event_listener, // BBB export. TODO: Remove in an upcoming version.
remove_event_listener: events.remove_event_listener, // BBB export. TODO: Remove in an upcoming version.
};
export default dom;