Compare commits

..
Author SHA1 Message Date
saberzero1 2635c6080a fix(links): don't decode link targets twice under slugs.stripDiacritics
slugOptionsOnLinkPath decoded and stripped the target's path before transformLink, which
decodes it again and (utils 1.3) strips diacritics itself. It changed nothing for any link
except one with a percent-encoded % (`%2520`), which it turned into a space, so the link
pointed at the wrong slug and was marked broken. Removed; the stripDiacritics link tests
still pass without it.
2026-11-27 04:45:48 +01:00
saberzero1 149c82f1da test: cover 5.3 changes the mutation audit found untested
- SlugRedirects emitter (emit/partialEmit, gating, live set, relative targets)
- loadQuartzConfig with extends: default (merged configuration, plugins,
  layout; before/after against built-ins; JSON configs)
- fetchRemoteConfig: offline cache, http redirect, 1 MB limit (bytes),
  memoisation counted, retry after a failure; non-object base; cycle chain
- resolveTarget refuses http URLs that contain https://
- orderPlugins with several before/after targets
- plugin entry keys before/after accepted by the CLI validator
- Head on the 404 page and tag pages
- isolateComponentCss warning; componentStylesheet extracted from
  ComponentResources so the test uses the emitter's own wrapping
- dateIsFromFrontmatter, pluginMatchKey without name/subdir
- todo: stripDiacritics link paths decode a percent-encoded % twice
2026-11-27 04:44:46 +01:00
Emile Bangma 29be20f41c Merge pull request #2712 from jackyzha0/dev-mode/block-id-caret
fix: block anchors are #^id, separate from headings (as in Obsidian)
2026-11-27 00:44:05 +01:00
saberzero1 f7b41e7bbf chore(deps): block anchors #^id (utils 1.3.2, rehype-obsidian 1.6.0 via OFM 2.5.3, GFM 2.2.2, canvas-page 1.1.4, note-properties 1.2.3, bases-page 1.5.5) 2026-11-27 00:42:31 +01:00
saberzero1 7c24cc66e1 Merge remote-tracking branch 'origin/v5' into dev-mode/block-id-caret 2026-11-27 00:41:24 +01:00
saberzero1 3df0062b6f fix(transclude): find blocks by their lowercased name; docs for #^id block anchors 2026-11-27 00:22:34 +01:00
Emile Bangma beca3bc26d 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
2026-11-27 00:21:42 +01:00
20 changed files with 726 additions and 101 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Block anchors are `#^id`, as in Obsidian: `@quartz-community/utils` 1.3.2 and `@quartz-community/rehype-obsidian` 1.6.0, bundled by obsidian-flavored-markdown 2.5.3, github-flavored-markdown 2.2.2, canvas-page 1.1.4, note-properties 1.2.3 and bases-page 1.5.5, give blocks `id="^id"` and link to them as `#^id`. A block and a heading with the same name (`^para-1`, `## Para 1`) no longer share an id, so `[[#^para-1]]` and `[[#Para 1]]` each reach their own target. canvas-page also scopes the ids of text nodes rendered with `textNodeMarkdown: basic`.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Block anchors are `#^id`: with @quartz-community/utils 1.3.2 and rehype-obsidian 1.6.0, blocks get the id `^id` and links to them `#^id` (was `#id`), as in Obsidian, so block `^para-1` and heading `## Para 1` no longer share an id. A block transclusion finds its block whatever the case of its `^id` (`![[note#^Para-1]]`), and the popover scrolls to a block it links to.
+2 -1
View File
@@ -65,5 +65,6 @@ Heading ids follow the GitHub rule (`github-slugger`, as `rehype-slug` and the t
- `slugHeading(text)`: the id of a heading with this text;
- `HeadingSlugger`: slugs all headings of one page in order and numbers repeats (`foo`, `foo-1`, …) — create one per page;
- `obsidianHeadingAnchor(text)`: the anchor Obsidian writes for a heading (it replaces `:`, `|`, `^`, `#` and `\` with spaces); slug it with `slugHeading` and add it as an extra id when it differs;
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, a block reference `#^name`, or a heading's text);
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, or a heading's text); a block reference `#^name` always points at the block (`#^name`), never at a heading;
- `blockAnchor(name)`: the anchor of the block `^name`, `#^name` (lowercased). Blocks have the id `^name`, so they never share an id with a heading;
- `slugTag(tag)`: the slug of a tag, as used for tag pages.
+1
View File
@@ -39,6 +39,7 @@ npx quartz plugin install --latest
### Changes you may notice
- **Block anchors**: a block's id is now `^id` and links to it are `#^id` (`[[note#^para-1]]` → `note#^para-1`, was `note#para-1`), as in Obsidian, where blocks and headings are separate namespaces: block `^para-1` and heading `## Para 1` no longer share an id, so `[[#^para-1]]` and `[[#Para 1]]` each land on their own target. Links inside the site are regenerated; old `#id` URLs of blocks from outside the site now go to the top of the page (or to a heading of that name). CSS or scripts that select a block by id need `#\^para-1` (or `getElementById`).
- **Unresolved links**: `configuration.links.disableBrokenWikilinks` is now on by default. Links to pages that don't exist get the `broken` class and are styled as unresolved, as in Obsidian. Links to pages a filter removes (drafts, unpublished notes) are marked the same way, with `data-filtered="<filter>"`. Set `links.disableBrokenWikilinks: false` to style them as before.
- **Mermaid diagrams** render with [Pele](https://pele.run) by default, as in Obsidian, inside a `<div class="mermaid">` rather than a code block. Set `diagramRenderer: mermaid` on [[ObsidianFlavoredMarkdown]] to keep Mermaid.js. See [[Mermaid diagrams]].
- **Block wrappers**: each top-level block of a note is wrapped in the `div` Obsidian puts it in (`div.el-p > p`, `div.el-h2 > h2`). Custom CSS that selects a page's blocks as direct children (`article > p`) no longer matches. Select them without `>`, or set `blockWrappers: false` on ObsidianFlavoredMarkdown.
+33 -33
View File
@@ -16,9 +16,9 @@
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.4",
"@quartz-community/bases-page": "^1.5.5",
"@quartz-community/breadcrumbs": "^1.0.5",
"@quartz-community/canvas-page": "^1.1.2",
"@quartz-community/canvas-page": "^1.1.4",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
@@ -33,12 +33,12 @@
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.3",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.1",
"@quartz-community/github-flavored-markdown": "^2.2.2",
"@quartz-community/graph": "^1.0.8",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.2",
"@quartz-community/note-properties": "^1.2.2",
"@quartz-community/obsidian-flavored-markdown": "^2.5.2",
"@quartz-community/note-properties": "^1.2.3",
"@quartz-community/obsidian-flavored-markdown": "^2.5.3",
"@quartz-community/og-image": "^1.1.3",
"@quartz-community/ox-hugo": "^1.0.3",
"@quartz-community/page-title": "^1.0.2",
@@ -97,7 +97,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.2",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
@@ -2330,14 +2330,14 @@
}
},
"node_modules/@quartz-community/bases-page": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.4.tgz",
"integrity": "sha512-WDUQ/FGMz3ynQbHCt/SCn6nAbEfkvK/isfxqKHbfQTl1e1eSBc4AImux9wtJSLpnCriwV9w7ChZpLidDRigk6Q==",
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.5.tgz",
"integrity": "sha512-aUJgKt3KjP2UOT4sfeHugkwMyptqXpkRBrHiOthyEND2NI43kZUTNQ2FicTZQLDMLOSnuUu4PXgHv0NF4Ntyrw==",
"license": "MIT",
"dependencies": {
"@lucide/icons": "^1.70.0",
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2383,13 +2383,13 @@
}
},
"node_modules/@quartz-community/canvas-page": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.2.tgz",
"integrity": "sha512-dAsTC/cGVdMQqxF+hJxppln3nNDjLOY9FxGszTBOWSFoyylciaoCKiqpdfJcgeVtI4JNUvFZ/kofaWcpW7FDkA==",
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.4.tgz",
"integrity": "sha512-HNvwpnIbv887epOKTKcr1fMV9cSN6JjQw7mxNSiBJSSe9dtYUu4F7FPIFE33JFSWOpilDgV6f+ApnYVQ1c9yaA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2712,13 +2712,13 @@
}
},
"node_modules/@quartz-community/github-flavored-markdown": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/github-flavored-markdown/-/github-flavored-markdown-2.2.1.tgz",
"integrity": "sha512-i1FwY8AY7d78TOs665XGgeGRZT2EefUZ8hZu35E0sNFiX09VrnSzGz0NmnamFYBMkmEc55R3N6gNtoqLVMr2Kw==",
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/@quartz-community/github-flavored-markdown/-/github-flavored-markdown-2.2.2.tgz",
"integrity": "sha512-JsSeydLs05VZj2jc2KT/5vse+zNGCDH92Ih8/yp5s6EUY+wwOmzSTPxT65Ey0LK/X/nclfkMu4S4Domd2RkwmA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.1.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2802,13 +2802,13 @@
}
},
"node_modules/@quartz-community/note-properties": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.2.tgz",
"integrity": "sha512-qyrNdL+Yveb1/mdN23B0yACvuDMDKPsPhTvATisaN4h0dNS/4i/Nu6J6W1wbcN3t1tKhE7cdNWMYpabay+l42g==",
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.3.tgz",
"integrity": "sha512-udQ8hWrkX9V1tcrxyxRniE8QkFXHAp1AFYjhZ9ZcRFNdSxgyu7Q18vHRl65jrW7MKoApN6VB3dOjUwiM1hn88A==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2828,15 +2828,15 @@
}
},
"node_modules/@quartz-community/obsidian-flavored-markdown": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.2.tgz",
"integrity": "sha512-t30nSwmEVLvIw4LnOp+iAe3ZcJNy2Bew+luAL425Ek/XM6udXkIzaafEhjXQXTN34k8/6rjvat1w2HGepdv/nw==",
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.3.tgz",
"integrity": "sha512-nevXFettUGuQemzqcXkDiUjKLeUKQ36RkITQx36G56gAB1TkrHv03gP4iX9EVXHi/9ZCSlgDdyHIkDRgP0lL4Q==",
"license": "MIT",
"dependencies": {
"@quartz-community/rehype-obsidian": "^1.5.1",
"@quartz-community/rehype-obsidian": "^1.6.0",
"@quartz-community/remark-obsidian": "^2.2.4",
"@quartz-community/types": "^1.1.0",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.2",
"pele": "^1.13.0"
},
"engines": {
@@ -2970,9 +2970,9 @@
}
},
"node_modules/@quartz-community/rehype-obsidian": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.5.1.tgz",
"integrity": "sha512-PvU1JCyAndgbkjPeFaPs1r/FnijtTFTDetn9F8mUBRGB9zEDEGIHqpo+/LZvQQUP46eCbRUXkz2RVc72g0V/UQ==",
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.6.0.tgz",
"integrity": "sha512-7NyJNKr515xtCBBhzLr4UdoENutGPgAJhh3GA0S3j6Qj2r7v+hFNSq4yd3gtFP0GK7b4PPfOtTTyAWCC8BYiig==",
"license": "MIT",
"engines": {
"node": ">=22"
@@ -3230,9 +3230,9 @@
}
},
"node_modules/@quartz-community/utils": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.1.tgz",
"integrity": "sha512-HGlcmwzt+nzu77sVfERtGFgw9CqO0/sApDX4RBM4pJZOxBDFKOL+5aKOw3TlHUW+57GJeDO1QM464foXbp+VWQ==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.2.tgz",
"integrity": "sha512-50SiiB1HY2zdpjO7SUJklITcFqH/sJNq6PE1a8dtc8HIvQfPW4kXALoiPUqvaYzcBVscnkZ9rfmlSgn/vaA4eA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
+6 -6
View File
@@ -46,9 +46,9 @@
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.4",
"@quartz-community/bases-page": "^1.5.5",
"@quartz-community/breadcrumbs": "^1.0.5",
"@quartz-community/canvas-page": "^1.1.2",
"@quartz-community/canvas-page": "^1.1.4",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
@@ -63,12 +63,12 @@
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.3",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.1",
"@quartz-community/github-flavored-markdown": "^2.2.2",
"@quartz-community/graph": "^1.0.8",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.2",
"@quartz-community/note-properties": "^1.2.2",
"@quartz-community/obsidian-flavored-markdown": "^2.5.2",
"@quartz-community/note-properties": "^1.2.3",
"@quartz-community/obsidian-flavored-markdown": "^2.5.3",
"@quartz-community/og-image": "^1.1.3",
"@quartz-community/ox-hugo": "^1.0.3",
"@quartz-community/page-title": "^1.0.2",
@@ -124,7 +124,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.2",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
+30
View File
@@ -198,6 +198,36 @@ describe("validatePluginEntry", () => {
)
})
test("accepts before, after and every layout key", () => {
assert.deepStrictEqual(
validatePluginEntry({
source: "@quartz-community/description",
enabled: true,
order: 60,
before: "Links",
after: ["obsidian-flavored-markdown"],
layout: {
position: "right",
priority: 5,
display: "desktop-only",
condition: "not-index",
group: "toolbar",
groupOptions: { grow: true },
},
}),
[],
)
})
test("an unknown key without a close match lists the allowed keys", () => {
assert.deepStrictEqual(
validatePluginEntry({ source: "x/y", enabled: true, zzzzzz: 1 }).map((i) => i.message),
[
'unknown key "zzzzzz" is ignored (allowed: source, enabled, options, order, before, after, layout)',
],
)
})
test("catches typoed keys and a missing enabled flag", () => {
const issues = validatePluginEntry({ source: "x/y", enable: true, option: {} })
const messages = issues.map((i) => i.message).join("\n")
+33
View File
@@ -64,4 +64,37 @@ describe("Head", () => {
})
assert.strictEqual(meta(html, "article:modified_time"), undefined)
})
test("the 404 page: no canonical, no article meta, og:url is the site's address", () => {
const real = new Date("2024-05-06T00:00:00Z")
// as the 404 page type generates it (a virtual page gets `404.md` as its relativePath)
const html = head({
slug: "404",
relativePath: "404.md",
frontmatter: { title: "Not Found", tags: [] },
dates: { created: real, modified: real, published: real },
})
assert.strictEqual(meta(html, "og:type"), "website")
assert.strictEqual(meta(html, "og:url"), "https://example.org/")
assert.strictEqual(meta(html, "twitter:url"), "https://example.org/")
assert.doesNotMatch(html, /rel="canonical"/)
assert.doesNotMatch(html, /article:/)
// a note has all three
const note = head({
slug: "notes/a b",
dates: { created: real, modified: real, published: real },
})
assert.strictEqual(meta(note, "og:url"), "https://example.org/notes/a%20b")
assert.match(note, /<link rel="canonical" href="https:\/\/example.org\/notes\/a%20b"\/>/)
assert.strictEqual(meta(note, "article:modified_time"), real.toISOString())
})
test("tag pages and pages without a file are not articles", () => {
assert.strictEqual(meta(head({ slug: "tags/recipes" }), "og:type"), "website")
assert.strictEqual(meta(head({ slug: "tags/food/recipes" }), "og:type"), "website")
// a note in a folder named like the tag folder is still an article
assert.strictEqual(meta(head({ slug: "notes/tags/recipes" }), "og:type"), "article")
assert.strictEqual(meta(head({ slug: "my-tags/x" }), "og:type"), "article")
assert.strictEqual(meta(head({ slug: "a", relativePath: undefined }), "og:type"), "website")
})
})
+42
View File
@@ -120,6 +120,48 @@ describe("renderTranscludes", () => {
assert.ok(texts.includes("Target content"), "transcluded content should be inlined")
})
test("a block transclusion finds the block by its name and scopes its ^id", () => {
const block: Element = {
type: "element",
tagName: "p",
properties: { id: "^para-1" },
children: [
{ type: "text", value: "Block text " },
{
type: "element",
tagName: "a",
properties: { href: "#^para-1" },
children: [{ type: "text", value: "self" }],
},
],
}
const heading: Element = {
type: "element",
tagName: "h2",
properties: { id: "para-1" },
children: [{ type: "text", value: "Para 1" }],
}
const targetHtml: Root = { type: "root", children: [heading, block] }
const allFiles = [makePageData("target", targetHtml, { blocks: { "para-1": block } })]
const root: Root = {
type: "root",
children: [makeTranscludeBlockquote("target", "#^Para-1")],
}
renderTranscludes(
root,
cfg,
"current" as FullSlug,
makeComponentData(allFiles) as QuartzComponentProps,
new Set<FullSlug>(["current" as FullSlug]),
)
const html = toHtml(root)
assert.ok(html.includes("Block text"), html)
assert.ok(!html.includes("Para 1"), "the heading of the same name isn't transcluded")
const id = /<p id="([^"]+)"/.exec(html)?.[1]
assert.ok(id?.endsWith("^para-1") && id !== "^para-1", `scoped block id, got ${id}`)
assert.ok(html.includes(`href="#${id}"`), "the link inside points at the scoped id")
})
test("allows the same page to be embedded twice as siblings", () => {
const root: Root = {
type: "root",
+3 -2
View File
@@ -308,8 +308,9 @@ export function renderTranscludes(
let blockRef = el.properties.dataBlock as string | undefined
if (blockRef?.startsWith("#^")) {
// block transclude
blockRef = blockRef.slice("#^".length)
// block transclude: `data.blocks` is keyed by the block's name, lowercased (`para-1`); the
// block element's id is `^para-1` (rehype-obsidian), its anchor `#^para-1`
blockRef = blockRef.slice("#^".length).toLowerCase()
let blockNode = page.blocks?.[blockRef]
if (blockNode) {
if (blockNode.tagName === "li") {
+21 -2
View File
@@ -41,8 +41,8 @@ import {
import type { PluginJsonEntry } from "../loader/types"
import type { BuildCtx } from "../../util/ctx"
import type { ContentDetails } from "../types"
import type { FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions } from "../../util/path"
import type { FilePath, FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions, slugifyFilePath } from "../../util/path"
import type { ProcessedContent } from "../vfile"
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
@@ -464,6 +464,25 @@ describe("links built-in", () => {
}
})
test("slugs.stripDiacritics: a percent-encoded % in a link target is decoded once", () => {
setSlugOptions({ stripDiacritics: true })
try {
// `Kódování/Mezera je %20.md`, linked as Obsidian writes a Markdown link to it
const target = slugifyFilePath("Kódování/Mezera je %20.md" as FilePath)
assert.strictEqual(target, "kodovani/mezera-je--percent20")
const { els } = run(
[a("K%C3%B3dov%C3%A1n%C3%AD/Mezera%20je%20%2520.md")],
"index",
{ markdownLinkResolution: "shortest" },
["index", target],
)
assert.strictEqual(els[0].properties.href, "./kodovani/mezera-je--percent20")
assert.ok(!(els[0].properties.className as string[]).includes("broken"))
} finally {
setSlugOptions(undefined)
}
})
test("without slugs.stripDiacritics link targets keep their diacritics", () => {
const { els } = run([a("Příliš")], "page", { markdownLinkResolution: "shortest" }, [
"page",
+1 -25
View File
@@ -15,8 +15,6 @@ import {
resolveRelative,
simplifySlug,
slugifyFilePath,
applySlugOptions,
getSlugOptions,
splitAnchor,
stripSlashes,
transformLink,
@@ -235,28 +233,6 @@ export function markLinksToRemovedPages(
/** 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,
* so the path part of the target is stripped the same way before it is resolved (wikilinks
* from obsidian-flavored-markdown are slugged with the plain rules first). The `#anchor` is
* left alone: heading ids keep their diacritics.
*/
function slugOptionsOnLinkPath(raw: string): string {
if (!getSlugOptions().stripDiacritics) return raw
const hash = raw.indexOf("#")
const linkPath = hash === -1 ? raw : raw.slice(0, hash)
const anchor = hash === -1 ? "" : raw.slice(hash)
let decoded = linkPath
try {
decoded = decodeURI(linkPath)
} catch {
// not percent-encoded (or malformed): strip as written
}
const stripped = applySlugOptions(decoded)
return stripped === decoded ? raw : stripped + anchor
}
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const opts = { ...linksDefaults, ...userOpts }
const instance: LinksInstance = {
@@ -283,7 +259,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, slugOptionsOnLinkPath(raw), transformOptions)
const rel = transformLink(pathSlug, raw, transformOptions)
if (!rebase) return rel
const hash = rel.indexOf("#")
const anchor = hash === -1 ? "" : rel.slice(hash)
+5 -11
View File
@@ -25,7 +25,7 @@ import {
import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild"
import { write } from "./helpers"
import { isolateComponentCss } from "../../util/componentCss"
import { componentStylesheet } from "../../util/componentCss"
/**
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
@@ -444,17 +444,11 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
const cssStringToFilename = new Map<string, string>()
const componentCss = [...componentResources.componentCssStrings]
if (componentCss.length > 0) {
const isolated = componentCss.map((c) =>
isolateComponentCss(c, componentResources.cssOwners.get(c)),
const minified = componentStylesheet(
componentCss,
(c) => componentResources.cssOwners.get(c),
lightningTargets,
)
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
const minified = transform({
filename: "component.css",
code: Buffer.from(wrapped),
minify: true,
targets: lightningTargets,
include: Features.MediaQueries,
}).code.toString()
const hash = hashContent(minified)
const slug = `component-${hash}`
+98 -2
View File
@@ -1,10 +1,15 @@
import assert from "node:assert/strict"
import test, { describe } from "node:test"
import test, { afterEach, describe } from "node:test"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { VFile } from "vfile"
import { Root } from "hast"
import { ProcessedContent } from "../vfile"
import { FilePath, FullSlug, setSlugOptions, slugifyFilePath } from "../../util/path"
import { strippedAddressMoves } from "./slugRedirects"
import { BuildCtx } from "../../util/ctx"
import type { StaticResources } from "../../util/resources"
import { SlugRedirects, strippedAddressMoves } from "./slugRedirects"
const page = (
relativePath: string,
@@ -50,3 +55,94 @@ describe("redirects from addresses slugs.stripDiacritics changed", () => {
}
})
})
describe("SlugRedirects emitter", () => {
const tempDirs: string[] = []
afterEach(async () => {
setSlugOptions(undefined)
await Promise.all(tempDirs.splice(0).map((dir) => fs.promises.rm(dir, { recursive: true })))
})
/** Runs `emit` (or `partialEmit`) into a temp output dir → output path → file contents. */
const emitAll = async (content: ProcessedContent[], partial = false) => {
const output = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-slug-redirects-"))
tempDirs.push(output)
const ctx = { argv: { output } } as unknown as BuildCtx
const plugin = SlugRedirects()
assert.equal(plugin.name, "SlugRedirects")
const emitted = partial
? plugin.partialEmit!(ctx, content, {} as StaticResources, [])
: plugin.emit(ctx, content, {} as StaticResources)
const written: Record<string, string> = {}
for await (const fp of emitted as AsyncIterable<string>) {
written[path.relative(output, fp).split(path.sep).join("/")] = await fs.promises.readFile(
fp,
"utf8",
)
}
return written
}
const redirect = (to: string, url: string) => `<!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>
`
const withAliases = (content: ProcessedContent, aliases: string[]): ProcessedContent => {
content[1].data.aliases = aliases as FullSlug[]
return content
}
test("writes a redirect at each unstripped address to the stripped one", async () => {
setSlugOptions({ stripDiacritics: true })
const content = [withAliases(page("české/Čeština.md", { aliases: ["stará"] }), ["stara"])]
assert.equal(content[0][1].data.slug, "ceske/cestina")
const expected = {
"české/čeština.html": redirect("ceske/cestina", "../ceske/cestina"),
"české/index.html": redirect("ceske/", "../ceske/"),
"stará.html": redirect("ceske/cestina", "./ceske/cestina"),
}
assert.deepEqual(await emitAll(content), expected)
assert.deepEqual(await emitAll(content, true), expected)
})
test("the redirect target is relative to the nested old address", async () => {
setSlugOptions({ stripDiacritics: true })
const written = await emitAll([page("Ä/b/Über.md")])
assert.deepEqual(written, {
"ä/b/über.html": redirect("a/b/uber", "../../a/b/uber"),
"ä/b/index.html": redirect("a/b/", "../../a/b/"),
"ä/index.html": redirect("a/", "../a/"),
})
})
test("an old address that is another page's alias is not overwritten", async () => {
setSlugOptions({ stripDiacritics: true })
// a page (e.g. from a plugin that registers addresses) already answers at `české/index`
const content = [page("české/Čeština.md"), withAliases(page("other.md"), ["české/index"])]
assert.deepEqual(Object.keys(await emitAll(content)).sort(), ["české/čeština.html"])
})
test("an old address that is a page without a file (a plugin's page) is not overwritten", async () => {
setSlugOptions({ stripDiacritics: true })
const virtual = new VFile("")
virtual.data = { slug: "české/index" as FullSlug, frontmatter: { title: "České" } }
const content: ProcessedContent[] = [
page("české/Čeština.md"),
[{ type: "root", children: [] } as Root, virtual],
]
assert.deepEqual(Object.keys(await emitAll(content)), ["české/čeština.html"])
})
test("nothing is emitted without slugs.stripDiacritics", async () => {
setSlugOptions({ stripDiacritics: false })
assert.deepEqual(await emitAll([page("české/Čeština.md", { aliases: ["stará"] })]), {})
})
})
+176 -6
View File
@@ -87,6 +87,7 @@ describe("pluginMatchKey for monorepo subdirectories", () => {
)
}
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer", subdir: "." }), "explorer")
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer" }), "explorer")
})
test("an overlay entry for one monorepo plugin leaves the other alone", () => {
const merged = mergeQuartzConfigs(
@@ -355,7 +356,10 @@ describe("resolveExtends", () => {
quartzRoot: root,
readFile,
}),
/cycle/,
{
name: "ConfigExtendsError",
message: '"extends" cycle: quartz.config.yaml → a.yaml → b.yaml → a.yaml',
},
)
await assert.rejects(
() =>
@@ -375,6 +379,21 @@ describe("resolveExtends", () => {
)
})
test("a base that is not a configuration object is an error", async () => {
files[path.join(root, "list.yaml")] = "- source: explorer\n- source: graph\n"
const file = path.join(root, "list.yaml")
await assert.rejects(
resolveExtends({ extends: "./list.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
{
name: "ConfigExtendsError",
message: `"extends: ./list.yaml": ${file} is not a valid config (${file} does not contain a configuration object)`,
},
)
})
test("extends: default reproduces the shipped default config exactly", async () => {
const defaultFile = path.resolve("quartz.config.default.yaml")
const shipped = YAML.parse(fs.readFileSync(defaultFile, "utf-8"))
@@ -448,11 +467,6 @@ describe("fetchRemoteConfig", () => {
await fetchRemoteConfig(url, { cacheDir, fetchImpl: ok("a: 1\n"), offline: false }),
"a: 1\n",
)
// memoised per process: a second call does not fetch again
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
"a: 1\n",
)
const warnings: string[] = []
const other = tmp()
fs.cpSync(cacheDir, other, { recursive: true })
@@ -503,3 +517,159 @@ describe("fetchRemoteConfig", () => {
)
})
})
describe("fetchRemoteConfig limits and memoisation", () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
/** A fetch that answers `body` (from `finalUrl` after redirects) and counts its calls. */
const counting = (body: string, finalUrl?: string) => {
const calls: string[] = []
const impl = (async (url: string) => {
calls.push(url)
return {
ok: true,
status: 200,
url: finalUrl ?? url,
text: async () => body,
}
}) as unknown as typeof fetch
return { calls, impl }
}
const failing = (async () => {
throw new Error("getaddrinfo ENOTFOUND")
}) as unknown as typeof fetch
test("two calls for one URL fetch once", async () => {
const cacheDir = tmp()
const { calls, impl } = counting("a: 1\n")
const url = "https://cfg.example/memo.yaml"
const warnings: string[] = []
const opts = {
cacheDir,
fetchImpl: impl,
offline: false,
warn: (m: string) => warnings.push(m),
}
const [first, second] = await Promise.all([
fetchRemoteConfig(url, opts),
fetchRemoteConfig(url, opts),
])
assert.strictEqual(await fetchRemoteConfig(url, opts), "a: 1\n")
assert.deepStrictEqual([first, second], ["a: 1\n", "a: 1\n"])
assert.deepStrictEqual(calls, [url])
assert.deepStrictEqual(warnings, [])
})
test("a failed fetch is tried again by the next call", async () => {
const cacheDir = tmp()
const url = "https://cfg.example/retry.yaml"
await assert.rejects(
fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
/could not be fetched: getaddrinfo ENOTFOUND/,
)
const { calls, impl } = counting("b: 2\n")
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir, fetchImpl: impl, offline: false }),
"b: 2\n",
)
assert.deepStrictEqual(calls, [url])
})
test("offline, the cached copy is returned without fetching", async () => {
const online = tmp()
const url = "https://cfg.example/offline.yaml"
await fetchRemoteConfig(url, { cacheDir: online, fetchImpl: counting("c: 3\n").impl })
const offlineDir = tmp()
fs.cpSync(online, offlineDir, { recursive: true })
const { calls, impl } = counting("c: changed\n")
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir: offlineDir, fetchImpl: impl, offline: true }),
"c: 3\n",
)
assert.deepStrictEqual(calls, [])
})
test("a redirect to http:// is an error, even with a cached copy", async () => {
const url = "https://cfg.example/redirected.yaml"
const cacheDir = tmp()
await fetchRemoteConfig(url, { cacheDir, fetchImpl: counting("d: 4\n").impl })
const other = tmp()
fs.cpSync(cacheDir, other, { recursive: true })
const warnings: string[] = []
await assert.rejects(
fetchRemoteConfig(url, {
cacheDir: other,
fetchImpl: counting("d: evil\n", "http://evil.example/x.yaml").impl,
offline: false,
warn: (m) => warnings.push(m),
}),
{
name: "ConfigExtendsError",
message: `"extends: ${url}" redirected to http://evil.example/x.yaml, which is not https`,
},
)
assert.deepStrictEqual(warnings, [])
// a redirect that stays on https is fine
assert.strictEqual(
await fetchRemoteConfig(url, {
cacheDir: tmp(),
fetchImpl: counting("d: 5\n", "https://mirror.example/x.yaml").impl,
offline: false,
}),
"d: 5\n",
)
})
test("a body over 1 MB is an error and is not cached", async () => {
const limit = 1024 * 1024
const exactly = tmp()
const atLimit = "#".repeat(limit)
assert.strictEqual(
await fetchRemoteConfig("https://cfg.example/1mb.yaml", {
cacheDir: exactly,
fetchImpl: counting(atLimit).impl,
offline: false,
}),
atLimit,
)
for (const [name, body] of [
["over.yaml", "#".repeat(limit + 1)],
// 524 289 characters, 1 048 578 bytes: the limit is in bytes
["utf8.yaml", "é".repeat(limit / 2 + 1)],
]) {
const url = `https://cfg.example/${name}`
const cacheDir = tmp()
await assert.rejects(
fetchRemoteConfig(url, { cacheDir, fetchImpl: counting(body).impl, offline: false }),
{ name: "ConfigExtendsError", message: `"extends: ${url}" is larger than 1 MB` },
)
assert.deepStrictEqual(fs.readdirSync(cacheDir), [])
}
})
})
describe("resolveTarget accepts only https URLs", () => {
const from = path.resolve("/site/quartz.config.yaml")
test("an http URL with https:// in its query is refused", () => {
for (const target of [
"http://evil.example/?https://cfg.example/x.yaml",
"http://evil.example/https://cfg.example/x.yaml",
"file:///etc/https://x.yaml",
]) {
assert.throws(() => resolveTarget(target, from, "/site"), {
name: "ConfigExtendsError",
message: `${from}: "extends: ${target}" — only https:// URLs can be extended`,
})
}
assert.throws(
() => resolveTarget("?https://x", "http://evil.example/base.yaml", "/site"),
/only https:\/\/ URLs can be extended/,
)
})
test("a local path that contains :// is a path, not a URL", () => {
assert.strictEqual(
resolveTarget("mirror/https://cfg.example/x.yaml", from, "/site"),
path.resolve("/site/mirror/https:/cfg.example/x.yaml"),
)
})
})
@@ -0,0 +1,159 @@
import test, { after, afterEach, before, describe } from "node:test"
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { registerHooks } from "node:module"
import { getSlugOptions, setSlugOptions } from "../../util/path"
import type { QuartzComponent } from "../../components/types"
// loadQuartzConfig imports the built-in emitters, whose SCSS and inline browser scripts esbuild
// bundles in a real build; under tsx they are stubbed out.
registerHooks({
load(url, context, next) {
if (url.endsWith(".scss") || /\.inline\.ts$/.test(url)) {
return { format: "module", source: "export default ''", shortCircuit: true }
}
return next(url, context)
},
})
const { loadQuartzConfig, loadQuartzLayout } = await import("./config-loader")
const names = (list: { name: string }[]) => list.map((p) => p.name)
const componentNames = (list: QuartzComponent[] | undefined) =>
(list ?? []).map((c) => c.displayName ?? c.name)
describe("loadQuartzConfig with extends: default", () => {
let dir: string
before(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
process.env.QUARTZ_CONFIG_QUIET = "1"
})
afterEach(() => {
delete process.env.QUARTZ_CONFIG_PATH
setSlugOptions(undefined)
})
after(() => {
delete process.env.QUARTZ_CONFIG_QUIET
fs.rmSync(dir, { recursive: true })
})
const useConfig = (name: string, content: string) => {
const file = path.join(dir, name)
fs.writeFileSync(file, content)
process.env.QUARTZ_CONFIG_PATH = file
}
test("merges configuration, plugins, layout and applies before/after", async () => {
useConfig(
"quartz.config.yaml",
`extends: default
configuration:
pageTitle: Extended garden
slugs:
stripDiacritics: true
plugins:
- source: "@quartz-community/description"
order: 60
before: Links
- source: "@quartz-community/favicon"
after: [CustomOgImages, Links]
# names that don't run among the transformers: a disabled plugin, an absorbed one, a built-in
# emitter. They are accepted and change nothing
- source: "@quartz-community/latex"
after: [citations, remove-draft, Fonts]
- source: "@quartz-community/explorer"
layout:
position: right
priority: 5
layout:
byPageType:
folder:
positions:
right: null
`,
)
const cfg = await loadQuartzConfig()
// the extending file's value, and the base's for what it leaves out
assert.equal(cfg.configuration.pageTitle, "Extended garden")
assert.equal(cfg.configuration.baseUrl, "quartz.jzhao.xyz")
assert.equal(getSlugOptions().stripDiacritics, true)
// plugins enabled only in the base are loaded; Description (order 60 here, 70 in the base)
// runs before the built-in Links at the same order
assert.deepEqual(names(cfg.plugins.transformers), [
"Frontmatter",
"NoteProperties",
"CreatedModifiedDate",
"SyntaxHighlighting",
"GitHubFlavoredMarkdown",
"ObsidianFlavoredMarkdown",
"UnlistedPages",
"TableOfContents",
"BasesTransformer",
"Description",
"Links",
"Latex",
"EncryptedPages",
])
// `after:` names og-image by its instance name; favicon comes first in the base list
assert.deepEqual(names(cfg.plugins.emitters), [
"ComponentResources",
"Assets",
"Static",
"SlugRedirects",
"ContentIndex",
"AliasRedirects",
"CustomOgImages",
"Favicon",
"CNAME",
"Fonts",
"EncryptedContentIndex",
"PageTypeDispatcher",
])
const layout = await loadQuartzLayout()
assert.deepEqual(componentNames(layout.defaults.right), [
"ExplorerComponent",
"Graph",
"TableOfContents",
"Backlinks",
])
assert.ok(!componentNames(layout.defaults.left).includes("ExplorerComponent"))
// `right: null` removed the base's `right: []` for folder pages
assert.deepEqual(Object.keys(layout.byPageType?.folder ?? {}), ["left"])
assert.deepEqual(Object.keys(layout.byPageType?.tag ?? {}).sort(), ["left", "right"])
})
test("after: on a built-in is checked against the order kept from the base", async () => {
useConfig(
"after-links.yaml",
`extends: default
plugins:
- source: "@quartz-community/table-of-contents"
after: Links
`,
)
await assert.rejects(loadQuartzConfig(), {
name: "PluginOrderError",
message:
'plugin "@quartz-community/table-of-contents" (order 50) must run after "Links", but "Links" has order 60, so it runs later. ' +
'Give "@quartz-community/table-of-contents" an order above 60, or "Links" one below 50.',
})
})
test("a JSON config extends too", async () => {
useConfig(
"quartz.plugins.json",
JSON.stringify({
extends: "default",
configuration: { pageTitle: "From JSON" },
plugins: [{ source: "@quartz-community/latex", enabled: false }],
}),
)
const cfg = await loadQuartzConfig()
assert.equal(cfg.configuration.pageTitle, "From JSON")
assert.equal(cfg.configuration.locale, "en-US")
const transformers = names(cfg.plugins.transformers)
assert.ok(!transformers.includes("Latex"))
assert.ok(transformers.includes("Description"))
})
})
@@ -26,6 +26,30 @@ describe("orderPlugins", () => {
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["z", "y", "x"])
})
test("one plugin before several others", () => {
const items = [item("b", 50), item("c", 50), item("a", 50, { before: ["b", "c"] })]
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "b", "c"])
})
test("one plugin after several others, and several targets in both directions", () => {
const items = [item("x", 50, { after: ["z", "y"] }), item("y", 50), item("z", 50)]
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["y", "z", "x"])
const mixed = [
item("p", 50),
item("q", 50, { after: ["r", "s"], before: ["p", "t"] }),
item("r", 50),
item("s", 50),
item("t", 50),
]
assert.deepStrictEqual(orderPlugins(mixed, known("p", "q", "r", "s", "t")), [
"r",
"s",
"q",
"p",
"t",
])
})
test("constraints that agree with order are fine and change nothing", () => {
const items = [item("late", 70, { after: ["early"] }), item("early", 40, { before: ["late"] })]
assert.deepStrictEqual(orderPlugins(items, known("late", "early")), ["early", "late"])
+30 -11
View File
@@ -1,20 +1,14 @@
import assert from "node:assert/strict"
import test, { describe } from "node:test"
import test, { beforeEach, describe } from "node:test"
import { Features, transform } from "lightningcss"
import { isolateComponentCss } from "./componentCss"
import { componentStylesheet, isolateComponentCss } from "./componentCss"
import { getDiagnostics, resetDiagnostics } from "./diagnostics"
/** 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()
const sheet = (chunks: string[]) => componentStylesheet(chunks, () => "Bad")
describe("isolateComponentCss", () => {
beforeEach(() => resetDiagnostics())
const later = ".later{color:red}"
for (const [what, bad] of [
["a missing }", ".bad{color:blue"],
@@ -24,11 +18,35 @@ describe("isolateComponentCss", () => {
]) {
test(`${what} in one component doesn't swallow the next one's rules`, () => {
assert.match(sheet([bad, later]), /@layer quartz-base\{.*\.later\{color:red\}\}$/)
// the end of the chunk closes what it left open: not an error
assert.deepEqual(getDiagnostics(), [])
})
}
test("a stray } doesn't fail the stylesheet", () => {
assert.match(sheet([".bad{color:blue}}", later]), /\.bad\{color:#00f\}.*\.later\{color:red\}/)
assert.deepEqual(
getDiagnostics().map((d) => d.message.split(" has ")[0]),
["The CSS of component Bad"],
)
})
test("CSS that doesn't parse keeps the rules that do, with a warning naming the component", () => {
assert.equal(
isolateComponentCss(".bad{color:blue}}", "Explorer"),
".bad {\n color: #00f;\n}\n",
)
assert.deepEqual(getDiagnostics(), [
{
severity: "warning",
area: "css",
message:
"The CSS of component Explorer has a syntax error (Unexpected end of input at line 1, column 18); the rules that parse are kept.",
},
])
resetDiagnostics()
isolateComponentCss(".bad{color:blue}}")
assert.match(getDiagnostics()[0].message, /^The CSS of a component has a syntax error/)
})
test("balanced CSS comes out as it did before", () => {
@@ -40,5 +58,6 @@ describe("isolateComponentCss", () => {
include: Features.MediaQueries,
}).code.toString()
assert.equal(sheet([css, later]), raw)
assert.deepEqual(getDiagnostics(), [])
})
})
+21 -1
View File
@@ -1,4 +1,4 @@
import { transform } from "lightningcss"
import { Features, Targets, transform } from "lightningcss"
import { recordDiagnostic } from "./diagnostics"
/**
@@ -31,3 +31,23 @@ export function isolateComponentCss(css: string, owner = ""): string {
}
}
}
/**
* All components' CSS as ComponentResources emits it: each chunk isolated, in order, in one
* `quartz-base` layer, minified.
*/
export function componentStylesheet(
chunks: string[],
ownerOf: (css: string) => string | undefined = () => undefined,
targets?: Targets,
): string {
const isolated = chunks.map((c) => isolateComponentCss(c, ownerOf(c)))
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
return transform({
filename: "component.css",
code: Buffer.from(wrapped),
minify: true,
targets,
include: Features.MediaQueries,
}).code.toString()
}
+31 -1
View File
@@ -1,6 +1,6 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import { realDate } from "./dates"
import { dateIsFromFrontmatter, realDate } from "./dates"
import type { QuartzPluginData } from "../plugins/vfile"
const data = (d: Record<string, unknown>) => d as unknown as QuartzPluginData
@@ -43,3 +43,33 @@ describe("realDate", () => {
assert.strictEqual(realDate(data({ dates: { modified: now } }), undefined), undefined)
})
})
describe("dateIsFromFrontmatter", () => {
test("a date-time value is compared as written, a date-only one as local midnight", () => {
const d = data({ frontmatter: { published: "2024-01-02T10:00:00" } })
assert.strictEqual(dateIsFromFrontmatter(d, new Date("2024-01-02T10:00:00"), "published"), true)
assert.strictEqual(
dateIsFromFrontmatter(d, new Date("2024-01-02T00:00:00"), "published"),
false,
)
const dateOnly = data({ frontmatter: { published: "2024-01-02" } })
assert.strictEqual(
dateIsFromFrontmatter(dateOnly, new Date("2024-01-02T00:00:00"), "published"),
true,
)
})
test("YAML dates and timestamps compare by value; other values and missing ones never match", () => {
const when = new Date("2024-01-02T10:00:00Z")
const of = (published: unknown) => data({ frontmatter: { published } })
assert.strictEqual(dateIsFromFrontmatter(of(new Date(when)), when, "published"), true)
assert.strictEqual(dateIsFromFrontmatter(of(when.getTime()), when, "published"), true)
assert.strictEqual(dateIsFromFrontmatter(of([when.toISOString()]), when, "published"), false)
assert.strictEqual(dateIsFromFrontmatter(of(""), new Date(0), "published"), false)
assert.strictEqual(dateIsFromFrontmatter(of(null), new Date(0), "published"), false)
assert.strictEqual(dateIsFromFrontmatter(of(when), new Date(NaN), "published"), false)
// the page's default date type
const d = data({ frontmatter: { modified: when.toISOString() }, defaultDateType: "modified" })
assert.strictEqual(dateIsFromFrontmatter(d, when), true)
})
})