Repository navigation
Expand file tree
/
Copy pathparseSection.ts
More file actions
78 lines (69 loc) · 2.16 KB
/
Copy pathparseSection.ts
File metadata and controls
78 lines (69 loc) · 2.16 KB
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
70
71
72
73
74
75
76
77
78
import path from 'node:path'
import parseLink from './parseLink'
import parseHTML from './parseHTML'
import convert from './converter'
import type { HtmlNodeObject, convertFuncType } from './types'
const isInternalUri = (uri: string) => {
return uri.indexOf('http://') === -1 && uri.indexOf('https://') === -1
}
export type ParseSectionConfig = {
id: string
htmlString: string
expand?: boolean
resourceResolver?: (path: string) => any
idResolver?: (link: string) => string
}
export class Section {
id: string
htmlString: string
htmlObjects?: HtmlNodeObject[]
private _resourceResolver?: (path: string) => any
private _idResolver?: (link: string) => string
private _convertToMarkdown: convertFuncType = convert
constructor({ id, htmlString, resourceResolver, idResolver, expand }: ParseSectionConfig) {
this.id = id
this.htmlString = htmlString
this._resourceResolver = resourceResolver
this._idResolver = idResolver
if (expand) {
this.htmlObjects = this.toHtmlObjects?.()
}
}
register(convertFunc: convertFuncType): Section {
this._convertToMarkdown = convertFunc;
return this
}
toMarkdown(): string {
return this._convertToMarkdown.call(null, this.htmlString);
}
toHtmlObjects(): HtmlNodeObject[] {
return parseHTML(this.htmlString, {
resolveHref: (href) => {
if (isInternalUri(href)) {
const { hash } = parseLink(href)
// todo: what if a link only contains hash part?
const sectionId = this._idResolver?.(href)
if (hash) {
return `#${sectionId},${hash}`
}
return `#${sectionId}`
}
return href
},
resolveSrc: (src) => {
if (isInternalUri(src)) {
// todo: may have bugs
const absolutePath = path.posix.resolve('/', src).substr(1)
const buffer = this._resourceResolver?.(absolutePath)?.asNodeBuffer()
const base64 = buffer.toString('base64')
return `data:image/png;base64,${base64}`
}
return src
},
})
}
}
const parseSection = (config: ParseSectionConfig) => {
return new Section(config)
}
export default parseSection