UNPKG

1.88 kBPlain TextView Raw
1// Copyright (c) Jupyter Development Team.
2// Distributed under the terms of the Modified BSD License.
3
4import { ArrayExt } from '@lumino/algorithm';
5import { UUID } from '@lumino/coreutils';
6import { ElementExt } from '@lumino/domutils';
7
8/**
9 * The namespace for DOM utilities.
10 */
11export namespace DOMUtils {
12 /**
13 * Get the index of the node at a client position, or `-1`.
14 */
15 export function hitTestNodes(
16 nodes: HTMLElement[] | HTMLCollection,
17 x: number,
18 y: number
19 ): number {
20 return ArrayExt.findFirstIndex(nodes, node => {
21 return ElementExt.hitTest(node, x, y);
22 });
23 }
24
25 /**
26 * Find the first element matching a class name.
27 */
28 export function findElement(
29 parent: HTMLElement,
30 className: string
31 ): HTMLElement {
32 return parent.querySelector(`.${className}`) as HTMLElement;
33 }
34
35 /**
36 * Find the first element matching a class name.
37 */
38 export function findElements(
39 parent: HTMLElement,
40 className: string
41 ): HTMLCollectionOf<HTMLElement> {
42 return parent.getElementsByClassName(
43 className
44 ) as HTMLCollectionOf<HTMLElement>;
45 }
46
47 /**
48 * Create a DOM id with prefix "id-" to solve bug for UUIDs beginning with numbers.
49 */
50 export function createDomID(): string {
51 return `id-${UUID.uuid4()}`;
52 }
53
54 /**
55 * Check whether the active element descendant from given parent is editable.
56 * When checking active elements it includes elements in the open shadow DOM.
57 */
58 export function hasActiveEditableElement(
59 parent: Node | DocumentFragment,
60 root: ShadowRoot | Document = document
61 ): boolean {
62 const element = root.activeElement;
63 return !!(
64 element &&
65 parent.contains(element) &&
66 (element.matches(':read-write') ||
67 (element.shadowRoot &&
68 hasActiveEditableElement(element.shadowRoot, element.shadowRoot)))
69 );
70 }
71}