replace.astro
1.3 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
---
import html from '@resources/provider-portal.html?raw'
import { walkSync } from 'ultrahtml'
import { parseHtml, createMatcher, findNode } from './html.ts'
import Match from './match.astro'
import type { SlotHandler, Replacements } from './astro.ts'
interface Props {
html?: string,
debug?: number,
xpath?: string,
replacements?: Replacements,
adjustments?: any,
}
const { props } = Astro
const { html, debug = 0, xpath, replacements = {}, adjustments = {} } = props
const doc = props.node ? props.node : parseHtml(props.html)
const node = xpath ? findNode(doc, xpath) : doc
const replacers = Object.entries(replacements).map(([ selector, handler ]) => [ createMatcher(selector), handler ])
const adjustmentsCompiled = Object.entries(adjustments).map(([ selector, handler ]) => [ createMatcher(selector), handler ])
const adjuster = (node, parent, index) => {
for (const [ matcher, handler ] of adjustmentsCompiled) {
if (matcher(node, parent, index, false)) {
node = handler(node)
}
}
return node
}
const slotHandler: SlotHandler = (slotName, node) => {
return Astro.slots.render(slotName, [ node, { slotHandler, replacers, adjuster } ] )
}
const nextDebug = debug ? debug - 1 : 0
---
<Match node={node} debug={nextDebug} replacers={replacers} slotHandler={slotHandler} adjuster={adjuster}/>