Jacky Zhao
2023-08-14 7bde99b4e2d49e30dad1e0d58ccc34c2e7482005
quartz/path.ts
@@ -1,5 +1,5 @@
import { slug } from "github-slugger"
import { trace } from "./trace"
// 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
@@ -43,17 +43,7 @@
//                                             └────────────┤ MD File ├─────┴─────────────────┘
//                                                          └─────────┘
const STRICT_TYPE_CHECKS = false
const HARD_EXIT_ON_FAIL = false
function conditionCheck<T>(name: string, label: "pre" | "post", s: T, chk: (x: any) => x is T) {
  if (STRICT_TYPE_CHECKS && !chk(s)) {
    trace(`${name} failed ${label}-condition check: ${s} does not pass ${chk.name}`, new Error())
    if (HARD_EXIT_ON_FAIL) {
      process.exit(1)
    }
  }
}
export const QUARTZ = "quartz"
/// Utility type to simulate nominal types in TypeScript
type SlugLike<T> = string & { __brand: T }
@@ -102,36 +92,29 @@
export function getClientSlug(window: Window): ClientSlug {
  const res = window.location.href as ClientSlug
  conditionCheck(getClientSlug.name, "post", res, isClientSlug)
  return res
}
export function getCanonicalSlug(window: Window): CanonicalSlug {
  const res = window.document.body.dataset.slug! as CanonicalSlug
  conditionCheck(getCanonicalSlug.name, "post", res, isCanonicalSlug)
  return res
}
export function canonicalizeClient(slug: ClientSlug): CanonicalSlug {
  conditionCheck(canonicalizeClient.name, "pre", slug, isClientSlug)
  const { pathname } = new URL(slug)
  let fp = pathname.slice(1)
  fp = fp.replace(new RegExp(_getFileExtension(fp) + "$"), "")
  const res = _canonicalize(fp) as CanonicalSlug
  conditionCheck(canonicalizeClient.name, "post", res, isCanonicalSlug)
  return res
}
export function canonicalizeServer(slug: ServerSlug): CanonicalSlug {
  conditionCheck(canonicalizeServer.name, "pre", slug, isServerSlug)
  let fp = slug as string
  const res = _canonicalize(fp) as CanonicalSlug
  conditionCheck(canonicalizeServer.name, "post", res, isCanonicalSlug)
  return res
}
export function slugifyFilePath(fp: FilePath): ServerSlug {
  conditionCheck(slugifyFilePath.name, "pre", fp, isFilePath)
  fp = _stripSlashes(fp) as FilePath
  const withoutFileExt = fp.replace(new RegExp(_getFileExtension(fp) + "$"), "")
  let slug = withoutFileExt
@@ -145,7 +128,6 @@
    slug = slug.replace(/_index$/, "index")
  }
  conditionCheck(slugifyFilePath.name, "post", slug, isServerSlug)
  return slug as ServerSlug
}
@@ -165,13 +147,11 @@
  let joined = joinSegments(_stripSlashes(prefix), _stripSlashes(fp))
  const res = (_addRelativeToStart(joined) + anchor) as RelativeURL
  conditionCheck(transformInternalLink.name, "post", res, isRelativeURL)
  return res
}
// resolve /a/b/c to ../../
export function pathToRoot(slug: CanonicalSlug): RelativeURL {
  conditionCheck(pathToRoot.name, "pre", slug, isCanonicalSlug)
  let rootPath = slug
    .split("/")
    .filter((x) => x !== "")
@@ -179,15 +159,11 @@
    .join("/")
  const res = _addRelativeToStart(rootPath) as RelativeURL
  conditionCheck(pathToRoot.name, "post", res, isRelativeURL)
  return res
}
export function resolveRelative(current: CanonicalSlug, target: CanonicalSlug): RelativeURL {
  conditionCheck(resolveRelative.name, "pre", current, isCanonicalSlug)
  conditionCheck(resolveRelative.name, "pre", target, isCanonicalSlug)
  const res = joinSegments(pathToRoot(current), target) as RelativeURL
  conditionCheck(resolveRelative.name, "post", res, isRelativeURL)
  return res
}
@@ -221,7 +197,43 @@
  return results
}
export const QUARTZ = "quartz"
export interface TransformOptions {
  strategy: "absolute" | "relative" | "shortest"
  allSlugs: ServerSlug[]
}
export function transformLink(
  src: CanonicalSlug,
  target: string,
  opts: TransformOptions,
): RelativeURL {
  let targetSlug: string = transformInternalLink(target)
  if (opts.strategy === "relative") {
    return _addRelativeToStart(targetSlug) as RelativeURL
  } else {
    targetSlug = _stripSlashes(targetSlug.slice(".".length))
    let [targetCanonical, targetAnchor] = splitAnchor(targetSlug)
    if (opts.strategy === "shortest") {
      // if the file name is unique, then it's just the filename
      const matchingFileNames = opts.allSlugs.filter((slug) => {
        const parts = slug.split("/")
        const fileName = parts.at(-1)
        return targetCanonical === fileName
      })
      // only match, just use it
      if (matchingFileNames.length === 1) {
        const targetSlug = canonicalizeServer(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), targetSlug) as RelativeURL
  }
}
function _canonicalize(fp: string): string {
  fp = _trimSuffix(fp, "index")
@@ -248,14 +260,14 @@
}
function _getFileExtension(s: string): string | undefined {
  return s.match(/\.[A-Za-z]+$/)?.[0]
  return s.match(/\.[A-Za-z0-9]+$/)?.[0]
}
function _isRelativeSegment(s: string): boolean {
  return /^\.{0,2}$/.test(s)
}
function _stripSlashes(s: string): string {
export function _stripSlashes(s: string): string {
  if (s.startsWith("/")) {
    s = s.substring(1)
  }