base path refactor to better support subpath hosting

This commit is contained in:
Jacky Zhao
2023-08-19 15:52:25 -07:00
parent a3703cbe0b
commit 303a867d60
29 changed files with 257 additions and 389 deletions

View File

@ -1,9 +1,9 @@
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
import style from "./styles/backlinks.scss"
import { canonicalizeServer, resolveRelative } from "../util/path"
import { resolveRelative, simplifySlug } from "../util/path"
function Backlinks({ fileData, allFiles }: QuartzComponentProps) {
const slug = canonicalizeServer(fileData.slug!)
const slug = simplifySlug(fileData.slug!)
const backlinkFiles = allFiles.filter((file) => file.links?.includes(slug))
return (
<div class="backlinks">
@ -12,7 +12,7 @@ function Backlinks({ fileData, allFiles }: QuartzComponentProps) {
{backlinkFiles.length > 0 ? (
backlinkFiles.map((f) => (
<li>
<a href={resolveRelative(slug, canonicalizeServer(f.slug!))} class="internal">
<a href={resolveRelative(fileData.slug!, f.slug!)} class="internal">
{f.frontmatter?.title}
</a>
</li>

View File

@ -1,14 +1,13 @@
import { canonicalizeServer, pathToRoot } from "../util/path"
import { pathToRoot } from "../util/path"
import { JSResourceToScriptElement } from "../util/resources"
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
export default (() => {
function Head({ cfg, fileData, externalResources }: QuartzComponentProps) {
const slug = canonicalizeServer(fileData.slug!)
const title = fileData.frontmatter?.title ?? "Untitled"
const description = fileData.description?.trim() ?? "No description provided"
const { css, js } = externalResources
const baseDir = pathToRoot(slug)
const baseDir = pathToRoot(fileData.slug!)
const iconPath = baseDir + "/static/icon.png"
const ogImagePath = `https://${cfg.baseUrl}/static/og-image.png`

View File

@ -1,4 +1,4 @@
import { CanonicalSlug, canonicalizeServer, resolveRelative } from "../util/path"
import { FullSlug, resolveRelative } from "../util/path"
import { QuartzPluginData } from "../plugins/vfile"
import { Date } from "./Date"
import { QuartzComponentProps } from "./types"
@ -25,7 +25,6 @@ type Props = {
} & QuartzComponentProps
export function PageList({ fileData, allFiles, limit }: Props) {
const slug = canonicalizeServer(fileData.slug!)
let list = allFiles.sort(byDateAndAlphabetical)
if (limit) {
list = list.slice(0, limit)
@ -35,7 +34,6 @@ export function PageList({ fileData, allFiles, limit }: Props) {
<ul class="section-ul">
{list.map((page) => {
const title = page.frontmatter?.title
const pageSlug = canonicalizeServer(page.slug!)
const tags = page.frontmatter?.tags ?? []
return (
@ -48,7 +46,7 @@ export function PageList({ fileData, allFiles, limit }: Props) {
)}
<div class="desc">
<h3>
<a href={resolveRelative(slug, pageSlug)} class="internal">
<a href={resolveRelative(fileData.slug!, page.slug!)} class="internal">
{title}
</a>
</h3>
@ -58,7 +56,7 @@ export function PageList({ fileData, allFiles, limit }: Props) {
<li>
<a
class="internal tag-link"
href={resolveRelative(slug, `tags/${tag}` as CanonicalSlug)}
href={resolveRelative(fileData.slug!, `tags/${tag}/index` as FullSlug)}
>
#{tag}
</a>

View File

@ -1,10 +1,9 @@
import { canonicalizeServer, pathToRoot } from "../util/path"
import { pathToRoot } from "../util/path"
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
function PageTitle({ fileData, cfg }: QuartzComponentProps) {
const title = cfg?.pageTitle ?? "Untitled Quartz"
const slug = canonicalizeServer(fileData.slug!)
const baseDir = pathToRoot(slug)
const baseDir = pathToRoot(fileData.slug!)
return (
<h1 class="page-title">
<a href={baseDir}>{title}</a>

View File

@ -1,10 +1,9 @@
import { canonicalizeServer, pathToRoot, slugTag } from "../util/path"
import { pathToRoot, slugTag } from "../util/path"
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
function TagList({ fileData }: QuartzComponentProps) {
const tags = fileData.frontmatter?.tags
const slug = canonicalizeServer(fileData.slug!)
const baseDir = pathToRoot(slug)
const baseDir = pathToRoot(fileData.slug!)
if (tags && tags.length > 0) {
return (
<ul class="tags">

View File

@ -5,13 +5,13 @@ import path from "path"
import style from "../styles/listPage.scss"
import { PageList } from "../PageList"
import { canonicalizeServer } from "../../util/path"
import { simplifySlug } from "../../util/path"
function FolderContent(props: QuartzComponentProps) {
const { tree, fileData, allFiles } = props
const folderSlug = canonicalizeServer(fileData.slug!)
const folderSlug = simplifySlug(fileData.slug!)
const allPagesInFolder = allFiles.filter((file) => {
const fileSlug = canonicalizeServer(file.slug!)
const fileSlug = simplifySlug(file.slug!)
const prefixed = fileSlug.startsWith(folderSlug) && fileSlug !== folderSlug
const folderParts = folderSlug.split(path.posix.sep)
const fileParts = fileSlug.split(path.posix.sep)

View File

@ -3,7 +3,7 @@ import { Fragment, jsx, jsxs } from "preact/jsx-runtime"
import { toJsxRuntime } from "hast-util-to-jsx-runtime"
import style from "../styles/listPage.scss"
import { PageList } from "../PageList"
import { ServerSlug, canonicalizeServer, getAllSegmentPrefixes } from "../../util/path"
import { FullSlug, getAllSegmentPrefixes, simplifySlug } from "../../util/path"
import { QuartzPluginData } from "../../plugins/vfile"
const numPages = 10
@ -15,7 +15,7 @@ function TagContent(props: QuartzComponentProps) {
throw new Error(`Component "TagContent" tried to render a non-tag page: ${slug}`)
}
const tag = canonicalizeServer(slug.slice("tags/".length) as ServerSlug)
const tag = simplifySlug(slug.slice("tags/".length) as FullSlug)
const allPagesWithTag = (tag: string) =>
allFiles.filter((file) =>
(file.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes).includes(tag),

View File

@ -3,7 +3,7 @@ import { QuartzComponent, QuartzComponentProps } from "./types"
import HeaderConstructor from "./Header"
import BodyConstructor from "./Body"
import { JSResourceToScriptElement, StaticResources } from "../util/resources"
import { CanonicalSlug, pathToRoot } from "../util/path"
import { FullSlug, joinSegments, pathToRoot } from "../util/path"
interface RenderComponents {
head: QuartzComponent
@ -15,19 +15,20 @@ interface RenderComponents {
footer: QuartzComponent
}
export function pageResources(
slug: CanonicalSlug,
staticResources: StaticResources,
): StaticResources {
export function pageResources(slug: FullSlug, staticResources: StaticResources): StaticResources {
const baseDir = pathToRoot(slug)
const contentIndexPath = baseDir + "/static/contentIndex.json"
const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json")
const contentIndexScript = `const fetchData = fetch(\`${contentIndexPath}\`).then(data => data.json())`
return {
css: [baseDir + "/index.css", ...staticResources.css],
css: [joinSegments(baseDir, "index.css"), ...staticResources.css],
js: [
{ src: baseDir + "/prescript.js", loadTime: "beforeDOMReady", contentType: "external" },
{
src: joinSegments(baseDir, "/prescript.js"),
loadTime: "beforeDOMReady",
contentType: "external",
},
{
loadTime: "beforeDOMReady",
contentType: "inline",
@ -46,7 +47,7 @@ export function pageResources(
}
export function renderPage(
slug: CanonicalSlug,
slug: FullSlug,
componentData: QuartzComponentProps,
components: RenderComponents,
pageResources: StaticResources,

View File

@ -1,31 +1,32 @@
import type { ContentDetails } from "../../plugins/emitters/contentIndex"
import * as d3 from "d3"
import { registerEscapeHandler, removeAllChildren } from "./util"
import { CanonicalSlug, getCanonicalSlug, getClientSlug, resolveRelative } from "../../util/path"
import { FullSlug, SimpleSlug, getFullSlug, resolveRelative, simplifySlug } from "../../util/path"
type NodeData = {
id: CanonicalSlug
id: SimpleSlug
text: string
tags: string[]
} & d3.SimulationNodeDatum
type LinkData = {
source: CanonicalSlug
target: CanonicalSlug
source: SimpleSlug
target: SimpleSlug
}
const localStorageKey = "graph-visited"
function getVisited(): Set<CanonicalSlug> {
function getVisited(): Set<SimpleSlug> {
return new Set(JSON.parse(localStorage.getItem(localStorageKey) ?? "[]"))
}
function addToVisited(slug: CanonicalSlug) {
function addToVisited(slug: SimpleSlug) {
const visited = getVisited()
visited.add(slug)
localStorage.setItem(localStorageKey, JSON.stringify([...visited]))
}
async function renderGraph(container: string, slug: CanonicalSlug) {
async function renderGraph(container: string, fullSlug: FullSlug) {
const slug = simplifySlug(fullSlug)
const visited = getVisited()
const graph = document.getElementById(container)
if (!graph) return
@ -47,16 +48,17 @@ async function renderGraph(container: string, slug: CanonicalSlug) {
const links: LinkData[] = []
for (const [src, details] of Object.entries<ContentDetails>(data)) {
const source = simplifySlug(src as FullSlug)
const outgoing = details.links ?? []
for (const dest of outgoing) {
if (src in data && dest in data) {
links.push({ source: src as CanonicalSlug, target: dest })
if (dest in data) {
links.push({ source, target: dest })
}
}
}
const neighbourhood = new Set<CanonicalSlug>()
const wl: (CanonicalSlug | "__SENTINEL")[] = [slug, "__SENTINEL"]
const neighbourhood = new Set<SimpleSlug>()
const wl: (SimpleSlug | "__SENTINEL")[] = [slug, "__SENTINEL"]
if (depth >= 0) {
while (depth >= 0 && wl.length > 0) {
// compute neighbours
@ -72,7 +74,7 @@ async function renderGraph(container: string, slug: CanonicalSlug) {
}
}
} else {
Object.keys(data).forEach((id) => neighbourhood.add(id as CanonicalSlug))
Object.keys(data).forEach((id) => neighbourhood.add(simplifySlug(id as FullSlug)))
}
const graphData: { nodes: NodeData[]; links: LinkData[] } = {
@ -171,11 +173,11 @@ async function renderGraph(container: string, slug: CanonicalSlug) {
.attr("fill", color)
.style("cursor", "pointer")
.on("click", (_, d) => {
const targ = resolveRelative(slug, d.id)
window.spaNavigate(new URL(targ, getClientSlug(window)))
const targ = resolveRelative(fullSlug, d.id)
window.spaNavigate(new URL(targ, window.location.toString()))
})
.on("mouseover", function (_, d) {
const neighbours: CanonicalSlug[] = data[slug].links ?? []
const neighbours: SimpleSlug[] = data[slug].links ?? []
const neighbourNodes = d3
.selectAll<HTMLElement, NodeData>(".node")
.filter((d) => neighbours.includes(d.id))
@ -271,7 +273,7 @@ async function renderGraph(container: string, slug: CanonicalSlug) {
}
function renderGlobalGraph() {
const slug = getCanonicalSlug(window)
const slug = getFullSlug(window)
const container = document.getElementById("global-graph-outer")
const sidebar = container?.closest(".sidebar") as HTMLElement
container?.classList.add("active")

View File

@ -1,11 +1,11 @@
import { Document } from "flexsearch"
import { ContentDetails } from "../../plugins/emitters/contentIndex"
import { registerEscapeHandler, removeAllChildren } from "./util"
import { CanonicalSlug, getClientSlug, resolveRelative } from "../../util/path"
import { FullSlug, getFullSlug, resolveRelative, simplifySlug } from "../../util/path"
interface Item {
id: number
slug: CanonicalSlug
slug: FullSlug
title: string
content: string
}
@ -73,7 +73,7 @@ document.addEventListener("nav", async (e: unknown) => {
const searchIcon = document.getElementById("search-icon")
const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
const results = document.getElementById("results-container")
const idDataMap = Object.keys(data) as CanonicalSlug[]
const idDataMap = Object.keys(data) as FullSlug[]
function hideSearch() {
container?.classList.remove("active")
@ -126,7 +126,7 @@ document.addEventListener("nav", async (e: unknown) => {
button.innerHTML = `<h3>${title}</h3><p>${content}</p>`
button.addEventListener("click", () => {
const targ = resolveRelative(currentSlug, slug)
window.spaNavigate(new URL(targ, getClientSlug(window)))
window.spaNavigate(new URL(targ, window.location.toString()))
})
return button
}
@ -192,7 +192,7 @@ document.addEventListener("nav", async (e: unknown) => {
for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
await index.addAsync(id, {
id,
slug: slug as CanonicalSlug,
slug: slug as FullSlug,
title: fileData.title,
content: fileData.content,
})

View File

@ -1,5 +1,5 @@
import micromorph from "micromorph"
import { CanonicalSlug, RelativeURL, getCanonicalSlug } from "../../util/path"
import { FullSlug, RelativeURL, getFullSlug } from "../../util/path"
// adapted from `micromorph`
// https://github.com/natemoo-re/micromorph
@ -31,7 +31,7 @@ const getOpts = ({ target }: Event): { url: URL; scroll?: boolean } | undefined
return { url: new URL(href), scroll: "routerNoscroll" in a.dataset ? false : undefined }
}
function notifyNav(url: CanonicalSlug) {
function notifyNav(url: FullSlug) {
const event: CustomEventMap["nav"] = new CustomEvent("nav", { detail: { url } })
document.dispatchEvent(event)
}
@ -81,7 +81,7 @@ async function navigate(url: URL, isBack: boolean = false) {
const elementsToAdd = html.head.querySelectorAll(":not([spa-preserve])")
elementsToAdd.forEach((el) => document.head.appendChild(el))
notifyNav(getCanonicalSlug(window))
notifyNav(getFullSlug(window))
delete announcer.dataset.persist
}
@ -129,7 +129,7 @@ function createRouter() {
}
createRouter()
notifyNav(getCanonicalSlug(window))
notifyNav(getFullSlug(window))
if (!customElements.get("route-announcer")) {
const attrs = {