UNPKG

2.34 kBPlain TextView Raw
1import {Scope} from './isolate';
2
3function isValidNode(obj: any): obj is Element {
4 const ELEM_TYPE = 1;
5 const FRAG_TYPE = 11;
6 return typeof HTMLElement === 'object'
7 ? obj instanceof HTMLElement || obj instanceof DocumentFragment
8 : obj &&
9 typeof obj === 'object' &&
10 obj !== null &&
11 (obj.nodeType === ELEM_TYPE || obj.nodeType === FRAG_TYPE) &&
12 typeof obj.nodeName === 'string';
13}
14
15export function isClassOrId(str: string): boolean {
16 return str.length > 1 && (str[0] === '.' || str[0] === '#');
17}
18
19export function isDocFrag(
20 el: Element | DocumentFragment
21): el is DocumentFragment {
22 return el.nodeType === 11;
23}
24
25export function checkValidContainer(
26 container: Element | DocumentFragment | string
27): void {
28 if (typeof container !== 'string' && !isValidNode(container)) {
29 throw new Error(
30 'Given container is not a DOM element neither a selector string.'
31 );
32 }
33}
34
35export function getValidNode(
36 selectors: Element | DocumentFragment | string
37): Element | DocumentFragment | null {
38 const domElement =
39 typeof selectors === 'string'
40 ? document.querySelector(selectors)
41 : selectors;
42
43 if (typeof selectors === 'string' && domElement === null) {
44 throw new Error(`Cannot render into unknown element \`${selectors}\``);
45 }
46 return domElement;
47}
48
49export function getSelectors(namespace: Array<Scope>): string {
50 let res = '';
51 for (let i = namespace.length - 1; i >= 0; i--) {
52 if (namespace[i].type !== 'selector') {
53 break;
54 }
55 res = namespace[i].scope + ' ' + res;
56 }
57 return res.trim();
58}
59
60export function isEqualNamespace(
61 a: Array<Scope> | undefined,
62 b: Array<Scope> | undefined
63): boolean {
64 if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
65 return false;
66 }
67 for (let i = 0; i < a.length; i++) {
68 if (a[i].type !== b[i].type || a[i].scope !== b[i].scope) {
69 return false;
70 }
71 }
72 return true;
73}
74
75export function makeInsert(
76 map: Map<string, Map<Element, any>>
77): (type: string, elm: Element, value: any) => void {
78 return (type, elm, value) => {
79 if (map.has(type)) {
80 const innerMap = map.get(type)!;
81 innerMap.set(elm, value);
82 } else {
83 const innerMap = new Map<Element, any>();
84 innerMap.set(elm, value);
85 map.set(type, innerMap);
86 }
87 };
88}