Merge pull request #2704 from jackyzha0/dev-mode/filtered-slugs

fix(links): mark links to pages removed by filters as broken (quartz-community/crawl-links#7)
This commit is contained in:
Emile Bangma authored and GitHub committed 2026-11-26 19:03:02 +01:00
commit 1c48865b9f
5 files changed
+165 -5

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Links to pages removed by a filter (drafts, ExplicitPublish) are now marked `broken` (with `data-filtered="<filter>"`), like links to pages that don't exist — they 404 on the site.
+1 -1
View File
@@ -32,7 +32,7 @@ Options:
- `openLinksInNewTab`: If `true`, configures external links to open in a new tab. Defaults to `false`.
- `lazyLoad`: If `true`, adds lazy loading to resource elements (`img`, `video`, etc.) to improve page load performance. Defaults to `false`.
- `externalLinkIcon`: Adds an icon next to external links when `true` (default) to visually distinguishing them from internal links.
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `true`, as Obsidian marks unresolved links. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed.
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `true`, as Obsidian marks unresolved links. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed. Links to pages that a filter removes (e.g. [[RemoveDrafts|drafts]] or pages without `publish: true` under [[ExplicitPublish]]) are marked `broken` too, since they 404; they also get `data-filtered="<filter name>"`. A folder link stays unbroken when only the folder's `index.md` is removed, because the folder still gets a generated folder page.
- `enabled`: set to `false` to turn link processing off (not recommended — links break on nested pages and backlinks/graph are empty).
- `order`: position among transformers. Defaults to `60`, after the Markdown flavour plugins (e.g. [[ObsidianFlavoredMarkdown]] at `40`) that turn wikilinks into links.
+16 -1
View File
@@ -26,7 +26,8 @@ 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, warn } from "./util/diagnostics"
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
import { LinksInstance, markLinksToRemovedPages } from "./plugins/builtins/links"
import { collectPermalinks } from "./util/permalinks"
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
@@ -66,6 +67,18 @@ function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
}
/** Mark links to pages the filters removed as broken (built-in links, crawl-links#7). */
function markRemovedLinks(
ctx: BuildCtx,
all: ProcessedContent[],
published: ProcessedContent[],
): void {
const links = ctx.cfg.plugins.transformers.find((t) => t.name === "Links") as
LinksInstance | undefined
// also when nothing was removed: in watch mode, marks from the last build may need undoing
if (links?.marksBrokenLinks) markLinksToRemovedPages(all, published, filteredBy)
}
function reportSlugCollisions(content: ProcessedContent[]): void {
const collisions = detectSlugCollisions(content)
if (collisions.length === 0) return
@@ -161,6 +174,7 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
const parsedFiles = await parseMarkdown(ctx, filePaths)
reportSlugCollisions(parsedFiles)
const filteredContent = filterContent(ctx, parsedFiles)
markRemovedLinks(ctx, parsedFiles, filteredContent)
await emitContent(ctx, filteredContent)
console.log(
@@ -418,6 +432,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
.map((file) => file.content)
reportSlugCollisions(markdownContent)
let processedFiles = filterContent(ctx, markdownContent)
markRemovedLinks(ctx, markdownContent, processedFiles)
let emittedFiles = 0
+73 -1
View File
@@ -13,7 +13,7 @@ import {
extractLinksFromValue,
readFrontmatterData,
} from "./frontmatter"
import { Links } from "./links"
import { Links, LinksInstance, markLinksToRemovedPages } from "./links"
import {
buildLayeredCSS,
buildUnlayeredCSS,
@@ -849,3 +849,75 @@ describe("fonts built-in", () => {
}
})
})
describe("links to pages removed by filters (crawl-links#7)", () => {
const link = (slug: string, className: string[] = ["internal", "internal-link"]): Element => ({
type: "element",
tagName: "a",
properties: { href: `./${slug}`, "data-slug": slug, className: [...className] },
children: [{ type: "text", value: slug }],
})
const page = (slug: string, links: Element[], data: Record<string, unknown> = {}) => {
const file = new VFile("")
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
return [{ type: "root", children: links } as Root, file] as ProcessedContent
}
const anchors = (item: ProcessedContent) => (item[0] as Root).children as Element[]
test("marks links to removed pages and their aliases broken, with the filter", () => {
const home = page("index", [
link("draft"),
link("old-name"),
link("published"),
link("folder/index"),
])
const draft = page("draft", [], { aliases: ["old-name"] })
const published = page("published", [])
const folderIndex = page("folder/index", [])
const all = [home, draft, published, folderIndex]
const marked = markLinksToRemovedPages(all, [home, published], (s) =>
s === "draft" || s === "folder/index" ? "RemoveDrafts" : undefined,
)
const [toDraft, toAlias, toPublished, toFolder] = anchors(home)
assert.strictEqual(marked, 2)
assert.ok((toDraft.properties.className as string[]).includes("broken"))
assert.strictEqual(toDraft.properties["data-filtered"], "RemoveDrafts")
assert.ok((toAlias.properties.className as string[]).includes("broken"))
assert.ok(!(toPublished.properties.className as string[]).includes("broken"))
// a folder whose index note is a draft still gets a generated folder page
assert.ok(!(toFolder.properties.className as string[]).includes("broken"))
})
test("a removed page's alias that a published page owns is not broken", () => {
const home = page("index", [link("shared")])
const draft = page("draft", [], { aliases: ["shared"] })
const owner = page("shared", [])
markLinksToRemovedPages([home, draft, owner], [home, owner])
assert.ok(!(anchors(home)[0].properties.className as string[]).includes("broken"))
})
test("unmarks links when the target is published again (watch mode)", () => {
const home = page("index", [link("draft")])
const draft = page("draft", [])
markLinksToRemovedPages([home, draft], [home])
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
markLinksToRemovedPages([home, draft], [home, draft])
const a = anchors(home)[0]
assert.deepStrictEqual(a.properties.className, ["internal", "internal-link"])
assert.strictEqual(a.properties["data-filtered"], undefined)
})
test("leaves links marked broken by the links transformer alone", () => {
const home = page("index", [link("missing", ["internal", "internal-link", "broken"])])
markLinksToRemovedPages([home], [home])
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
})
test("the Links instance says whether it marks broken links", () => {
assert.strictEqual((Links() as LinksInstance).marksBrokenLinks, true)
assert.strictEqual(
(Links({ disableBrokenWikilinks: false }) as LinksInstance).marksBrokenLinks,
false,
)
})
})
+70 -2
View File
@@ -3,7 +3,8 @@ import { visit } from "unist-util-visit"
import isAbsoluteUrl from "is-absolute-url"
import { Element, Root, Text } from "hast"
import { VFile } from "vfile"
import { QuartzTransformerPlugin } from "../types"
import { QuartzTransformerPlugin, QuartzTransformerPluginInstance } from "../types"
import { ProcessedContent } from "../vfile"
import { LinksConfig } from "../../cfg"
import {
FullSlug,
@@ -88,6 +89,71 @@ export function pageExists(allSlugs: readonly string[], full: string): boolean {
return false
}
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
const FILTERED_ATTR = "data-filtered"
/**
* Links are classified while the transformers run, before the filters decide what is
* published, so a link to a page a filter removes (a draft, a page without `publish: true`)
* still points at an address in `allSlugs` and is not marked `broken` — yet it 404s
* (crawl-links#7). This runs after the filters: links in published pages whose target was
* removed get the `broken` class and `data-filtered="<filter>"`. Links that were marked this
* way and whose target is published again (watch mode) lose both. Returns the number of links
* marked.
*/
export function markLinksToRemovedPages(
all: ProcessedContent[],
published: ProcessedContent[],
filteredBy: (slug: string) => string | undefined = () => "filter",
): number {
const publishedSet = new Set(published)
const live = new Set<string>()
for (const item of published) {
const data = item[1].data
if (data.slug) live.add(data.slug)
for (const alias of data.aliases ?? []) live.add(alias)
}
const removed = new Map<string, string>()
for (const item of all) {
if (publishedSet.has(item)) continue
const data = item[1].data
if (!data.slug) continue
const reason = filteredBy(data.slug) ?? "filter"
// its aliases (and the file path of a page with a permalink) are gone with it
for (const slug of [data.slug, ...(data.aliases ?? [])]) {
// a folder whose index note is removed still gets a generated folder page
if (slug.endsWith("/index")) continue
if (!live.has(slug) && !removed.has(slug)) removed.set(slug, reason)
}
}
let marked = 0
for (const [tree] of published) {
visit(tree as Root, "element", (node: Element) => {
if (node.tagName !== "a" || !node.properties) return
const target = node.properties["data-slug"]
if (typeof target !== "string") return
const classes = Array.isArray(node.properties.className)
? (node.properties.className as string[])
: []
const reason = removed.get(target)
if (reason !== undefined) {
if (!classes.includes("broken")) classes.push("broken")
node.properties.className = classes
node.properties[FILTERED_ATTR] = reason
marked++
} else if (node.properties[FILTERED_ATTR] !== undefined) {
node.properties.className = classes.filter((c) => c !== "broken")
delete node.properties[FILTERED_ATTR]
}
})
}
return marked
}
/** The Links instance marks links to removed pages after filtering (see build.ts). */
export type LinksInstance = QuartzTransformerPluginInstance & { marksBrokenLinks: boolean }
/**
* Link targets are written as in the vault (`[[Čeština]]`, `../české/x.png`). With
* `configuration.slugs.stripDiacritics` the pages and files they point at have stripped slugs,
@@ -112,8 +178,9 @@ function slugOptionsOnLinkPath(raw: string): string {
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const opts = { ...linksDefaults, ...userOpts }
return {
const instance: LinksInstance = {
name: "Links",
marksBrokenLinks: opts.disableBrokenWikilinks,
htmlPlugins(ctx) {
return [
() => {
@@ -286,4 +353,5 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
]
},
}
return instance
}