generated from neoncitylights/node
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walkDescriptionList.ts
58 lines (54 loc) · 1.52 KB
/
walkDescriptionList.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
const ELEMENT_NAME_DIV = 'DIV';
const ELEMENT_NAME_DT = 'DT';
const ELEMENT_NAME_DD = 'DD';
export type DListFn<T> = (element: HTMLElement) => T;
/**
* Extracts data from a description list into a map of key-value pairs,
* where keys store data of a `<dt>`, and values store data of a `<dd>`.
*
* This implementation attempts to follow the HTML Standard by the WHATWG
* as closely as possible.
* @see https://html.spec.whatwg.org/multipage/grouping-content.html#the-dl-element
*/
export function walkDescriptionList<K,V>(
dList: HTMLDListElement|HTMLDivElement,
termFn: DListFn<K>,
detailsFn: DListFn<V>,
): Map<K, V> {
const children: HTMLCollection = dList.children;
if (children.length === 0) {
return new Map<K, V>();
}
let descriptionList = new Map<K, V>();
let terms: K[] = [];
for (const child of children) {
const elementTagName = child.tagName;
switch (elementTagName) {
case ELEMENT_NAME_DT:
terms.push(termFn(child as HTMLElement));
break;
case ELEMENT_NAME_DD:
if (child.previousElementSibling?.tagName === ELEMENT_NAME_DT) {
terms.forEach(term => descriptionList.set(
term,
detailsFn(child as HTMLElement),
));
terms = [];
}
break;
case ELEMENT_NAME_DIV:
descriptionList = new Map([
...descriptionList.entries(),
...walkDescriptionList(
child as HTMLDivElement,
termFn,
detailsFn,
),
]);
break;
default:
throw new TypeError(`Expected a <dt>, <dd>, or <div> element; found <${elementTagName}> instead`);
}
}
return descriptionList;
}