feat: permalinks as in Obsidian Publish — the note's address; its file path redirects there (#2572)

This commit is contained in:
saberzero1 committed 2026-11-07 23:35:44 +01:00
1 parent 5b6de1fe4c
commit 15b8eeffbf
12 files changed
+269 -32

No files matched your search

@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Permalinks work as in Obsidian Publish (jackyzha0/quartz#2572): `permalink: page` makes the note's address `/page`, whatever its file path. Links to the note, backlinks, the graph, the sitemap, RSS and the content index use the permalink, links inside the note still resolve relative to its file, and the note's file path redirects to the permalink (with AliasRedirects, like `aliases`). Previously the permalink was only a redirect to the file path. A permalink that is already another page's address is ignored with a warning.
+2 -2
View File
@@ -31,8 +31,8 @@ Some common frontmatter fields that are natively supported by Quartz:
- `title`: Title of the page. If it isn't provided, Quartz will use the name of the file as the title.
- `description`: Description of the page used for link previews.
- `permalink`: A custom URL for the page that will remain constant even if the path to the file changes.
- `aliases`: Other names for this note. This is a list of strings.
- `permalink`: The page's address on the site, as in Obsidian Publish: `note.md` with `permalink: page` is published at `/page`, whatever its folder or file name. Links to the note (`[[note]]`) point there, and its file path redirects to it. A permalink that is already another page's address is ignored with a warning.
- `aliases`: Other addresses for this note that redirect to it (with the [[AliasRedirects]] plugin), so old links and links from other sites keep working after a note is renamed or moved. This is a list of strings.
- `tags`: Tags for this note.
- `draft`: Whether to publish the page or not. This is one way to make [[private pages|pages private]] in Quartz.
- `date`: A string representing the day the note was published. Normally uses `YYYY-MM-DD` format.
+2
View File
@@ -33,6 +33,8 @@ The emitter supports the following frontmatter fields:
- `aliases`
- `alias`
A note with a `permalink` is published at its permalink, and its file path becomes a redirect as well: `notes/foo.md` with `permalink: foo` lives at `host.me/foo`, and `host.me/notes/foo` redirects there. An alias that is another page's address (or the page's own) is skipped with a warning, so a redirect never replaces a page.
### Case-Preserving Redirects
Quartz v5 normalizes all URLs to lowercase. If you are migrating from v4 (which preserved the original casing), previously indexed URLs containing uppercase letters (e.g. `/Diary/My-Note`) would return 404 errors.
+1 -1
View File
@@ -102,7 +102,7 @@ Quartz supports the following frontmatter fields. Where multiple keys are listed
| Description | `description` | Page description for metadata and search. |
| Tags | `tags`, `tag` | Categorization tags. Slugified the same way as file paths: spaces become `-`, `&` becomes `-and-`, `%` becomes `-percent`, and tags are lowercased so that `#MyTag` and `#mytag` resolve to the same tag page (matching Obsidian). |
| Aliases | `aliases`, `alias` | Alternative names for the page, used for link resolution. |
| Permalink | `permalink` | Custom URL slug. Also added to aliases. |
| Permalink | `permalink` | The page's address (Obsidian Publish): published at this path; its file path redirects there. |
| CSS classes | `cssclasses`, `cssclass` | CSS classes applied to the page body. |
| Social image | `socialImage`, `image`, `cover` | Image used for social media previews. |
| Social description | `socialDescription` | Description used specifically for social media previews. |
+35 -3
View File
@@ -1,6 +1,7 @@
import sourceMapSupport from "source-map-support"
sourceMapSupport.install(options)
import path from "path"
import fs from "fs"
import { PerfTimer } from "./util/perf"
import { rm, readdir } from "fs/promises"
import { GlobbyFilterFunction, isGitIgnored } from "globby"
@@ -25,10 +26,41 @@ import { minimatch } from "minimatch"
import { formatLayoutReport, getLayoutReport } from "./plugins/loader/layoutReport"
import { getBuiltinPlan } from "./plugins/loader/config-loader"
import { prepareContentIndex } from "./plugins/builtins/contentIndex"
import { printDiagnosticsSummary } from "./util/diagnostics"
import { printDiagnosticsSummary, warn } from "./util/diagnostics"
import { collectPermalinks } from "./util/permalinks"
import { 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.
*/
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 : {}
ctx.permalinks = enabled
? collectPermalinks({
files: allFiles.filter((fp) => fp.endsWith(".md")),
permalinkOf: (fp) => {
const source = fs.readFileSync(path.join(ctx.argv.directory, fp))
if (!source.includes("permalink")) return undefined
try {
return readFrontmatterData(source, options).permalink
} catch {
return undefined // reported when the file is parsed
}
},
warn: (message) => warn({ area: "permalinks", message }),
})
: {}
const pathSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
}
function reportSlugCollisions(content: ProcessedContent[]): void {
const collisions = detectSlugCollisions(content)
if (collisions.length === 0) return
@@ -119,7 +151,7 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
const filePaths = markdownPaths.map((fp) => joinSegments(argv.directory, fp) as FilePath)
ctx.allFiles = allFiles
ctx.allSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
updateSlugs(ctx, allFiles)
const parsedFiles = await parseMarkdown(ctx, filePaths)
reportSlugCollisions(parsedFiles)
@@ -374,7 +406,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
// update allFiles and then allSlugs with the consistent view of content map
ctx.allFiles = Array.from(contentMap.keys())
ctx.allSlugs = ctx.allFiles.map((fp) => slugifyFilePath(fp as FilePath))
updateSlugs(ctx, ctx.allFiles)
const markdownContent = Array.from(contentMap.values())
.filter((file) => file.type === "markdown")
+36 -3
View File
@@ -210,9 +210,10 @@ describe("frontmatter built-in", () => {
)
})
test("normalizeFrontmatter registers permalink as an alias slug", () => {
const data: Record<string, unknown> = { permalink: "short" }
assert.deepStrictEqual(normalizeFrontmatter(data, "x").aliases, ["short"])
test("a permalink is the page's address, not an alias (Obsidian Publish)", () => {
const data: Record<string, unknown> = { permalink: "short", aliases: ["old-name"] }
assert.deepStrictEqual(normalizeFrontmatter(data, "x").aliases, ["old-name"])
assert.strictEqual(data.permalink, "short")
})
})
@@ -240,6 +241,38 @@ describe("links built-in", () => {
children: [{ type: "text", value: text }],
})
test("permalinks: links resolve by file path and point at the permalink", () => {
// folder/page.md has permalink "home"; folder/target.md has permalink "t"
const tree: Root = {
type: "root",
children: [
a("target", "Target"),
a("./sibling"),
{
type: "element",
tagName: "img",
properties: { src: "img.png" },
children: [],
},
],
}
const file = new VFile("")
file.data = { slug: "home" as FullSlug, relativePath: "folder/page.md" as never }
const ctx = {
allSlugs: ["folder/page", "folder/target", "folder/sibling", "folder/img.png", "home", "t"],
permalinks: { "folder/page.md": "home", "folder/target.md": "t" },
} as unknown as BuildCtx
const [factory] = Links({ markdownLinkResolution: "shortest" }).htmlPlugins!(ctx) as [
() => (t: Root, f: VFile) => void,
]
factory()(tree, file)
const [target, sibling, img] = tree.children as Element[]
assert.strictEqual(target.properties.href, "./t") // the target's permalink, from /home
assert.strictEqual(sibling.properties.href, "./folder/sibling") // relative to the file
assert.strictEqual(img.properties.src, "./folder/img.png")
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
})
test("makes internal links relative, records outgoing links, marks external ones", () => {
const { els, file } = run(
[a("other/note", "Note"), a("https://example.com"), a("#heading")],
+24 -9
View File
@@ -105,9 +105,9 @@ export function normalizeFrontmatter(
aliasSlugs.push(...getAliasSlugs(aliases))
}
// The page's address (Obsidian Publish semantics); applied before parsing, see util/permalinks.ts
if (data.permalink != null && data.permalink.toString() !== "") {
data.permalink = data.permalink.toString()
aliasSlugs.push(data.permalink as FullSlug)
}
const cssclasses = coerceToArray(coalesceAliases(data, ["cssclasses", "cssclass"]))
@@ -130,6 +130,22 @@ export function normalizeFrontmatter(
return { aliases: aliasSlugs }
}
/** Parse a file's frontmatter with the configured delimiters and language (`{}` when it has none). */
export function readFrontmatterData(
source: Buffer | string,
options: Pick<FrontmatterConfig, "delimiters" | "language"> = {},
): Record<string, unknown> {
const { data } = matter(Buffer.isBuffer(source) ? source : Buffer.from(source), {
delimiters: options.delimiters ?? frontmatterDefaults.delimiters,
language: options.language ?? frontmatterDefaults.language,
engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
toml: (s) => toml.parse(s) as object,
},
})
return data
}
export const Frontmatter: QuartzTransformerPlugin<FrontmatterConfig> = (userOpts) => {
const opts = { ...frontmatterDefaults, ...userOpts }
return {
@@ -140,16 +156,15 @@ export const Frontmatter: QuartzTransformerPlugin<FrontmatterConfig> = (userOpts
[remarkFrontmatter, ["yaml", "toml"]],
() => {
return (_, file) => {
const { data } = matter(Buffer.from(file.value as Uint8Array), {
delimiters: opts.delimiters,
language: opts.language,
engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
toml: (s) => toml.parse(s) as object,
},
})
const data = readFrontmatterData(Buffer.from(file.value as Uint8Array), opts)
const { aliases } = normalizeFrontmatter(data, file.stem ?? "Untitled")
// With a permalink the page lives at the permalink (set in parse.ts); its file path
// becomes an extra address that redirects there (like an alias).
const pathSlug = file.data.relativePath
? slugifyFilePath(file.data.relativePath)
: undefined
if (pathSlug && file.data.slug && file.data.slug !== pathSlug) aliases.push(pathSlug)
if (aliases.length > 0) {
file.data.aliases = aliases
allSlugs.push(...aliases)
+25 -12
View File
@@ -10,11 +10,14 @@ import {
RelativeURL,
SimpleSlug,
TransformOptions,
resolveRelative,
simplifySlug,
slugifyFilePath,
splitAnchor,
stripSlashes,
transformLink,
} from "../../util/path"
import { permalinkTargets } from "../../util/permalinks"
/**
* Built-in link processing (formerly `@quartz-community/crawl-links`).
@@ -73,6 +76,24 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
allSlugs: ctx.allSlugs,
}
// Permalinks: links are written relative to the note's file, and resolved by file
// path (as in Obsidian). Resolve against the file's path slug, then point at where
// the target is published (its permalink) from where this page is published.
const targets = permalinkTargets(ctx.permalinks)
const pathSlug = file.data.relativePath
? slugifyFilePath(file.data.relativePath)
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, raw, transformOptions)
if (!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) +
anchor) as RelativeURL
}
visit(tree, "element", (node: Element) => {
if (
node.tagName === "a" &&
@@ -124,7 +145,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const isInternal = !(isExternal || dest.startsWith("#"))
if (isInternal) {
dest = node.properties.href = transformLink(fileSlug, dest, transformOptions)
dest = node.properties.href = resolveLink(dest)
const full = canonicalSlug(dest, curSlug)
outgoing.add(simplifySlug(full))
node.properties["data-slug"] = full
@@ -155,11 +176,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
) {
if (opts.lazyLoad) node.properties.loading = "lazy"
if (!isExternalUrl(node.properties.src)) {
node.properties.src = transformLink(
fileSlug,
node.properties.src as RelativeURL,
transformOptions,
)
node.properties.src = resolveLink(node.properties.src as RelativeURL)
}
}
@@ -174,11 +191,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
!value.startsWith("#") &&
!isExternalUrl(value)
) {
node.properties[resourceAttr] = transformLink(
fileSlug,
value as RelativeURL,
transformOptions,
)
node.properties[resourceAttr] = resolveLink(value as RelativeURL)
}
}
})
@@ -189,7 +202,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
if (isExternalUrl(fmLink)) continue
const [targetRaw] = splitAnchor(fmLink)
if (!targetRaw) continue
const dest = transformLink(fileSlug, targetRaw, transformOptions)
const dest = resolveLink(targetRaw)
outgoing.add(simplifySlug(canonicalSlug(dest, curSlug)))
}
+4 -2
View File
@@ -7,7 +7,8 @@ import { Root as HTMLRoot } from "hast"
import { MarkdownContent, ProcessedContent } from "../plugins/vfile"
import { PerfTimer } from "../util/perf"
import { read } from "to-vfile"
import { FilePath, QUARTZ, slugifyFilePath } from "../util/path"
import { FilePath, QUARTZ } from "../util/path"
import { slugForFile } from "../util/permalinks"
import path from "path"
import workerpool, { Promise as WorkerPromise } from "workerpool"
import { QuartzLogger } from "../util/log"
@@ -117,7 +118,8 @@ export function createFileParser(ctx: BuildCtx, fps: FilePath[]) {
// base data properties that plugins may use
file.data.filePath = file.path as FilePath
file.data.relativePath = path.posix.relative(argv.directory, file.path) as FilePath
file.data.slug = slugifyFilePath(file.data.relativePath)
// a frontmatter permalink is the page's address (util/permalinks.ts)
file.data.slug = slugForFile(file.data.relativePath, ctx.permalinks)
const ast = processor.parse(file)
const newAst = await processor.run(ast, file)
+5
View File
@@ -35,6 +35,11 @@ export interface BuildCtx {
cfg: QuartzConfig
allSlugs: FullSlug[]
allFiles: FilePath[]
/**
* Frontmatter permalinks: content file (relative path) → the slug it is published at
* (Obsidian Publish semantics, see util/permalinks.ts). Plain data, so it reaches worker threads.
*/
permalinks?: Record<string, FullSlug>
trie?: FileTrieNode<BuildTimeTrieData>
incremental: boolean
/** Virtual pages generated by page type plugins (e.g. tag pages, folder pages, bases pages) */
+53
View File
@@ -0,0 +1,53 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import {
collectPermalinks,
normalizePermalink,
permalinkTargets,
slugForFile,
type Permalinks,
} from "./permalinks"
describe("permalinks (Obsidian Publish semantics)", () => {
test("normalizePermalink slugifies and strips slashes", () => {
assert.strictEqual(normalizePermalink("page"), "page")
assert.strictEqual(normalizePermalink("/a/b/"), "a/b")
assert.strictEqual(normalizePermalink("My Page"), "my-page")
assert.strictEqual(normalizePermalink(""), undefined)
assert.strictEqual(normalizePermalink("/"), undefined)
assert.strictEqual(normalizePermalink(undefined), undefined)
assert.strictEqual(normalizePermalink(2024), "2024")
})
test("collectPermalinks maps files to their permalink; the address can't be taken twice", () => {
const fm: Record<string, unknown> = {
"folder/note.md": "page",
"self.md": "self", // its own path: nothing to do
"other.md": "existing", // another file's path
"dup.md": "page", // already used by folder/note.md
}
const warnings: string[] = []
const permalinks = collectPermalinks({
files: ["folder/note.md", "self.md", "other.md", "dup.md", "existing.md"],
permalinkOf: (f) => fm[f],
warn: (m) => warnings.push(m),
})
assert.deepStrictEqual(permalinks, { "folder/note.md": "page" })
assert.strictEqual(warnings.length, 2)
assert.match(
warnings[0],
/other\.md: permalink "existing" is already the address of existing\.md/,
)
assert.match(
warnings[1],
/dup\.md: permalink "page" is already the address of folder\/note\.md/,
)
})
test("slugForFile and permalinkTargets", () => {
const permalinks = { "folder/note.md": "page" } as unknown as Permalinks
assert.strictEqual(slugForFile("folder/note.md", permalinks), "page")
assert.strictEqual(slugForFile("folder/other.md", permalinks), "folder/other")
assert.deepStrictEqual([...permalinkTargets(permalinks)], [["folder/note", "page"]])
})
})
+77
View File
@@ -0,0 +1,77 @@
import { FilePath, FullSlug, slugifyFilePath } from "./path"
/**
* Permalinks, as in Obsidian Publish: `permalink: page` in a note's frontmatter makes the note's
* address on the site `/page`, whatever its file path. (`aliases` are extra addresses that
* redirect to the note; see the alias-redirects plugin.)
*
* Quartz needs every page's address before parsing (links resolve against `ctx.allSlugs`), so
* permalinks are collected from frontmatter up front, keyed by the file's path relative to the
* content directory.
*/
export type Permalinks = Record<string, FullSlug>
/** The slug for a frontmatter `permalink` value, or undefined when it is empty. */
export function normalizePermalink(raw: unknown): FullSlug | undefined {
if (raw === null || raw === undefined) return undefined
const value = String(raw)
.trim()
.replace(/\\/g, "/")
.replace(/^\/+|\/+$/g, "")
if (value === "" || value === ".") return undefined
return slugifyFilePath(`${value}.md` as FilePath)
}
export interface CollectPermalinksOptions {
/** Markdown files, relative to the content directory. */
files: string[]
/** Frontmatter `permalink` of a file (undefined when it has none). */
permalinkOf: (file: string) => unknown
/** Called for permalinks that are ignored because the address is taken. */
warn?: (message: string) => void
}
/**
* Permalinks of `files`. A permalink is ignored (with a warning) when another page already has
* that address — its file path or an earlier permalink — so a permalink never replaces a page.
*/
export function collectPermalinks({
files,
permalinkOf,
warn = () => {},
}: CollectPermalinksOptions): Permalinks {
const pathSlugs = new Map(files.map((f) => [slugifyFilePath(f as FilePath), f]))
const taken = new Map<FullSlug, string>()
const permalinks: Permalinks = {}
for (const file of files) {
const slug = normalizePermalink(permalinkOf(file))
if (!slug) continue
const own = slugifyFilePath(file as FilePath)
if (slug === own) continue // the note's own path: nothing to do
const owner = pathSlugs.get(slug) ?? taken.get(slug)
if (owner !== undefined) {
warn(
`${file}: permalink "${slug}" is already the address of ${owner}; the note keeps its own path.`,
)
continue
}
taken.set(slug, file)
permalinks[file] = slug
}
return permalinks
}
/** The slug a content file is published at: its permalink, else its slugified path. */
export function slugForFile(file: string, permalinks: Permalinks | undefined): FullSlug {
return permalinks?.[file] ?? slugifyFilePath(file as FilePath)
}
/** Path slug → permalink slug, for mapping links resolved by file path to the page's address. */
export function permalinkTargets(permalinks: Permalinks | undefined): Map<FullSlug, FullSlug> {
return new Map(
Object.entries(permalinks ?? {}).map(([file, slug]) => [
slugifyFilePath(file as FilePath),
slug,
]),
)
}