Compare commits

..
Author SHA1 Message Date
saberzero1 f47668e024 test: broken-link marking for published folder notes and after page generation
markUnpublishedLinks never marks a link to a published page (a folder note that no page
type generates, an alias) once the page types ran, and a draft folder note leaves the link
to the generated folder page or marks it missing. markLinksToUnpublishedPages (exported for
the test) builds the generated set from the virtual pages, marks drafts with their filter
and folders no page type generated as missing, reports changed pages once, and marks
nothing when the Links transformer doesn't mark broken links.
2026-11-27 04:24:38 +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
saberzero1 0e16919455 docs(slugs): old addresses redirect when stripDiacritics is on; fold the redirect changeset into the option's 2026-11-27 00:20:07 +01:00
saberzero1 81b358224b fix(popover): escape the target id in the popover's scroll-to selector (ids like ^block-id are not CSS identifiers) 2026-11-26 23:30:54 +01:00
saberzero1 0346dc6149 feat(slugs): redirect from addresses that slugs.stripDiacritics changed 2026-11-26 23:25:25 +01:00
saberzero1 e0f1e03913 fix(spa): keep a scroll position still pending when Back/Forward leaves the entry 2026-11-26 23:23:03 +01:00
saberzero1 c79adab53b fix(css): parse each component's CSS on its own before joining the component stylesheet 2026-11-26 23:20:33 +01:00
saberzero1 af36801547 fix(links): mark links to folder/tag pages that aren't generated; re-emit pages whose link marks change in watch mode 2026-11-26 23:18:49 +01:00
Emile Bangma b1fc7acd8e Merge pull request #2707 from jackyzha0/docs/5-3-release-notes
docs: 5.2 and 5.3 release notes, upgrade steps and new plugin options
2026-11-26 23:13:24 +01:00
28 changed files with 688 additions and 77 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.
+5
View File
@@ -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.
+5
View File
@@ -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.
+1 -1
View File
@@ -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.
+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 -1
View File
@@ -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.
+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",
+6 -3
View File
@@ -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 {
+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") {
+2 -1
View File
@@ -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
+40 -4
View File
@@ -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()
}
+89 -1
View File
@@ -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,88 @@ 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("links to published folder notes and pages are not marked once page types ran", () => {
// `notes/index` is a content page (notes/index.md or a folder note), so no page type
// generates it: it is live because it is published, not because it was generated
const home = page("index", [
link("notes/index"),
link("projects/index"),
link("published"),
link("aka"),
link("tags/x"),
])
const notes = page("notes/index", [])
const projects = page("projects/index", [], { aliases: ["aka"] })
const published = page("published", [])
const changed = new Set<FullSlug>()
const marked = markUnpublishedLinks(
[home, notes, projects, published],
new Map(),
new Set(["tags/x"]),
changed,
)
assert.strictEqual(marked, 0)
for (const a of anchors(home)) {
assert.deepStrictEqual(a.properties.className, ["internal", "internal-link"])
assert.strictEqual(a.properties["data-missing"], undefined)
assert.strictEqual(a.properties["data-filtered"], undefined)
}
assert.deepStrictEqual([...changed], [])
})
test("a folder note that is a draft: its folder page is generated, or the link is missing", () => {
const home = page("index", [link("notes/index"), link("drafts/index")])
const notesIndex = page("notes/index", [])
const draftsIndex = page("drafts/index", [])
const all = [home, notesIndex, draftsIndex]
const removed = removedPages(all, [home], () => "RemoveDrafts")
// folder index notes are left to the generated pages
assert.deepStrictEqual([...removed], [])
markUnpublishedLinks([home], removed, new Set(["notes/index"]))
const [toNotes, toDrafts] = anchors(home)
assert.ok(!(toNotes.properties.className as string[]).includes("broken"))
assert.ok((toDrafts.properties.className as string[]).includes("broken"))
assert.strictEqual(toDrafts.properties["data-missing"], "")
assert.strictEqual(toDrafts.properties["data-filtered"], undefined)
})
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(
+77 -21
View File
@@ -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 }
+13 -2
View File
@@ -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
View File
@@ -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)
}
})
})
+105
View File
@@ -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),
})
+1
View File
@@ -749,6 +749,7 @@ export async function loadQuartzConfig(
builtinPlugins.ComponentResources(),
builtinPlugins.Assets(),
builtinPlugins.Static(),
builtinPlugins.SlugRedirects(),
]
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
+79 -1
View File
@@ -8,6 +8,7 @@ import {
collectTreeTransforms,
folderTrie,
generateVirtualPages,
markLinksToUnpublishedPages,
pageOutputPath,
processVirtualPageHtml,
referencesByTarget,
@@ -19,7 +20,10 @@ import { QuartzComponent } from "../../components/types"
import { FilePath, FullSlug, SimpleSlug, setSlugOptions } from "../../util/path"
import { Root as HtmlRoot } from "hast"
import { BuildCtx } from "../../util/ctx"
import { defaultProcessedContent } from "../vfile"
import { defaultProcessedContent, ProcessedContent } from "../vfile"
import { removedPages } from "../builtins/links"
import { Element, Root } from "hast"
import { VFile } from "vfile"
const StubA: QuartzComponent = (() => null) as unknown as QuartzComponent
const StubB: QuartzComponent = (() => null) as unknown as QuartzComponent
@@ -557,3 +561,77 @@ describe("publish filters on pages that stand for files (bases-page#11)", () =>
assert.strictEqual(processVirtualPageHtml(ve, makeCtx(), []), true)
})
})
describe("links to unpublished pages, after the page types ran (crawl-links#7)", () => {
const link = (slug: string): Element => ({
type: "element",
tagName: "a",
properties: { href: `./${slug}`, "data-slug": slug, className: ["internal"] },
children: [],
})
const content = (slug: string, links: string[] = []): ProcessedContent => {
const file = new VFile("")
file.data = { slug: slug as FullSlug, frontmatter: { title: slug } } as VFile["data"]
return [{ type: "root", children: links.map(link) } as Root, file]
}
const marks = (item: ProcessedContent) =>
((item[0] as Root).children as Element[]).map((a) =>
(a.properties.className as string[]).includes("broken")
? (a.properties["data-filtered"] ?? (a.properties["data-missing"] === "" ? "missing" : "?"))
: "ok",
)
// a folder page type that generates a page for each folder with a published note, as folder-page does
const folders = makePageType({
name: "folders",
generate: ({ content }) =>
[...new Set(content.map(([, f]) => f.data.slug!.split("/").slice(0, -1).join("/")))]
.filter((f) => f !== "" && !content.some(([, g]) => g.data.slug === `${f}/index`))
.map((f) => ({ slug: `${f}/index` as FullSlug, title: f, data: {} })),
})
const setup = async (removedBy: ((slug: string) => string | undefined) | undefined) => {
const home = content("index", [
"notes/a",
"notes/index",
"drafts/index",
"drafts/b",
"projects/index",
"missing-in-source",
])
const all = [home, content("notes/a"), content("drafts/b"), content("projects/index")]
const published = all.filter(([, f]) => f.data.slug !== "drafts/b")
const ctx = {
cfg: { configuration: {} },
virtualPages: [],
removedPages: removedBy ? removedPages(all, published, removedBy) : undefined,
} as unknown as BuildCtx
const entries = await generateVirtualPages([folders], published, ctx, { head: StubHead }, {})
return { home, ctx, published, entries }
}
test("marks drafts with their filter and folders no page type generated as missing", async () => {
const { home, ctx, published, entries } = await setup(() => "RemoveDrafts")
assert.deepStrictEqual(
entries.map((e) => e.vpSlug),
["notes/index"],
)
const changed = markLinksToUnpublishedPages(ctx, published, entries)
assert.deepStrictEqual(marks(home), [
"ok", // notes/a: published
"ok", // notes/index: generated folder page
"missing", // drafts/index: its only note is a draft, so no folder page
"RemoveDrafts", // drafts/b
"ok", // projects/index: a published folder note
"ok", // not in the content: the Links transformer's own check, not this one
])
assert.deepStrictEqual([...changed], ["index"])
// run again (watch mode, nothing changed): nothing to re-emit
assert.deepStrictEqual([...markLinksToUnpublishedPages(ctx, published, entries)], [])
})
test("marks nothing when the Links transformer doesn't mark broken links", async () => {
const { home, ctx, published, entries } = await setup(undefined)
assert.deepStrictEqual([...markLinksToUnpublishedPages(ctx, published, entries)], [])
assert.ok(marks(home).every((m) => m === "ok"))
})
})
+26
View File
@@ -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.
*/
export 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
+44
View File
@@ -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)
})
})
+33
View File
@@ -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 ""
}
}
}
+6
View File
@@ -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. */