Jacky Zhao
2025-03-13 d9159e0ac9bfc22e584c78bc8aa04ecd82c14eea
quartz/util/path.ts
@@ -1,198 +1,205 @@
import { slug } from "github-slugger"
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)
// Quartz Paths
// Things in boxes are not actual types but rather sources which these types can be acquired from
//
//                                                         ┌────────────┐
//                                             ┌───────────┤  Browser   ├────────────┐
//                                             │           └────────────┘            │
//                                             │                                     │
//                                             ▼                                     ▼
//                                        ┌────────┐                          ┌─────────────┐
//                    ┌───────────────────┤ Window │                          │ LinkElement │
//                    │                   └────┬───┘                          └──────┬──────┘
//                    │                        │                                     │
//                    │        getClientSlug() │                               .href │
//                    │                        ▼                                     ▼
//                    │
//                    │                  Client Slug                    ┌───►  Relative URL
// getCanonicalSlug() │     https://test.ca/note/abc#anchor?query=123   │      ../note/def#anchor
//                    │                                                 │
//                    │   canonicalizeClient() │                        │      ▲     ▲
//                    │                        ▼                        │      │     │
//                    │                                  pathToRoot()   │      │     │
//                    └───────────────►  Canonical Slug ────────────────┘      │     │
//                                          note/abc                           │     │
//                                                   ──────────────────────────┘     │
//                                             ▲             resolveRelative()       │
//                        canonicalizeServer() │                                     │
//                                                                                   │
// HTML File                               Server Slug                               │
//  note/abc/index.html  ◄─────────────   note/abc/index                             │
//                                                                                   │
//                                             ▲                            ┌────────┴────────┐
//                           slugifyFilePath() │            transformLink() │                 │
//                                             │                            │                 │
//                                   ┌─────────┴──────────┐           ┌─────┴─────┐  ┌────────┴──────┐
//                                   │     File Path      │           │ Wikilinks │  │ Markdown Link │
//                                   │  note/abc/index.md │           └───────────┘  └───────────────┘
//                                   └────────────────────┘                 ▲                 ▲
//                                             ▲                            │                 │
//                                             │            ┌─────────┐     │                 │
//                                             └────────────┤ MD File ├─────┴─────────────────┘
//                                                          └─────────┘
export const QUARTZ = "quartz"
/// Utility type to simulate nominal types in TypeScript
type SlugLike<T> = string & { __brand: T }
/** Client-side slug, usually obtained through `window.location` */
export type ClientSlug = SlugLike<"client">
export function isClientSlug(s: string): s is ClientSlug {
  const res = /^https?:\/\/.+/.test(s)
  return res
}
/** Canonical slug, should be used whenever you need to refer to the location of a file/note.
 * On the client, this is normally stored in `document.body.dataset.slug`
 */
export type CanonicalSlug = SlugLike<"canonical">
export function isCanonicalSlug(s: string): s is CanonicalSlug {
  const validStart = !(s.startsWith(".") || s.startsWith("/"))
  const validEnding = !(s.endsWith("/") || s.endsWith("/index") || s === "index")
  return validStart && !_containsForbiddenCharacters(s) && validEnding && !_hasFileExtension(s)
}
/** A relative link, 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) ?? "")
}
/** A server side slug. This is what Quartz uses to emit files so uses index suffixes */
export type ServerSlug = SlugLike<"server">
export function isServerSlug(s: string): s is ServerSlug {
  const validStart = !(s.startsWith(".") || s.startsWith("/"))
  const validEnding = !s.endsWith("/")
  return validStart && validEnding && !_containsForbiddenCharacters(s)
}
/** The real file path to a file on disk */
/** Cannot be relative and must have a file extension. */
export type FilePath = SlugLike<"filepath">
export function isFilePath(s: string): s is FilePath {
  const validStart = !s.startsWith(".")
  return validStart && _hasFileExtension(s)
}
export function getClientSlug(window: Window): ClientSlug {
  const res = window.location.href as ClientSlug
/** Cannot be relative and may not have leading or trailing slashes. It can have `index` as it's last segment. Use this wherever possible is it's the most 'general' interpretation of a slug. */
export type FullSlug = SlugLike<"full">
export function isFullSlug(s: string): s is FullSlug {
  const validStart = !(s.startsWith(".") || s.startsWith("/"))
  const validEnding = !s.endsWith("/")
  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 = !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 = !endsWith(s, "index")
  return validStart && validEnding && ![".md", ".html"].includes(getFileExtension(s) ?? "")
}
export function getFullSlug(window: Window): FullSlug {
  const res = window.document.body.dataset.slug! as FullSlug
  return res
}
export function getCanonicalSlug(window: Window): CanonicalSlug {
  const res = window.document.body.dataset.slug! as CanonicalSlug
  return res
function sluggify(s: string): string {
  return s
    .split("/")
    .map((segment) =>
      segment
        .replace(/\s/g, "-")
        .replace(/&/g, "-and-")
        .replace(/%/g, "-percent")
        .replace(/\?/g, "")
        .replace(/#/g, ""),
    )
    .join("/") // always use / as sep
    .replace(/\/$/, "")
}
export function canonicalizeClient(slug: ClientSlug): CanonicalSlug {
  const { pathname } = new URL(slug)
  let fp = pathname.slice(1)
  fp = fp.replace(new RegExp(_getFileExtension(fp) + "$"), "")
  const res = _canonicalize(fp) as CanonicalSlug
  return res
}
export function canonicalizeServer(slug: ServerSlug): CanonicalSlug {
  let fp = slug as string
  const res = _canonicalize(fp) as CanonicalSlug
  return res
}
export function slugifyFilePath(fp: FilePath, excludeExt?: boolean): ServerSlug {
  fp = _stripSlashes(fp) as FilePath
  let ext = _getFileExtension(fp)
export function slugifyFilePath(fp: FilePath, excludeExt?: boolean): FullSlug {
  fp = stripSlashes(fp) as FilePath
  let ext = getFileExtension(fp)
  const withoutFileExt = fp.replace(new RegExp(ext + "$"), "")
  if (excludeExt || [".md", ".html", undefined].includes(ext)) {
    ext = ""
  }
  let slug = withoutFileExt
    .split("/")
    .map((segment) => segment.replace(/\s/g, "-")) // slugify all segments
    .join("/") // always use / as sep
    .replace(/\/$/, "") // remove trailing slash
  let slug = sluggify(withoutFileExt)
  // treat _index as index
  if (_endsWith(slug, "_index")) {
  if (endsWith(slug, "_index")) {
    slug = slug.replace(/_index$/, "index")
  }
  return slug + ext as ServerSlug
  return (slug + ext) as FullSlug
}
export function simplifySlug(fp: FullSlug): SimpleSlug {
  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 =
    fplike.endsWith("index") ||
    fplike.endsWith("index.md") ||
    fplike.endsWith("index.html") ||
    fplike.endsWith("/")
  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)).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
  fp = canonicalizeServer(slugifyFilePath(fp as FilePath) as ServerSlug)
  const joined = joinSegments(_stripSlashes(prefix), _stripSlashes(fp))
  const simpleSlug = simplifySlug(slugifyFilePath(fp as FilePath))
  const joined = joinSegments(stripSlashes(prefix), stripSlashes(simpleSlug))
  const trail = folderPath ? "/" : ""
  const res = (_addRelativeToStart(joined) + trail + anchor) as RelativeURL
  return res
}
// resolve /a/b/c to ../../..
export function pathToRoot(slug: CanonicalSlug): RelativeURL {
// from micromorph/src/utils.ts
// https://github.com/natemoo-re/micromorph/blob/main/src/utils.ts#L5
const _rebaseHtmlElement = (el: Element, attr: string, newBase: string | URL) => {
  const rebased = new URL(el.getAttribute(attr)!, newBase)
  el.setAttribute(attr, rebased.pathname + rebased.hash)
}
export function normalizeRelativeURLs(el: Element | Document, destination: string | URL) {
  el.querySelectorAll('[href=""], [href^="./"], [href^="../"]').forEach((item) =>
    _rebaseHtmlElement(item, "href", destination),
  )
  el.querySelectorAll('[src=""], [src^="./"], [src^="../"]').forEach((item) =>
    _rebaseHtmlElement(item, "src", destination),
  )
}
const _rebaseHastElement = (
  el: HastElement,
  attr: string,
  curBase: FullSlug,
  newBase: FullSlug,
) => {
  if (el.properties?.[attr]) {
    if (!isRelativeURL(String(el.properties[attr]))) {
      return
    }
    const rel = joinSegments(resolveRelative(curBase, newBase), "..", el.properties[attr] as string)
    el.properties[attr] = rel
  }
}
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) {
    el.children = el.children.map((child) =>
      normalizeHastElement(child as HastElement, curBase, newBase),
    )
  }
  return el
}
// resolve /a/b/c to ../..
export function pathToRoot(slug: FullSlug): RelativeURL {
  let rootPath = slug
    .split("/")
    .filter((x) => x !== "")
    .slice(0, -1)
    .map((_) => "..")
    .join("/")
  const res = _addRelativeToStart(rootPath) as RelativeURL
  return res
  if (rootPath.length === 0) {
    rootPath = "."
  }
  return rootPath as RelativeURL
}
export function resolveRelative(current: CanonicalSlug, target: CanonicalSlug): RelativeURL {
  const res = joinSegments(pathToRoot(current), target) as RelativeURL
export function resolveRelative(current: FullSlug, target: FullSlug | SimpleSlug): RelativeURL {
  const res = joinSegments(pathToRoot(current), simplifySlug(target as FullSlug)) as RelativeURL
  return res
}
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]
}
export function slugAnchor(anchor: string) {
  return slug(anchor)
}
export function slugTag(tag: string) {
  return tag
    .split("/")
    .map((tagSegment) => slug(tagSegment))
    .map((tagSegment) => sluggify(tagSegment))
    .join("/")
}
export function joinSegments(...args: string[]): string {
  return args.filter((segment) => segment !== "").join("/")
  if (args.length === 0) {
    return ""
  }
  let joined = args
    .filter((segment) => segment !== "" && segment !== "/")
    .map((segment) => stripSlashes(segment))
    .join("/")
  // 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[] {
@@ -206,21 +213,17 @@
export interface TransformOptions {
  strategy: "absolute" | "relative" | "shortest"
  allSlugs: ServerSlug[]
  allSlugs: FullSlug[]
}
export function transformLink(
  src: CanonicalSlug,
  target: string,
  opts: TransformOptions,
): RelativeURL {
  let targetSlug: string = transformInternalLink(target)
export function transformLink(src: FullSlug, target: string, opts: TransformOptions): RelativeURL {
  let targetSlug = transformInternalLink(target)
  if (opts.strategy === "relative") {
    return _addRelativeToStart(targetSlug) as RelativeURL
    return targetSlug as RelativeURL
  } else {
    const folderTail = targetSlug.endsWith("/") ? "/" : ""
    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") {
@@ -233,54 +236,59 @@
      // only match, just use it
      if (matchingFileNames.length === 1) {
        const targetSlug = canonicalizeServer(matchingFileNames[0])
        const targetSlug = matchingFileNames[0]
        return (resolveRelative(src, targetSlug) + targetAnchor) as RelativeURL
      }
    }
    // if it's not unique, then it's the absolute path from the vault root
    return joinSegments(pathToRoot(src), canonicalSlug) + folderTail as RelativeURL
    return (joinSegments(pathToRoot(src), canonicalSlug) + folderTail) as RelativeURL
  }
}
function _canonicalize(fp: string): string {
  fp = _trimSuffix(fp, "index")
  return _stripSlashes(fp)
// path helpers
function isFolderPath(fplike: string): boolean {
  return (
    fplike.endsWith("/") ||
    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)) {
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): string {
export function stripSlashes(s: string, onlyStripPrefix?: boolean): string {
  if (s.startsWith("/")) {
    s = s.substring(1)
  }
  if (s.endsWith("/")) {
  if (!onlyStripPrefix && s.endsWith("/")) {
    s = s.slice(0, -1)
  }