Skip to content

Commit

Permalink
fix(aliases): Teach SPA and popovers to handle HTML redirects
Browse files Browse the repository at this point in the history
This makes aliases work great, because even with the resolution fix
from my previous commit they had no popovers and clicking on alias
links caused a full reload.
  • Loading branch information
necauqua committed Dec 25, 2024
1 parent e7b1cdc commit ecd78b1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
3 changes: 2 additions & 1 deletion quartz/components/scripts/popover.inline.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
import { normalizeRelativeURLs } from "../../util/path"
import { fetchCanonical } from "./util"

const p = new DOMParser()
async function mouseEnterHandler(
Expand Down Expand Up @@ -37,7 +38,7 @@ async function mouseEnterHandler(
targetUrl.hash = ""
targetUrl.search = ""

const response = await fetch(`${targetUrl}`).catch((err) => {
const response = await fetchCanonical(targetUrl).catch((err) => {
console.error(err)
})

Expand Down
3 changes: 2 additions & 1 deletion quartz/components/scripts/spa.inline.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import micromorph from "micromorph"
import { FullSlug, RelativeURL, getFullSlug, normalizeRelativeURLs } from "../../util/path"
import { fetchCanonical } from "./util"

// adapted from `micromorph`
// https://github.com/natemoo-re/micromorph
Expand Down Expand Up @@ -45,7 +46,7 @@ window.addCleanup = (fn) => cleanupFns.add(fn)
let p: DOMParser
async function navigate(url: URL, isBack: boolean = false) {
p = p || new DOMParser()
const contents = await fetch(`${url}`)
const contents = await fetchCanonical(url)
.then((res) => {
const contentType = res.headers.get("content-type")
if (contentType?.startsWith("text/html")) {
Expand Down
13 changes: 13 additions & 0 deletions quartz/components/scripts/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,16 @@ export function removeAllChildren(node: HTMLElement) {
node.removeChild(node.firstChild)
}
}

const canonicalRegex = /<link rel="canonical" href="([^"]*)"/

export async function fetchCanonical(url: URL): Promise<Response> {
return fetch(`${url}`).then(async (res) => {
if (!res.headers.get("content-type")?.startsWith("text/html")) {
return res
}
const text = await res.clone().text()
const [_, redirect] = text.match(canonicalRegex) ?? []
return redirect ? fetch(redirect) : res
})
}

0 comments on commit ecd78b1

Please sign in to comment.