- Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathdom.ts
69 lines (66 loc) · 2.35 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
import{notEmpty}from'@theia/core/lib/common/objects';
/**
* Finds the closest child HTMLButtonElement representing a Theia button.
* A button is a Theia button if it's a `<button>` element and has the `"theia-button"` class.
* If an element has multiple Theia button children, this function prefers `"main"` over `"secondary"` button.
*/
exportfunctionfindChildTheiaButton(
element: HTMLElement,
recursive=false
): HTMLButtonElement|undefined{
letbutton: HTMLButtonElement|undefined=undefined;
constchildren=Array.from(element.children);
for(constchildofchildren){
if(
childinstanceofHTMLButtonElement&&
child.classList.contains('theia-button')
){
if(child.classList.contains('main')){
returnchild;
}
button=child;
}
}
if(!button&&recursive){
button=children
.filter(isHTMLElement)
.map((childElement)=>findChildTheiaButton(childElement,true))
.filter(notEmpty)
.shift();
}
returnbutton;
}
functionisHTMLElement(element: Element): element is HTMLElement{
returnelementinstanceofHTMLElement;
}
typeSegment=string|{textContent: string;bold: true};
/**
* Returns with an array of `Segments` by splitting raw HTML text on the `<b></b>` groups. If splitting is not possible, returns `undefined`.
* Example: `one<b>two</b>three<b>four</b>five` will provide an five element length array. Where the 1<sup>st</sup> and 3<sup>rd</sup> elements are objects and the rest are string.
*/
exportfunctionsplitByBoldTag(text: string): Segment[]|undefined{
constmatches=text.matchAll(newRegExp(/<\s*b[^>]*>(.*?)<\s*\/\s*b>/gm));
if(!matches){
returnundefined;
}
constsegments: Segment[]=[];
consttextLength=text.length;
letprocessedLength=0;
for(constmatchofmatches){
const{ index }=match;
if(typeofindex==='number'){
if(!segments.length&&index){
segments.push(text.substring(0,index));
}
if(processedLength>0){
segments.push(text.substring(processedLength,index));
}
segments.push({textContent: match[1],bold: true});
processedLength=index+match[0].length;
}
}
if(segments.length&&textLength>processedLength){
segments.push(text.substring(processedLength));
}
returnsegments.length ? segments : undefined;
}