mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-30 22:44:41 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
724d70a631 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Links resolve against pages before aliases, as in Obsidian, where aliases aren't link targets: `[[upgrading]]` reaches the note `getting-started/upgrading.md` even when another address `upgrading` is an alias, and a note named like an alias wins over it. A link that only an alias matches now goes straight to the page with the alias, so its `#anchor` works (the alias's redirect page dropped it), and backlinks and the graph count it as a link to that page. Aliases are read before the build, like permalinks, so large sites built with worker threads resolve every alias. Redirect pages Quartz writes for `slugs.stripDiacritics` keep the `#anchor` of the address they redirect from.
|
||||
+39
-19
@@ -10,7 +10,7 @@ import { parseMarkdown } from "./processors/parse"
|
||||
import { filterContent } from "./processors/filter"
|
||||
import { emitContent } from "./processors/emit"
|
||||
import cfg from "../quartz"
|
||||
import { FilePath, joinSegments, slugifyFilePath } from "./util/path"
|
||||
import { FilePath, FullSlug, joinSegments, slugifyFilePath } from "./util/path"
|
||||
import { detectSlugCollisions, formatCollisionWarning } from "./util/slugCollisions"
|
||||
import chokidar from "chokidar"
|
||||
import { ProcessedContent } from "./plugins/vfile"
|
||||
@@ -29,42 +29,62 @@ import { prepareContentIndex } from "./plugins/builtins/contentIndex"
|
||||
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
|
||||
import { LinksInstance, removedPages } from "./plugins/builtins/links"
|
||||
import { collectPermalinks } from "./util/permalinks"
|
||||
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
|
||||
import { collectAliases } from "./util/aliases"
|
||||
import { aliasSlugsOf, readFrontmatterData } from "./plugins/builtins/frontmatter"
|
||||
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
|
||||
import { diffContentFiles, pollingEnabled } from "./util/contentWatcher"
|
||||
|
||||
/**
|
||||
* Every page's address: permalinks (frontmatter `permalink`, read up front so links can resolve
|
||||
* to them) and the slugified paths of all files. A permalinked note's file path stays in
|
||||
* `allSlugs`: it becomes a redirect to the permalink.
|
||||
* `allSlugs`: it becomes a redirect to the permalink. Frontmatter `aliases` are read up front
|
||||
* too (`ctx.aliases`), so links that only an alias matches go to the page (util/aliases.ts).
|
||||
*/
|
||||
function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
|
||||
const frontmatter = ctx.cfg.configuration.frontmatter
|
||||
const enabled =
|
||||
frontmatter !== false && (typeof frontmatter !== "object" || frontmatter.enabled !== false)
|
||||
const options = typeof frontmatter === "object" ? frontmatter : {}
|
||||
const markdown = allFiles.filter((fp) => fp.endsWith(".md"))
|
||||
// frontmatter of the files that may set a permalink or aliases, read once
|
||||
const data = new Map<string, Record<string, unknown>>()
|
||||
if (enabled) {
|
||||
for (const fp of markdown) {
|
||||
let source: Buffer
|
||||
try {
|
||||
source = fs.readFileSync(path.join(ctx.argv.directory, fp))
|
||||
} catch {
|
||||
continue // an unreadable file is reported when the file is parsed
|
||||
}
|
||||
if (!source.includes("permalink") && !source.includes("alias")) continue
|
||||
try {
|
||||
data.set(fp, readFrontmatterData(source, options))
|
||||
} catch {
|
||||
// reported when the file is parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.permalinks = enabled
|
||||
? collectPermalinks({
|
||||
files: allFiles.filter((fp) => fp.endsWith(".md")),
|
||||
permalinkOf: (fp) => {
|
||||
let source: Buffer
|
||||
try {
|
||||
source = fs.readFileSync(path.join(ctx.argv.directory, fp))
|
||||
} catch {
|
||||
return undefined // an unreadable file is reported when the file is parsed
|
||||
}
|
||||
if (!source.includes("permalink")) return undefined
|
||||
try {
|
||||
return readFrontmatterData(source, options).permalink
|
||||
} catch {
|
||||
return undefined // reported when the file is parsed
|
||||
}
|
||||
},
|
||||
files: markdown,
|
||||
permalinkOf: (fp) => data.get(fp)?.permalink,
|
||||
warn: (message) => warn({ area: "permalinks", message }),
|
||||
})
|
||||
: {}
|
||||
ctx.aliases = enabled
|
||||
? collectAliases({
|
||||
files: allFiles,
|
||||
aliasesOf: (fp) => {
|
||||
const fm = data.get(fp)
|
||||
return fm ? aliasSlugsOf(fm) : []
|
||||
},
|
||||
permalinks: ctx.permalinks,
|
||||
})
|
||||
: {}
|
||||
const pathSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
|
||||
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
|
||||
ctx.allSlugs = [
|
||||
...new Set([...pathSlugs, ...Object.values(ctx.permalinks), ...Object.keys(ctx.aliases)]),
|
||||
] as FullSlug[]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -471,6 +471,71 @@ describe("links built-in", () => {
|
||||
assert.strictEqual(slugOf("index", "current"), "projects/beta/current")
|
||||
})
|
||||
|
||||
describe("aliases", () => {
|
||||
// getting-started/upgrading.md has `aliases: [upgrading]`; guide.md has `aliases: [How To]`
|
||||
const aliasCtx = (extra: Record<string, unknown> = {}) =>
|
||||
({
|
||||
allSlugs: [
|
||||
"index",
|
||||
"getting-started/upgrading",
|
||||
"guide",
|
||||
"notes/how-to",
|
||||
"upgrading",
|
||||
"how-to",
|
||||
],
|
||||
aliases: { upgrading: "getting-started/upgrading", "how-to": "guide" },
|
||||
...extra,
|
||||
}) as unknown as BuildCtx
|
||||
const resolve = (links: Element[], slug = "getting-started/whats-new", ctx = aliasCtx()) => {
|
||||
const tree: Root = { type: "root", children: links }
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug }
|
||||
const [factory] = Links({ markdownLinkResolution: "shortest" }).htmlPlugins!(ctx) as [
|
||||
() => (t: Root, f: VFile) => void,
|
||||
]
|
||||
factory()(tree, file)
|
||||
return { links: tree.children as Element[], file }
|
||||
}
|
||||
|
||||
test("a link with an alias's name goes to the page, keeping its anchor", () => {
|
||||
const { links, file } = resolve(
|
||||
[a("upgrading#upgrading-from-52-to-53", "Upgrading")],
|
||||
"index",
|
||||
)
|
||||
// not ./upgrading#…: the alias's redirect page would drop the anchor
|
||||
assert.strictEqual(
|
||||
links[0]!.properties.href,
|
||||
"./getting-started/upgrading#upgrading-from-52-to-53",
|
||||
)
|
||||
assert.strictEqual(links[0]!.properties["data-slug"], "getting-started/upgrading")
|
||||
// backlinks and the graph see a link to the page
|
||||
assert.deepStrictEqual(file.data.links, ["getting-started/upgrading"])
|
||||
})
|
||||
|
||||
test("a page beats an alias with its name, as in Obsidian", () => {
|
||||
// `How To` is an alias of guide.md, but notes/how-to.md is a note with that name
|
||||
const { links } = resolve([a("how-to")], "index")
|
||||
assert.strictEqual(links[0]!.properties["data-slug"], "notes/how-to")
|
||||
})
|
||||
|
||||
test("a name only an alias has goes to its page", () => {
|
||||
const ctx = aliasCtx({
|
||||
allSlugs: ["index", "guide", "how-to"],
|
||||
aliases: { "how-to": "guide" },
|
||||
})
|
||||
const { links } = resolve([a("how-to#step-2", "How To")], "notes/page", ctx)
|
||||
assert.strictEqual(links[0]!.properties.href, "../guide#step-2")
|
||||
assert.ok(!(links[0]!.properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("an alias named like an Object property is still an alias", () => {
|
||||
const ctx = aliasCtx({ allSlugs: ["index", "guide"], aliases: {} })
|
||||
const { links } = resolve([a("constructor")], "index", ctx)
|
||||
assert.strictEqual(links[0]!.properties["data-slug"], "constructor")
|
||||
assert.ok((links[0]!.properties.className as string[]).includes("broken"))
|
||||
})
|
||||
})
|
||||
|
||||
test("slugs.stripDiacritics: link targets are stripped like the slugs they point at (#2410)", () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
|
||||
@@ -58,6 +58,12 @@ function getAliasSlugs(aliases: string[]): FullSlug[] {
|
||||
})
|
||||
}
|
||||
|
||||
/** Slugs of the `aliases` (or `alias`) in raw frontmatter, as {@link normalizeFrontmatter} reads them. */
|
||||
export function aliasSlugsOf(data: Record<string, unknown>): FullSlug[] {
|
||||
const aliases = coerceToArray(coalesceAliases(data, ["aliases", "alias"]))
|
||||
return aliases ? getAliasSlugs(aliases) : []
|
||||
}
|
||||
|
||||
/** `[[Some Note#Heading]]` target → `some-note#heading` (same slugging as wikilinks). */
|
||||
export function slugifyWikilinkTarget(target: string): string {
|
||||
const [rawPath, anchor] = splitAnchor(target)
|
||||
|
||||
@@ -112,6 +112,29 @@ export function linkTargetMissing(allSlugs: readonly string[], full: string): bo
|
||||
return VAULT_FILE_TYPES.has(ext)
|
||||
}
|
||||
|
||||
/**
|
||||
* `allSlugs` without alias addresses (see util/aliases.ts), for resolving links against pages.
|
||||
* Cached: `allSlugs` only grows while files are parsed, and `aliases` is replaced on a rebuild.
|
||||
*/
|
||||
let pageSlugsCache: {
|
||||
from: readonly string[]
|
||||
length: number
|
||||
aliases: object
|
||||
slugs: FullSlug[]
|
||||
} = { from: [], length: -1, aliases: {}, slugs: [] }
|
||||
/** The page an alias slug belongs to (own keys only: `constructor` is a fine slug). */
|
||||
const aliasTarget = (aliases: Record<string, FullSlug>, slug: string): FullSlug | undefined =>
|
||||
Object.hasOwn(aliases, slug) ? aliases[slug] : undefined
|
||||
|
||||
export function pageSlugs(allSlugs: FullSlug[], aliases: Record<string, FullSlug>): FullSlug[] {
|
||||
if (Object.keys(aliases).length === 0) return allSlugs
|
||||
const c = pageSlugsCache
|
||||
if (c.from === allSlugs && c.length === allSlugs.length && c.aliases === aliases) return c.slugs
|
||||
const slugs = allSlugs.filter((slug) => !Object.hasOwn(aliases, slug))
|
||||
pageSlugsCache = { from: allSlugs, length: allSlugs.length, aliases, slugs }
|
||||
return slugs
|
||||
}
|
||||
|
||||
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
|
||||
const FILTERED_ATTR = "data-filtered"
|
||||
/** The `broken` mark for links to folder and tag pages that no page type generated. */
|
||||
@@ -258,13 +281,29 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
? slugifyFilePath(file.data.relativePath)
|
||||
: fileSlug
|
||||
const rebase = targets.size > 0 || pathSlug !== fileSlug
|
||||
// Aliases: links resolve against the site's pages first (in Obsidian aliases aren't
|
||||
// link targets, so `[[upgrading]]` is the note `getting-started/upgrading`, not the
|
||||
// alias `upgrading` of some note). A link only an alias matches goes straight to the
|
||||
// page with the alias, keeping its anchor, which the alias's redirect page drops.
|
||||
const aliases = ctx.aliases ?? {}
|
||||
const pageOptions: TransformOptions = {
|
||||
...transformOptions,
|
||||
allSlugs: pageSlugs(ctx.allSlugs, aliases),
|
||||
}
|
||||
const resolveLink = (raw: string): RelativeURL => {
|
||||
const rel = transformLink(pathSlug, raw, transformOptions)
|
||||
if (!rebase) return rel
|
||||
let rel = transformLink(pathSlug, raw, pageOptions)
|
||||
let target = canonicalSlug(rel, simplifySlug(pathSlug))
|
||||
let page = aliasTarget(aliases, target)
|
||||
if (page === undefined && linkTargetMissing(pageOptions.allSlugs, target)) {
|
||||
// a name only an alias has, resolved like a page's (e.g. a path alias `a/b`)
|
||||
rel = transformLink(pathSlug, raw, transformOptions)
|
||||
target = canonicalSlug(rel, simplifySlug(pathSlug))
|
||||
page = aliasTarget(aliases, target)
|
||||
}
|
||||
if (page === undefined && !rebase) return rel
|
||||
const hash = rel.indexOf("#")
|
||||
const anchor = hash === -1 ? "" : rel.slice(hash)
|
||||
const target = canonicalSlug(rel, simplifySlug(pathSlug))
|
||||
return (resolveRelative(fileSlug, targets.get(target) ?? target) +
|
||||
return (resolveRelative(fileSlug, page ?? targets.get(target) ?? target) +
|
||||
anchor) as RelativeURL
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ describe("SlugRedirects emitter", () => {
|
||||
<link rel="canonical" href="${url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<script>location.replace(${JSON.stringify(url)} + location.hash)</script>
|
||||
<meta http-equiv="refresh" content="0; url=${url}">
|
||||
</head>
|
||||
</html>
|
||||
|
||||
@@ -73,6 +73,7 @@ function redirectHtml(to: string, url: string): string {
|
||||
<link rel="canonical" href="${url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<script>location.replace(${JSON.stringify(url).replace(/</g, "\\u003c")} + location.hash)</script>
|
||||
<meta http-equiv="refresh" content="0; url=${url}">
|
||||
</head>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, test } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { collectAliases } from "./aliases"
|
||||
import { FullSlug } from "./path"
|
||||
|
||||
describe("collectAliases", () => {
|
||||
const files = [
|
||||
"index.md",
|
||||
"getting-started/upgrading.md",
|
||||
"guide.md",
|
||||
"notes/how-to.md",
|
||||
"moved.md",
|
||||
"img/how-to.png",
|
||||
]
|
||||
const frontmatter: Record<string, string[]> = {
|
||||
"getting-started/upgrading.md": ["upgrading", "getting-started/upgrading"],
|
||||
"guide.md": ["how-to", "guide-old", "notes/how-to", "img/how-to.png"],
|
||||
"moved.md": ["guide-old", "previous"],
|
||||
}
|
||||
const aliases = collectAliases({
|
||||
files,
|
||||
aliasesOf: (file) => (frontmatter[file] ?? []) as FullSlug[],
|
||||
permalinks: { "moved.md": "elsewhere/moved" as FullSlug },
|
||||
})
|
||||
|
||||
test("maps each alias to the page that has it, at its published address", () => {
|
||||
assert.deepStrictEqual(aliases, {
|
||||
upgrading: "getting-started/upgrading",
|
||||
"how-to": "guide",
|
||||
"guide-old": "guide",
|
||||
previous: "elsewhere/moved",
|
||||
})
|
||||
})
|
||||
|
||||
test("a page's address is never an alias: its own path, another page's or a file's", () => {
|
||||
for (const slug of ["getting-started/upgrading", "notes/how-to", "img/how-to.png"]) {
|
||||
assert.ok(!Object.hasOwn(aliases, slug), slug)
|
||||
}
|
||||
})
|
||||
|
||||
test("of two notes with an alias, the first keeps it", () => {
|
||||
assert.strictEqual(aliases["guide-old"], "guide")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { FilePath, FullSlug, slugifyFilePath } from "./path"
|
||||
import { Permalinks, slugForFile } from "./permalinks"
|
||||
|
||||
/**
|
||||
* Frontmatter `aliases`: alias slug → the slug of the page that has the alias.
|
||||
*
|
||||
* An alias is an extra address of a note: the alias-redirects plugin writes a redirect page
|
||||
* there. Links resolve against real pages first (as in Obsidian, where aliases are not link
|
||||
* targets), and a link that only an alias matches goes straight to the page, so an `#anchor`
|
||||
* survives (a redirect page drops it). Like permalinks, aliases are collected up front, so every
|
||||
* worker thread knows all of them, not only those of the files it parsed.
|
||||
*/
|
||||
export type Aliases = Record<string, FullSlug>
|
||||
|
||||
export interface CollectAliasesOptions {
|
||||
/** All content files, relative to the content directory. */
|
||||
files: string[]
|
||||
/** Alias slugs of a Markdown file (from its frontmatter); empty when it has none. */
|
||||
aliasesOf: (file: string) => readonly FullSlug[]
|
||||
permalinks?: Permalinks
|
||||
}
|
||||
|
||||
/**
|
||||
* Aliases of `files`. An alias that is a page's address (a file path or a permalink) is left
|
||||
* out: the page wins, as the redirect pages never replace a page either. Of two notes with the
|
||||
* same alias, the first keeps it.
|
||||
*/
|
||||
export function collectAliases({ files, aliasesOf, permalinks }: CollectAliasesOptions): Aliases {
|
||||
const pages = new Set<string>(files.map((f) => slugifyFilePath(f as FilePath)))
|
||||
for (const slug of Object.values(permalinks ?? {})) pages.add(slug)
|
||||
const aliases: Aliases = {}
|
||||
for (const file of files) {
|
||||
if (!file.endsWith(".md")) continue
|
||||
const page = slugForFile(file, permalinks)
|
||||
for (const alias of aliasesOf(file)) {
|
||||
if (alias === page || pages.has(alias) || Object.hasOwn(aliases, alias)) continue
|
||||
aliases[alias] = page
|
||||
}
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
@@ -11,6 +11,7 @@ describe("workerCtx", () => {
|
||||
allSlugs: ["index", "elsewhere/moved"] as FullSlug[],
|
||||
allFiles: ["index.md", "Moved.md"] as FilePath[],
|
||||
permalinks: { "Moved.md": "elsewhere/moved" as FullSlug },
|
||||
aliases: { "old-name": "index" as FullSlug },
|
||||
incremental: false,
|
||||
virtualPages: [],
|
||||
trie: {},
|
||||
@@ -20,6 +21,10 @@ describe("workerCtx", () => {
|
||||
assert.deepStrictEqual(workerCtx(ctx).permalinks, { "Moved.md": "elsewhere/moved" })
|
||||
})
|
||||
|
||||
test("carries aliases to worker threads", () => {
|
||||
assert.deepStrictEqual(workerCtx(ctx).aliases, { "old-name": "index" })
|
||||
})
|
||||
|
||||
test("holds plain data only, and survives structured cloning", () => {
|
||||
const worker = workerCtx(ctx)
|
||||
assert.ok(!("cfg" in worker) && !("trie" in worker))
|
||||
|
||||
+9
-1
@@ -40,6 +40,11 @@ export interface BuildCtx {
|
||||
* (Obsidian Publish semantics, see util/permalinks.ts). Plain data, so it reaches worker threads.
|
||||
*/
|
||||
permalinks?: Record<string, FullSlug>
|
||||
/**
|
||||
* Frontmatter aliases: alias slug → the slug of the page that has it (util/aliases.ts).
|
||||
* Plain data, so it reaches worker threads.
|
||||
*/
|
||||
aliases?: Record<string, FullSlug>
|
||||
trie?: FileTrieNode<BuildTimeTrieData>
|
||||
incremental: boolean
|
||||
/**
|
||||
@@ -95,7 +100,9 @@ export type WorkerSerializableBuildCtx = Omit<BuildCtx, "cfg" | "trie">
|
||||
|
||||
/** The plain-data fields of {@link BuildCtx} that worker threads need, each one required. */
|
||||
type WorkerCtxFields = {
|
||||
[K in "buildId" | "argv" | "allSlugs" | "allFiles" | "permalinks" | "incremental"]-?: BuildCtx[K]
|
||||
[
|
||||
K in "buildId" | "argv" | "allSlugs" | "allFiles" | "permalinks" | "aliases" | "incremental"
|
||||
]-?: BuildCtx[K]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,6 +118,7 @@ export function workerCtx(ctx: BuildCtx): WorkerSerializableBuildCtx {
|
||||
allSlugs: ctx.allSlugs,
|
||||
allFiles: ctx.allFiles,
|
||||
permalinks: ctx.permalinks ?? {},
|
||||
aliases: ctx.aliases ?? {},
|
||||
incremental: ctx.incremental,
|
||||
}
|
||||
return { ...fields, virtualPages: [] }
|
||||
|
||||
Reference in new issue
Block a user