mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
Merge pull request #2711 from jackyzha0/dev-mode/investigate-c
fix: broken marks for missing folder/tag pages, watch-mode re-emit, per-component CSS isolation, SPA scroll, stripDiacritics redirects, popover selector
This commit is contained in:
19 files changed
+467
-34
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Each component's CSS is parsed on its own before the component stylesheet is put together, so a missing `}` or an unclosed comment in one plugin's CSS no longer swallows the rules of every component after it, and a stray `}` no longer fails the build; a syntax error is reported with the component's name.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
A scroll made just before Back (less than 150 ms) is no longer lost: Forward returns to where the reader scrolled.
|
||||
@@ -2,4 +2,4 @@
|
||||
"@jackyzha0/quartz": minor
|
||||
---
|
||||
|
||||
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses; heading anchors keep their diacritics. Turning it on changes the URLs of existing pages; add the old addresses as `aliases` where links to them must keep working. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
|
||||
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses; heading anchors keep their diacritics. Turning it on changes the URLs of existing pages; their old addresses redirect to the new ones. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
|
||||
@@ -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.
|
||||
@@ -91,7 +91,7 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `stripDiacritics`: `true` strips accents and other diacritics from page, folder and file URLs, e.g. `české/čeština.md` is published at `/ceske/cestina` instead of `/české/čeština` (which browsers show as `%C4%8Desk%C3%A9/...` when copied). Off by default.
|
||||
- Links keep working as written in your notes: `[[čeština]]`, `[[české/čeština#Nadpis]]` and embeds like `![[obrázek.png]]` resolve to the stripped addresses. Aliases and `permalink`s are stripped the same way. Heading anchors (`#Nadpis`) keep their diacritics. Tag pages and the pages plugins generate from files (canvas, bases, …) are stripped too with `@quartz-community/utils` 1.3 or newer; with older versions they keep their diacritics.
|
||||
- Only Latin letters change: they lose their accents (`á č é ů …`), and Latin letters without a decomposition fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`). Other scripts (Chinese, Japanese, Korean, Greek, Cyrillic, Arabic, Hebrew, Devanagari, …) are left as written, marks included.
|
||||
- Turning it on changes the URLs of existing pages; links shared elsewhere to the old addresses will 404 unless you add the old addresses as `aliases`.
|
||||
- Turning it on changes the URLs of existing pages. Quartz writes a redirect from each page's, folder's and alias's old address (the slug with its diacritics) to the new one, so links shared elsewhere keep working. Old `permalink` addresses are not redirected; add them as `aliases` if they need to keep working.
|
||||
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
|
||||
- `theme`: configure how the site looks.
|
||||
- `fontOrigin`: where to load fonts from.
|
||||
|
||||
+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 {
|
||||
|
||||
@@ -32,7 +32,8 @@ async function mouseEnterHandler(
|
||||
if (hash !== "") {
|
||||
const inner = popoverElement.querySelector(".popover-inner") as HTMLElement | null
|
||||
if (inner) {
|
||||
const targetAnchor = `#popover-internal-${hash.slice(1)}`
|
||||
// ids are not CSS identifiers: block ids start with `^`, headings may start with a digit
|
||||
const targetAnchor = `#${CSS.escape(`popover-internal-${hash.slice(1)}`)}`
|
||||
const heading = inner.querySelector(targetAnchor) as HTMLElement | null
|
||||
if (heading) {
|
||||
// leave ~12px of buffer when scrolling to a heading
|
||||
|
||||
@@ -70,13 +70,43 @@ history.scrollRestoration = "manual"
|
||||
let renderedPath = window.location.pathname
|
||||
let saveTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
// Each entry the router creates gets a key, so a position that was still waiting to be saved
|
||||
// when Back or Forward left its entry (history.state is the new entry's by then) is kept here
|
||||
// and written to the entry when it is shown again.
|
||||
type EntryState = { key?: string; scrollY?: unknown } | null
|
||||
const newKey = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
const unsavedScroll = new Map<string, number>()
|
||||
let shownKey: string | undefined
|
||||
|
||||
function entryKey(): string {
|
||||
let key = (history.state as EntryState)?.key
|
||||
if (typeof key !== "string") {
|
||||
key = newKey()
|
||||
history.replaceState({ ...(history.state ?? {}), key }, "")
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
function pushEntry(url: URL) {
|
||||
history.pushState({ key: newKey() }, "", url)
|
||||
shownKey = entryKey()
|
||||
}
|
||||
|
||||
function saveScroll() {
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = undefined
|
||||
history.replaceState({ ...(history.state ?? {}), scrollY: window.scrollY }, "")
|
||||
}
|
||||
|
||||
function savedScroll(): number | undefined {
|
||||
const y = (history.state as { scrollY?: unknown } | null)?.scrollY
|
||||
const key = entryKey()
|
||||
const unsaved = unsavedScroll.get(key)
|
||||
if (unsaved !== undefined) {
|
||||
unsavedScroll.delete(key)
|
||||
history.replaceState({ ...(history.state ?? {}), scrollY: unsaved }, "")
|
||||
return unsaved
|
||||
}
|
||||
const y = (history.state as EntryState)?.scrollY
|
||||
return typeof y === "number" ? y : undefined
|
||||
}
|
||||
|
||||
@@ -185,7 +215,7 @@ async function _navigate(url: URL, isBack: boolean = false) {
|
||||
// delay setting the url until now
|
||||
// at this point everything is loaded so changing the url should resolve to the correct addresses
|
||||
if (!isBack) {
|
||||
history.pushState({}, "", finalUrl)
|
||||
pushEntry(finalUrl)
|
||||
}
|
||||
renderedPath = window.location.pathname
|
||||
|
||||
@@ -220,7 +250,7 @@ function createRouter() {
|
||||
if (isSamePage(url) && url.hash) {
|
||||
// Save where the reader was, then add the entry, then jump: Back returns here.
|
||||
saveScroll()
|
||||
history.pushState({}, "", url)
|
||||
pushEntry(url)
|
||||
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
|
||||
el?.scrollIntoView()
|
||||
return
|
||||
@@ -230,8 +260,13 @@ function createRouter() {
|
||||
})
|
||||
|
||||
window.addEventListener("popstate", () => {
|
||||
// Whatever is pending belongs to the entry just left.
|
||||
// Whatever is pending belongs to the entry just left: keep it for when it's shown again.
|
||||
if (saveTimer !== undefined && shownKey !== undefined) {
|
||||
unsavedScroll.set(shownKey, window.scrollY)
|
||||
}
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = undefined
|
||||
shownKey = entryKey()
|
||||
// Back or Forward between headings of the page on screen: only scroll.
|
||||
if (window.location.pathname === renderedPath) {
|
||||
restoreScroll()
|
||||
@@ -257,6 +292,7 @@ function createRouter() {
|
||||
window.addEventListener("pagehide", () => {
|
||||
if (!isNavigating) saveScroll()
|
||||
})
|
||||
shownKey = entryKey()
|
||||
if (savedScroll() !== undefined) restoreScroll()
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { Features, transform } from "lightningcss"
|
||||
import { transform as transpile } from "esbuild"
|
||||
import { write } from "./helpers"
|
||||
import { isolateComponentCss } from "../../util/componentCss"
|
||||
|
||||
/**
|
||||
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
|
||||
@@ -39,6 +40,8 @@ type ComponentResources = {
|
||||
beforeDOMLoaded: string[]
|
||||
afterDOMLoaded: string[]
|
||||
componentCssStrings: Set<string>
|
||||
/** Component CSS → the component that brought it, to name it in warnings. */
|
||||
cssOwners: Map<string, string>
|
||||
}
|
||||
|
||||
function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
@@ -61,9 +64,13 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
afterDOMLoaded: new Set<string>(),
|
||||
}
|
||||
|
||||
const cssOwners = new Map<string, string>()
|
||||
for (const component of allComponents) {
|
||||
const { css, beforeDOMLoaded, afterDOMLoaded } = component
|
||||
for (const c of normalizeResource(css)) componentResources.css.add(c)
|
||||
for (const c of normalizeResource(css)) {
|
||||
componentResources.css.add(c)
|
||||
if (!cssOwners.has(c)) cssOwners.set(c, component.displayName ?? component.name ?? "")
|
||||
}
|
||||
for (const b of normalizeResource(beforeDOMLoaded)) componentResources.beforeDOMLoaded.add(b)
|
||||
for (const a of normalizeResource(afterDOMLoaded)) componentResources.afterDOMLoaded.add(a)
|
||||
}
|
||||
@@ -73,6 +80,7 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
beforeDOMLoaded: [...componentResources.beforeDOMLoaded],
|
||||
afterDOMLoaded: [...componentResources.afterDOMLoaded],
|
||||
componentCssStrings: new Set(componentResources.css),
|
||||
cssOwners,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,7 +444,10 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
|
||||
const cssStringToFilename = new Map<string, string>()
|
||||
const componentCss = [...componentResources.componentCssStrings]
|
||||
if (componentCss.length > 0) {
|
||||
const wrapped = `@layer quartz-base {\n${componentCss.join("\n")}\n}`
|
||||
const isolated = componentCss.map((c) =>
|
||||
isolateComponentCss(c, componentResources.cssOwners.get(c)),
|
||||
)
|
||||
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
|
||||
const minified = transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(wrapped),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export { Assets } from "./assets"
|
||||
export { Static } from "./static"
|
||||
export { ComponentResources } from "./componentResources"
|
||||
export { SlugRedirects } from "./slugRedirects"
|
||||
@@ -0,0 +1,52 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { describe } from "node:test"
|
||||
import { VFile } from "vfile"
|
||||
import { Root } from "hast"
|
||||
import { ProcessedContent } from "../vfile"
|
||||
import { FilePath, FullSlug, setSlugOptions, slugifyFilePath } from "../../util/path"
|
||||
import { strippedAddressMoves } from "./slugRedirects"
|
||||
|
||||
const page = (
|
||||
relativePath: string,
|
||||
frontmatter: Record<string, unknown> = {},
|
||||
): ProcessedContent => {
|
||||
const file = new VFile("")
|
||||
file.data = {
|
||||
relativePath: relativePath as FilePath,
|
||||
slug: slugifyFilePath(relativePath as FilePath),
|
||||
frontmatter: { title: relativePath, ...frontmatter },
|
||||
} as VFile["data"]
|
||||
return [{ type: "root", children: [] } as Root, file]
|
||||
}
|
||||
|
||||
describe("redirects from addresses slugs.stripDiacritics changed", () => {
|
||||
test("pages, their folders and aliases redirect from the unstripped address", () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
const content = [
|
||||
page("české/Žluťoučký kůň/poznámka.md", { aliases: ["stará"] }),
|
||||
page("plain/note.md"),
|
||||
]
|
||||
const live = new Set(content.map(([, f]) => f.data.slug!))
|
||||
assert.deepEqual(Object.fromEntries(strippedAddressMoves(content, live)), {
|
||||
"české/žluťoučký-kůň/poznámka": "ceske/zlutoucky-kun/poznamka",
|
||||
"české/index": "ceske/index",
|
||||
"české/žluťoučký-kůň/index": "ceske/zlutoucky-kun/index",
|
||||
stará: "ceske/zlutoucky-kun/poznamka",
|
||||
})
|
||||
} finally {
|
||||
setSlugOptions(undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test("an old address that is a page of the site is left alone", () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
const content = [page("café.md")]
|
||||
const live = new Set(["café" as FullSlug, "cafe" as FullSlug])
|
||||
assert.equal(strippedAddressMoves(content, live).size, 0)
|
||||
} finally {
|
||||
setSlugOptions(undefined)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { ProcessedContent } from "../vfile"
|
||||
import {
|
||||
FilePath,
|
||||
FullSlug,
|
||||
getSlugOptions,
|
||||
resolveRelative,
|
||||
setSlugOptions,
|
||||
simplifySlug,
|
||||
slugifyFilePath,
|
||||
} from "../../util/path"
|
||||
import { write } from "./helpers"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
|
||||
/** The slug `fp` had without `slugs.stripDiacritics` (lowercased, diacritics kept). */
|
||||
function unstrippedSlug(fp: string): FullSlug {
|
||||
const options = getSlugOptions()
|
||||
setSlugOptions({ ...options, stripDiacritics: false })
|
||||
try {
|
||||
return slugifyFilePath(fp as FilePath)
|
||||
} finally {
|
||||
setSlugOptions(options)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The addresses `slugs.stripDiacritics` changed → where they moved: every published page's
|
||||
* address as it was without the option (`české/žluťoučký-kůň/poznámka` →
|
||||
* `ceske/zlutoucky-kun/poznamka`), its folders' (`české/` → `ceske/`) and its aliases'. An old
|
||||
* address that is a page of the site, or another old address's, is left alone.
|
||||
*/
|
||||
export function strippedAddressMoves(
|
||||
content: ProcessedContent[],
|
||||
live: ReadonlySet<string>,
|
||||
): Map<FullSlug, FullSlug> {
|
||||
const moves = new Map<FullSlug, FullSlug>()
|
||||
const add = (from: FullSlug, to: FullSlug) => {
|
||||
if (from === to || live.has(from) || moves.has(from)) return
|
||||
moves.set(from, to)
|
||||
}
|
||||
for (const [, file] of content) {
|
||||
const { slug, relativePath } = file.data
|
||||
if (!slug || !relativePath) continue
|
||||
const old = unstrippedSlug(relativePath)
|
||||
const now = slugifyFilePath(relativePath as FilePath)
|
||||
// a page at its file path (not a permalink) moved with it
|
||||
if (now === slug) add(old, slug)
|
||||
// its folders: `české/žluťoučký-kůň/x` → `české/index`, `české/žluťoučký-kůň/index`
|
||||
const oldParts = old.split("/")
|
||||
const nowParts = now.split("/")
|
||||
if (oldParts.length === nowParts.length) {
|
||||
for (let i = 1; i < oldParts.length; i++) {
|
||||
add(
|
||||
[...oldParts.slice(0, i), "index"].join("/") as FullSlug,
|
||||
[...nowParts.slice(0, i), "index"].join("/") as FullSlug,
|
||||
)
|
||||
}
|
||||
}
|
||||
for (const alias of (file.data.frontmatter?.aliases as unknown[] | undefined) ?? []) {
|
||||
if (typeof alias !== "string") continue
|
||||
const fp = alias.endsWith(".md") ? alias : `${alias}.md`
|
||||
add(unstrippedSlug(fp), slug)
|
||||
}
|
||||
}
|
||||
return moves
|
||||
}
|
||||
|
||||
function redirectHtml(to: string, url: string): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<title>${to}</title>
|
||||
<link rel="canonical" href="${url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="refresh" content="0; url=${url}">
|
||||
</head>
|
||||
</html>
|
||||
`
|
||||
}
|
||||
|
||||
async function* emitMoves(ctx: BuildCtx, content: ProcessedContent[]) {
|
||||
if (!getSlugOptions().stripDiacritics) return
|
||||
const live = new Set<string>()
|
||||
for (const [, file] of content) {
|
||||
if (file.data.slug) live.add(file.data.slug)
|
||||
for (const alias of file.data.aliases ?? []) live.add(alias)
|
||||
}
|
||||
for (const [from, to] of strippedAddressMoves(content, live)) {
|
||||
const url = resolveRelative(from, simplifySlug(to) as unknown as FullSlug)
|
||||
yield write({ ctx, slug: from, ext: ".html", content: redirectHtml(simplifySlug(to), url) })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* With `configuration.slugs.stripDiacritics`, pages, folders and aliases whose names have
|
||||
* diacritics get new addresses. This writes a redirect at each old address (as Quartz 5 slugged
|
||||
* it: lowercased, diacritics kept) to the new one, so links and bookmarks to the old site keep
|
||||
* working. alias-redirects' case redirects only cover the address as spelled in the vault.
|
||||
*/
|
||||
export const SlugRedirects: QuartzEmitterPlugin = () => ({
|
||||
name: "SlugRedirects",
|
||||
emit: (ctx, content) => emitMoves(ctx, content),
|
||||
partialEmit: (ctx, content) => emitMoves(ctx, content),
|
||||
})
|
||||
@@ -749,6 +749,7 @@ export async function loadQuartzConfig(
|
||||
builtinPlugins.ComponentResources(),
|
||||
builtinPlugins.Assets(),
|
||||
builtinPlugins.Static(),
|
||||
builtinPlugins.SlugRedirects(),
|
||||
]
|
||||
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { describe } from "node:test"
|
||||
import { Features, transform } from "lightningcss"
|
||||
import { isolateComponentCss } from "./componentCss"
|
||||
|
||||
/** The component stylesheet as ComponentResources builds it. */
|
||||
const sheet = (chunks: string[]) =>
|
||||
transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(
|
||||
`@layer quartz-base {\n${chunks.map((c) => isolateComponentCss(c, "Bad")).join("\n")}\n}`,
|
||||
),
|
||||
minify: true,
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
|
||||
describe("isolateComponentCss", () => {
|
||||
const later = ".later{color:red}"
|
||||
for (const [what, bad] of [
|
||||
["a missing }", ".bad{color:blue"],
|
||||
["an unclosed comment", ".bad{color:blue} /* note"],
|
||||
["an unclosed @media", ".bad{color:blue} @media (min-width: 1px) { .x { color: red }"],
|
||||
["an unclosed string", '.bad{content:"x'],
|
||||
]) {
|
||||
test(`${what} in one component doesn't swallow the next one's rules`, () => {
|
||||
assert.match(sheet([bad, later]), /@layer quartz-base\{.*\.later\{color:red\}\}$/)
|
||||
})
|
||||
}
|
||||
|
||||
test("a stray } doesn't fail the stylesheet", () => {
|
||||
assert.match(sheet([".bad{color:blue}}", later]), /\.bad\{color:#00f\}.*\.later\{color:red\}/)
|
||||
})
|
||||
|
||||
test("balanced CSS comes out as it did before", () => {
|
||||
const css = ".a{color:red;& .b{margin:0}}@media (max-width:800px){.a{display:none}}"
|
||||
const raw = transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(`@layer quartz-base {\n${css}\n${later}\n}`),
|
||||
minify: true,
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
assert.equal(sheet([css, later]), raw)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { transform } from "lightningcss"
|
||||
import { recordDiagnostic } from "./diagnostics"
|
||||
|
||||
/**
|
||||
* One component's CSS, parsed on its own and printed back balanced. All components' CSS goes
|
||||
* into one stylesheet: an unclosed `{`, `/*` or string in one would swallow every later
|
||||
* component's rules, and a stray `}` close the shared layer (and fail the build). Parsed alone,
|
||||
* the end of the chunk closes what it left open, as a stylesheet of its own would in a browser;
|
||||
* a chunk that doesn't parse is printed with the rules that do, with a warning naming the
|
||||
* component.
|
||||
*/
|
||||
export function isolateComponentCss(css: string, owner = ""): string {
|
||||
const name = owner ? `component ${owner}` : "a component"
|
||||
const parse = (errorRecovery: boolean) =>
|
||||
transform({ filename: "component.css", code: Buffer.from(css), errorRecovery })
|
||||
try {
|
||||
return parse(false).code.toString()
|
||||
} catch (err) {
|
||||
const loc = (err as { loc?: { line: number; column: number } }).loc
|
||||
recordDiagnostic({
|
||||
severity: "warning",
|
||||
area: "css",
|
||||
message:
|
||||
`The CSS of ${name} has a syntax error (${(err as Error).message}` +
|
||||
`${loc ? ` at line ${loc.line}, column ${loc.column}` : ""}); the rules that parse are kept.`,
|
||||
})
|
||||
try {
|
||||
return parse(true).code.toString()
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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