(html: string, opts?: Partial<IHtmlParserOptions>)
| 103 | } |
| 104 | |
| 105 | export function parseHtml(html: string, opts?: Partial<IHtmlParserOptions>) { |
| 106 | const options = { |
| 107 | ...defaultOptions, |
| 108 | ...opts, |
| 109 | }; |
| 110 | const $ = load(html); |
| 111 | let $root: Cheerio<any> = $('body'); |
| 112 | if (!$root.length) $root = $.root(); |
| 113 | let id = 0; |
| 114 | const rootNode: IHtmlNode = { |
| 115 | id, |
| 116 | tag: '', |
| 117 | html: '', |
| 118 | level: Levels.None, |
| 119 | parent: 0, |
| 120 | childrenLevel: Levels.None, |
| 121 | children: [], |
| 122 | }; |
| 123 | const headingStack: IHtmlNode[] = []; |
| 124 | let skippingHeading = Levels.None; |
| 125 | checkNodes($root.children()); |
| 126 | return rootNode; |
| 127 | |
| 128 | function addChild(props: { |
| 129 | parent: IHtmlNode; |
| 130 | nesting: boolean; |
| 131 | tagName: string; |
| 132 | level: Levels; |
| 133 | html: string; |
| 134 | comments?: string[]; |
| 135 | data?: Record<string, unknown>; |
| 136 | }) { |
| 137 | const { parent } = props; |
| 138 | const node: IHtmlNode = { |
| 139 | id: ++id, |
| 140 | tag: props.tagName, |
| 141 | level: props.level, |
| 142 | html: props.html, |
| 143 | childrenLevel: Levels.None, |
| 144 | children: props.nesting ? [] : undefined, |
| 145 | parent: parent.id, |
| 146 | }; |
| 147 | if (props.comments?.length) { |
| 148 | node.comments = props.comments; |
| 149 | } |
| 150 | if (Object.keys(props.data || {}).length) { |
| 151 | node.data = props.data; |
| 152 | } |
| 153 | if (parent.children) { |
| 154 | if ( |
| 155 | parent.childrenLevel === Levels.None || |
| 156 | parent.childrenLevel > node.level |
| 157 | ) { |
| 158 | parent.children = []; |
| 159 | parent.childrenLevel = node.level; |
| 160 | } |
| 161 | if (parent.childrenLevel === node.level) { |
| 162 | parent.children.push(node); |
no test coverage detected