-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anchor.ts
24 lines (22 loc) · 1006 Bytes
/
anchor.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
import { ParserDef } from '../types'
import { until, attrs, parseAttrList, createParseData } from '../utils'
const ANCHOR_END = Symbol('isLinkEnd')
export const anchor: ParserDef = {
name: 'anchor',
regex:
/(?<start>\[)|(?<end>\])(?:\((?<href>[^")]+?)(?: "(?<title>[^"]+)")?\))?(?:\{:(?<ial>.+?)\})?/,
handler: ({ start, href, title, ial }, { index, src, lastIndex, parseNext, parseIter }) => {
if (!start) return ['', index, lastIndex, { href, title, ial, [ANCHOR_END]: true }]
const contentRaw = [...until(parseIter(src.slice(index + 1)), (x) => x[3]?.[ANCHOR_END])]
const content = contentRaw.map(([x]) => x).join('')
const endIndex = contentRaw.at(-1)?.[2] ?? 0
const end = parseNext(src, index + endIndex + 1)
const { ial: al, ...attr } = (end[3] as Record<string, string>) ?? {}
return createParseData(
`<a${attrs(attr ?? {})}${parseAttrList(al)}>${content}</a>`,
index,
end[2],
{ content, ...end[3], [ANCHOR_END]: false }
)
},
}