external.astro 1.49 KB
---
import { parseHtml, createMatcher, findNode } from './html.ts'
import { getUrl, getSitePage } from './remote-content.ts'
import Match from './match.astro'

export const getHtmlFromProps = (props) => {
  const { site, page, url, html } = props
  if (html) return { data: html }
  if (url) return getUrl(url)
  if (site && page) return getSitePage(site, page)
  return { data: null }
}

export const getDocFromProps = async (props, options) => {
  if (props.node) return props.node;
  const { data: html } = await getHtmlFromProps(props)
  const adjuster = createAdjuster(props.adjustments)
  return parseHtml(html, { ...options, adjuster })
}

export const getNodeFromProps = async (props, options) => {
  const doc = await getDocFromProps(props, options)
  const { xpath } = props
  return xpath ? findNode(doc, xpath) : doc
}

export const createAdjuster = (adjustments = {}) => {
  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
  }
  return adjuster
}

const { props } = Astro
const { debug, replacers, slotHandler } = props
const node = await getNodeFromProps(props)

const nextDebug = debug ? debug - 1 : 0
---
<Match node={node} debug={nextDebug} replacers={replacers} slotHandler={slotHandler} adjuster={adjuster}/>