Created
November 12, 2023 03:03
-
-
Save cowboyd/fbf7bd576241236aa6052058a6f932b9 to your computer and use it in GitHub Desktop.
revolution html middleware that rebases a document at a different url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { posixNormalize } from "https://deno.land/[email protected]/path/_normalize.ts"; | |
import { selectAll } from "npm:[email protected]"; | |
import type { Element } from "hastx/jsx-runtime"; | |
/** | |
* Rebase an HTML document at a different URL. This replaces all `<a href>` and | |
* `<img src>` attributes that contain an absolute path. Any path that is | |
* relative or contains a fully qualitfied URL will be left alone. | |
* | |
* @param tree - the HTML tree to transform | |
* @param baseUrl - a string representing a fully qualified url, e.g. | |
* http://frontside.com/effection | |
*/ | |
export function rebase(tree: JSX.Element, baseUrl?: string): void { | |
if (baseUrl) { | |
let base = new URL(baseUrl); | |
let hrefs: Element[] = selectAll('[href^="/"],[src^="/"]', tree); | |
for (let element of hrefs) { | |
let properties = element.properties!; | |
if (properties.href) { | |
properties.href = posixNormalize(`${base.pathname}${properties.href}`); | |
} | |
if (properties.src) { | |
properties.src = posixNormalize(`${base.pathname}${properties.src}`); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment