-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlToAnsi.ts
33 lines (30 loc) · 1.03 KB
/
htmlToAnsi.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
import { parse, HTMLElement, Node, TextNode } from "./tsdom/tsdom"
import { StyleParser } from "./tsdom/styleparser"
export function toAnsi(html: string): string {
let data = `<ink>${html}</ink>`
data = data.replace(/\<ink\>/gi, "<div>")
data = data.replace(/\<ink\/\>/gi, "</div>")
data = data.trim()
const root = parse(data)
if (root instanceof HTMLElement) {
let res = getInked(root.firstChild);
return res;
}
return html; //in case of error
}
function getInked(n: Node, parentAnsiStart: string = ""): string {
let rtnVal = ""
n.childNodes.forEach(el => {
if (el instanceof TextNode) {
rtnVal += el.text
}
if (el instanceof HTMLElement) {
let style = el.attributes.style
StyleParser.parse(style);
let ansiStart = StyleParser.toAnsiStart()
let ansiEnd = `${StyleParser.toAnsiEnd()}${parentAnsiStart}`
rtnVal += `${ansiStart}${getInked(el, ansiStart)}${ansiEnd}`
}
})
return rtnVal
}