mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
fix(links): mark links to folder/tag pages that aren't generated; re-emit pages whose link marks change in watch mode
This commit is contained in:
6 files changed
+164
-25
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Links to a folder or tag page that isn't generated (a folder whose notes are all drafts or that holds only images, a tag no published page uses) are marked broken, and in watch mode a page whose links to a page that was published or filtered out change is re-emitted, so its marks don't go stale.
|
||||
+6
-3
@@ -27,7 +27,7 @@ import { formatLayoutReport, getLayoutReport } from "./plugins/loader/layoutRepo
|
||||
import { getBuiltinPlan } from "./plugins/loader/config-loader"
|
||||
import { prepareContentIndex } from "./plugins/builtins/contentIndex"
|
||||
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
|
||||
import { LinksInstance, markLinksToRemovedPages } from "./plugins/builtins/links"
|
||||
import { LinksInstance, removedPages } from "./plugins/builtins/links"
|
||||
import { collectPermalinks } from "./util/permalinks"
|
||||
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
|
||||
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
|
||||
@@ -67,7 +67,10 @@ 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). */
|
||||
/**
|
||||
* Record the pages the filters removed, so PageTypeDispatcher marks links to them as broken
|
||||
* (built-in links, crawl-links#7) once it knows which folder and tag pages are generated.
|
||||
*/
|
||||
function markRemovedLinks(
|
||||
ctx: BuildCtx,
|
||||
all: ProcessedContent[],
|
||||
@@ -76,7 +79,7 @@ function markRemovedLinks(
|
||||
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)
|
||||
ctx.removedPages = links?.marksBrokenLinks ? removedPages(all, published, filteredBy) : undefined
|
||||
}
|
||||
|
||||
function reportSlugCollisions(content: ProcessedContent[]): void {
|
||||
|
||||
@@ -14,7 +14,13 @@ import {
|
||||
extractLinksFromValue,
|
||||
readFrontmatterData,
|
||||
} from "./frontmatter"
|
||||
import { Links, LinksInstance, markLinksToRemovedPages } from "./links"
|
||||
import {
|
||||
Links,
|
||||
LinksInstance,
|
||||
markLinksToRemovedPages,
|
||||
markUnpublishedLinks,
|
||||
removedPages,
|
||||
} from "./links"
|
||||
import {
|
||||
buildLayeredCSS,
|
||||
buildUnlayeredCSS,
|
||||
@@ -1054,6 +1060,43 @@ describe("links to pages removed by filters (crawl-links#7)", () => {
|
||||
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("marks links to folder and tag pages no page type generated", () => {
|
||||
const home = page("index", [
|
||||
link("drafts/index"),
|
||||
link("notes/index"),
|
||||
link("tags/unused"),
|
||||
link("tags/used"),
|
||||
link("tags/parent"),
|
||||
link("index"),
|
||||
])
|
||||
const generated = new Set(["notes/index", "tags/used", "tags/parent/index", "tags/index"])
|
||||
const changed = new Set<FullSlug>()
|
||||
const marked = markUnpublishedLinks([home], new Map(), generated, changed)
|
||||
const broken = anchors(home).map((a) => (a.properties.className as string[]).includes("broken"))
|
||||
assert.deepStrictEqual(broken, [true, false, true, false, false, false])
|
||||
assert.strictEqual(marked, 2)
|
||||
assert.strictEqual(anchors(home)[0].properties["data-missing"], "")
|
||||
assert.deepStrictEqual([...changed], ["index"])
|
||||
})
|
||||
|
||||
test("reports the pages whose marks changed, so watch mode re-emits them", () => {
|
||||
const home = page("index", [link("draft")])
|
||||
const other = page("other", [link("published")])
|
||||
const draft = page("draft", [])
|
||||
const all = [home, other, draft]
|
||||
const changed = new Set<FullSlug>()
|
||||
markUnpublishedLinks([home, other], removedPages(all, [home, other]), new Set(), changed)
|
||||
assert.deepStrictEqual([...changed], ["index"])
|
||||
changed.clear()
|
||||
// nothing changed: nothing to re-emit
|
||||
markUnpublishedLinks([home, other], removedPages(all, [home, other]), new Set(), changed)
|
||||
assert.deepStrictEqual([...changed], [])
|
||||
// the draft is published: its link is unmarked, the page re-emitted
|
||||
markUnpublishedLinks([home, other, draft], removedPages(all, all), new Set(), changed)
|
||||
assert.deepStrictEqual([...changed], ["index"])
|
||||
assert.deepStrictEqual(anchors(home)[0].properties.className, ["internal", "internal-link"])
|
||||
})
|
||||
|
||||
test("the Links instance says whether it marks broken links", () => {
|
||||
assert.strictEqual((Links() as LinksInstance).marksBrokenLinks, true)
|
||||
assert.strictEqual(
|
||||
|
||||
@@ -116,21 +116,19 @@ export function linkTargetMissing(allSlugs: readonly string[], full: string): bo
|
||||
|
||||
/** 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. */
|
||||
const MISSING_ATTR = "data-missing"
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The pages the filters removed (drafts, pages without `publish: true`, …) and their aliases,
|
||||
* each with the filter that removed it. A folder's `index` note is left out: the folder may still
|
||||
* get a generated folder page, which only the generated pages tell (markUnpublishedLinks).
|
||||
*/
|
||||
export function markLinksToRemovedPages(
|
||||
export function removedPages(
|
||||
all: ProcessedContent[],
|
||||
published: ProcessedContent[],
|
||||
filteredBy: (slug: string) => string | undefined = () => "filter",
|
||||
): number {
|
||||
): Map<string, string> {
|
||||
const publishedSet = new Set(published)
|
||||
const live = new Set<string>()
|
||||
for (const item of published) {
|
||||
@@ -146,36 +144,94 @@ export function markLinksToRemovedPages(
|
||||
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)
|
||||
}
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
/** Link targets that page types generate (folder pages, tag pages), unknown while transforming. */
|
||||
function isGeneratedTarget(slug: string): boolean {
|
||||
return (
|
||||
slug === "tags" || slug.startsWith("tags/") || (slug !== "index" && slug.endsWith("/index"))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Links are classified while the transformers run, before the filters decide what is
|
||||
* published and before page types generate folder and tag pages, so two kinds of links that
|
||||
* 404 are not marked `broken` then:
|
||||
*
|
||||
* - a link to a page a filter removes (a draft, a page without `publish: true`) still points at
|
||||
* an address in `allSlugs` (crawl-links#7): it gets `data-filtered="<filter>"`;
|
||||
* - a link to a folder or tag page (see pageExists) that no page type generated — a folder whose
|
||||
* notes are all drafts or that holds only images, a tag no published page uses, any folder or
|
||||
* tag when folder-page / tag-page isn't installed: it gets `data-missing`.
|
||||
*
|
||||
* With `generated` (the slugs of the virtual pages, once page types ran) both are checked;
|
||||
* without it only removed pages, and folder pages are assumed to exist. Links marked this way
|
||||
* whose target is published again (watch mode) lose the mark; pages whose tree changed are added
|
||||
* to `changed`, so watch mode re-emits them. Returns the number of links marked.
|
||||
*/
|
||||
export function markUnpublishedLinks(
|
||||
published: ProcessedContent[],
|
||||
removed: ReadonlyMap<string, string>,
|
||||
generated?: ReadonlySet<string>,
|
||||
changed?: Set<FullSlug>,
|
||||
): number {
|
||||
const live = new Set<string>(generated ?? [])
|
||||
for (const [, file] of published) {
|
||||
if (file.data.slug) live.add(file.data.slug)
|
||||
for (const alias of file.data.aliases ?? []) live.add(alias)
|
||||
}
|
||||
let marked = 0
|
||||
for (const [tree] of published) {
|
||||
for (const [tree, file] of published) {
|
||||
let touched = false
|
||||
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) {
|
||||
const props = node.properties
|
||||
const classes = Array.isArray(props.className) ? (props.className as string[]) : []
|
||||
let attr: string | undefined
|
||||
let value = ""
|
||||
// a parent tag's page is `tags/a/index`, served at `tags/a` too
|
||||
if (!live.has(target) && !live.has(`${target}/index`)) {
|
||||
const reason = removed.get(target)
|
||||
if (reason !== undefined) [attr, value] = [FILTERED_ATTR, reason]
|
||||
else if (generated && isGeneratedTarget(target)) attr = MISSING_ATTR
|
||||
}
|
||||
let cleared = false
|
||||
for (const other of [FILTERED_ATTR, MISSING_ATTR]) {
|
||||
if (other === attr || props[other] === undefined) continue
|
||||
delete props[other]
|
||||
cleared = touched = true
|
||||
}
|
||||
if (attr !== undefined) {
|
||||
if (props[attr] !== value || !classes.includes("broken")) touched = true
|
||||
if (!classes.includes("broken")) classes.push("broken")
|
||||
node.properties.className = classes
|
||||
node.properties[FILTERED_ATTR] = reason
|
||||
props.className = classes
|
||||
props[attr] = value
|
||||
marked++
|
||||
} else if (node.properties[FILTERED_ATTR] !== undefined) {
|
||||
node.properties.className = classes.filter((c) => c !== "broken")
|
||||
delete node.properties[FILTERED_ATTR]
|
||||
} else if (cleared) {
|
||||
props.className = classes.filter((c) => c !== "broken")
|
||||
}
|
||||
})
|
||||
if (touched && changed && file.data.slug) changed.add(file.data.slug)
|
||||
}
|
||||
return marked
|
||||
}
|
||||
|
||||
/** {@link removedPages} + {@link markUnpublishedLinks}, before page types ran. */
|
||||
export function markLinksToRemovedPages(
|
||||
all: ProcessedContent[],
|
||||
published: ProcessedContent[],
|
||||
filteredBy: (slug: string) => string | undefined = () => "filter",
|
||||
): number {
|
||||
return markUnpublishedLinks(published, removedPages(all, published, filteredBy))
|
||||
}
|
||||
|
||||
/** The Links instance marks links to removed pages after filtering (see build.ts). */
|
||||
export type LinksInstance = QuartzTransformerPluginInstance & { marksBrokenLinks: boolean }
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import { htmlToJsx } from "../../util/jsx"
|
||||
import { trace } from "../../util/trace"
|
||||
import { attributeError, originOf } from "../../util/pluginErrors"
|
||||
import { rejectingFilter } from "../../processors/filter"
|
||||
import { markUnpublishedLinks } from "../builtins/links"
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
|
||||
@@ -382,6 +383,24 @@ function populateVirtualPageHtmlAst(
|
||||
return virtualEntries.filter((ve) => !failed.has(ve))
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark links to pages that are not emitted: removed by a filter, or a folder / tag page no page
|
||||
* type generated (markUnpublishedLinks). Returns the pages whose links changed, which watch mode
|
||||
* re-emits although their source didn't change.
|
||||
*/
|
||||
function markLinksToUnpublishedPages(
|
||||
ctx: BuildCtx,
|
||||
content: ProcessedContent[],
|
||||
virtualEntries: VirtualEntry[],
|
||||
): Set<FullSlug> {
|
||||
const changed = new Set<FullSlug>()
|
||||
if (ctx.removedPages) {
|
||||
const generated = new Set<string>(virtualEntries.map((ve) => ve.vpSlug))
|
||||
markUnpublishedLinks(content, ctx.removedPages, generated, changed)
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>> = (userOpts) => {
|
||||
const defaults = userOpts?.defaults ?? {}
|
||||
const byPageType = userOpts?.byPageType ?? {}
|
||||
@@ -413,6 +432,8 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
|
||||
byPageType,
|
||||
)
|
||||
|
||||
markLinksToUnpublishedPages(ctx, content, virtualEntries)
|
||||
|
||||
if (virtualEntries.some((ve) => ve.fileBacked)) {
|
||||
ctx.trie = folderTrie(allFiles, virtualEntries)
|
||||
}
|
||||
@@ -507,6 +528,11 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
|
||||
|
||||
ctx.trie = folderTrie(allFiles, virtualEntries)
|
||||
|
||||
// a page whose links to a published / removed page changed is re-emitted too
|
||||
for (const slug of markLinksToUnpublishedPages(ctx, content, virtualEntries)) {
|
||||
changedSlugs.add(slug)
|
||||
}
|
||||
|
||||
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
|
||||
|
||||
// Render Body components to populate htmlAst for transclusion
|
||||
|
||||
@@ -49,6 +49,12 @@ export interface BuildCtx {
|
||||
* `.base` / `.canvas` pages).
|
||||
*/
|
||||
virtualPages: ProcessedContent[]
|
||||
/**
|
||||
* Pages the filters removed (and their aliases) → the filter, set after filtering when the
|
||||
* Links transformer marks broken links. PageTypeDispatcher marks links to them, and to folder
|
||||
* and tag pages no page type generated, once the virtual pages exist (markUnpublishedLinks).
|
||||
*/
|
||||
removedPages?: ReadonlyMap<string, string>
|
||||
/** Content-hashed asset filenames, populated by ComponentResources emitter */
|
||||
hashedResourceNames?: HashedResourceNames
|
||||
/** Maps CSS content strings to their emitted hashed filenames. Populated by ComponentResources. */
|
||||
|
||||
Reference in new issue
Block a user