From c538c151c7462ad0395ff2c15c5e11e89e362aa8 Mon Sep 17 00:00:00 2001
From: Striven <sg.striven@cutecat.club>
Date: Sat, 04 Apr 2026 19:47:16 +0000
Subject: [PATCH] Initial commit

---
 quartz/util/path.ts |  109 +++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 74 insertions(+), 35 deletions(-)

diff --git a/quartz/util/path.ts b/quartz/util/path.ts
index 92cfabe..b957701 100644
--- a/quartz/util/path.ts
+++ b/quartz/util/path.ts
@@ -1,5 +1,7 @@
 import { slug as slugAnchor } from "github-slugger"
 import type { Element as HastElement } from "hast"
+import { clone } from "./clone"
+
 // this file must be isomorphic so it can't use node libs (e.g. path)
 
 export const QUARTZ = "quartz"
@@ -19,23 +21,32 @@
 export function isFullSlug(s: string): s is FullSlug {
   const validStart = !(s.startsWith(".") || s.startsWith("/"))
   const validEnding = !s.endsWith("/")
-  return validStart && validEnding && !_containsForbiddenCharacters(s)
+  return validStart && validEnding && !containsForbiddenCharacters(s)
 }
 
 /** Shouldn't be a relative path and shouldn't have `/index` as an ending or a file extension. It _can_ however have a trailing slash to indicate a folder path. */
 export type SimpleSlug = SlugLike<"simple">
 export function isSimpleSlug(s: string): s is SimpleSlug {
   const validStart = !(s.startsWith(".") || (s.length > 1 && s.startsWith("/")))
-  const validEnding = !(s.endsWith("/index") || s === "index")
-  return validStart && !_containsForbiddenCharacters(s) && validEnding && !_hasFileExtension(s)
+  const validEnding = !endsWith(s, "index")
+  return validStart && !containsForbiddenCharacters(s) && validEnding && !_hasFileExtension(s)
 }
 
 /** Can be found on `href`s but can also be constructed for client-side navigation (e.g. search and graph) */
 export type RelativeURL = SlugLike<"relative">
 export function isRelativeURL(s: string): s is RelativeURL {
   const validStart = /^\.{1,2}/.test(s)
-  const validEnding = !(s.endsWith("/index") || s === "index")
-  return validStart && validEnding && ![".md", ".html"].includes(_getFileExtension(s) ?? "")
+  const validEnding = !endsWith(s, "index")
+  return validStart && validEnding && ![".md", ".html"].includes(getFileExtension(s) ?? "")
+}
+
+export function isAbsoluteURL(s: string): boolean {
+  try {
+    new URL(s)
+  } catch {
+    return false
+  }
+  return true
 }
 
 export function getFullSlug(window: Window): FullSlug {
@@ -46,14 +57,21 @@
 function sluggify(s: string): string {
   return s
     .split("/")
-    .map((segment) => segment.replace(/\s/g, "-").replace(/%/g, "-percent").replace(/\?/g, "-q")) // slugify all segments
+    .map((segment) =>
+      segment
+        .replace(/\s/g, "-")
+        .replace(/&/g, "-and-")
+        .replace(/%/g, "-percent")
+        .replace(/\?/g, "")
+        .replace(/#/g, ""),
+    )
     .join("/") // always use / as sep
     .replace(/\/$/, "")
 }
 
 export function slugifyFilePath(fp: FilePath, excludeExt?: boolean): FullSlug {
-  fp = _stripSlashes(fp) as FilePath
-  let ext = _getFileExtension(fp)
+  fp = stripSlashes(fp) as FilePath
+  let ext = getFileExtension(fp)
   const withoutFileExt = fp.replace(new RegExp(ext + "$"), "")
   if (excludeExt || [".md", ".html", undefined].includes(ext)) {
     ext = ""
@@ -62,7 +80,7 @@
   let slug = sluggify(withoutFileExt)
 
   // treat _index as index
-  if (_endsWith(slug, "_index")) {
+  if (endsWith(slug, "_index")) {
     slug = slug.replace(/_index$/, "index")
   }
 
@@ -70,21 +88,21 @@
 }
 
 export function simplifySlug(fp: FullSlug): SimpleSlug {
-  const res = _stripSlashes(_trimSuffix(fp, "index"), true)
+  const res = stripSlashes(trimSuffix(fp, "index"), true)
   return (res.length === 0 ? "/" : res) as SimpleSlug
 }
 
 export function transformInternalLink(link: string): RelativeURL {
   let [fplike, anchor] = splitAnchor(decodeURI(link))
 
-  const folderPath = _isFolderPath(fplike)
+  const folderPath = isFolderPath(fplike)
   let segments = fplike.split("/").filter((x) => x.length > 0)
-  let prefix = segments.filter(_isRelativeSegment).join("/")
-  let fp = segments.filter((seg) => !_isRelativeSegment(seg) && seg !== "").join("/")
+  let prefix = segments.filter(isRelativeSegment).join("/")
+  let fp = segments.filter((seg) => !isRelativeSegment(seg) && seg !== "").join("/")
 
   // manually add ext here as we want to not strip 'index' if it has an extension
   const simpleSlug = simplifySlug(slugifyFilePath(fp as FilePath))
-  const joined = joinSegments(_stripSlashes(prefix), _stripSlashes(simpleSlug))
+  const joined = joinSegments(stripSlashes(prefix), stripSlashes(simpleSlug))
   const trail = folderPath ? "/" : ""
   const res = (_addRelativeToStart(joined) + trail + anchor) as RelativeURL
   return res
@@ -97,10 +115,10 @@
   el.setAttribute(attr, rebased.pathname + rebased.hash)
 }
 export function normalizeRelativeURLs(el: Element | Document, destination: string | URL) {
-  el.querySelectorAll('[href^="./"], [href^="../"]').forEach((item) =>
+  el.querySelectorAll('[href=""], [href^="./"], [href^="../"]').forEach((item) =>
     _rebaseHtmlElement(item, "href", destination),
   )
-  el.querySelectorAll('[src^="./"], [src^="../"]').forEach((item) =>
+  el.querySelectorAll('[src=""], [src^="./"], [src^="../"]').forEach((item) =>
     _rebaseHtmlElement(item, "src", destination),
   )
 }
@@ -121,7 +139,8 @@
   }
 }
 
-export function normalizeHastElement(el: HastElement, curBase: FullSlug, newBase: FullSlug) {
+export function normalizeHastElement(rawEl: HastElement, curBase: FullSlug, newBase: FullSlug) {
+  const el = clone(rawEl) // clone so we dont modify the original page
   _rebaseHastElement(el, "src", curBase, newBase)
   _rebaseHastElement(el, "href", curBase, newBase)
   if (el.children) {
@@ -156,6 +175,9 @@
 
 export function splitAnchor(link: string): [string, string] {
   let [fp, anchor] = link.split("#", 2)
+  if (fp.endsWith(".pdf")) {
+    return [fp, anchor === undefined ? "" : `#${anchor}`]
+  }
   anchor = anchor === undefined ? "" : "#" + slugAnchor(anchor)
   return [fp, anchor]
 }
@@ -168,10 +190,26 @@
 }
 
 export function joinSegments(...args: string[]): string {
-  return args
-    .filter((segment) => segment !== "")
+  if (args.length === 0) {
+    return ""
+  }
+
+  let joined = args
+    .filter((segment) => segment !== "" && segment !== "/")
+    .map((segment) => stripSlashes(segment))
     .join("/")
-    .replace(/\/\/+/g, "/")
+
+  // if the first segment starts with a slash, add it back
+  if (args[0].startsWith("/")) {
+    joined = "/" + joined
+  }
+
+  // if the last segment is a folder, add a trailing slash
+  if (args[args.length - 1].endsWith("/")) {
+    joined = joined + "/"
+  }
+
+  return joined
 }
 
 export function getAllSegmentPrefixes(tags: string): string[] {
@@ -194,8 +232,8 @@
   if (opts.strategy === "relative") {
     return targetSlug as RelativeURL
   } else {
-    const folderTail = _isFolderPath(targetSlug) ? "/" : ""
-    const canonicalSlug = _stripSlashes(targetSlug.slice(".".length))
+    const folderTail = isFolderPath(targetSlug) ? "/" : ""
+    const canonicalSlug = stripSlashes(targetSlug.slice(".".length))
     let [targetCanonical, targetAnchor] = splitAnchor(canonicalSlug)
 
     if (opts.strategy === "shortest") {
@@ -218,43 +256,44 @@
   }
 }
 
-function _isFolderPath(fplike: string): boolean {
+// path helpers
+export function isFolderPath(fplike: string): boolean {
   return (
     fplike.endsWith("/") ||
-    _endsWith(fplike, "index") ||
-    _endsWith(fplike, "index.md") ||
-    _endsWith(fplike, "index.html")
+    endsWith(fplike, "index") ||
+    endsWith(fplike, "index.md") ||
+    endsWith(fplike, "index.html")
   )
 }
 
-function _endsWith(s: string, suffix: string): boolean {
+export function endsWith(s: string, suffix: string): boolean {
   return s === suffix || s.endsWith("/" + suffix)
 }
 
-function _trimSuffix(s: string, suffix: string): string {
-  if (_endsWith(s, suffix)) {
+export function trimSuffix(s: string, suffix: string): string {
+  if (endsWith(s, suffix)) {
     s = s.slice(0, -suffix.length)
   }
   return s
 }
 
-function _containsForbiddenCharacters(s: string): boolean {
-  return s.includes(" ") || s.includes("#") || s.includes("?")
+function containsForbiddenCharacters(s: string): boolean {
+  return s.includes(" ") || s.includes("#") || s.includes("?") || s.includes("&")
 }
 
 function _hasFileExtension(s: string): boolean {
-  return _getFileExtension(s) !== undefined
+  return getFileExtension(s) !== undefined
 }
 
-function _getFileExtension(s: string): string | undefined {
+export function getFileExtension(s: string): string | undefined {
   return s.match(/\.[A-Za-z0-9]+$/)?.[0]
 }
 
-function _isRelativeSegment(s: string): boolean {
+function isRelativeSegment(s: string): boolean {
   return /^\.{0,2}$/.test(s)
 }
 
-export function _stripSlashes(s: string, onlyStripPrefix?: boolean): string {
+export function stripSlashes(s: string, onlyStripPrefix?: boolean): string {
   if (s.startsWith("/")) {
     s = s.substring(1)
   }

--
Gitblit v1.10.0