replace.astro 1.3 KB
---
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}/>