-
Notifications
You must be signed in to change notification settings - Fork 2
/
toc.js
49 lines (35 loc) · 977 Bytes
/
toc.js
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
import { JSDOM } from 'jsdom'
function recurseTree (nav, prefix = '', parent = null, tree = {}) {
for (const child of nav.children) {
if (child.nodeName !== 'navPoint') {
continue
}
const title = child.querySelector('navLabel text').textContent
const path = child.querySelector('content').getAttribute('src')
tree[`${prefix}${path}`] = {
title,
parent
}
recurseTree(child, prefix, tree[`${prefix}${path}`], tree)
}
return tree
}
export default async function getToc (zip) {
let prefix = ''
let entry = zip.getEntry('toc.ncx')
if (!entry) {
entry = zip.getEntry('OEBPS/toc.ncx')
prefix = 'OEBPS/'
}
if (!entry) {
console.error('Could not find ToC')
return {}
}
const xml = await entry.getData()
const jsdom = new JSDOM(xml, {
contentType: 'application/xml'
})
const nav = jsdom.window.document.querySelector('navMap')
const toc = recurseTree(nav, prefix)
return toc
}