Compare commits

..
Author SHA1 Message Date
saberzero1 dd667ee315 fix(slugs): pass slugs.stripDiacritics to browser scripts; plugins bundling utils 1.3 (bases-page, breadcrumbs, canvas-page, explorer, folder-page, note-properties, OFM) 2026-11-26 21:22:39 +01:00
saberzero1 673a596cf8 refactor(slugs): use @quartz-community/utils' slug options instead of core's copy (core requires utils 1.3) 2026-11-26 20:59:45 +01:00
Emile Bangma 623e710fe8 Merge pull request #2706 from jackyzha0/deps/plugins-5-3-followups
chore(deps): plugin releases for 5.3.0 (explorer, OFM, GFM, canvas-page, utils, …)
2026-11-26 19:26:01 +01:00
saberzero1 8c612458cd chore(deps): explorer 1.2.0, OFM 2.5.0, GFM 2.2.0, canvas-page 1.1.0, utils 1.3.0, created-modified-date 1.0.4, ox-hugo 1.0.2 2026-11-26 19:24:25 +01:00
Emile Bangma 1c48865b9f Merge pull request #2704 from jackyzha0/dev-mode/filtered-slugs
fix(links): mark links to pages removed by filters as broken (quartz-community/crawl-links#7)
2026-11-26 19:03:02 +01:00
saberzero1 c608817610 Merge remote-tracking branch 'origin/v5' into dev-mode/filtered-slugs
# Conflicts:
#	quartz/plugins/builtins/links.ts
2026-11-26 19:02:58 +01:00
Emile Bangma 2bea104934 Merge pull request #2703 from jackyzha0/dev-mode/content-index-date
feat(content-index): write the page date to contentIndex.json (quartz-community/explorer#5)
2026-11-26 19:02:13 +01:00
Emile Bangma 5071ecd403 Merge pull request #2702 from jackyzha0/dev-mode/config-extends
feat(config): experimental extends: merge quartz.config.yaml onto the default config (#2440)
2026-11-26 19:01:48 +01:00
saberzero1 51c13bcca4 Merge remote-tracking branch 'origin/v5' into dev-mode/config-extends
# Conflicts:
#	quartz/plugins/loader/config-loader.ts
2026-11-26 19:01:44 +01:00
Emile Bangma 01f8f963ea Merge pull request #2701 from jackyzha0/dev-mode/is-index-condition
feat(layout): is-index and is-folder-index conditions, not-<condition> negation (#2465)
2026-11-26 18:58:31 +01:00
Emile Bangma 11334aa029 Merge pull request #2700 from jackyzha0/dev-mode/strip-diacritics-slugs
feat(slugs): opt-in configuration.slugs.stripDiacritics (#2410)
2026-11-26 18:58:06 +01:00
saberzero1 c2293500d7 feat(config): before/after plugin constraints checked against order; https:// extends with cache (#2440) 2026-11-26 17:14:21 +01:00
saberzero1 4172d3f56c feat(slugs): pass slugs.stripDiacritics to @quartz-community/utils (setSlugOptions) when it supports it
utils 1.3 (quartz-community/utils dev-mode/strip-diacritics) applies the option to every slug
it computes, so plugins slugging through utils (tag pages, canvas, bases, alias-redirects)
agree with core. With the current utils (1.2) core's own wrapper still covers core's slugs.
2026-11-26 17:09:24 +01:00
saberzero1 09a6b0336a feat(content-index): dateFromFrontmatter marks dates set in frontmatter 2026-11-26 17:06:08 +01:00
Emile Bangma 415af8a52d Merge pull request #2705 from jackyzha0/deps/graph-1-0-7
chore(deps): @quartz-community/graph 1.0.7, utils 1.2.1
2026-11-26 17:05:27 +01:00
saberzero1 6ce31a4814 chore(deps): @quartz-community/graph 1.0.7, utils 1.2.1 2026-11-26 17:04:07 +01:00
saberzero1 df11e31ef3 feat(config): experimental extends: merge quartz.config.yaml onto the default config (#2440) 2026-11-26 16:07:12 +01:00
saberzero1 734e1b8531 fix(links): mark links to pages removed by filters as broken (quartz-community/crawl-links#7) 2026-11-26 16:02:10 +01:00
saberzero1 b25eba0dca feat(slugs): opt-in configuration.slugs.stripDiacritics (#2410) 2026-11-26 15:59:49 +01:00
Emile Bangma 465d0e03eb Merge pull request #2698 from jackyzha0/docs/5-3-0-audit
docs: 5.3.0 options and behaviour
2026-11-26 15:59:26 +01:00
Emile Bangma 3a1dc46aab Merge pull request #2699 from jackyzha0/ci/release-lightweight-tag
ci(release): verified lightweight release tags; build the Docker image for each release
2026-11-26 15:58:28 +01:00
saberzero1 d5dad620d8 feat(content-index): write the page date to contentIndex.json (quartz-community/explorer#5) 2026-11-26 15:54:27 +01:00
saberzero1 661b56afc3 ci(release): verified lightweight release tags; build the Docker image for each release (#2455) 2026-11-26 15:54:17 +01:00
saberzero1 2209ee6d7d feat(layout): is-index and is-folder-index conditions, not-<condition> negation (#2465) 2026-11-26 15:53:06 +01:00
saberzero1 caec7d24ee docs: 5.3.0 options and behaviour (Bases propertyLabels, OFM blockWrappers, SPA scroll restoration, <main> in custom frames, KaTeX stylesheet loading) 2026-11-26 14:45:20 +01:00
Emile Bangma 773e2c7fe1 Merge pull request #2697 from jackyzha0/deps/plugins-a11y
chore(deps): accessibility and page-speed plugin releases for 5.3.0
2026-11-26 14:40:08 +01:00
saberzero1 96fc9c1bfb chore(deps): accessibility and page-speed plugin releases for 5.3.0 2026-11-26 13:02:56 +01:00
Emile Bangma 7ef986a16b Merge pull request #2696 from jackyzha0/a11y/page-list-h2
fix(a11y): PageList entries are h2 at the h3 size
2026-11-26 12:53:30 +01:00
Emile Bangma a5b07e3c48 Merge pull request #2695 from jackyzha0/a11y/template-contrast
fix(a11y): template colours meet WCAG AA contrast in light and dark mode
2026-11-26 12:53:05 +01:00
Emile Bangma c97a377b84 Merge pull request #2694 from jackyzha0/a11y/main-landmark
fix(a11y): page frames use <main> and <aside> landmarks
2026-11-26 12:52:40 +01:00
saberzero1 52af9f1a29 fix(a11y): PageList entries are h2 at the h3 size 2026-11-26 03:44:28 +01:00
saberzero1 093d233d2c fix(a11y): template colours meet WCAG AA contrast in light and dark mode 2026-11-26 03:40:04 +01:00
saberzero1 a55f25f185 fix(a11y): page frames use <main> and <aside> landmarks 2026-11-26 03:37:00 +01:00
Emile Bangma 050586dc14 Merge pull request #2692 from jackyzha0/fix/spa-scroll-restoration
fix(spa): the router restores scroll positions on Back and Forward
2026-11-26 03:33:13 +01:00
Emile Bangma 0cfcfc868b Merge pull request #2691 from jackyzha0/perf/single-component-css
perf(css): one stylesheet for all component styles
2026-11-26 03:32:48 +01:00
Emile Bangma 2f2c35d64c Merge pull request #2690 from jackyzha0/seo/head-meta
feat(head): canonical link and Open Graph fixes; font preconnect
2026-11-26 03:32:23 +01:00
Emile Bangma fb6464ef68 Merge pull request #2689 from jackyzha0/fix/frontmatter-angle-links
fix(frontmatter): Markdown links with an angle-bracket destination resolve
2026-11-26 03:31:58 +01:00
Emile Bangma dc10654108 Merge pull request #2693 from jackyzha0/deps/graph-1.0.5
chore(deps): @quartz-community/graph 1.0.5
2026-11-26 03:31:33 +01:00
saberzero1 c33b6cfc48 chore(deps): @quartz-community/graph 1.0.5 2026-11-26 03:30:08 +01:00
saberzero1 3ab4503fe0 fix(spa): the router restores scroll positions on Back and Forward (#2674) 2026-11-26 03:10:05 +01:00
saberzero1 799b8e370f perf(css): one stylesheet for all component styles 2026-11-26 03:00:51 +01:00
saberzero1 9d6cdba8e4 feat(head): canonical link, og:url without index, og:site_name property, article og:type; fix font preconnect 2026-11-26 02:59:24 +01:00
saberzero1 71454c77b6 fix(frontmatter): Markdown links with an angle-bracket destination resolve (#2672) 2026-11-26 02:51:25 +01:00
Emile Bangma 8417bdc03f Merge pull request #2688 from jackyzha0/dev-mode/deps-obsidian-plugins
chore(deps): @quartz-themes/core 3.2.0 and this round's plugin releases
2026-11-26 02:28:53 +01:00
saberzero1 db7484e05e chore(deps): @quartz-themes/core 3.2.0 and this round's plugin releases 2026-11-26 02:25:54 +01:00
Emile Bangma 52f7895ea6 Merge pull request #2687 from jackyzha0/dev-mode/obsidian-template-folding
feat(templates): the obsidian template folds headings and lists; obsidian-flavored-markdown 2.4.0, og-image 1.1.2
2026-11-26 01:31:16 +01:00
saberzero1 0bab8ea1bb chore(deps): obsidian-flavored-markdown 2.4.0, og-image 1.1.2 2026-11-26 01:29:09 +01:00
Emile Bangma 282ef789b6 Merge branch 'v5' into dev-mode/obsidian-template-folding 2026-11-26 01:26:40 +01:00
Emile Bangma c97c545f0c Merge pull request #2684 from jackyzha0/dev-mode/obsidian-collapse-indicators
fix: hide Obsidian's fold arrows in headings and list items
2026-11-26 01:09:13 +01:00
Emile Bangma e85dceaf23 Merge branch 'v5' into dev-mode/obsidian-collapse-indicators 2026-11-26 01:06:59 +01:00
Emile Bangma 7ce0665400 Merge pull request #2673 from jackyzha0/dev-mode/obsidian-block-wrappers
fix: heading transclusions and embedded footnotes look through Obsidian's per-block wrappers
2026-11-26 01:06:55 +01:00
Emile Bangma cc22cfe413 Merge branch 'v5' into dev-mode/obsidian-block-wrappers 2026-11-26 01:05:23 +01:00
Emile Bangma ed5912a53b Merge pull request #2671 from jackyzha0/dev-mode/obsidian-embed-markup
feat: Obsidian's embed markup for transclusions
2026-11-26 01:05:18 +01:00
Emile Bangma 43e2eb9e11 Merge branch 'v5' into dev-mode/obsidian-embed-markup 2026-11-26 01:03:46 +01:00
Emile Bangma cfa0413736 Merge pull request #2670 from jackyzha0/dev-mode/broken-links-default
feat(links): mark broken links by default, as Obsidian marks unresolved links
2026-11-26 01:03:41 +01:00
Emile Bangma a96d993bf5 Merge branch 'v5' into dev-mode/broken-links-default 2026-11-26 01:01:48 +01:00
Emile Bangma 09c0e5203d Merge pull request #2669 from jackyzha0/dev-mode/footnote-link-classes
fix: footnote anchors stay internal without internal-link, like Obsidian
2026-11-26 01:01:43 +01:00
Emile Bangma d70ab4e164 Merge branch 'v5' into dev-mode/footnote-link-classes 2026-11-26 00:59:48 +01:00
saberzero1 fd744c0a9e feat(templates): the obsidian template folds headings and lists 2026-11-26 00:59:16 +01:00
saberzero1 d9566ec223 Revert "feat(templates): the obsidian template folds headings and lists"
This reverts commit c568c93fa0.
2026-11-26 00:59:15 +01:00
Emile Bangma 72097c86e4 Merge pull request #2681 from jackyzha0/deps/ci-actions
ci: checkout 7, setup-node 7, cache 6, github-slug-action 5.7.1, cosign-installer 4.1.3
2026-11-26 00:41:51 +01:00
saberzero1 9c172ca3a4 Merge remote-tracking branch 'origin/v5' into deps/ci-actions 2026-11-26 00:39:43 +01:00
Emile Bangma 39ecd2a76d Merge pull request #2680 from jackyzha0/deps/typescript-7
chore(deps-dev): TypeScript 7
2026-11-26 00:39:41 +01:00
saberzero1 a9b4be1046 Merge remote-tracking branch 'origin/v5' into deps/typescript-7 2026-11-26 00:37:32 +01:00
Emile Bangma b7316ae8fa Merge pull request #2679 from jackyzha0/deps/minor-updates
chore(deps): hast-util-to-html 9.0.7, ws 8.23.0
2026-11-26 00:37:30 +01:00
saberzero1 d77bc173d3 Merge remote-tracking branch 'origin/v5' into deps/minor-updates 2026-11-26 00:35:21 +01:00
Emile Bangma 488da675e7 Merge pull request #2678 from jackyzha0/deps/changesets-cli-3
chore(deps-dev): @changesets/cli 3 and changesets/action 2
2026-11-26 00:35:18 +01:00
saberzero1 16bc33e9fb chore: regenerate package-lock.json 2026-11-26 00:33:20 +01:00
saberzero1 33acb1c716 Merge remote-tracking branch 'origin/v5' into deps/changesets-cli-3 2026-11-26 00:33:11 +01:00
Emile Bangma 6f689dcdb9 Merge pull request #2677 from jackyzha0/deps/chokidar-6
chore(deps): chokidar 6 (Quartz requires Node.js 22.22)
2026-11-26 00:33:09 +01:00
saberzero1 4679f825fd Merge remote-tracking branch 'origin/v5' into deps/chokidar-6 2026-11-26 00:30:54 +01:00
Emile Bangma 05b5082388 Merge pull request #2676 from jackyzha0/deps/is-absolute-url-5
chore(deps): is-absolute-url 5
2026-11-26 00:30:51 +01:00
saberzero1 c4d02241d5 Merge remote-tracking branch 'origin/v5' into deps/is-absolute-url-5 2026-11-26 00:28:28 +01:00
Emile Bangma 8ce7599280 Merge pull request #2675 from jackyzha0/deps/js-yaml-5
chore(deps): js-yaml 5
2026-11-26 00:28:09 +01:00
saberzero1 edd97cc665 docs: Node.js 22.22 in the prerequisites and on the home page 2026-11-26 00:25:58 +01:00
saberzero1 fd8256e4a0 ci: actions/checkout 7, actions/setup-node 7, actions/cache 6, github-slug-action 5.7.1, cosign-installer 4.1.3 2026-11-26 00:23:16 +01:00
saberzero1 fd1e5eb8bf ci(release): changesets/action 2 (needs @changesets/cli 3; renamed inputs and outputs, token as input) 2026-11-26 00:23:05 +01:00
saberzero1 7c3df898ed chore(deps-dev): TypeScript 7 (bundler module resolution; the GoatCounter test reads its template without the compiler API) 2026-11-26 00:22:29 +01:00
saberzero1 5bec47ee54 chore(deps): hast-util-to-html 9.0.7, ws 8.23.0 2026-11-26 00:19:02 +01:00
saberzero1 ea2b3485bf chore(deps-dev): @changesets/cli 3 2026-11-26 00:17:45 +01:00
saberzero1 857de3b2bc chore(deps): chokidar 6 (requires Node.js 22.22) 2026-11-26 00:16:56 +01:00
saberzero1 df13ac29e5 chore(deps): is-absolute-url 5 (Quartz already passes httpOnly: false; its types now include the option) 2026-11-26 00:11:56 +01:00
saberzero1 3b78d1658d chore(deps): js-yaml 5 (frontmatter reads YAML 1.2's core schema; comment-only frontmatter has no properties) 2026-11-26 00:10:30 +01:00
saberzero1 c568c93fa0 feat(templates): the obsidian template folds headings and lists 2026-11-26 00:05:15 +01:00
saberzero1 dfd1d6bd67 docs: foldHeadings / foldLists show the fold arrows Quartz hides 2026-11-25 23:42:05 +01:00
saberzero1 b4d73585f7 fix: hide Obsidian's fold arrows in headings and list items 2026-11-25 23:24:44 +01:00
saberzero1 723759f931 fix: MathJax display maths stays centred in Obsidian's block wrappers and maths elements 2026-11-25 21:50:58 +01:00
saberzero1 f5773b611f feat: Obsidian's icon link on embeds (.markdown-embed-link), hidden unless a theme shows it 2026-11-25 21:50:33 +01:00
saberzero1 7714325740 fix: heading transclusions look through Obsidian's per-block wrappers 2026-11-25 19:07:18 +01:00
saberzero1 4036e25a77 fix(links): tag and folder pages are not broken links 2026-11-25 00:34:42 +01:00
saberzero1 c770681ba8 feat: Obsidian's embed markup for transclusions (embed title, content, rendered view) 2026-11-24 23:48:56 +01:00
saberzero1 55311cb0bc feat(links): mark broken links by default, as Obsidian marks unresolved links 2026-11-24 23:43:56 +01:00
saberzero1 cc253bea53 fix: footnote anchors stay internal without internal-link, like Obsidian 2026-11-23 13:41:21 +01:00
Emile Bangma 2386362d57 Merge pull request #2668 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-22 23:48:35 +01:00
github-actions[bot] d533468802 chore: release Quartz 2026-11-22 22:47:05 +00:00
Emile Bangma 048519774a Merge pull request #2667 from jackyzha0/dev-mode/themes-core-3.1.1
chore: @quartz-themes/core 3.1.1 (Obsidian template's default theme)
2026-11-22 23:46:38 +01:00
saberzero1 ee1cdffd0d chore: @quartz-themes/core 3.1.1 (Obsidian template's default theme) 2026-11-22 23:41:06 +01:00
Emile Bangma 08fddad0e8 Merge pull request #2665 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-22 21:54:11 +01:00
github-actions[bot] 506a7caa8c chore: release Quartz 2026-11-22 20:52:31 +00:00
Emile Bangma 678398d235 Merge pull request #2666 from jackyzha0/dev-mode/themes-core-3
chore: @quartz-themes/core 3.1, @quartz-community/explorer 1.1.1
2026-11-22 21:52:08 +01:00
saberzero1 6f82d03fd4 chore: @quartz-community/explorer 1.1.1 in the lockfile 2026-11-22 21:49:37 +01:00
saberzero1 95e96b4871 chore: @quartz-themes/core 3.1 (themes converted at build time) 2026-11-22 21:28:07 +01:00
Emile Bangma 23b70cdba0 Merge pull request #2663 from jackyzha0/dev-mode/mobile-grid-minmax
fix(styles): phone/tablet content column can't grow past the screen
2026-11-22 21:27:45 +01:00
Emile Bangma 829bec461f Merge pull request #2664 from jackyzha0/dev-mode/fonts-body-overrides
fix(fonts): explicit fonts apply under Obsidian themes; interface and heading fonts load
2026-11-22 21:27:27 +01:00
saberzero1 c392e177a7 fix(fonts): load the interface and per-heading fonts; single-weight fonts request their weight 2026-11-22 21:25:05 +01:00
saberzero1 3f8104fb50 fix(fonts): explicit body, code and interface fonts apply with an Obsidian theme (Obsidian's --font-*-override variables on body) 2026-11-22 20:44:21 +01:00
saberzero1 7531e678f5 fix(styles): the phone/tablet content column is minmax(0, 1fr), and header text wraps, so wide chrome can't widen the page 2026-11-22 14:01:07 +01:00
Emile Bangma 568004496b Merge pull request #2630 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-22 01:16:12 +01:00
github-actions[bot] d80bb003f1 chore: release Quartz 2026-11-22 00:12:17 +00:00
Emile Bangma 6f79e008e2 Merge pull request #2660 from jackyzha0/dev-mode/plugin-checkout-force
fix(plugins): force the checkout of a pinned plugin commit (#2639)
2026-11-22 01:11:58 +01:00
saberzero1 166d09b876 fix(plugins): force the checkout of a pinned plugin commit, so a build's changed package-lock.json can't block it (#2639) 2026-11-22 01:06:13 +01:00
Emile Bangma 3960252445 Merge pull request #2658 from jackyzha0/dev-mode/changeset-config-flag
chore: changeset for quartz build --config (#2646)
2026-11-22 00:48:04 +01:00
Emile Bangma 436cce7610 Merge pull request #2657 from jackyzha0/dev-mode/deps-minor
chore(deps): minor and patch updates from #2640
2026-11-22 00:46:33 +01:00
saberzero1 4ed26b3943 chore: changeset for quartz build --config (#2646) 2026-11-22 00:44:19 +01:00
Emile Bangma 8f469ed237 Merge pull request #2646 from mabramo/feat/config-flag
feat: Add --config flag to override config file path
2026-11-22 00:43:20 +01:00
saberzero1 cdc5a0297f chore(deps): minor and patch updates from #2640 (clack, simple-git, isomorphic-git, minimatch, preact-render-to-string, prettier) 2026-11-22 00:42:09 +01:00
Emile Bangma 1dfe7fcdb0 Merge pull request #2656 from jackyzha0/dev-mode/callout-title-inner
fix(styles): style callout titles on .callout-title-inner
2026-11-21 21:44:23 +01:00
saberzero1 7453f7f0d0 chore: lockfile for obsidian-flavored-markdown 2.3.1 (callout titles without a <p>) 2026-11-21 21:42:15 +01:00
saberzero1 9c46b01c57 fix(styles): style callout titles on .callout-title-inner (obsidian-flavored-markdown renders no <p> there, as in Obsidian) 2026-11-21 19:08:56 +01:00
Emile Bangma 842a293ab1 Merge pull request #2653 from jackyzha0/dev-mode/permalink-fixes
fix: permalinks on large sites, permalinks with .. segments, pretty links; alias-redirects 1.0.4, note-properties 1.1.5
2026-11-21 17:07:26 +01:00
saberzero1 6f872d4302 chore: lockfile for alias-redirects 1.0.4 and note-properties 1.1.5 (#2641, #2635) 2026-11-21 17:05:45 +01:00
saberzero1 8578f2fdb2 chore: changeset for the permalink and pretty-link fixes 2026-11-21 16:27:29 +01:00
saberzero1 5b863b0752 fix(links): prettyLinks shortens wikilinks to notes whose name has a space or a non-ASCII letter (#2643)
Link text was compared with the percent-encoded href, so these links were classed alias.
Patch proposed in the issue by TraceKotae.
2026-11-21 16:27:29 +01:00
saberzero1 d092a3179b fix: worker threads get every plain-data field of the build context (workerCtx), with a test for permalinks (#2644) 2026-11-21 16:27:29 +01:00
saberzero1 dacfeba928 Merge #2642: ignore permalinks with . or .. segments 2026-11-21 16:23:44 +01:00
saberzero1 5fafbf37b7 Merge #2644: permalinks in the worker-thread context 2026-11-21 16:23:44 +01:00
Emile Bangma 2e4ef40bc0 Merge pull request #2652 from jackyzha0/dev-mode/bases-page-1.5.1
chore: lockfile for bases-page 1.5.1
2026-11-21 03:17:23 +01:00
saberzero1 99685cf741 chore: lockfile for bases-page 1.5.1 (bases in transcluded notes, link settings) 2026-11-21 02:54:23 +01:00
Emile Bangma b58a7f20fe Merge pull request #2651 from jackyzha0/dev-mode/transclusion-ids
fix: unique ids in transcluded content; heading transclusions hold only their own footnotes
2026-11-21 02:45:32 +01:00
saberzero1 49d05638f2 fix: transcluded content gets ids unique on the page and links to them; heading transclusions hold only their own footnotes 2026-11-21 02:32:00 +01:00
Emile Bangma d7d6c7b17f Merge pull request #2650 from jackyzha0/dev-mode/encrypted-pages-1.3
chore: lockfile for encrypted-pages 1.3.0 and types 1.5.0
2026-11-21 01:37:13 +01:00
saberzero1 db2ce262b7 chore: lockfile for encrypted-pages 1.3.0 and types 1.5.0 (render-time encryption) 2026-11-21 01:22:19 +01:00
Emile Bangma 29a5bdf4b9 Merge pull request #2649 from jackyzha0/dev-mode/render-transforms
feat: renderTransforms, render-time transforms around transclusions and treeTransforms
2026-11-21 01:13:54 +01:00
Michael Abramo 64dde0cb9c Add -C shorthand for --config and document the build flag 2026-11-20 11:49:54 -05:00
Michael Abramo 46312a6197 Add --config flag to override config file path
Content is relocatable with -d and output with -o, but the config path is
hardcoded to process.cwd()/quartz.config.yaml. This adds --config so the
config can live outside the Quartz checkout, letting one install build
multiple content repos that each carry their own config.

The flag is resolved to an absolute path and passed down via QUARTZ_CONFIG_PATH
so it reaches the esbuild-bundled build code and worker threads. The three
resolveConfigPath() helpers honor it when set, otherwise fall back to the
existing cwd lookup. --watch/--serve also watches the external config.
Includes a unit test for the override.
2026-11-20 00:17:06 -05:00
yavidor f690faad9e Added permalinks to worker context 2026-11-19 14:08:29 +02:00
goranai 546703340e fix: ignore permalinks with . or .. segments so pages stay in the output folder
Fixes #2641
2026-11-16 10:11:16 +08:00
118 changed files with 4228 additions and 1416 deletions

No files matched your search

-9
View File
@@ -1,9 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Bases (bases-page 1.4.0) render closer to Obsidian:
- custom summaries are evaluated, and summaries show their name and appear per group;
- `html()`, `image()`, `icon()`, regular expressions and `file.backlinks` work in formulas;
- `kanban` views, `groupOrder`, grouped list and cards views, and the list and row height options work.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Bases columns are labelled with the property's name, as in Obsidian (`priority`, `file name`), instead of title-cased (`Priority`, `Name`); bases-page's new `propertyLabels: title` option keeps the title-cased labels (bases-page 1.5.0).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Links: `disableBrokenWikilinks` is on by default. Internal links to pages that don't exist get the `broken` class, as Obsidian marks unresolved links (`is-unresolved`), so Quartz's and Obsidian themes' unresolved-link styles apply. Tag and folder pages, which are generated later, count as existing. Set `links.disableBrokenWikilinks: false` for the old behaviour.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Links to pages removed by a filter (drafts, ExplicitPublish) are now marked `broken` (with `data-filtered="<filter>"`), like links to pages that don't exist — they 404 on the site.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Quartz now requires Node.js 22.22 or later (was 22), for chokidar 6, which watches content in `--serve` mode. chokidar 6 confirms each change against the file system before rebuilding and fixes missed and duplicate change events.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Experimental `extends` in `quartz.config.yaml`: `extends: default` (or a path) starts from `quartz.config.default.yaml` and applies only the changes in your file. `configuration` and `layout` merge key by key, plugin entries merge with the default entry of the same plugin. Configs without `extends` behave exactly as before.
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
`contentIndex.json` entries have `dateFromFrontmatter: true` when their `date` is the one set in the page's frontmatter for the configured date type (not from git or the file system), so client-side components can tell explicit dates apart, e.g. for folder dates in the explorer.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
`contentIndex.json` entries now include the page's `date` (the one `defaultDateType` selects) as an ISO 8601 string, so client-side components such as the explorer can sort by date. Pages without a date have no `date` field.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Footnote references and back-links keep the `internal` class but no longer get `internal-link`: Obsidian doesn't treat them as note links, and Obsidian themes' link styles (underline, colour) overrode their footnote styles.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Markdown links in frontmatter with an angle-bracket destination, which Obsidian writes for paths with spaces (`[Exec Briefing](<./Exec Briefing.md>)`), resolve to the note instead of a missing `….md` page, so the note gets the backlink and graph edge.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
@quartz-community/graph 1.0.5: the graph scales to large sites. On 3,000 notes and 33,000 links, the global graph opens in 0.5 s instead of 2.5 s, and it stops using the CPU once its layout settles. It also loads d3 and PixiJS as pinned, integrity-checked versions, with PixiJS's minified build (200 KB instead of 2.5 MB on every page).
+6
View File
@@ -0,0 +1,6 @@
---
"@jackyzha0/quartz": patch
---
- `@quartz-community/graph` 1.0.7: the local graph on folder index pages shows the folder's connections instead of a single node.
- `@quartz-community/utils` 1.2.1: `unescapeHTML` decodes each entity once, so a page description that mentions `&lt;br&gt;` keeps it in the page's meta tags instead of turning it into `<br>`.
+7
View File
@@ -0,0 +1,7 @@
---
"@jackyzha0/quartz": patch
---
Pages get a canonical link (`<link rel="canonical">`, the page's URL as the sitemap lists it), and `og:url` uses the same URL: `folder/` instead of `folder/index`, and the site root for the home page. `og:site_name` is a `property` (it was a `name`, which Open Graph readers ignore). Notes are `og:type: article`, with `article:modified_time` and, when the frontmatter has a date, `article:published_time`. The home page and folder and tag pages stay `website`.
The `fonts.gstatic.com` preconnect is a CORS connection, which the font files can reuse, and the unused `cdnjs.cloudflare.com` preconnect is gone.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Layout conditions: add `is-index` (only on the home page) and `is-folder-index` (only on folder index pages), and let `not-<condition>` negate any condition, built-in or registered (`not-has-tags`, `not-has-backlinks`, …).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Frontmatter is read with js-yaml 5, using YAML 1.2's core schema (the values Quartz read before are unchanged). Frontmatter with only comments now has no properties, as in Obsidian, instead of being reported as invalid frontmatter.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
The page frames mark their regions for assistive technology: the centre column is a `<main>` (it was a `div.center`; the classes are unchanged) and the default frame's sidebars are `<aside>` elements. Screen readers can jump to the page's content, and the page looks the same.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Heading transclusions and their footnotes look through Obsidian's per-block wrappers (`div.el-h2 > h2`), which `@quartz-community/rehype-obsidian` now renders around each of a note's top-level blocks. `blockOf()` (in `components/transcludeScope.ts`) returns the block inside a wrapper, for other code that walks a page's top-level blocks.
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Obsidian's fold arrows in headings and list items (`.heading-collapse-indicator`, `.list-collapse-indicator`, rendered by rehype-obsidian for Obsidian themes) are hidden unless obsidian-flavored-markdown's `foldHeadings` / `foldLists` turn folding on.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Transclusions use Obsidian's embed markup: a `div.markdown-embed-title` (the note's title, for a whole-note embed; it was an `h1`), then the content in `div.markdown-embed-content > div.markdown-preview-view.markdown-rendered`, then the link to the original. Obsidian themes' embed styles apply (embed titles, padding, maximum height). The title looks as before without a theme. Obsidian's icon link to the note (`a.markdown-embed-link`, Lucide's maximize-2) follows; Quartz hides it, and Obsidian themes, through @quartz-themes/core, show it in the embed's corner.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
@quartz-community/obsidian-flavored-markdown 2.4.0 (Obsidian's block wrappers, heading and list folding, missing-attachment embeds, Pele diagrams) and @quartz-community/og-image 1.1.2 (no build failure on emoji variants such as the footnote back-link `↩︎`).
+14
View File
@@ -0,0 +1,14 @@
---
"@jackyzha0/quartz": patch
---
@quartz-themes/core 3.2.0 (Obsidian's block wrappers styled natively, property inputs, fold arrows) and the plugin releases that carry Obsidian's markup:
- latex 1.1.0: maths in Obsidian's math elements;
- note-properties 1.2.0: Obsidian's properties markup;
- search 1.1.0: the quick switcher's classes, excerpts as written;
- explorer 1.1.2: Obsidian's folder rows;
- table-of-contents 1.0.4: the collapsed table of contents no longer clips its header;
- graph 1.0.4: colours follow Obsidian themes;
- syntax-highlighting 1.0.4: the copy button's stylesheet in the base layer;
- canvas-page 1.0.4: heading embeds look through the block wrappers.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
The `obsidian` template folds headings and lists (obsidian-flavored-markdown's `foldHeadings` and `foldLists`), as Obsidian does by default.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
`PageList` entries are `h2` headings under the page's `h1` (they were `h3`, which skipped a level for screen readers), at the `h3`'s size, as in `@quartz-community/folder-page` and `@quartz-community/tag-page`.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
+13
View File
@@ -0,0 +1,13 @@
---
"@jackyzha0/quartz": patch
---
Plugin updates:
- `@quartz-community/explorer` 1.2.0: `sort` option (rules applied in sequence, e.g. folders first, then newest) and `rootFolder` option, so several explorers on one page work side by side; the `order` option is applied; scroll fixes (the bottom fade, the scroll position across SPA navigation with `layout.sidebars.left: scroll`, and opening a page no longer scrolls the page itself).
- `@quartz-community/obsidian-flavored-markdown` 2.5.0: notes, canvases and bases embedded with a Markdown link (`![](note.md#Section)`) are transcluded, as in Obsidian; `math` option (`false` leaves dollar signs as text). With `@quartz-community/rehype-obsidian` 1.5.1: same-page block links (`[[#^id]]`) reach their block, and only images on YouTube become YouTube embeds.
- `@quartz-community/github-flavored-markdown` 2.2.0: `singleTilde` option (`false` strikes only `~~text~~`, as Obsidian does) and `replacements` option (for example Quartz 4's arrows), empty by default.
- `@quartz-community/canvas-page` 1.1.0: the mouse wheel and trackpad pan the canvas, as in Obsidian (`wheelBehavior`); text nodes are rendered with the site's Markdown plugins, so Mermaid diagrams, callouts and math work in them (`textNodeMarkdown`).
- `@quartz-community/utils` 1.3.0: the `stripDiacritics` slug option reaches plugins too; links in embedded folder notes point at the right directory.
- `@quartz-community/created-modified-date` 1.0.4: git dates resolve when `content/` is a symlink to a vault in another git repository.
- `@quartz-community/ox-hugo` 1.0.2: the Markdown rewrites leave code alone and no longer match across unrelated text.
+12
View File
@@ -0,0 +1,12 @@
---
"@jackyzha0/quartz": patch
---
Plugin updates for accessibility and page speed:
- Text in the table of contents, footer, folder and tag listings, search button and Bases group headings meets WCAG AA contrast in light and dark mode. Under an Obsidian theme from quartz-themes (`@quartz-themes/core` 3.2.1), the search button and Bases group headings keep the theme's faint text colour.
- Page listings in folder and tag pages use `<h2>` titles (at the previous size), so headings no longer skip a level.
- Valid ARIA and unique ids in the table of contents, explorer, backlinks, heading anchors and Bases views.
- The graph loads d3 and PixiJS only when it scrolls into view (or when the global graph opens), instead of on every page.
- KaTeX's stylesheet no longer blocks rendering on pages without math.
- `@quartz-community/remark-obsidian` 2.2.3: the `legacy` parser no longer uses memory that grows with the square of the note's length on notes with many tables, lists or other blocks.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Updated plugins that rely on Quartz 5.1 and now declare it (`quartzVersion: ">=5.1.0"`): encrypted-pages 1.2.0, explicit-publish 1.2.0, unlisted-pages 1.2.0, obsidian-flavored-markdown 2.2.0, folder-page 1.1.0 and bases-page 1.3.0.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Theme support for Obsidian themes: plugin factories may be async (Quartz awaits them); font loading is built in as `configuration.fonts` (formerly the `@quartz-community/quartz-fonts` plugin, whose config entry is applied automatically); callouts and transclusions render as `<div>` like in Obsidian; popovers carry Obsidian's `hover-popover`/`markdown-embed` classes.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Release tags are verified on GitHub: the release workflow creates each `vX.Y.Z` tag as a lightweight tag on the merged release commit (which GitHub signs) instead of letting the release create an unsigned annotated tag. It also starts the Docker build for the tag, so versioned images (`5.3.0`, `5.3`) are published for each release (none were built for 5.1.0–5.2.2).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Transformers can declare `renderTransforms`: transforms of a page's content when it is rendered, `before` transclusions are inlined and page types' `treeTransforms` run (bases are filled in), and `after` them, on the finished content. encrypted-pages uses them to encrypt a note's finished content, so bases and transclusions in encrypted notes show when unlocked (quartz-community/encrypted-pages#2).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Component styles are one stylesheet (`component-<hash>.css`, in the `quartz-base` layer as before) instead of one per component. Pages load about 20 fewer render-blocking stylesheets (29 to 11 on the docs site), and the styles they compute are unchanged.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
With SPA navigation, Back and Forward return to where the reader was on each page. The router keeps each history entry's scroll position and restores it after swapping the page in. The browser restored the position while the previous page was still on screen, so it came out wrong: Back after a table-of-contents link stayed at the heading, and Back to a page landed at its top or bottom. Back and Forward between headings of the same page now only scroll, instead of reloading the page, and a reload keeps the position.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
`slugs.stripDiacritics` reaches plugins and the browser: bases-page 1.5.3, breadcrumbs 1.0.4, canvas-page 1.1.1, explorer 1.2.1, folder-page 1.1.2, note-properties 1.2.1 and obsidian-flavored-markdown 2.5.1 bundle `@quartz-community/utils` 1.3, so their links, tag pages from inline tags, canvas file nodes and base views use the stripped addresses. Quartz also passes the option to scripts in the browser, so the explorer places folders and pages with accents where the build put them.
+5
View File
@@ -0,0 +1,5 @@
---
"@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, and the old addresses redirect to them; heading anchors keep their diacritics. Letters without a separate accent (`ł`, `ø`, `ß`) are kept, as are Korean, Japanese, Chinese, Indic, Hebrew and Arabic text. 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.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
The templates' colours meet WCAG AA contrast (4.5:1) on their backgrounds. Light `gray` goes from #b8b8b8 to #727272 (was 1.9:1), dark `gray` from #646464 to #7f7f7f (was 3.1:1), and light `tertiary`, the link hover colour, from #84a59d to #587971 (was 2.5:1). Text selection mixes 40% of `tertiary` instead of 60%, so text stays readable on it in both modes. Existing sites keep the colours in their own `quartz.config.yaml`.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Type checking (`npm run check`) uses TypeScript 7. `tsconfig.json` switches `moduleResolution` from `node` (removed in TypeScript 7) to `bundler`, which reads packages' `exports`: custom code that imports a package's internal files may need to import from the package itself.
+4 -4
View File
@@ -11,17 +11,17 @@ jobs:
runs-on: ubuntu-latest
name: Build Preview
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version: 22
- name: Cache dependencies
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
@@ -29,7 +29,7 @@ jobs:
${{ runner.os }}-node-
- name: Cache Quartz plugins
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: .quartz/plugins
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
+6 -6
View File
@@ -19,17 +19,17 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version: 24
- name: Cache dependencies
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
@@ -37,7 +37,7 @@ jobs:
${{ runner.os }}-node-
- name: Cache Quartz plugins
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: .quartz/plugins
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
@@ -71,11 +71,11 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version: 24
- name: Get package version
+4 -4
View File
@@ -16,17 +16,17 @@ jobs:
runs-on: ubuntu-latest
name: Deploy v5 to Cloudflare Pages
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version: 24
- name: Cache dependencies
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
@@ -34,7 +34,7 @@ jobs:
${{ runner.os }}-node-
- name: Cache Quartz plugins
uses: actions/cache@v5
uses: actions/cache@v6
with:
path: .quartz/plugins
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
+3 -3
View File
@@ -21,11 +21,11 @@ jobs:
echo "OWNER_LOWERCASE=${OWNER,,}" >> ${GITHUB_ENV}
env:
OWNER: "${{ github.repository_owner }}"
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 1
- name: Inject slug/short variables
uses: rlespinasse/github-slug-action@v5.6.0
uses: rlespinasse/github-slug-action@v5.7.1
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
@@ -37,7 +37,7 @@ jobs:
network=host
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@v4.1.2
uses: sigstore/cosign-installer@v4.1.3
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
if: github.event_name != 'pull_request'
+19 -14
View File
@@ -21,12 +21,13 @@ jobs:
permissions:
contents: write
pull-requests: write
actions: write # start the Docker build for the new tag
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: actions/setup-node@v6
- uses: actions/setup-node@v7
with:
node-version: 24
@@ -34,16 +35,15 @@ jobs:
- name: Create or update the release PR
id: changesets
uses: changesets/action@v1
uses: changesets/action@v2
with:
version: npm run version-packages
title: "chore: release Quartz"
commit: "chore: release Quartz"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
version-script: npm run version-packages
pr-title: "chore: release Quartz"
commit-message: "chore: release Quartz"
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Tag and publish the GitHub release
if: steps.changesets.outputs.hasChangesets == 'false'
if: steps.changesets.outputs.has-changesets == 'false'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
@@ -60,8 +60,13 @@ jobs:
echo "CHANGELOG.md has no section for $VERSION — not tagging."
exit 0
fi
# GitHub creates the tag, on the commit this push brought (the merged release PR). A tag
# made here with `git tag -a` is an unsigned tag object, which GitHub marks "Unverified"
# (jackyzha0/quartz#2455). This one points straight at the commit, which shows as verified
# because GitHub signs the commits it merges. `git describe --tags` sees it all the same.
gh release create "$TAG" --target "$GITHUB_SHA" --title "Quartz $VERSION" --notes-file release-notes.md
# The tag is a lightweight ref straight to the merged release commit, created here
# before the release. GitHub signs the commits it merges, so the tag shows as verified.
# Letting `gh release create` make the tag instead gives an unsigned annotated tag
# object (tagger: whoever merged the release PR), which GitHub marks "Unverified"
# (jackyzha0/quartz#2455). `git describe --tags` reads lightweight tags as well.
gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" >/dev/null
gh release create "$TAG" --verify-tag --title "Quartz $VERSION" --notes-file release-notes.md
# A tag created with GITHUB_TOKEN doesn't trigger `on: push: tags`, so the Docker workflow
# never built the versioned images; start it for the tag explicitly.
gh workflow run docker-build-push.yaml --ref "$TAG"
+1 -1
View File
@@ -1 +1 @@
v22.16.0
v22.22.0
+41
View File
@@ -1,5 +1,46 @@
# @jackyzha0/quartz
## 5.2.2
### Patch Changes
- ee1cdff: Updates `@quartz-themes/core` to 3.1.1: the Obsidian template (`theme: default`) works again (since 3.0 the plugin failed to initialise looking "default" up as a community theme); `default`, `obsidian` and `Obsidian default` use Obsidian's built-in theme.
## 5.2.1
### Patch Changes
- 3f8104f: Fonts: explicitly configured `body`, `code` and `interface` fonts now apply with an Obsidian theme. They are also written to Obsidian's `--font-*-override` variables on `body`, which the theme's styles read; before, the theme's own `body` font variables won over Quartz's `:root` ones.
- c392e17: Fonts: the `interface` font and per-heading fonts (`h1` … `h6`) are now loaded from Google Fonts (or self-hosted with `fontOrigin: selfHosted`) like the other fonts; before, they only rendered if installed locally. A font with a single weight now loads that weight (`weights: [700]` loaded 400), and a single-weight italic font no longer makes the Google Fonts request fail.
- 7531e67: On phones and tablets, one too-wide item in the header row (a long page title, or an Obsidian theme's styled header) no longer widens the page past the screen. The content column is `minmax(0, 1fr)` instead of `auto` (also in the full-width and minimal frames), and text in the phone header row may break anywhere.
- 95e96b4: Updates `@quartz-themes/core` to 3.1, which converts any Obsidian community theme at build time: name a theme as Obsidian lists it (`Minimal`, `AnuPpuccin`), a GitHub repository, a URL or a local `theme.css`; Style Settings exports and CSS snippets apply as in Obsidian. Theme ids from 2.x (`tokyo-night`) keep working; `aspects`, `include`, `calloutStyle` and `fonts` were removed, and the `@quartz-themes/<theme>` packages are no longer needed. Quartz keeps its own page layout under a theme, `themeFonts: false` uses the site's Quartz fonts, and a theme's embedded fonts ship as separate files. See [ThemesCore](https://quartz.jzhao.xyz/plugins/ThemesCore).
## 5.2.0
### Minor Changes
- 4ed26b3: `quartz build --config <path>` (or `-C`) reads the site configuration from another file than `./quartz.config.yaml`, so the config can live with the content outside the Quartz folder, and one Quartz install can build several content repositories (#2646). With `--watch`/`--serve`, changes to that file trigger a rebuild.
- 607ccb8: Theme support for Obsidian themes: plugin factories may be async (Quartz awaits them); font loading is built in as `configuration.fonts` (formerly the `@quartz-community/quartz-fonts` plugin, whose config entry is applied automatically); callouts and transclusions render as `<div>` like in Obsidian; popovers carry Obsidian's `hover-popover`/`markdown-embed` classes.
- 9705969: Transformers can declare `renderTransforms`: transforms of a page's content when it is rendered, `before` transclusions are inlined and page types' `treeTransforms` run (bases are filled in), and `after` them, on the finished content. encrypted-pages uses them to encrypt a note's finished content, so bases and transclusions in encrypted notes show when unlocked (quartz-community/encrypted-pages#2).
### Patch Changes
- ed4f653: Bases (bases-page 1.4.0) render closer to Obsidian:
- custom summaries are evaluated, and summaries show their name and appear per group;
- `html()`, `image()`, `icon()`, regular expressions and `file.backlinks` work in formulas;
- `kanban` views, `groupOrder`, grouped list and cards views, and the list and row height options work.
- 99685cf: Bases inside a transcluded note render that note's own base, and links in bases follow `configuration.links` (external-link icon, new tab, lazy images, popovers) (bases-page 1.5.1).
- 9a04652: Bases columns are labelled with the property's name, as in Obsidian (`priority`, `file name`), instead of title-cased (`Priority`, `Name`); bases-page's new `propertyLabels: title` option keeps the title-cased labels (bases-page 1.5.0).
- 9c46b01: Updates `@quartz-community/obsidian-flavored-markdown` to 2.3.1, which renders callout titles in `.callout-title-inner` without a `<p>`, as in Obsidian (themes put the title below its icon otherwise). Callout titles are styled on `.callout-title-inner` itself (colour, margin, line height); the `> p` rule stays for sites on an older obsidian-flavored-markdown.
- cdc5a02: Updates dependencies with minor and patch releases: `@clack/prompts` 1.9.0, `@napi-rs/simple-git` 1.2.0, `isomorphic-git` 1.44.18, `minimatch` 11.0.9, `preact-render-to-string` 6.8.3 and `prettier` 3.10.1.
- 8578f2f: Permalinks work on large sites: sites of 192 or more files are parsed in worker threads, which didn't receive the permalinks, so a note with a `permalink` was published at its file path (#2644). A permalink with `.` or `..` segments is ignored with a warning instead of writing pages outside the output folder (#2641). With `prettyLinks`, a wikilink to a note whose name has a space or a non-ASCII letter reads as the note's name without its folder, as other links do (#2643).
- 166d09b: `quartz plugin install` moves a plugin to its pinned commit even when the plugin's build left tracked files changed (its `package-lock.json`). In CI, a plugin cache restored through `restore-keys` kept those changes, and installing an updated plugin failed with "Please commit your changes or stash them" (#2639).
- 6f872d4: Updates `@quartz-community/alias-redirects` to 1.0.4 (aliases that point outside the site are skipped, #2641) and `@quartz-community/note-properties` to 1.1.5 (links in properties to missing pages get the `broken` class with `disableBrokenWikilinks`, #2635).
- 0ab525c: Updated plugins that rely on Quartz 5.1 and now declare it (`quartzVersion: ">=5.1.0"`): encrypted-pages 1.2.0, explicit-publish 1.2.0, unlisted-pages 1.2.0, obsidian-flavored-markdown 2.2.0, folder-page 1.1.0 and bases-page 1.3.0.
- 49d0563: Transcluded content no longer duplicates ids. Headings and footnotes inside a transclusion get ids unique on the page, and the links inside it go to them, so the host's footnotes and a `[[#Heading]]` link inside a transclusion jump to the right place. A same-page link whose target isn't in the transcluded section links to the transcluded page. A heading transclusion (`![[note#Heading]]`) holds only the footnotes it references instead of the page's whole footnotes section.
## 5.1.0
### Minor Changes
+3 -2
View File
@@ -556,10 +556,10 @@ export const MyFrame: PageFrame = {
`,
render({ componentData, pageBody: Content, footer: Footers }: PageFrameProps): unknown {
return (
<div class="center">
<main class="center">
{Content(componentData) as ComponentChildren}
{Footers.map((Footer) => Footer(componentData) as ComponentChildren)}
</div>
</main>
)
},
}
@@ -569,6 +569,7 @@ Key requirements:
- `name`: A unique string identifier. This is what page types and YAML config reference.
- `render()`: Receives all layout slots (header, sidebars, content, footer) and returns JSX for the inner page structure. Note that `footer` is a `QuartzComponent[]` (an array) — frames should iterate over it with `.map()` to render all footer components.
- Put the page's content in a `<main>` element (and sidebars in `<aside>`), as the built-in frames do, so screen readers can jump to it.
- `css` (optional): Frame-specific CSS. Scope it with `.page[data-frame="my-frame"]` selectors to avoid conflicts.
**2. Re-export the frame:**
+12
View File
@@ -11,6 +11,7 @@ The `build` command transforms your Markdown content into a static HTML website.
| Flag | Shorthand | Description | Default |
| ----------------- | --------- | ---------------------------------------------------------------------------------- | ------------------ |
| `--directory` | `-d` | The content folder | `content` |
| `--config` | `-C` | Path to the config file to load (see [[#Custom config file]]) | quartz.config.yaml |
| `--verbose` | `-v` | Print detailed build information (see [[#Verbose output]]) | `false` |
| `--output` | `-o` | The directory where the built site will be saved | `public` |
| `--serve` | | Start a local development server | `false` |
@@ -56,6 +57,17 @@ If you have a very large vault, you can limit the number of concurrent workers t
npx quartz build --concurrency 2
```
### Custom config file
By default Quartz loads `quartz.config.yaml` from the current working directory. Use `--config` (or `-C`) to point at a config file elsewhere — for example when the config lives alongside your content rather than inside the Quartz install.
```shell
npx quartz build --config ../my-vault/quartz.config.yaml
```
> [!note]
> The shorthand for `--config` is an uppercase `-C`. A lowercase `-c` is the shorthand for `--concurrency`, so the two are distinct.
### Verbose output
`npx quartz build --verbose` also prints:
+48
View File
@@ -23,6 +23,35 @@ layout:
`configuration` and `plugins` are described below; the `layout` section (component groups, `byPageType` overrides, sidebar modes) is described in [[layout]].
## Extending the default configuration
Without a `quartz.config.yaml`, Quartz uses `quartz.config.default.yaml`. A `quartz.config.yaml` normally replaces it completely. With `extends`, your file can hold just the changes you make to another configuration instead:
```yaml title="quartz.config.yaml"
extends: default # quartz.config.default.yaml
configuration:
pageTitle: "My Site"
baseUrl: example.com
plugins:
- source: "@quartz-community/graph"
enabled: false # turn off a default plugin
- source: "@quartz-community/explorer"
options:
folderDefaultState: open # only this option changes
- source: github:me/my-plugin # a plugin the defaults don't have
enabled: true
```
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. Later entries in the list win.
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
> [!warning] Experimental
> `npx quartz plugin` commands that edit plugin entries (`enable`, `disable`, `config`, …) only see the entries in your own file so far. Edit an extending `quartz.config.yaml` by hand.
## General Configuration
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
@@ -54,6 +83,11 @@ This part of the configuration concerns anything that can affect the whole site.
- `"all"` (default): every file that isn't ignored.
- `"referenced"`: only files a published page links to or embeds. Use this with [[ExplicitPublish]] or [[private pages|drafts]], so that files only unpublished notes use stay private.
- Files that Quartz renders as pages themselves (e.g. `.base` and `.canvas` files) are never copied as raw assets.
- `slugs`: how file paths become URLs.
- `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 combining accents (`á č é ů …`) are removed. Letters without a decomposition (`ø`, `ł`, `ß`, `æ`) and non-Latin scripts (Chinese, Japanese, Korean, Arabic, Devanagari, …) are kept as they are.
- 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`.
- `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.
@@ -133,6 +167,20 @@ plugins:
Plugins are categorized by their type (transformer, filter, emitter, pageType) based on their manifest. The `order` field controls execution order within each category.
`before` and `after` name plugins that this one must run before or after (one name or a list; `obsidian-flavored-markdown`, `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` all work, as do the built-ins `frontmatter`, `links`, `drafts` and `contentIndex`). They never override `order`; they are checked against it:
```yaml title="quartz.config.yaml"
plugins:
- source: github:me/my-transformer
enabled: true
order: 45
after: obsidian-flavored-markdown # needs the links OFM creates
```
- Between plugins with the same `order`, `before`/`after` decide the order (otherwise the list order does).
- If `order` contradicts a constraint (here: OFM moved to order 50), the build stops with an error that names both orders, instead of silently running the plugins the wrong way round.
- A name that isn't in your config is an error. A plugin that is disabled, or runs in another category (a filter named by a transformer), is skipped: the constraint applies only where both plugins run.
> [!note]
> For advanced TS override of plugin configuration, you can modify `quartz.ts`:
>
+2
View File
@@ -15,4 +15,6 @@ Under the hood, this is done by hijacking page navigations and instead fetching
Pages are fetched ahead of a click by [[prefetching]], which the router uses to show them at once; the fetched pages are also reused by [[popover previews]].
Back and Forward return to where you were on each page: the router keeps each history entry's scroll position and restores it after the page is swapped in, and a reload keeps it too. Links to a heading on the same page add a history entry and only scroll, so Back returns to where you clicked.
Redirects are followed: when a link is redirected (for example `folder` → `folder/` on static hosts, or an alias page to its canonical page), the address bar shows the final URL and relative links on the new page resolve against it.
+1 -1
View File
@@ -33,7 +33,7 @@ configuration:
openLinksInNewTab: false
lazyLoad: false
externalLinkIcon: true
disableBrokenWikilinks: false
disableBrokenWikilinks: true
drafts:
publish: false # true = publish drafts anyway (e.g. preview deployments)
contentIndex:
+2 -2
View File
@@ -8,13 +8,13 @@ This guide walks you through setting up Quartz from scratch. If you already ran
You need these tools installed before continuing:
- **[Node.js](https://nodejs.org/) v22 or later** (run `node -v` to check)
- **[Node.js](https://nodejs.org/) v22.22 or later** (run `node -v` to check)
- **npm v10.9.2 or later** (bundled with Node — run `npm -v` to check)
- **[Git](https://git-scm.com/)** (run `git -v` to check)
> [!warning] Common issues
>
> - **Linux**: System packages (`apt install nodejs`) often ship much older versions. Use [nvm](https://github.com/nvm-sh/nvm) or the [NodeSource](https://github.com/nodesource/distributions) repository to get Node.js v22.
> - **Linux**: System packages (`apt install nodejs`) often ship much older versions. Use [nvm](https://github.com/nvm-sh/nvm) or the [NodeSource](https://github.com/nodesource/distributions) repository to get Node.js v22.22 or later.
> - **Windows**: When installing Git, make sure **"Git from the command line and also from 3rd-party software"** is selected so that `git` is available in your terminal. If `node -v` or `git -v` shows "command not found", restart your terminal or check your PATH.
> - **macOS**: The Xcode command-line tools include Git (`xcode-select --install`). For Node.js, [nvm](https://github.com/nvm-sh/nvm) or the [official installer](https://nodejs.org/) both work.
+1 -1
View File
@@ -39,7 +39,7 @@ cd quartz
## 2. Install Dependencies
> [!important]
> Quartz requires **Node.js 22** or later. Check your version with `node -v` and upgrade at [nodejs.org](https://nodejs.org/) if needed.
> Quartz requires **Node.js 22.22** or later. Check your version with `node -v` and upgrade at [nodejs.org](https://nodejs.org/) if needed.
```bash
npm i
+1 -1
View File
@@ -6,7 +6,7 @@ Quartz is a fast, batteries-included static-site generator that transforms Markd
## 🪴 Get Started
Quartz requires **at least [Node](https://nodejs.org/) v22** and `npm` v10.9.2 to function correctly. Ensure you have these installed on your machine before continuing. See the [[getting-started/index#Prerequisites|prerequisites]] for help installing them.
Quartz requires **at least [Node](https://nodejs.org/) v22.22** and `npm` v10.9.2 to function correctly. Ensure you have these installed on your machine before continuing. See the [[getting-started/index#Prerequisites|prerequisites]] for help installing them.
> [!tip] GitHub users
> You can also use the **[GitHub template](https://github.com/jackyzha0/quartz/generate)** to create your repository in one click, then clone that instead. See [[installation#Option A Use the GitHub Template Recommended|Option A]] in the installation guide.
+11 -6
View File
@@ -170,12 +170,17 @@ plugins:
Available built-in conditions:
| Condition | Description |
| --------------- | ----------------------------------------------------- |
| `not-index` | Only render when the page is not the root `index.md` |
| `has-tags` | Only render when the page has tags in its frontmatter |
| `has-backlinks` | Only render when the page has backlinks |
| `has-toc` | Only render when the page has a table of contents |
| Condition | Description |
| ----------------- | --------------------------------------------------------------------------- |
| `is-index` | Only render on the root `index.md` (the home page) |
| `not-index` | Only render when the page is not the root `index.md` |
| `is-folder-index` | Only render on a folder's index page (`folder/index.md` or a generated one) |
| `has-tags` | Only render when the page has tags in its frontmatter |
| `has-backlinks` | Only render when the page has backlinks |
| `has-toc` | Only render when the page has a table of contents |
| `not-<condition>` | Negates any other condition, e.g. `not-has-tags`, `not-has-backlinks` |
The `not-` prefix also works for conditions registered by plugins or in `quartz.ts`. To change the layout of a whole page type (folder pages, tag pages, …) rather than single pages, use `layout.byPageType` (see [[layout#Per-page-type overrides]]).
### TS Override
+9 -6
View File
@@ -132,12 +132,15 @@ plugins:
Available conditions:
| Condition | Effect |
| --------------- | ------------------------------------------------------------------------ |
| `not-index` | Hidden on the root index page, shown everywhere else |
| `has-tags` | Only shown on pages that have tags in frontmatter |
| `has-backlinks` | Only shown on pages that another (listed) page links to |
| `has-toc` | Only shown on pages with a table of contents (needs `table-of-contents`) |
| Condition | Effect |
| ----------------- | ---------------------------------------------------------------------------- |
| `is-index` | Only shown on the root index page (the home page) |
| `not-index` | Hidden on the root index page, shown everywhere else |
| `is-folder-index` | Only shown on folder index pages (`folder/index.md` or a generated one) |
| `has-tags` | Only shown on pages that have tags in frontmatter |
| `has-backlinks` | Only shown on pages that another (listed) page links to |
| `has-toc` | Only shown on pages with a table of contents (needs `table-of-contents`) |
| `not-<condition>` | Negates any condition, built-in or registered: `not-has-tags`, `not-has-toc` |
Plugins can register additional conditions. An unknown condition name prints a warning at build time and the component is always shown.
+1
View File
@@ -63,6 +63,7 @@ With Quartz 5.1, `.base` pages follow the site's publish filters (e.g. [[Explici
This plugin accepts the following configuration options:
- `propertyLabels`: How column and property labels are shown. `"name"` (default) shows a property's name as Obsidian does (`priority`, `file name`); `"title"` title-cases it (`Priority`, `Name`). A property's `displayName` is always used.
- `defaultViewType`: Open a base on its first view of this type. Unset by default: a base opens on its first view, as in Obsidian.
- `linkResolution`: How to resolve internal links in view renderers. Should match `configuration.links.markdownLinkResolution` (built-in [[CrawlLinks|link processing]]). Can be `"absolute"`, `"relative"`, or `"shortest"`. Defaults to `"shortest"`.
- `customViews`: A map of custom view renderers. Keys are view type names. These override built-in renderers for the same type, or add new view types. Requires a TS override.
+4
View File
@@ -36,6 +36,10 @@ Options:
> [!note]
> An existing `@quartz-community/content-index` entry is applied to `configuration.contentIndex` automatically. Run `npx quartz plugin doctor --fix` to move it.
## `contentIndex.json`
Each entry of `static/contentIndex.json` is keyed by slug and holds `slug`, `filePath`, `title`, `links`, `tags` and `content` (the page's text), plus `date` when the page has one: the date selected by `defaultDateType` of [[CreatedModifiedDate]] (the same date [[ContentMeta]] shows and the RSS feed uses), as an ISO 8601 string such as `"2024-01-02T03:04:05.000Z"`. Client-side components can use it to sort by date, e.g. `new Date(entry.date)`. When that date is the one the page's frontmatter sets for the configured date type (e.g. `modified:` / `lastmod:` with `defaultDateType: modified`), rather than one from git or the file system, the entry also has `dateFromFrontmatter: true`; otherwise the field is absent.
## Adding fields
Plugins can add their own fields to each entry of `contentIndex.json` with `extendContentIndex` — see [[making plugins#Extending the content index]].
+1 -1
View File
@@ -32,7 +32,7 @@ Options:
- `openLinksInNewTab`: If `true`, configures external links to open in a new tab. Defaults to `false`.
- `lazyLoad`: If `true`, adds lazy loading to resource elements (`img`, `video`, etc.) to improve page load performance. Defaults to `false`.
- `externalLinkIcon`: Adds an icon next to external links when `true` (default) to visually distinguishing them from internal links.
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `false`. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed.
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `true`, as Obsidian marks unresolved links. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed. Links to pages that a filter removes (e.g. [[RemoveDrafts|drafts]] or pages without `publish: true` under [[ExplicitPublish]]) are marked `broken` too, since they 404; they also get `data-filtered="<filter name>"`. A folder link stays unbroken when only the folder's `index.md` is removed, because the folder still gets a generated folder page.
- `enabled`: set to `false` to turn link processing off (not recommended — links break on nested pages and backlinks/graph are empty).
- `order`: position among transformers. Defaults to `60`, after the Markdown flavour plugins (e.g. [[ObsidianFlavoredMarkdown]] at `40`) that turn wikilinks into links.
+1 -1
View File
@@ -22,7 +22,7 @@ This plugin accepts the following configuration options:
- `mathJaxOptions`: Additional options passed to the MathJax renderer. See the [MathJax docs](https://docs.mathjax.org/en/latest/options/) for available options.
- `typstOptions`: Additional options passed to the Typst renderer.
With KaTeX, the KaTeX stylesheet and its copy-tex script are loaded from jsDelivr.
With KaTeX, the KaTeX stylesheet and its copy-tex script are loaded from jsDelivr. The stylesheet blocks rendering only on pages with math; elsewhere it loads in the background, ready for pages opened with SPA navigation.
### Default options
+3
View File
@@ -34,6 +34,9 @@ This plugin accepts the following configuration options:
- `enableVideoEmbed`: If `true` (default), enables the embedding of video files.
- `enableCheckbox`: If `true`, adds support for interactive checkboxes in content, including custom task characters (e.g. `- [?]`, `- [!]`, `- [/]`). Defaults to `false`; the default `quartz.config.yaml` turns it on.
- `enableObsidianUri`: If `true` (default), marks `obsidian://` protocol links with a CSS class and data attribute for custom styling.
- `blockWrappers`: If `true` (default), wraps each top-level block in the `div` Obsidian puts it in (`div.el-p > p`), which Obsidian themes space blocks with. No visible change without a theme.
- `foldHeadings`: If `true`, headings fold as in Obsidian's reading view ("Fold heading"): an arrow before each heading, shown on hover, hides everything up to the next heading of the same or a higher level. Defaults to `false`.
- `foldLists`: If `true`, list items with a sublist fold as in Obsidian's reading view ("Fold indent"): an arrow before the item, shown on hover, hides its sublist. Defaults to `false`.
Also supported:
Vendored
+6
View File
@@ -3,6 +3,12 @@ declare module "*.scss" {
export = content
}
// micromorph ships these types, but its package.json "exports" don't list them, so TypeScript's
// "bundler" resolution doesn't find them
declare module "micromorph" {
export default function micromorph(from: Node, to: Node): Promise<void>
}
// dom custom event
interface CustomEventMap {
prenav: CustomEvent<{}>
+969 -1055
View File
File diff suppressed because it is too large. Load diff
+32 -33
View File
@@ -1,8 +1,8 @@
{
"name": "@jackyzha0/quartz",
"description": "\ud83c\udf31 publish your digital garden and notes as a website",
"description": "🌱 publish your digital garden and notes as a website",
"private": true,
"version": "5.1.0",
"version": "5.2.2",
"type": "module",
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
"license": "MIT",
@@ -25,7 +25,7 @@
},
"engines": {
"npm": ">=10.9.2",
"node": ">=22"
"node": ">=22.22"
},
"keywords": [
"site generator",
@@ -42,60 +42,60 @@
"@clack/prompts": "^1.8.0",
"@floating-ui/dom": "^1.7.4",
"@myriaddreamin/rehype-typst": "^0.7.0",
"@napi-rs/simple-git": "1.1.0",
"@napi-rs/simple-git": "1.2.0",
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.3",
"@quartz-community/bases-page": "^1.3.0",
"@quartz-community/breadcrumbs": "^1.0.3",
"@quartz-community/canvas-page": "^1.0.3",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.3",
"@quartz-community/breadcrumbs": "^1.0.4",
"@quartz-community/canvas-page": "^1.1.1",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
"@quartz-community/content-meta": "^1.0.2",
"@quartz-community/content-page": "^1.0.3",
"@quartz-community/created-modified-date": "^1.0.3",
"@quartz-community/created-modified-date": "^1.0.4",
"@quartz-community/darkmode": "^1.0.2",
"@quartz-community/description": "^1.0.2",
"@quartz-community/encrypted-pages": "^1.2.0",
"@quartz-community/explicit-publish": "^1.2.0",
"@quartz-community/explorer": "^1.0.3",
"@quartz-community/explorer": "^1.2.1",
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.0",
"@quartz-community/footer": "^1.1.1",
"@quartz-community/github-flavored-markdown": "^2.1.1",
"@quartz-community/graph": "^1.0.3",
"@quartz-community/folder-page": "^1.1.2",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.0",
"@quartz-community/graph": "^1.0.7",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.0.2",
"@quartz-community/note-properties": "^1.1.4",
"@quartz-community/obsidian-flavored-markdown": "^2.2.0",
"@quartz-community/og-image": "^1.1.1",
"@quartz-community/ox-hugo": "^1.0.1",
"@quartz-community/latex": "^1.1.1",
"@quartz-community/note-properties": "^1.2.1",
"@quartz-community/obsidian-flavored-markdown": "^2.5.1",
"@quartz-community/og-image": "^1.1.2",
"@quartz-community/ox-hugo": "^1.0.2",
"@quartz-community/page-title": "^1.0.2",
"@quartz-community/reader-mode": "^1.0.2",
"@quartz-community/recent-notes": "^1.0.3",
"@quartz-community/roam": "^1.1.0",
"@quartz-community/search": "^1.0.3",
"@quartz-community/search": "^1.1.1",
"@quartz-community/spacer": "^1.0.2",
"@quartz-community/stacked-pages": "^1.0.3",
"@quartz-community/syntax-highlighting": "^1.0.3",
"@quartz-community/table-of-contents": "^1.0.3",
"@quartz-community/syntax-highlighting": "^1.0.4",
"@quartz-community/table-of-contents": "^1.0.5",
"@quartz-community/tag-list": "^1.0.3",
"@quartz-community/tag-page": "^1.0.5",
"@quartz-community/tag-page": "^1.0.6",
"@quartz-community/unlisted-pages": "^1.2.0",
"@quartz-themes/core": "^2.0.1",
"@quartz-themes/core": "^3.2.1",
"ansi-truncate": "^1.4.0",
"async-mutex": "^0.5.0",
"chokidar": "^5.0.0",
"chokidar": "^6.0.0",
"esbuild-sass-plugin": "^3.6.0",
"globby": "^16.1.0",
"gray-matter": "^4.0.3",
"hast-util-from-html": "^2.0.0",
"hast-util-to-html": "^9.0.5",
"hast-util-to-html": "^9.0.7",
"hast-util-to-jsx-runtime": "^2.3.6",
"is-absolute-url": "^4.0.1",
"is-absolute-url": "^5.0.0",
"isomorphic-git": "^1.36.3",
"js-yaml": "^4.1.0",
"js-yaml": "^5.5.0",
"lightningcss": "^1.31.1",
"micromorph": "^0.4.5",
"minimatch": "^11.0.5",
@@ -117,16 +117,15 @@
"unist-util-visit": "^5.1.0",
"vfile": "^6.0.3",
"workerpool": "^10.0.1",
"ws": "^8.19.0",
"ws": "^8.23.0",
"yaml": "^2.8.2",
"yargs": "^18.0.0"
},
"devDependencies": {
"@changesets/cli": "^2.29.2",
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.2.0",
"@quartz-community/utils": "^1.3.0",
"@types/hast": "^3.0.4",
"@types/js-yaml": "^4.0.9",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
"@types/semver": "^7.7.1",
@@ -136,6 +135,6 @@
"esbuild": "^0.28.2",
"prettier": "^3.8.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
"typescript": "^7.0.2"
}
}
+4 -4
View File
@@ -24,17 +24,17 @@ configuration:
lightMode:
light: "#faf8f8"
lightgray: "#e5e5e5"
gray: "#b8b8b8"
gray: "#727272"
darkgray: "#4e4e4e"
dark: "#2b2b2b"
secondary: "#284b63"
tertiary: "#84a59d"
tertiary: "#587971"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#fff23688"
darkMode:
light: "#161618"
lightgray: "#393639"
gray: "#646464"
gray: "#7f7f7f"
darkgray: "#d4d4d4"
dark: "#ebebec"
secondary: "#7b97aa"
@@ -99,7 +99,7 @@ plugins:
- source: "@quartz-themes/core"
enabled: false
options:
theme: tokyo-night
theme: Tokyo Night
mode: both
- source: "@quartz-community/explicit-publish"
enabled: false
+3 -3
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env -S node --no-deprecation
const [major] = process.versions.node.split(".").map(Number)
if (major < 22) {
const [major, minor] = process.versions.node.split(".").map(Number)
if (major < 22 || (major === 22 && minor < 22)) {
console.error(
`\nQuartz requires Node.js >= 22, but you are running Node.js ${process.version}.\n` +
`\nQuartz requires Node.js >= 22.22, but you are running Node.js ${process.version}.\n` +
`Please upgrade: https://nodejs.org/\n`,
)
process.exit(1)
+16 -1
View File
@@ -26,7 +26,8 @@ import { minimatch } from "minimatch"
import { formatLayoutReport, getLayoutReport } from "./plugins/loader/layoutReport"
import { getBuiltinPlan } from "./plugins/loader/config-loader"
import { prepareContentIndex } from "./plugins/builtins/contentIndex"
import { printDiagnosticsSummary, warn } from "./util/diagnostics"
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
import { LinksInstance, markLinksToRemovedPages } from "./plugins/builtins/links"
import { collectPermalinks } from "./util/permalinks"
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
@@ -66,6 +67,18 @@ function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
}
/** Mark links to pages the filters removed as broken (built-in links, crawl-links#7). */
function markRemovedLinks(
ctx: BuildCtx,
all: ProcessedContent[],
published: ProcessedContent[],
): void {
const links = ctx.cfg.plugins.transformers.find((t) => t.name === "Links") as
LinksInstance | undefined
// also when nothing was removed: in watch mode, marks from the last build may need undoing
if (links?.marksBrokenLinks) markLinksToRemovedPages(all, published, filteredBy)
}
function reportSlugCollisions(content: ProcessedContent[]): void {
const collisions = detectSlugCollisions(content)
if (collisions.length === 0) return
@@ -161,6 +174,7 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
const parsedFiles = await parseMarkdown(ctx, filePaths)
reportSlugCollisions(parsedFiles)
const filteredContent = filterContent(ctx, parsedFiles)
markRemovedLinks(ctx, parsedFiles, filteredContent)
await emitContent(ctx, filteredContent)
console.log(
@@ -418,6 +432,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
.map((file) => file.content)
reportSlugCollisions(markdownContent)
let processedFiles = filterContent(ctx, markdownContent)
markRemovedLinks(ctx, markdownContent, processedFiles)
let emittedFiles = 0
+11 -1
View File
@@ -109,6 +109,16 @@ export interface GlobalConfiguration {
* - "referenced": Only copy assets referenced by published pages
*/
publishAssets?: "all" | "referenced"
/** How file paths become URLs. */
slugs?: SlugsConfig
}
export interface SlugsConfig {
/**
* Strip accents and other diacritics from generated slugs (`české/čeština.md` →
* `ceske/cestina`), aliases and permalinks; links are resolved the same way. Off by default.
*/
stripDiacritics?: boolean
}
/** Shared by every built-in: `enabled: false` turns it off (e.g. to replace it with a plugin). */
@@ -136,7 +146,7 @@ export interface LinksConfig extends BuiltinToggle {
lazyLoad?: boolean
/** Add an icon after external links. Default `true`. */
externalLinkIcon?: boolean
/** Add a `broken` class to internal links whose target does not exist. Default `false`. */
/** Add a `broken` class to internal links whose target does not exist, as Obsidian marks unresolved links. Default `true`. */
disableBrokenWikilinks?: boolean
}
+5
View File
@@ -76,6 +76,11 @@ export const SyncArgv = {
export const BuildArgv = {
...CommonArgv,
config: {
string: true,
alias: ["C"],
describe: "path to the config file (default: ./quartz.config.yaml)",
},
output: {
string: true,
alias: ["o"],
+13 -1
View File
@@ -334,6 +334,17 @@ export async function handleBuild(argv) {
argv.watch = true
}
// Let `--config <path>` override the default ./quartz.config.yaml. Passed down
// via env so it reaches the esbuild-bundled build code and worker threads.
if (argv.config) {
const resolved = path.resolve(argv.config)
if (!fs.existsSync(resolved)) {
console.error(`Config file not found: ${resolved}`)
process.exit(1)
}
process.env.QUARTZ_CONFIG_PATH = resolved
}
// " Quartz v5.1.0 " for a release checkout, plus `git describe` (e.g. v5.1.0-3-g1a2b3c4-dirty) otherwise
const checkout = describeQuartzCheckout()
const describe = checkout.describe && checkout.describe !== `v${version}` ? checkout.describe : ""
@@ -607,8 +618,9 @@ export async function handleBuild(argv) {
"quartz.config.yaml",
"quartz.config.default.yaml",
])
const extraWatch = process.env.QUARTZ_CONFIG_PATH ? [process.env.QUARTZ_CONFIG_PATH] : []
chokidar
.watch(paths, { ignoreInitial: true })
.watch([...paths, ...extraWatch], { ignoreInitial: true })
.on("add", () => build(clientRefresh))
.on("change", () => build(clientRefresh))
.on("unlink", () => build(clientRefresh))
+1
View File
@@ -13,6 +13,7 @@ const LEGACY_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.json")
const LEGACY_DEFAULT_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.default.json")
function resolveConfigPath() {
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
if (fs.existsSync(CONFIG_YAML_PATH)) return CONFIG_YAML_PATH
if (fs.existsSync(LEGACY_PLUGINS_JSON_PATH)) return LEGACY_PLUGINS_JSON_PATH
if (fs.existsSync(DEFAULT_CONFIG_YAML_PATH)) return DEFAULT_CONFIG_YAML_PATH
+4 -2
View File
@@ -176,11 +176,13 @@ async function cloneAtCommitAsync({ url, ref, commit, dir }) {
/**
* Move a shallow clone to a pinned commit. The commit is fetched by SHA (GitHub and most hosts
* allow fetching reachable commits), so a pin that is no longer the branch tip works (#2559).
* The checkout is forced: the plugin directory is Quartz's clone, and its build (npm install)
* rewrites tracked files such as package-lock.json, which a restored CI cache keeps (#2639).
*/
async function checkoutPinnedCommitAsync(dir, commit) {
export async function checkoutPinnedCommitAsync(dir, commit) {
assertCommit(commit)
await gitAsync(["fetch", "--depth", "1", "origin", commit], { cwd: dir })
await gitAsync(["checkout", "--quiet", commit], { cwd: dir })
await gitAsync(["checkout", "--quiet", "--force", commit], { cwd: dir })
}
/**
+52 -1
View File
@@ -4,7 +4,13 @@ import { execSync } from "child_process"
import fs from "fs"
import os from "os"
import path from "path"
import { buildPluginAsync, linkPeerPlugins, pluginSourceChanged } from "./plugin-git-handlers.js"
import { pathToFileURL } from "url"
import {
buildPluginAsync,
checkoutPinnedCommitAsync,
linkPeerPlugins,
pluginSourceChanged,
} from "./plugin-git-handlers.js"
let root
let hostPreact
@@ -161,3 +167,48 @@ describe("pluginSourceChanged", () => {
assert.strictEqual(pluginSourceChanged(priorEntry, "github:owner/new-repo"), true)
})
})
describe("checkoutPinnedCommitAsync", () => {
const git = (cwd, cmd) =>
execSync(`git -c user.name=t -c user.email=t@t -c commit.gpgsign=false ${cmd}`, {
cwd,
stdio: "pipe",
timeout: 30000,
})
.toString()
.trim()
function makeRemote() {
const remote = path.join(root, "remote")
fs.mkdirSync(remote)
git(remote, "init -q -b main")
git(remote, "config uploadpack.allowAnySHA1InWant true")
fs.writeFileSync(path.join(remote, "package-lock.json"), `{ "v": 1 }`)
git(remote, "add -A")
git(remote, "commit -q -m one")
const first = git(remote, "rev-parse HEAD")
fs.writeFileSync(path.join(remote, "package-lock.json"), `{ "v": 2 }`)
git(remote, "commit -q -am two")
return { remote, first }
}
test("moves to a pinned commit that is not the branch tip", async () => {
const { remote, first } = makeRemote()
const dir = path.join(root, "plugin")
git(root, `clone -q --depth 1 ${pathToFileURL(remote).href} "${dir}"`)
await checkoutPinnedCommitAsync(dir, first)
assert.strictEqual(git(dir, "rev-parse HEAD"), first)
})
// a plugin's build (npm install) rewrites its tracked package-lock.json; a restored CI cache
// keeps that change, and the checkout refused to move ("commit your changes or stash them")
test("moves even when the plugin's build left tracked files changed (#2639)", async () => {
const { remote, first } = makeRemote()
const dir = path.join(root, "plugin")
git(root, `clone -q --depth 1 ${pathToFileURL(remote).href} "${dir}"`)
fs.writeFileSync(path.join(dir, "package-lock.json"), `{ "v": "rewritten by npm" }`)
await checkoutPinnedCommitAsync(dir, first)
assert.strictEqual(git(dir, "rev-parse HEAD"), first)
assert.strictEqual(fs.readFileSync(path.join(dir, "package-lock.json"), "utf-8"), `{ "v": 1 }`)
})
})
+9 -1
View File
@@ -5,7 +5,15 @@
// see plugin-validation.d.ts).
/** Top-level keys allowed on a plugin entry (mirrors quartz-plugins.schema.json). */
export const PLUGIN_ENTRY_KEYS = ["source", "enabled", "options", "order", "layout"]
export const PLUGIN_ENTRY_KEYS = [
"source",
"enabled",
"options",
"order",
"before",
"after",
"layout",
]
/** Keys allowed on an object-form `source`. */
export const SOURCE_OBJECT_KEYS = ["repo", "subdir", "ref", "name"]
+3 -3
View File
@@ -25,17 +25,17 @@ configuration:
lightMode:
light: "#faf8f8"
lightgray: "#e5e5e5"
gray: "#b8b8b8"
gray: "#727272"
darkgray: "#4e4e4e"
dark: "#2b2b2b"
secondary: "#284b63"
tertiary: "#84a59d"
tertiary: "#587971"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#fff23688"
darkMode:
light: "#161618"
lightgray: "#393639"
gray: "#646464"
gray: "#7f7f7f"
darkgray: "#d4d4d4"
dark: "#ebebec"
secondary: "#7b97aa"
+3 -3
View File
@@ -25,17 +25,17 @@ configuration:
lightMode:
light: "#faf8f8"
lightgray: "#e5e5e5"
gray: "#b8b8b8"
gray: "#727272"
darkgray: "#4e4e4e"
dark: "#2b2b2b"
secondary: "#284b63"
tertiary: "#84a59d"
tertiary: "#587971"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#fff23688"
darkMode:
light: "#161618"
lightgray: "#393639"
gray: "#646464"
gray: "#7f7f7f"
darkgray: "#d4d4d4"
dark: "#ebebec"
secondary: "#7b97aa"
+3 -3
View File
@@ -26,17 +26,17 @@ configuration:
lightMode:
light: "#faf8f8"
lightgray: "#e5e5e5"
gray: "#b8b8b8"
gray: "#727272"
darkgray: "#4e4e4e"
dark: "#2b2b2b"
secondary: "#284b63"
tertiary: "#84a59d"
tertiary: "#587971"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#fff23688"
darkMode:
light: "#161618"
lightgray: "#393639"
gray: "#646464"
gray: "#7f7f7f"
darkgray: "#d4d4d4"
dark: "#ebebec"
secondary: "#7b97aa"
+6 -4
View File
@@ -25,17 +25,17 @@ configuration:
lightMode:
light: "#faf8f8"
lightgray: "#e5e5e5"
gray: "#b8b8b8"
gray: "#727272"
darkgray: "#4e4e4e"
dark: "#2b2b2b"
secondary: "#284b63"
tertiary: "#84a59d"
tertiary: "#587971"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#fff23688"
darkMode:
light: "#161618"
lightgray: "#393639"
gray: "#646464"
gray: "#7f7f7f"
darkgray: "#d4d4d4"
dark: "#ebebec"
secondary: "#7b97aa"
@@ -44,7 +44,7 @@ configuration:
textHighlight: "#b3aa0288"
links:
markdownLinkResolution: shortest
# disableBrokenWikilinks: false # Set true to add a "broken" CSS class to internal links whose target does not exist.
# disableBrokenWikilinks: true # Set false to stop adding a "broken" CSS class to internal links whose target does not exist.
contentIndex:
enableSiteMap: true
enableRSS: true
@@ -80,6 +80,8 @@ plugins:
enableYouTubeEmbed: true
enableVideoEmbed: true
enableCheckbox: true
foldHeadings: true
foldLists: true
order: 40
- source: "@quartz-community/github-flavored-markdown"
enabled: true
+4 -4
View File
@@ -25,17 +25,17 @@ configuration:
lightMode:
light: "#faf8f8"
lightgray: "#e5e5e5"
gray: "#b8b8b8"
gray: "#727272"
darkgray: "#4e4e4e"
dark: "#2b2b2b"
secondary: "#284b63"
tertiary: "#84a59d"
tertiary: "#587971"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#fff23688"
darkMode:
light: "#161618"
lightgray: "#393639"
gray: "#646464"
gray: "#7f7f7f"
darkgray: "#d4d4d4"
dark: "#ebebec"
secondary: "#7b97aa"
@@ -44,7 +44,7 @@ configuration:
textHighlight: "#b3aa0288"
links:
markdownLinkResolution: shortest
# disableBrokenWikilinks: false # Set true to add a "broken" CSS class to internal links whose target does not exist.
# disableBrokenWikilinks: true # Set false to stop adding a "broken" CSS class to internal links whose target does not exist.
contentIndex:
enableSiteMap: true
enableRSS: true
+28 -10
View File
@@ -1,5 +1,5 @@
import { i18n } from "../i18n"
import { FullSlug, getFileExtension, joinSegments, pathToRoot } from "../util/path"
import { FullSlug, getFileExtension, joinSegments, pathToRoot, simplifySlug } from "../util/path"
import { CSSResourceToStyleElement, JSResourceToScriptElement } from "../util/resources"
import { googleFontHref, googleFontSubsetHref } from "../util/theme"
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
@@ -27,9 +27,24 @@ export default (() => {
const baseDir = fileData.slug === "404" ? path : pathToRoot(fileData.slug!)
const iconPath = joinSegments(baseDir, "static/icon.png")
// Url of current page
const socialUrl =
fileData.slug === "404" ? url.toString() : joinSegments(url.toString(), fileData.slug!)
// The page's public URL, as the sitemap lists it: `folder/` for `folder/index`,
// no `index` for the home page, encoded.
const isNotFound = fileData.slug === "404"
const pageUrl = isNotFound
? url.toString()
: joinSegments(url.toString(), encodeURI(simplifySlug(fileData.slug!)))
// Notes (not the home page, folder or tag pages) are articles.
const isArticle =
!isNotFound &&
fileData.relativePath !== undefined &&
!fileData.slug!.endsWith("index") &&
!fileData.slug!.startsWith("tags/")
const isoDate = (d: unknown) =>
d instanceof Date && !isNaN(d.getTime()) ? d.toISOString() : undefined
// Without a frontmatter date, the published date is only the build time.
const published =
isArticle && fileData.frontmatter?.published ? isoDate(fileData.dates?.published) : undefined
const modified = isArticle ? isoDate(fileData.dates?.modified) : undefined
const usesCustomOgImage = ctx.cfg.plugins.emitters.some((e) => e.name === "CustomOgImages")
const ogImageDefaultPath = `https://${cfg.baseUrl}/static/og-image.png`
@@ -50,19 +65,21 @@ export default (() => {
{cfg.theme.cdnCaching && cfg.theme.fontOrigin === "googleFonts" && (
<>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
{/* Font files are fetched with CORS, so only a CORS connection is reused. */}
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link rel="stylesheet" href={googleFontHref(cfg.theme)} />
{cfg.theme.typography.title && (
<link rel="stylesheet" href={googleFontSubsetHref(cfg.theme, cfg.pageTitle)} />
)}
</>
)}
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossOrigin="anonymous" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="og:site_name" content={cfg.pageTitle}></meta>
<meta property="og:site_name" content={cfg.pageTitle} />
<meta property="og:title" content={title} />
<meta property="og:type" content="website" />
<meta property="og:type" content={isArticle ? "article" : "website"} />
{published && <meta property="article:published_time" content={published} />}
{modified && <meta property="article:modified_time" content={modified} />}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
@@ -84,8 +101,9 @@ export default (() => {
{cfg.baseUrl && (
<>
<meta property="twitter:domain" content={cfg.baseUrl}></meta>
<meta property="og:url" content={socialUrl}></meta>
<meta property="twitter:url" content={socialUrl}></meta>
<meta property="og:url" content={pageUrl}></meta>
<meta property="twitter:url" content={pageUrl}></meta>
{!isNotFound && <link rel="canonical" href={pageUrl} />}
</>
)}
+5 -3
View File
@@ -74,14 +74,14 @@ export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit, sort
<div class="section">
<p class="meta">{page.dates && <Date date={getDate(page)!} locale={cfg.locale} />}</p>
<div class="desc">
<h3>
<h2>
<a
href={resolveRelative(fileData.slug!, page.slug!)}
class="internal internal-link"
>
{title}
</a>
</h3>
</h2>
</div>
<ul class="tags">
{tags.map((tag) => (
@@ -104,8 +104,10 @@ export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit, sort
}
PageList.css = `
.section h3 {
/* An h2 under the page's h1 (it was an h3, which skipped a level), at the h3's size. */
.section h2 {
margin: 0;
font-size: 1.12rem;
}
.section > .tags {
+6 -6
View File
@@ -24,12 +24,12 @@ export const DefaultFrame: PageFrame = {
}: PageFrameProps) {
return (
<>
<div class="left sidebar" data-sidebar-mode={sidebars?.left ?? "fit"}>
<aside class="left sidebar" data-sidebar-mode={sidebars?.left ?? "fit"}>
{left.map((BodyComponent) => (
<BodyComponent {...componentData} />
))}
</div>
<div class="center">
</aside>
<main class="center">
<div class="page-header">
<Header {...componentData}>
{header.map((HeaderComponent) => (
@@ -49,12 +49,12 @@ export const DefaultFrame: PageFrame = {
<BodyComponent {...componentData} />
))}
</div>
</div>
<div class="right sidebar" data-sidebar-mode={sidebars?.right ?? "fit"}>
</main>
<aside class="right sidebar" data-sidebar-mode={sidebars?.right ?? "fit"}>
{right.map((BodyComponent) => (
<BodyComponent {...componentData} />
))}
</div>
</aside>
{footer.map((FooterComponent) => (
<FooterComponent {...componentData} />
))}
+2 -2
View File
@@ -23,7 +23,7 @@ export const FullWidthFrame: PageFrame = {
}: PageFrameProps) {
return (
<>
<div class="center full-width">
<main class="center full-width">
<div class="page-header">
<Header {...componentData}>
{header.map((HeaderComponent) => (
@@ -43,7 +43,7 @@ export const FullWidthFrame: PageFrame = {
<BodyComponent {...componentData} />
))}
</div>
</div>
</main>
{footer.map((FooterComponent) => (
<FooterComponent {...componentData} />
))}
+2 -2
View File
@@ -13,9 +13,9 @@ export const MinimalFrame: PageFrame = {
render({ componentData, pageBody: Content, footer }: PageFrameProps) {
return (
<>
<div class="center minimal">
<main class="center minimal">
<Content {...componentData} />
</div>
</main>
{footer.map((FooterComponent) => (
<FooterComponent {...componentData} />
))}
+110 -1
View File
@@ -3,7 +3,9 @@ import { toHtml } from "hast-util-to-html"
import assert from "node:assert"
import { renderTranscludes, pageResources, transformPageContent } from "./renderPage"
import { Root, Element } from "hast"
import { FullSlug } from "../util/path"
import { FullSlug, setSlugOptions } from "../util/path"
import { slugifyFilePath } from "@quartz-community/utils"
import vm from "node:vm"
import { GlobalConfiguration } from "../cfg"
import { QuartzComponentProps } from "./types"
import { StaticResources } from "../util/resources"
@@ -49,6 +51,42 @@ function makeComponentData(
}
describe("renderTranscludes", () => {
test("wraps transcluded content in Obsidian's embed markup", () => {
const root: Root = { type: "root", children: [makeTranscludeBlockquote("target")] }
const targetHtml: Root = {
type: "root",
children: [
{
type: "element",
tagName: "p",
properties: {},
children: [{ type: "text", value: "Target content" }],
},
],
}
renderTranscludes(
root,
cfg,
"current" as FullSlug,
makeComponentData([makePageData("target", targetHtml)]) as QuartzComponentProps,
new Set<FullSlug>(["current" as FullSlug]),
)
const [title, content, link, embedLink] = (root.children[0] as Element).children as Element[]
assert.deepStrictEqual(title.properties.className, ["embed-title", "markdown-embed-title"])
assert.deepStrictEqual(content.properties.className, ["markdown-embed-content"])
const view = content.children[0] as Element
assert.deepStrictEqual(view.properties.className, [
"markdown-preview-view",
"markdown-rendered",
])
assert.strictEqual((view.children[0] as Element).tagName, "p")
assert.deepStrictEqual(link.properties.class, ["internal", "internal-link", "transclude-src"])
// Obsidian's icon link to the note, after Quartz's (hidden unless a theme shows it).
assert.deepStrictEqual(embedLink.properties.className, ["markdown-embed-link"])
assert.strictEqual(embedLink.properties.href, link.properties.href)
assert.strictEqual((embedLink.children[0] as Element).tagName, "svg")
})
test("resolves a single page transclusion", () => {
const root: Root = {
type: "root",
@@ -184,6 +222,43 @@ describe("renderTranscludes", () => {
assert.ok(!secondText.includes("Circular transclusion"), "should not show circular warning")
})
test("a header transclusion finds headings inside Obsidian's block wrappers", () => {
const root: Root = {
type: "root",
children: [makeTranscludeBlockquote("target", "#details")],
}
const wrap = (tagName: string, properties: Element["properties"], value: string): Element => ({
type: "element",
tagName: "div",
properties: { className: [`el-${tagName}`] },
children: [{ type: "element", tagName, properties, children: [{ type: "text", value }] }],
})
const targetHtml: Root = {
type: "root",
children: [
wrap("h2", { id: "intro" }, "Intro"),
wrap("p", {}, "Intro text"),
wrap("h2", { id: "details" }, "Details"),
wrap("p", {}, "Details text"),
wrap("h2", { id: "after" }, "After"),
wrap("p", {}, "After text"),
],
}
renderTranscludes(
root,
cfg,
"current" as FullSlug,
makeComponentData([makePageData("target", targetHtml)]) as QuartzComponentProps,
new Set<FullSlug>(["current" as FullSlug]),
)
const html = toHtml(root.children[0] as Element)
assert.ok(html.includes('<div class="el-p"><p>Details text</p></div>'), html)
assert.ok(!html.includes("Intro text"), "the slice starts at its heading")
assert.ok(!html.includes("After text"), "the slice ends at the next heading")
})
test("a header transclusion matches a heading's Obsidian-anchor alias", () => {
const root: Root = {
type: "root",
@@ -386,6 +461,40 @@ describe("pageResources", () => {
)
})
const inlineScript = (result: ReturnType<typeof pageResources>) =>
result.js
.filter((j) => j.contentType === "inline")
.map((j) => ("script" in j ? j.script : ""))
.join("\n")
test("slugs.stripDiacritics reaches scripts in the browser (#2410)", () => {
setSlugOptions({ stripDiacritics: true })
try {
const script = inlineScript(pageResources("." as FullSlug, emptyResources))
// run it as the page does; the global it sets is the one utils reads
const page = vm.createContext({
fetch: () => new Promise(() => {}),
location: { href: "https://x/" },
URL,
})
vm.runInContext(script.replace("window.", "globalThis."), page)
const set = vm.runInContext(
`JSON.stringify(globalThis[Symbol.for("@quartz-community/utils/slugOptions")])`,
page,
)
assert.strictEqual(set, JSON.stringify({ stripDiacritics: true }))
// same global as utils in this thread: a script with utils 1.3 slugs as the build does
assert.strictEqual(slugifyFilePath("české/čeština.md" as never), "ceske/cestina")
} finally {
setSlugOptions(undefined)
}
})
test("the default slug options write nothing to the page", () => {
const script = inlineScript(pageResources("." as FullSlug, emptyResources))
assert.ok(!script.includes("slugOptions"), script)
})
test("omits subpath prefix when baseDir is empty (serve mode)", () => {
const result = pageResources("." as FullSlug, emptyResources)
for (const css of result.css) {
+123 -60
View File
@@ -7,7 +7,13 @@ import {
JSResourceToScriptElement,
StaticResources,
} from "../util/resources"
import { FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path"
import {
FullSlug,
RelativeURL,
getSlugOptions,
joinSegments,
normalizeHastElement,
} from "../util/path"
import { clone } from "../util/clone"
import { Root, Element, ElementContent } from "hast"
import { GlobalConfiguration, SidebarModes } from "../cfg"
@@ -15,6 +21,7 @@ import { i18n } from "../i18n"
import { styleText } from "util"
import { resolveFrame } from "./frames"
import type { PageTreeTransforms, TreeTransform } from "../plugins/types"
import { blockOf, createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
import type { BuildCtx } from "../util/ctx"
interface RenderComponents {
@@ -50,6 +57,17 @@ function headingHasId(heading: Element, id: string): boolean {
)
return hasAlias(heading)
}
/**
* `configuration.slugs` for scripts in the browser. @quartz-community/utils (1.3+) keeps its slug
* options on this global, so every plugin script that slugs (the explorer places pages by their
* file path) slugs as the build did. Nothing is written with the default options.
*/
export function slugOptionsScript(): string {
const options = getSlugOptions()
if (!options.stripDiacritics) return ""
return `;globalThis[Symbol.for("@quartz-community/utils/slugOptions")] = ${JSON.stringify(options)}`
}
export function pageResources(
baseDir: FullSlug | RelativeURL,
staticResources: StaticResources,
@@ -101,7 +119,8 @@ export function pageResources(
`.catch(e => { console.warn("[Quartz] Could not load ${contentIndexPath} (" + e.message + "); is configuration.contentIndex disabled?"); return {} });` +
// Absolute URL of static/ (plugin assets live in static/plugins/<to>). Resolved once on the
// first page, so it stays valid across SPA navigations.
`window.quartzStaticUrl = new URL(${JSON.stringify(joinSegments(baseDir, "static") + "/")}, location.href).href`
`window.quartzStaticUrl = new URL(${JSON.stringify(joinSegments(baseDir, "static") + "/")}, location.href).href` +
slugOptionsScript()
const resources: StaticResources = {
css: [
@@ -138,6 +157,73 @@ export function pageResources(
return resources
}
/** Lucide's maximize-2, Obsidian's icon for opening an embedded note. */
const MAXIMIZE_ICON: Element = {
type: "element",
tagName: "svg",
properties: {
xmlns: "http://www.w3.org/2000/svg",
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
className: ["svg-icon", "lucide-maximize-2"],
},
children: ["M15 3h6v6", "m21 3-7 7", "m3 21 7-7", "M9 21H3v-6"].map((d) => ({
type: "element",
tagName: "path",
properties: { d },
children: [],
})),
}
/**
* Obsidian's embed markup around transcluded content, so Obsidian themes' embed
* styles apply: the title (the note's, for a whole-note embed), then the content in a
* rendered view, then Quartz's link to the original, then Obsidian's icon link to it
* (`.markdown-embed-link`), which Quartz hides and Obsidian's styles show.
*/
function obsidianEmbed(title: string, content: ElementContent[], link: Element): ElementContent[] {
const embedLink: Element = {
type: "element",
tagName: "a",
properties: {
href: link.properties.href,
className: ["markdown-embed-link"],
ariaLabel: (link.children[0] as { value?: string } | undefined)?.value,
dataNoPopover: true,
},
children: [structuredClone(MAXIMIZE_ICON)],
}
return [
{
type: "element",
tagName: "div",
properties: { className: ["embed-title", "markdown-embed-title"] },
children: title ? [{ type: "text", value: title }] : [],
},
{
type: "element",
tagName: "div",
properties: { className: ["markdown-embed-content"] },
children: [
{
type: "element",
tagName: "div",
properties: { className: ["markdown-preview-view", "markdown-rendered"] },
children: content,
},
],
},
link,
embedLink,
]
}
/** @internal Exported for testing only. */
export function renderTranscludes(
root: Root,
@@ -146,6 +232,9 @@ export function renderTranscludes(
componentData: QuartzComponentProps,
visited: Set<FullSlug>,
) {
// a prefix per transclusion, unique on the page, for the ids inside it
const scopeFor = createIdScopes()
// Walk the tree manually instead of using visit() so we can track the
// ancestor chain for cycle detection. visit() runs the callback before
// descending into replaced children, so a Set-based guard there falsely
@@ -168,6 +257,15 @@ export function renderTranscludes(
}
const inner = el.children[0] as Element
const linkToOriginal = (): Element => ({
type: "element",
tagName: "a",
properties: {
href: inner.properties?.href,
class: ["internal", "internal-link", "transclude-src"],
},
children: [{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal }],
})
const transcludeTarget = (inner.properties["data-slug"] ?? slug) as FullSlug
if (visited.has(transcludeTarget)) {
console.warn(
@@ -223,20 +321,11 @@ export function renderTranscludes(
}
}
el.children = [
normalizeHastElement(blockNode, slug, transcludeTarget),
{
type: "element",
tagName: "a",
properties: {
href: inner.properties?.href,
class: ["internal", "internal-link", "transclude-src"],
},
children: [
{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal },
],
},
]
el.children = obsidianEmbed(
"",
[normalizeHastElement(blockNode, slug, transcludeTarget)],
linkToOriginal(),
)
}
} else if (blockRef?.startsWith("#") && page.htmlAst) {
// header transclude
@@ -244,7 +333,9 @@ export function renderTranscludes(
let startIdx = undefined
let startDepth = undefined
let endIdx = undefined
for (const [i, htmlEl] of page.htmlAst.children.entries()) {
for (const [i, child] of page.htmlAst.children.entries()) {
// The heading, inside its block wrapper if it has one (`div.el-h2 > h2`).
const htmlEl = blockOf(child as ElementContent)
if (!(htmlEl.type === "element" && htmlEl.tagName.match(headerRegex))) continue
const depth = Number(htmlEl.tagName.substring(1))
@@ -264,60 +355,32 @@ export function renderTranscludes(
continue
}
el.children = [
...(page.htmlAst.children.slice(startIdx, endIdx) as ElementContent[]).map((c) =>
el.children = obsidianEmbed(
"",
sliceWithFootnotes(page.htmlAst.children as ElementContent[], startIdx, endIdx).map((c) =>
normalizeHastElement(c as Element, slug, transcludeTarget),
),
{
type: "element",
tagName: "a",
properties: {
href: inner.properties?.href,
class: ["internal", "internal-link", "transclude-src"],
},
children: [
{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal },
],
},
]
linkToOriginal(),
)
} else if (page.htmlAst) {
// page transclude
el.children = [
{
type: "element",
tagName: "h1",
properties: {},
children: [
{
type: "text",
value:
page.frontmatter?.title ??
i18n(cfg.locale).components.transcludes.transcludeOf({
targetSlug: page.slug!,
}),
},
],
},
...(page.htmlAst.children as ElementContent[]).map((c) =>
el.children = obsidianEmbed(
page.frontmatter?.title ??
i18n(cfg.locale).components.transcludes.transcludeOf({
targetSlug: page.slug!,
}),
(page.htmlAst.children as ElementContent[]).map((c) =>
normalizeHastElement(c as Element, slug, transcludeTarget),
),
{
type: "element",
tagName: "a",
properties: {
href: inner.properties?.href,
class: ["internal", "internal-link", "transclude-src"],
},
children: [
{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal },
],
},
]
linkToOriginal(),
)
}
// Recurse into the replaced children to resolve nested transclusions,
// then remove from visited so sibling embeds of the same target work.
walk(el)
// its ids (headings, footnotes) are unique on the page, and links inside it go to them
scopeTranscludedIds(el, scopeFor(transcludeTarget), inner.properties?.href as string)
visited.delete(transcludeTarget)
}
}
+73 -12
View File
@@ -62,6 +62,37 @@ function stopLoading() {
}
}
// Scroll positions are restored by the router, not the browser (#2674). The browser
// saves an entry's position when `pushState` runs and restores it on Back while the
// *other* page's content is still shown, before the router swaps the page in, so
// positions came out wrong. Each entry keeps its own `scrollY` in `history.state`.
history.scrollRestoration = "manual"
let renderedPath = window.location.pathname
let saveTimer: ReturnType<typeof setTimeout> | undefined
function saveScroll() {
clearTimeout(saveTimer)
history.replaceState({ ...(history.state ?? {}), scrollY: window.scrollY }, "")
}
function savedScroll(): number | undefined {
const y = (history.state as { scrollY?: unknown } | null)?.scrollY
return typeof y === "number" ? y : undefined
}
/** Scrolls to where the current entry was left, else to its `#heading`, else to the top. */
function restoreScroll() {
const y = savedScroll()
if (y !== undefined) {
window.scrollTo({ top: y, behavior: "instant" })
return
}
const hash = window.location.hash
const el = hash ? document.getElementById(decodeURIComponent(hash.substring(1))) : null
if (el) el.scrollIntoView({ behavior: "instant" })
else window.scrollTo({ top: 0, behavior: "instant" })
}
let isNavigating = false
let p: DOMParser
async function _navigate(url: URL, isBack: boolean = false) {
@@ -104,6 +135,10 @@ async function _navigate(url: URL, isBack: boolean = false) {
if (!contents) return
// Keep the position of the page being left, for Back. (On Back, the entry has
// already changed: what's on screen belongs to another entry.)
if (!isBack) saveScroll()
// notify about to nav
const event: CustomEventMap["prenav"] = new CustomEvent("prenav", { detail: {} })
document.dispatchEvent(event)
@@ -132,13 +167,13 @@ async function _navigate(url: URL, isBack: boolean = false) {
micromorph(document.body, html.body)
// scroll into place and add history
if (!isBack) {
if (url.hash) {
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
el?.scrollIntoView()
} else {
window.scrollTo({ top: 0 })
}
if (isBack) {
restoreScroll()
} else if (url.hash) {
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
el?.scrollIntoView()
} else {
window.scrollTo({ top: 0 })
}
// now, patch head, re-executing scripts
@@ -152,6 +187,7 @@ async function _navigate(url: URL, isBack: boolean = false) {
if (!isBack) {
history.pushState({}, "", finalUrl)
}
renderedPath = window.location.pathname
notifyNav(getFullSlug(window))
delete announcer.dataset.persist
@@ -182,21 +218,46 @@ function createRouter() {
event.preventDefault()
if (isSamePage(url) && url.hash) {
// Save where the reader was, then add the entry, then jump: Back returns here.
saveScroll()
history.pushState({}, "", url)
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
el?.scrollIntoView()
history.pushState({}, "", url)
return
}
navigate(url, false)
})
window.addEventListener("popstate", (event) => {
const { url } = getOpts(event) ?? {}
if (window.location.hash && window.location.pathname === url?.pathname) return
window.addEventListener("popstate", () => {
// Whatever is pending belongs to the entry just left.
clearTimeout(saveTimer)
// Back or Forward between headings of the page on screen: only scroll.
if (window.location.pathname === renderedPath) {
restoreScroll()
return
}
navigate(new URL(window.location.toString()), true)
return
})
// Record the position as the reader scrolls, so that Forward (and Back to an
// entry left without a link) also lands where the reader was.
window.addEventListener(
"scroll",
() => {
if (isNavigating) return
clearTimeout(saveTimer)
saveTimer = setTimeout(() => {
if (!isNavigating) saveScroll()
}, 150)
},
{ passive: true },
)
// A reload or a return from another site: the browser no longer restores it.
window.addEventListener("pagehide", () => {
if (!isNavigating) saveScroll()
})
if (savedScroll() !== undefined) restoreScroll()
}
return new (class Router {
+152
View File
@@ -0,0 +1,152 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import type { Element, ElementContent } from "hast"
import { blockOf, createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
const h = (
tagName: string,
properties: Element["properties"] = {},
children: ElementContent[] = [],
): Element => ({ type: "element", tagName, properties, children })
const text = (value: string): ElementContent => ({ type: "text", value })
describe("createIdScopes", () => {
test("a prefix per transclusion, unique on the page", () => {
const scope = createIdScopes()
assert.strictEqual(scope("notes/Source"), "source--")
assert.strictEqual(scope("notes/source"), "source-2--")
assert.strictEqual(scope("other"), "other--")
})
})
describe("scopeTranscludedIds", () => {
test("prefixes ids and the references to them inside the transclusion", () => {
const el = h("div", { className: ["transclude"] }, [
h("h2", { id: "details" }, [text("Details")]),
h("p", {}, [
h("a", { href: "#details" }, [text("jump")]),
h("sup", {}, [
h(
"a",
{
href: "#user-content-fn-1",
id: "user-content-fnref-1",
dataFootnoteRef: "",
ariaDescribedBy: ["footnote-label"],
},
[text("1")],
),
]),
]),
h("section", { dataFootnotes: "" }, [
h("h2", { id: "footnote-label" }, [text("Footnotes")]),
h("ol", {}, [
h("li", { id: "user-content-fn-1" }, [
h("a", { href: "#user-content-fnref-1" }, [text("↩")]),
]),
]),
]),
])
scopeTranscludedIds(el, "source--", "./source")
const [heading, para, section] = el.children as Element[]
assert.strictEqual(heading!.properties.id, "source--details")
const [jump, sup] = para!.children as Element[]
assert.strictEqual(jump!.properties.href, "#source--details")
const ref = (sup!.children[0] as Element).properties
assert.strictEqual(ref.href, "#source--user-content-fn-1")
assert.strictEqual(ref.id, "source--user-content-fnref-1")
assert.deepStrictEqual(ref.ariaDescribedBy, ["source--footnote-label"])
const li = (section!.children[1] as Element).children[0] as Element
assert.strictEqual(li.properties.id, "source--user-content-fn-1")
assert.strictEqual((li.children[0] as Element).properties.href, "#source--user-content-fnref-1")
})
test("a same-page link whose target isn't in the transclusion goes to the transcluded page", () => {
const el = h("div", {}, [h("a", { href: "#elsewhere" }, [text("x")])])
scopeTranscludedIds(el, "source--", "./source#overview")
assert.strictEqual((el.children[0] as Element).properties.href, "./source#elsewhere")
})
test("leaves inline svg and math alone, and other links", () => {
const el = h("div", {}, [
h("svg", {}, [h("linearGradient", { id: "grad" }), h("rect", { fill: "url(#grad)" })]),
h("a", { href: "./other#x" }, [text("x")]),
])
scopeTranscludedIds(el, "source--", "./source")
const svg = el.children[0] as Element
assert.strictEqual((svg.children[0] as Element).properties.id, "grad")
assert.strictEqual((el.children[1] as Element).properties.href, "./other#x")
})
})
describe("sliceWithFootnotes", () => {
const page: ElementContent[] = [
h("h2", { id: "a" }, [text("A")]),
h("p", {}, [h("a", { href: "#user-content-fn-2", dataFootnoteRef: "" }, [text("2")])]),
h("h2", { id: "b" }, [text("B")]),
h("p", {}, [h("a", { href: "#user-content-fn-1", dataFootnoteRef: "" }, [text("1")])]),
h("section", { dataFootnotes: "", className: ["footnotes"] }, [
h("ol", {}, [h("li", { id: "user-content-fn-1" }), h("li", { id: "user-content-fn-2" })]),
]),
]
const footnoteIds = (nodes: ElementContent[]) =>
nodes
.filter((n): n is Element => n.type === "element" && n.tagName === "section")
.flatMap((s) =>
((s.children[0] as Element).children as Element[]).map((li) => li.properties.id),
)
test("the last section gets only its own footnotes, not the whole footnotes section", () => {
assert.deepStrictEqual(footnoteIds(sliceWithFootnotes(page, 2, undefined)), [
"user-content-fn-1",
])
})
test("an earlier section gets its footnotes too", () => {
const slice = sliceWithFootnotes(page, 0, 2)
assert.strictEqual(slice.length, 3)
assert.deepStrictEqual(footnoteIds(slice), ["user-content-fn-2"])
})
test("a section without footnote references gets no footnotes section", () => {
const plain = [h("h2", { id: "c" }), h("p"), page[4]!]
assert.deepStrictEqual(footnoteIds(sliceWithFootnotes(plain, 0, undefined)), [])
})
})
describe("block wrappers", () => {
const wrap = (block: Element) => h("div", { className: [`el-${block.tagName}`] }, [block])
const page: ElementContent[] = [
wrap(h("h2", { id: "a" }, [text("A")])),
text("\n"),
wrap(h("p", {}, [h("a", { href: "#user-content-fn-1", dataFootnoteRef: "" }, [text("1")])])),
text("\n"),
wrap(
h("section", { dataFootnotes: "", className: ["footnotes"] }, [
h("ol", {}, [h("li", { id: "user-content-fn-1" }), h("li", { id: "user-content-fn-2" })]),
]),
),
]
test("blockOf looks through Obsidian's per-block wrapper", () => {
assert.strictEqual((blockOf(page[0]!) as Element).tagName, "h2")
const plain = h("p")
assert.strictEqual(blockOf(plain), plain)
const callout = h("div", { className: ["callout"] }, [h("p")])
assert.strictEqual(blockOf(callout), callout)
})
test("a heading slice gets its footnotes in the section's wrapper", () => {
const slice = sliceWithFootnotes(page, 0, undefined)
const wrappers = slice.filter((n): n is Element => n.type === "element")
assert.deepStrictEqual(
wrappers.map((w) => w.properties.className),
[["el-h2"], ["el-p"], ["el-section"]],
)
const section = wrappers[2]!.children[0] as Element
const ids = ((section.children[0] as Element).children as Element[]).map(
(li) => li.properties.id,
)
assert.deepStrictEqual(ids, ["user-content-fn-1"])
})
})
+153
View File
@@ -0,0 +1,153 @@
import type { Element, ElementContent, Root } from "hast"
/**
* Transcluded content is a copy of another page's HTML, ids included: two transclusions (or a
* transclusion and its host) share heading ids and footnote ids (`user-content-fn-1`), so a
* footnote reference or a `[[#Heading]]` link jumps to whichever element comes first on the page.
* Obsidian resolves each embed on its own.
*
* {@link scopeTranscludedIds} gives the ids inside one transclusion a prefix, unique on the page,
* and rewrites the references inside it to match. The host's ids stay as they are. A same-page
* link (`#id`) whose target isn't in the transclusion (a heading slice that doesn't hold it) links
* to the id on the transcluded page instead.
*/
/** Space-separated id references (hast property names). */
const ID_LIST_PROPERTIES = [
"ariaDescribedBy",
"ariaLabelledBy",
"ariaControls",
"ariaOwns",
"ariaDetails",
"ariaFlowTo",
"htmlFor",
"headers",
] as const
/** Subtrees whose ids are referenced from inside them in ways we don't rewrite (`url(#id)`). */
const OPAQUE = new Set(["svg", "math"])
function forEachElement(node: Element | Root, fn: (el: Element) => void) {
for (const child of node.children) {
if (child.type !== "element") continue
fn(child)
if (!OPAQUE.has(child.tagName)) forEachElement(child, fn)
}
}
/** Per page render: a prefix for each transclusion, unique on the page. */
export function createIdScopes(): (target: string) => string {
const used = new Map<string, number>()
return (target) => {
const base =
(target.split("/").pop() ?? target)
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "") || "transclude"
const count = (used.get(base) ?? 0) + 1
used.set(base, count)
return count === 1 ? `${base}--` : `${base}-${count}--`
}
}
/**
* Prefixes the ids inside the transclusion `el` with `prefix` and rewrites references to them
* inside it. `sourceHref` is the link to the transcluded page (relative to the host), for
* same-page links whose target isn't in the transclusion.
*/
export function scopeTranscludedIds(el: Element, prefix: string, sourceHref?: string) {
const ids = new Set<string>()
forEachElement(el, (node) => {
const id = node.properties?.id
if (typeof id === "string" && id) ids.add(id)
})
const pageHref = typeof sourceHref === "string" ? sourceHref.split("#")[0] : undefined
const scoped = (id: string) => (ids.has(id) ? `${prefix}${id}` : id)
forEachElement(el, (node) => {
const props = node.properties
if (!props) return
if (typeof props.id === "string" && ids.has(props.id)) props.id = `${prefix}${props.id}`
const href = props.href
if (typeof href === "string" && href.startsWith("#") && href.length > 1) {
let target = href.slice(1)
try {
target = decodeURIComponent(target)
} catch {
// keep as written
}
if (ids.has(target)) props.href = `#${prefix}${target}`
else if (pageHref) props.href = `${pageHref}${href}`
}
const record = props as Record<string, unknown>
for (const name of ID_LIST_PROPERTIES) {
const value = record[name]
if (Array.isArray(value)) record[name] = value.map((token) => scoped(String(token)))
else if (typeof value === "string") record[name] = value.split(/\s+/).map(scoped).join(" ")
}
})
}
/**
* The block inside Obsidian's per-block wrapper (`div.el-p > p`, `div.el-h2 > h2`), which
* `@quartz-community/rehype-obsidian` renders around each of a note's top-level blocks; any other
* node is its own block. Code walking a page's top-level blocks looks through the wrappers.
*/
export function blockOf(node: ElementContent): ElementContent {
if (node.type !== "element" || node.tagName !== "div") return node
const classes = ([] as unknown[]).concat(node.properties?.className ?? [])
if (!classes.some((c) => /^el-[a-z0-9]+$/.test(String(c)))) return node
const inner = node.children.filter((c) => c.type === "element")
return inner.length === 1 ? inner[0]! : node
}
function isFootnotesSection(node: ElementContent): node is Element {
node = blockOf(node)
if (node.type !== "element" || node.tagName !== "section") return false
const props = node.properties ?? {}
const classes = (props.className ?? []) as string[]
return props.dataFootnotes !== undefined || classes.includes("footnotes")
}
/**
* A heading transclusion: the slice of the page from the heading to the next one of the same or
* a higher level. The page's footnotes section is not part of the section; the footnotes the
* slice references are added after it (in a copy of the section holding only those, in its block
* wrapper if it has one).
*/
export function sliceWithFootnotes(
pageChildren: ElementContent[],
start: number,
end: number | undefined,
): ElementContent[] {
const slice = pageChildren.slice(start, end).filter((node): boolean => !isFootnotesSection(node))
const section = pageChildren.find(isFootnotesSection)
if (!section) return slice
const referenced = new Set<string>()
const collect = (node: Element | Root) =>
forEachElement(node, (child) => {
const href = child.properties?.href
if (child.properties?.dataFootnoteRef !== undefined && typeof href === "string")
referenced.add(href.replace(/^#/, ""))
})
for (const node of slice) if (node.type === "element") collect(node as Element)
if (referenced.size === 0) return slice
const copy = structuredClone(section) as Element
const keep = (list: Element) => {
list.children = list.children.filter(
(item) =>
item.type !== "element" ||
item.tagName !== "li" ||
referenced.has(String(item.properties?.id ?? "")),
)
}
forEachElement(copy, (node) => {
if (node.tagName === "ol") keep(node)
})
return [...slice, copy]
}
+302 -3
View File
@@ -13,8 +13,14 @@ import {
extractLinksFromValue,
readFrontmatterData,
} from "./frontmatter"
import { Links } from "./links"
import { buildLayeredCSS, buildUnlayeredCSS, resolveFonts } from "./fonts"
import { Links, LinksInstance, markLinksToRemovedPages } from "./links"
import {
buildLayeredCSS,
buildUnlayeredCSS,
googleFontHref,
resolveFontSpecs,
resolveFonts,
} from "./fonts"
import { isContentError } from "../../util/pluginErrors"
import { Drafts, isDraft } from "./drafts"
import {
@@ -28,7 +34,8 @@ import {
import type { PluginJsonEntry } from "../loader/types"
import type { BuildCtx } from "../../util/ctx"
import type { ContentDetails } from "../types"
import type { FullSlug } from "../../util/path"
import type { FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions } from "../../util/path"
import type { ProcessedContent } from "../vfile"
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
@@ -217,6 +224,34 @@ describe("frontmatter built-in", () => {
)
})
test("frontmatter Markdown links with an angle-bracket destination drop the brackets", () => {
assert.deepStrictEqual(
extractLinksFromValue([
"[Exec Briefing](<./Exec Briefing.md>)",
"[x](<./Exec Briefing.md#Next steps>)",
"[y](./Exec Briefing.md)",
]),
["./Exec Briefing.md", "./Exec Briefing.md#Next steps", "./Exec Briefing.md"],
)
})
test("reads YAML frontmatter with YAML 1.2's core schema, as Obsidian does", () => {
const data = readFrontmatterData(
"---\ntitle: Hello world\ndate: 2024-01-02\ndraft: True\nn: 012\nnone: ~\nratio: .5\nalias: yes\n---\n",
)
assert.deepStrictEqual(data, {
title: "Hello world",
date: "2024-01-02",
draft: true,
n: 12,
none: null,
ratio: 0.5,
alias: "yes",
})
// a block without a document holds no properties
assert.deepStrictEqual(readFrontmatterData("---\n# only a comment\n---\nbody\n"), {})
})
test("refuses JavaScript frontmatter instead of executing it", async () => {
const g = globalThis as { __quartzFrontmatterRan?: boolean }
delete g.__quartzFrontmatterRan
@@ -331,11 +366,64 @@ describe("links built-in", () => {
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
})
test("slugs.stripDiacritics: link targets are stripped like the slugs they point at (#2410)", () => {
setSlugOptions({ stripDiacritics: true })
try {
const img: Element = {
type: "element",
tagName: "img",
properties: { src: "obr%C3%A1zek.png" },
children: [],
}
const { els, file } = run(
[a("./%C4%8Ce%C5%A1tina#%C4%8Cesk%C3%BD-nadpis", "Čeština"), a("Příliš"), img],
"ceske/page",
{ markdownLinkResolution: "shortest" },
["ceske/page", "ceske/cestina", "jine/prilis", "ceske/obrazek.png"],
)
const [cestina, prilis] = els.filter((e) => e.tagName === "a")
assert.strictEqual(cestina.properties.href, "../ceske/cestina#český-nadpis")
assert.ok(!(cestina.properties.className as string[]).includes("broken"))
assert.strictEqual(prilis.properties.href, "../jine/prilis")
assert.strictEqual(
els.find((e) => e.tagName === "img")!.properties.src,
"../ceske/obrazek.png",
)
assert.ok(file.data.links?.includes("ceske/cestina" as SimpleSlug))
} finally {
setSlugOptions(undefined)
}
})
test("without slugs.stripDiacritics link targets keep their diacritics", () => {
const { els } = run([a("Příliš")], "page", { markdownLinkResolution: "shortest" }, [
"page",
"jine/příliš",
])
assert.strictEqual(els[0].properties.href, "./jine/příliš")
})
test("footnote anchors stay internal without Obsidian's note-link class", () => {
const fn = (props: Record<string, unknown>): Element => ({
type: "element",
tagName: "a",
properties: { href: "#user-content-fn-1", ...props },
children: [{ type: "text", value: "1" }],
})
const { els } = run([fn({ dataFootnoteRef: "" }), fn({ dataFootnoteBackref: "" })])
for (const el of els.filter((e) => e.tagName === "a")) {
const classes = el.properties.className as string[]
assert.ok(classes.includes("internal"))
assert.ok(!classes.includes("internal-link"))
}
})
test("makes internal links relative, records outgoing links, marks external ones", () => {
const { els, file } = run(
[a("other/note", "Note"), a("https://example.com"), a("#heading")],
"folder/page",
{ markdownLinkResolution: "absolute" },
["folder/page", "other/note"],
)
const [internal, external] = els.filter((e) => e.tagName === "a")
assert.strictEqual(internal.properties.href, "../other/note")
@@ -408,6 +496,47 @@ describe("links built-in", () => {
)
})
test("pretty links shorten a link whose text is its percent-decoded href (#2643)", () => {
const { els } = run(
[
a("Folder/Name%20With%20Space", "Folder/Name With Space"),
a("Ordner/%C3%9Cbersicht", "Ordner/Übersicht"),
a("Folder/Name%20With%20Space", "own text"),
],
"page",
{ prettyLinks: true },
)
const links = els.filter((e) => e.tagName === "a")
assert.deepStrictEqual(
links.map((e) => (e.children[0] as Text).value),
["Name With Space", "Übersicht", "own text"],
)
assert.deepStrictEqual(
links.map((e) => (e.properties.className as string[]).includes("alias")),
[false, false, true],
)
})
test("missing targets get the broken class by default, as Obsidian marks them", () => {
const { els } = run([a("missing"), a("page")], "page", {}, ["page"])
assert.ok((els[0].properties.className as string[]).includes("broken"))
assert.ok(!(els[1].properties.className as string[]).includes("broken"))
})
test("tag and folder pages, generated later, are not broken", () => {
const { els } = run([a("tags/specimen"), a("folder/"), a("empty/")], "page", {}, [
"page",
"folder/note",
])
const broken = els.map((e) => (e.properties.className as string[]).includes("broken"))
assert.deepStrictEqual(broken, [false, false, true])
})
test("disableBrokenWikilinks: false leaves missing targets unmarked", () => {
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: false }, ["page"])
assert.ok(!(els[0].properties.className as string[]).includes("broken"))
})
test("disableBrokenWikilinks adds a broken class to missing targets", () => {
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: true }, ["page"])
assert.ok((els[0].properties.className as string[]).includes("broken"))
@@ -463,6 +592,57 @@ describe("content index built-in", () => {
])
})
test("writes the page date to contentIndex.json as an ISO string (explorer#5)", () => {
const created = new Date("2024-01-02T03:04:05.000Z")
const modified = new Date("2025-06-07T08:09:10.000Z")
const dated = page("dated", { defaultDateType: "created", dates: { created, modified } })
const idx = buildContentIndex(ctxWith([]), [dated, page("undated")])
const json = JSON.parse(serializeContentIndex(idx))
assert.strictEqual(json.dated.date, "2024-01-02T03:04:05.000Z")
assert.ok(!("description" in json.dated))
// pages without a date keep the build-time stand-in for RSS, but not in the JSON
assert.ok(idx.get("undated" as FullSlug)!.date instanceof Date)
assert.ok(!("date" in json.undated))
})
test("dateFromFrontmatter marks dates set in frontmatter for the configured type", () => {
const fmModified = new Date("2024-03-04T00:00:00") // local midnight, like the date plugin
const gitModified = new Date("2025-01-01T10:00:00.000Z")
const created = new Date("2020-01-01T00:00:00.000Z")
const fromFm = page("fm", {
defaultDateType: "modified",
frontmatter: { title: "FM", modified: "2024-03-04" },
dates: { created, modified: fmModified },
})
const fromGit = page("git", {
defaultDateType: "modified",
frontmatter: { title: "GIT", created: "2020-01-01T00:00:00.000Z" },
dates: { created, modified: gitModified },
})
// frontmatter has a date, but for another type than the configured one
const otherType = page("other", {
defaultDateType: "created",
frontmatter: { title: "O", modified: "2024-03-04" },
dates: { created: gitModified, modified: fmModified },
})
// frontmatter value lost to a higher-priority source (date differs)
const overridden = page("over", {
defaultDateType: "modified",
frontmatter: { title: "OV", modified: "2023-01-01" },
dates: { created, modified: gitModified },
})
const json = JSON.parse(
serializeContentIndex(
buildContentIndex(ctxWith([]), [fromFm, fromGit, otherType, overridden, page("undated")]),
),
)
assert.strictEqual(json.fm.dateFromFrontmatter, true)
assert.strictEqual(json.fm.date, fmModified.toISOString())
for (const slug of ["git", "other", "over", "undated"]) {
assert.ok(!("dateFromFrontmatter" in json[slug]), slug)
}
})
test("plugins add fields through extendContentIndex", () => {
const ctx = ctxWith([
{
@@ -621,4 +801,123 @@ describe("fonts built-in", () => {
delete (globalThis as Record<string, unknown>).__quartzFonts
}
})
test("the interface and per-heading fonts are loaded from Google Fonts", () => {
const href = decodeURIComponent(
googleFontHref(
resolveFontSpecs(
{ interface: "Inter", h1: { name: "Playfair Display", weights: [700] } },
{},
),
),
)
assert.match(href, /family=Inter:wght@400;600/)
assert.match(href, /family=Playfair Display:wght@700/)
assert.doesNotMatch(decodeURIComponent(googleFontHref(resolveFontSpecs({}, {}))), /Inter/)
const single = (spec: object) =>
decodeURIComponent(googleFontHref(resolveFontSpecs({ title: spec as never }, {})))
assert.match(single({ name: "Lora", weights: [400] }), /family=Lora&/)
assert.match(
single({ name: "Lora", weights: [400], includeItalic: true }),
/family=Lora:ital@0;1&/,
)
assert.match(
single({ name: "Lora", weights: [700], includeItalic: true }),
/family=Lora:ital,wght@0,700;1,700&/,
)
})
test("explicit body/interface/code fonts set Obsidian's overrides on body", () => {
;(globalThis as Record<string, unknown>).__quartzFonts = {
themeName: "Things",
fonts: { "--font-text": "Inter", "--font-monospace": "JetBrains Mono" },
}
try {
const opts = { body: "Lora", code: "Fira Code" }
const css = buildUnlayeredCSS(resolveFonts(opts, {}), opts, true)
assert.match(css, /html body \{[^}]*--font-text-override: Lora;/)
assert.match(css, /html body \{[^}]*--font-monospace-override: Fira Code;/)
assert.doesNotMatch(css, /--font-interface-override/)
// a theme with themeFonts: false registers no fonts, but still reads the overrides
assert.match(
buildUnlayeredCSS(resolveFonts({ interface: "Inter" }, {}), { interface: "Inter" }, false),
/html body \{\n --font-interface-override: Inter;\n\}/,
)
assert.doesNotMatch(buildUnlayeredCSS(resolveFonts({}, {}), {}, true), /override/)
} finally {
delete (globalThis as Record<string, unknown>).__quartzFonts
}
})
})
describe("links to pages removed by filters (crawl-links#7)", () => {
const link = (slug: string, className: string[] = ["internal", "internal-link"]): Element => ({
type: "element",
tagName: "a",
properties: { href: `./${slug}`, "data-slug": slug, className: [...className] },
children: [{ type: "text", value: slug }],
})
const page = (slug: string, links: Element[], data: Record<string, unknown> = {}) => {
const file = new VFile("")
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
return [{ type: "root", children: links } as Root, file] as ProcessedContent
}
const anchors = (item: ProcessedContent) => (item[0] as Root).children as Element[]
test("marks links to removed pages and their aliases broken, with the filter", () => {
const home = page("index", [
link("draft"),
link("old-name"),
link("published"),
link("folder/index"),
])
const draft = page("draft", [], { aliases: ["old-name"] })
const published = page("published", [])
const folderIndex = page("folder/index", [])
const all = [home, draft, published, folderIndex]
const marked = markLinksToRemovedPages(all, [home, published], (s) =>
s === "draft" || s === "folder/index" ? "RemoveDrafts" : undefined,
)
const [toDraft, toAlias, toPublished, toFolder] = anchors(home)
assert.strictEqual(marked, 2)
assert.ok((toDraft.properties.className as string[]).includes("broken"))
assert.strictEqual(toDraft.properties["data-filtered"], "RemoveDrafts")
assert.ok((toAlias.properties.className as string[]).includes("broken"))
assert.ok(!(toPublished.properties.className as string[]).includes("broken"))
// a folder whose index note is a draft still gets a generated folder page
assert.ok(!(toFolder.properties.className as string[]).includes("broken"))
})
test("a removed page's alias that a published page owns is not broken", () => {
const home = page("index", [link("shared")])
const draft = page("draft", [], { aliases: ["shared"] })
const owner = page("shared", [])
markLinksToRemovedPages([home, draft, owner], [home, owner])
assert.ok(!(anchors(home)[0].properties.className as string[]).includes("broken"))
})
test("unmarks links when the target is published again (watch mode)", () => {
const home = page("index", [link("draft")])
const draft = page("draft", [])
markLinksToRemovedPages([home, draft], [home])
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
markLinksToRemovedPages([home, draft], [home, draft])
const a = anchors(home)[0]
assert.deepStrictEqual(a.properties.className, ["internal", "internal-link"])
assert.strictEqual(a.properties["data-filtered"], undefined)
})
test("leaves links marked broken by the links transformer alone", () => {
const home = page("index", [link("missing", ["internal", "internal-link", "broken"])])
markLinksToRemovedPages([home], [home])
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
})
test("the Links instance says whether it marks broken links", () => {
assert.strictEqual((Links() as LinksInstance).marksBrokenLinks, true)
assert.strictEqual(
(Links({ disableBrokenWikilinks: false }) as LinksInstance).marksBrokenLinks,
false,
)
})
})
+63 -6
View File
@@ -53,6 +53,7 @@ export const CORE_CONTENT_INDEX_FIELDS = new Set([
"content",
"richContent",
"date",
"dateFromFrontmatter",
"description",
])
@@ -150,6 +151,50 @@ export function prepareContentIndex(ctx: BuildCtx, content: ProcessedContent[]):
return index
}
/**
* Pages without a date get the build time, so RSS and the sitemap keep working as before.
* Those stand-in dates are remembered here and not written to contentIndex.json, where a
* build-time date would look like a real one to client-side sorting (explorer, recent notes).
*/
const buildTimeDates = new WeakSet<Date>()
function buildTimeDate(): Date {
const date = new Date()
buildTimeDates.add(date)
return date
}
function entryDate(data: QuartzPluginData): Date {
const date = getDate(data as Parameters<typeof getDate>[0])
if (!date) return buildTimeDate()
if (dateIsFromFrontmatter(data, date)) frontmatterDates.add(date)
return date
}
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
/**
* Whether the page's `date` is the one its frontmatter sets for the configured date type
* (`defaultDateType`: created / modified / published, after the frontmatter built-in's
* aliases such as `date` or `lastmod`), rather than one from git or the file system. Compared
* by value, so it holds whatever `priority` the date plugin uses. Date-only values
* (`2024-01-02`) are local midnight, as the date plugin reads them.
*/
export function dateIsFromFrontmatter(data: QuartzPluginData, date: Date | undefined): boolean {
if (!(date instanceof Date) || isNaN(date.getTime())) return false
const type = data.defaultDateType as string | undefined
const frontmatter = data.frontmatter as Record<string, unknown> | undefined
if (!type || !frontmatter) return false
let raw = frontmatter[type]
if (raw === undefined || raw === null || raw === "") return false
if (typeof raw === "string" && DATE_ONLY.test(raw)) raw = `${raw}T00:00:00`
if (!(raw instanceof Date) && typeof raw !== "string" && typeof raw !== "number") return false
const fromFrontmatter = new Date(raw)
return !isNaN(fromFrontmatter.getTime()) && fromFrontmatter.getTime() === date.getTime()
}
/** Pages whose date came from frontmatter (see dateIsFromFrontmatter). */
const frontmatterDates = new WeakSet<Date>()
/** Build the index from processed content (also used by tests and potentially other emitters). */
export function buildContentIndex(
ctx: BuildCtx,
@@ -176,7 +221,7 @@ export function buildContentIndex(
options.rssFullHtml && data.encrypted !== true
? escapeHTML(toHtml(tree as Root, { allowDangerousHtml: true }))
: undefined,
date: getDate(data as Parameters<typeof getDate>[0]) ?? new Date(),
date: entryDate(data),
description: (data.description as string | undefined) ?? "",
}
index.set(slug, applyContentIndexExtensions(ctx, extensions, entry, data))
@@ -240,13 +285,25 @@ function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndexMap, limit?:
</rss>`
}
/** Entries as written to contentIndex.json (date and description are RSS/sitemap-only). */
/**
* Entries as written to contentIndex.json. `date` is the page's date (the one
* `defaultDateType` selects, as shown by ContentMeta and used by RSS) as an ISO 8601 string,
* left out for pages without a date. `dateFromFrontmatter: true` is added when that date is the
* one the page's frontmatter sets for the date type (absent otherwise). `description` is
* RSS-only.
*/
export function serializeContentIndex(idx: ContentIndexMap): string {
const simplified = Object.fromEntries(
Array.from(idx).map(([slug, { date: _date, description: _description, ...rest }]) => [
slug,
rest,
]),
Array.from(idx).map(([slug, { date, description: _description, ...rest }]) => {
const hasDate = date instanceof Date && !isNaN(date.getTime()) && !buildTimeDates.has(date)
if (!hasDate) return [slug, rest]
return [
slug,
frontmatterDates.has(date)
? { ...rest, date: date.toISOString(), dateFromFrontmatter: true }
: { ...rest, date: date.toISOString() },
]
}),
)
return JSON.stringify(simplified)
}
+50 -20
View File
@@ -23,7 +23,7 @@ import { QuartzEmitterPlugin } from "../types"
const HEADING_LEVELS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const
type HeadingLevel = (typeof HEADING_LEVELS)[number]
type FontRole = "title" | "header" | "body" | "code"
type FontRole = "title" | "header" | "body" | "code" | "interface"
export const SELF_HOSTED_STYLESHEET = "static/fonts/quartz-fonts.css"
export const QUARTZ_DEFAULT_HEADER = "Schibsted Grotesk"
@@ -40,12 +40,14 @@ const DEFAULT_WEIGHTS: Record<FontRole, number[]> = {
header: [400, 700],
body: [400, 600],
code: [400, 600],
interface: [400, 600],
}
const DEFAULT_ITALIC: Record<FontRole, boolean> = {
title: false,
header: false,
body: true,
code: false,
interface: false,
}
/** Option defaults; every key is listed so unknown options can be reported. */
@@ -107,13 +109,20 @@ export function readConfiguredTypography(ctx: BuildCtx | undefined): ConfiguredT
return result
}
/** Options first, then `configuration.theme.typography`, then Quartz's defaults. */
/**
* Options first, then `configuration.theme.typography`, then Quartz's defaults. The interface
* and per-heading fonts exist only as options.
*/
export function resolveFontSpecs(options: FontsConfig, typography: ConfiguredTypography) {
return {
title: options.title ?? typography.title,
header: options.header ?? typography.header ?? QUARTZ_DEFAULT_HEADER,
body: options.body ?? typography.body ?? QUARTZ_DEFAULT_BODY,
code: options.code ?? typography.code ?? QUARTZ_DEFAULT_CODE,
interface: options.interface,
headings: HEADING_LEVELS.map((l) => options[l]).filter(
(spec): spec is FontSpecification => spec !== undefined,
),
}
}
@@ -140,20 +149,16 @@ function mergeInto(map: Map<string, MergedFont>, role: FontRole, spec: FontSpeci
}
}
/** Google Fonts css2 `family` value; a single weight still names its axis unless it's 400. */
function formatMerged(entry: MergedFont): string {
const weights = [...entry.weights].sort((a, b) => a - b)
const features: string[] = []
if (entry.italic) features.push("ital")
if (weights.length > 1) {
const spec = entry.italic
? weights
.flatMap((w) => [`0,${w}`, `1,${w}`])
.sort()
.join(";")
: weights.join(";")
features.push(`wght@${spec}`)
const defaultWeight = weights.length === 1 && weights[0] === 400
if (entry.italic) {
if (defaultWeight) return `${entry.name}:ital@0;1`
const tuples = [...weights.map((w) => `0,${w}`), ...weights.map((w) => `1,${w}`)]
return `${entry.name}:ital,wght@${tuples.join(";")}`
}
return features.length > 0 ? `${entry.name}:${features.join(",")}` : entry.name
return defaultWeight ? entry.name : `${entry.name}:wght@${weights.join(";")}`
}
export function googleFontHref(fonts: ReturnType<typeof resolveFontSpecs>): string {
@@ -162,6 +167,8 @@ export function googleFontHref(fonts: ReturnType<typeof resolveFontSpecs>): stri
mergeInto(merged, "body", fonts.body)
mergeInto(merged, "code", fonts.code)
if (fonts.title) mergeInto(merged, "title", fonts.title)
if (fonts.interface) mergeInto(merged, "interface", fonts.interface)
for (const spec of fonts.headings) mergeInto(merged, "header", spec)
const params = [...merged.values()]
.map(formatMerged)
.map((f) => `family=${encodeURIComponent(f)}`)
@@ -218,6 +225,7 @@ function validate(options: FontsConfig) {
check("header", options.header, "header")
check("body", options.body, "body")
check("code", options.code, "code")
check("interface", options.interface, "interface")
for (const level of HEADING_LEVELS) check(level, options[level], "header")
}
@@ -310,15 +318,37 @@ export function buildLayeredCSS(fonts: ResolvedFonts, options: FontsConfig, them
].join("\n")
}
/** Unlayered heading fonts beat every layer; with a theme, only explicitly configured ones. */
/** Obsidian's override variables for the body, interface and code roles. */
const OBSIDIAN_OVERRIDES: [string, "body" | "interface" | "code"][] = [
["--font-text-override", "body"],
["--font-interface-override", "interface"],
["--font-monospace-override", "code"],
]
/**
* Unlayered heading fonts beat every layer; with a theme, only explicitly configured ones.
*
* Explicitly configured body/interface/code fonts also go to Obsidian's `--font-*-override`
* variables on `body`: an Obsidian theme's app.css sets `--font-text` and friends on `body`
* itself, so the `:root` values from {@link buildLayeredCSS} never reach the page. This holds
* whether or not the theme registers its fonts (with `themeFonts: false` it maps the overrides
* to Quartz's font variables on `body`), so the selector is `html body`, which wins over a
* theme's `body` rule regardless of stylesheet order. Without an Obsidian theme nothing reads
* the overrides.
*/
export function buildUnlayeredCSS(
fonts: ResolvedFonts,
options: FontsConfig,
themeActive: boolean,
) {
return HEADING_LEVELS.filter((l) => !themeActive || isExplicit(options, l))
.map((l) => `${l} { font-family: ${fonts[l]}; }`)
.join("\n")
const rules = HEADING_LEVELS.filter((l) => !themeActive || isExplicit(options, l)).map(
(l) => `${l} { font-family: ${fonts[l]}; }`,
)
const overrides = OBSIDIAN_OVERRIDES.filter(([, key]) => options[key] !== undefined).map(
([name, key]) => ` ${name}: ${fonts[key]};`,
)
if (overrides.length > 0) rules.push(["html body {", ...overrides, "}"].join("\n"))
return rules.join("\n")
}
// ---- plugin ------------------------------------------------------------------------
@@ -345,9 +375,9 @@ export const Fonts: QuartzEmitterPlugin<FontsConfig> = (userOpts) => {
const theme = ctx?.cfg?.configuration?.theme as
{ cdnCaching?: boolean; fontOrigin?: string } | undefined
const headLinksTypography = theme?.cdnCaching === true && theme?.fontOrigin === "googleFonts"
const overridesTypography = (["title", "header", "body", "code"] as const).some(
(k) => options[k] !== undefined,
)
const overridesTypography = (
["title", "header", "body", "code", "interface", ...HEADING_LEVELS] as const
).some((k) => options[k] !== undefined)
if (options.fontOrigin === "googleFonts" && (!headLinksTypography || overridesTypography)) {
const href = googleFontHref(resolveFontSpecs(options, typography))
additionalHead = [
+19 -3
View File
@@ -1,6 +1,6 @@
import matter from "gray-matter"
import remarkFrontmatter from "remark-frontmatter"
import yaml from "js-yaml"
import { CORE_SCHEMA, loadAll } from "js-yaml"
import toml from "toml"
import { QuartzTransformerPlugin } from "../types"
import { QuartzPluginData } from "../vfile"
@@ -75,7 +75,12 @@ export function extractLinksFromValue(value: unknown): string[] {
const links: string[] = []
for (const match of value.matchAll(WIKILINK_PATTERN))
links.push(slugifyWikilinkTarget(match[1]!))
for (const match of value.matchAll(MDLINK_PATTERN)) links.push(match[1]!)
for (const match of value.matchAll(MDLINK_PATTERN)) {
// `[x](<./My Note.md>)`: CommonMark's angle-bracket destination, which
// Obsidian writes for paths with spaces. The brackets aren't part of it.
const dest = match[1]!.trim()
links.push(dest.startsWith("<") && dest.endsWith(">") ? dest.slice(1, -1) : dest)
}
return links
}
if (Array.isArray(value)) return value.flatMap((item) => extractLinksFromValue(item))
@@ -141,6 +146,17 @@ const refuseJavaScript = (): never => {
)
}
/**
* YAML frontmatter as properties. YAML 1.2's core schema, as Obsidian reads properties: `true`,
* `null`, `~` and numbers resolve, dates stay strings. A block without a document (empty, or only
* comments) holds no properties.
*/
function loadYaml(source: string): object {
const docs = loadAll(source, { schema: CORE_SCHEMA })
if (docs.length > 1)
throw new Error("expected a single document in the frontmatter, but found more")
return (docs[0] ?? {}) as object
}
/** Parse a file's frontmatter with the configured delimiters and language (`{}` when it has none). */
export function readFrontmatterData(
source: Buffer | string,
@@ -158,7 +174,7 @@ export function readFrontmatterData(
delimiters: options.delimiters ?? frontmatterDefaults.delimiters,
language,
engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
yaml: loadYaml,
toml: (s) => toml.parse(s) as object,
javascript: refuseJavaScript,
js: refuseJavaScript,
+136 -10
View File
@@ -3,7 +3,8 @@ import { visit } from "unist-util-visit"
import isAbsoluteUrl from "is-absolute-url"
import { Element, Root, Text } from "hast"
import { VFile } from "vfile"
import { QuartzTransformerPlugin } from "../types"
import { QuartzTransformerPlugin, QuartzTransformerPluginInstance } from "../types"
import { ProcessedContent } from "../vfile"
import { LinksConfig } from "../../cfg"
import {
FullSlug,
@@ -14,6 +15,8 @@ import {
resolveRelative,
simplifySlug,
slugifyFilePath,
applySlugOptions,
getSlugOptions,
splitAnchor,
stripSlashes,
transformLink,
@@ -38,7 +41,7 @@ export const linksDefaults: Required<Omit<LinksConfig, "enabled" | "order">> = {
openLinksInNewTab: false,
lazyLoad: false,
externalLinkIcon: true,
disableBrokenWikilinks: false,
disableBrokenWikilinks: true,
}
/** Defaults of the former crawl-links plugin, applied when its config entry is migrated. */
@@ -46,10 +49,18 @@ export const legacyCrawlLinksDefaults: Partial<LinksConfig> = {
markdownLinkResolution: "absolute",
}
const isAbsolute = isAbsoluteUrl as (url: string, options?: { httpOnly?: boolean }) => boolean
// As in Obsidian: a URL with a scheme (`x:y`, but not `../x:y`), or a link whose path is not valid
// percent-encoding (`%zz`, `a%E2.md`), which names no file
const isExternalUrl = (url: string) => isAbsolute(url, { httpOnly: false }) || !linkPathDecodes(url)
const isExternalUrl = (url: string) =>
isAbsoluteUrl(url, { httpOnly: false }) || !linkPathDecodes(url)
// An href percent-decoded, to compare with link text; left as it is when it does not decode
const decodedHref = (href: string) => {
try {
return decodeURI(href)
} catch {
return href
}
}
const EXTERNAL_ICON_PATH =
"M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z"
@@ -63,10 +74,113 @@ function canonicalSlug(dest: string, curSlug: SimpleSlug): FullSlug {
return decodeURIComponent(stripSlashes(canonical, true)) as FullSlug
}
/**
* Whether a link's target is a page of the site. Tag and folder pages are generated after
* the transformers run, so they aren't in `allSlugs` yet: a tag page (`tags/…`) exists for
* every tag that is used, and a folder page (`folder/index`) for every folder with content.
*/
export function pageExists(allSlugs: readonly string[], full: string): boolean {
if (allSlugs.includes(full)) return true
if (full === "index" || full.startsWith("tags/")) return true
if (full.endsWith("/index")) {
const folder = full.slice(0, -"index".length)
return allSlugs.some((s) => s.startsWith(folder))
}
return false
}
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
const FILTERED_ATTR = "data-filtered"
/**
* Links are classified while the transformers run, before the filters decide what is
* published, so a link to a page a filter removes (a draft, a page without `publish: true`)
* still points at an address in `allSlugs` and is not marked `broken` — yet it 404s
* (crawl-links#7). This runs after the filters: links in published pages whose target was
* removed get the `broken` class and `data-filtered="<filter>"`. Links that were marked this
* way and whose target is published again (watch mode) lose both. Returns the number of links
* marked.
*/
export function markLinksToRemovedPages(
all: ProcessedContent[],
published: ProcessedContent[],
filteredBy: (slug: string) => string | undefined = () => "filter",
): number {
const publishedSet = new Set(published)
const live = new Set<string>()
for (const item of published) {
const data = item[1].data
if (data.slug) live.add(data.slug)
for (const alias of data.aliases ?? []) live.add(alias)
}
const removed = new Map<string, string>()
for (const item of all) {
if (publishedSet.has(item)) continue
const data = item[1].data
if (!data.slug) continue
const reason = filteredBy(data.slug) ?? "filter"
// its aliases (and the file path of a page with a permalink) are gone with it
for (const slug of [data.slug, ...(data.aliases ?? [])]) {
// a folder whose index note is removed still gets a generated folder page
if (slug.endsWith("/index")) continue
if (!live.has(slug) && !removed.has(slug)) removed.set(slug, reason)
}
}
let marked = 0
for (const [tree] of published) {
visit(tree as Root, "element", (node: Element) => {
if (node.tagName !== "a" || !node.properties) return
const target = node.properties["data-slug"]
if (typeof target !== "string") return
const classes = Array.isArray(node.properties.className)
? (node.properties.className as string[])
: []
const reason = removed.get(target)
if (reason !== undefined) {
if (!classes.includes("broken")) classes.push("broken")
node.properties.className = classes
node.properties[FILTERED_ATTR] = reason
marked++
} else if (node.properties[FILTERED_ATTR] !== undefined) {
node.properties.className = classes.filter((c) => c !== "broken")
delete node.properties[FILTERED_ATTR]
}
})
}
return marked
}
/** The Links instance marks links to removed pages after filtering (see build.ts). */
export type LinksInstance = QuartzTransformerPluginInstance & { marksBrokenLinks: boolean }
/**
* Link targets are written as in the vault (`[[Čeština]]`, `../české/x.png`). With
* `configuration.slugs.stripDiacritics` the pages and files they point at have stripped slugs,
* 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 }
return {
const instance: LinksInstance = {
name: "Links",
marksBrokenLinks: opts.disableBrokenWikilinks,
htmlPlugins(ctx) {
return [
() => {
@@ -88,7 +202,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, raw, transformOptions)
const rel = transformLink(pathSlug, slugOptionsOnLinkPath(raw), transformOptions)
if (!rebase) return rel
const hash = rel.indexOf("#")
const anchor = hash === -1 ? "" : rel.slice(hash)
@@ -106,8 +220,17 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
let dest = node.properties.href as RelativeURL
const classes = (node.properties.className ?? []) as string[]
const isExternal = isExternalUrl(dest)
// Footnote anchors aren't note links: Obsidian gives them `footnote-link`,
// never `internal-link`, whose link styles would override theirs.
const isFootnote =
node.properties.dataFootnoteRef !== undefined ||
node.properties.dataFootnoteBackref !== undefined
classes.push(
...(isExternal ? ["external", "external-link"] : ["internal", "internal-link"]),
...(isExternal
? ["external", "external-link"]
: isFootnote
? ["internal"]
: ["internal", "internal-link"]),
)
if (isExternal && opts.externalLinkIcon) {
@@ -131,12 +254,14 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
})
}
// link text differs from the href → it's an alias ("[[note|text]]")
// link text differs from the href → it's an alias ("[[note|text]]"). The href is
// percent-encoded by now ("a%20b" for "a b"), so it is compared decoded too (#2643)
const firstChild = node.children[0]
if (
node.children.length === 1 &&
firstChild?.type === "text" &&
firstChild.value !== dest
firstChild.value !== dest &&
firstChild.value !== decodedHref(dest)
) {
classes.push("alias")
}
@@ -153,7 +278,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
outgoing.add(simplifySlug(full))
node.properties["data-slug"] = full
if (opts.disableBrokenWikilinks && !ctx.allSlugs.includes(full)) {
if (opts.disableBrokenWikilinks && !pageExists(ctx.allSlugs, full)) {
classes.push("broken")
node.properties.className = classes
}
@@ -228,4 +353,5 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
]
},
}
return instance
}
@@ -2,26 +2,19 @@ import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import test, { describe } from "node:test"
import { createContext, runInContext, runInNewContext } from "node:vm"
import ts from "typescript"
// Exercise the actual generated script without importing the emitter's SCSS
// and inline-script assets into Node or copying its counting implementation.
const source = ts.createSourceFile(
"componentResources.ts",
readFileSync(new URL("./componentResources.ts", import.meta.url), "utf8"),
ts.ScriptTarget.Latest,
true,
)
let template: ts.TemplateExpression | undefined
function findTemplate(node: ts.Node) {
if (ts.isTemplateExpression(node) && node.head.text.includes("window.goatcounter = {")) {
assert.equal(template, undefined, "expected a single GoatCounter script")
template = node
}
ts.forEachChild(node, findTemplate)
}
findTemplate(source)
assert.ok(template, "GoatCounter script template must exist")
// The script is a template literal without nested template literals: it runs from the
// backtick before its first line to the next backtick.
const emitterSource = readFileSync(new URL("./componentResources.ts", import.meta.url), "utf8")
const marker = "window.goatcounter = {"
assert.equal(emitterSource.split(marker).length, 2, "expected a single GoatCounter script")
const markerAt = emitterSource.indexOf(marker)
const templateStart = emitterSource.lastIndexOf("`", markerAt)
const templateEnd = emitterSource.indexOf("`", markerAt)
assert.ok(templateStart >= 0 && templateEnd > markerAt, "GoatCounter script template must exist")
const template = emitterSource.slice(templateStart, templateEnd + 1)
type Pageview = { path: string; title?: string }
type Script = {
@@ -65,7 +58,7 @@ function setup(
context.window = context
// the emitter writes config values with this helper (JSON string literals)
const js = (value: unknown) => JSON.stringify(String(value)).replace(/</g, "\\u003c")
const script = runInNewContext(template!.getText(source), { analytics, js })
const script = runInNewContext(template, { analytics, js })
runInContext(script, context)
return {
@@ -430,11 +430,13 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
include: Features.MediaQueries,
}).code.toString()
// All component styles go into one stylesheet, in their order, in one
// `quartz-base` layer: a file per component meant ~20 render-blocking
// requests per page, many for a few hundred bytes.
const cssStringToFilename = new Map<string, string>()
for (const cssString of componentResources.componentCssStrings) {
if (cssStringToFilename.has(cssString)) continue
const wrapped = `@layer quartz-base {\n${cssString}\n}`
const componentCss = [...componentResources.componentCssStrings]
if (componentCss.length > 0) {
const wrapped = `@layer quartz-base {\n${componentCss.join("\n")}\n}`
const minified = transform({
filename: "component.css",
code: Buffer.from(wrapped),
@@ -446,7 +448,7 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
const hash = hashContent(minified)
const slug = `component-${hash}`
const filename = `${slug}.css`
cssStringToFilename.set(cssString, filename)
for (const cssString of componentCss) cssStringToFilename.set(cssString, filename)
yield write({
ctx,
+59 -1
View File
@@ -1,6 +1,6 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import { getCondition, hasBacklinks } from "./conditions"
import { getCondition, hasBacklinks, registerCondition } from "./conditions"
import type { QuartzComponentProps } from "../../components/types"
type Props = Pick<QuartzComponentProps, "fileData" | "allFiles">
@@ -51,3 +51,61 @@ describe("has-backlinks condition", () => {
assert.strictEqual(hasBacklinks({ fileData: { slug: "a" } } as unknown as Props), false)
})
})
describe("index conditions (#2465)", () => {
const run = (name: string, slug: string | undefined) =>
getCondition(name)!({ fileData: { slug }, allFiles: [] } as unknown as QuartzComponentProps)
test("is-index is true only on the root index page", () => {
assert.strictEqual(run("is-index", "index"), true)
assert.strictEqual(run("is-index", "folder/index"), false)
assert.strictEqual(run("is-index", "page"), false)
assert.strictEqual(run("is-index", undefined), false)
})
test("is-index and not-index are complements", () => {
for (const slug of ["index", "folder/index", "a/b", undefined]) {
assert.strictEqual(run("is-index", slug), !run("not-index", slug))
}
})
test("is-folder-index matches folder index pages, not the root index", () => {
assert.strictEqual(run("is-folder-index", "folder/index"), true)
assert.strictEqual(run("is-folder-index", "a/b/index"), true)
assert.strictEqual(run("is-folder-index", "index"), false)
assert.strictEqual(run("is-folder-index", "folder/indexes"), false)
assert.strictEqual(run("is-folder-index", undefined), false)
})
})
describe("not-<condition> negation", () => {
const withTags = { fileData: { slug: "a", frontmatter: { tags: ["x"] } }, allFiles: [] }
const noTags = { fileData: { slug: "a", frontmatter: {} }, allFiles: [] }
const call = (name: string, p: unknown) => getCondition(name)!(p as QuartzComponentProps)
test("not-has-tags negates has-tags", () => {
assert.strictEqual(call("not-has-tags", withTags), false)
assert.strictEqual(call("not-has-tags", noTags), true)
})
test("negates custom conditions too", () => {
registerCondition("is-draft-test", (p) => p.fileData.slug === "draft")
assert.strictEqual(call("not-is-draft-test", { fileData: { slug: "draft" } }), false)
assert.strictEqual(call("not-is-draft-test", { fileData: { slug: "x" } }), true)
})
test("an exact name wins over negation (not-index is its own built-in)", () => {
assert.strictEqual(call("not-index", { fileData: { slug: "index" } }), false)
assert.strictEqual(call("not-index", { fileData: { slug: "a" } }), true)
})
test("unknown names stay unknown", () => {
assert.strictEqual(getCondition("not-nonexistent"), undefined)
assert.strictEqual(getCondition("not-"), undefined)
assert.strictEqual(getCondition("nonexistent"), undefined)
})
test("double negation works", () => {
assert.strictEqual(call("not-not-has-tags", withTags), true)
})
})
+20 -1
View File
@@ -4,7 +4,13 @@ import { FullSlug, simplifySlug } from "../../util/path"
export type ConditionPredicate = (props: QuartzComponentProps) => boolean
const builtinConditions: Record<string, ConditionPredicate> = {
"is-index": (props) => props.fileData.slug === "index",
"not-index": (props) => props.fileData.slug !== "index",
// A folder's index page: `folder/index.md` or a generated folder page, not the root index.
"is-folder-index": (props) => {
const slug = props.fileData.slug
return typeof slug === "string" && slug.endsWith("/index")
},
"has-tags": (props) => {
const tags = props.fileData.frontmatter?.tags
return Array.isArray(tags) && tags.length > 0
@@ -36,8 +42,21 @@ export function registerCondition(name: string, predicate: ConditionPredicate):
customConditions.set(name, predicate)
}
const NEGATION_PREFIX = "not-"
/**
* Look up a condition. Besides the registered names, `not-<name>` negates any other
* condition (`not-has-tags`, `not-is-folder-index`, a custom `not-<custom>`), unless a
* condition with that exact name exists (`not-index` is its own built-in).
*/
export function getCondition(name: string): ConditionPredicate | undefined {
return customConditions.get(name) ?? builtinConditions[name]
const direct = customConditions.get(name) ?? builtinConditions[name]
if (direct) return direct
if (name.startsWith(NEGATION_PREFIX)) {
const inner = getCondition(name.slice(NEGATION_PREFIX.length))
if (inner) return (props) => !inner(props)
}
return undefined
}
export function getAllConditionNames(): string[] {
@@ -0,0 +1,377 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import path from "path"
import fs from "fs"
import YAML from "yaml"
import {
ConfigExtendsError,
deepMerge,
mergeQuartzConfigs,
pluginMatchKey,
resolveExtends,
resolveTarget,
fetchRemoteConfig,
} from "./config-extends"
import os from "os"
import type { QuartzPluginsJson } from "./types"
const base = (): QuartzPluginsJson => ({
configuration: {
pageTitle: "Quartz",
ignorePatterns: ["private", ".obsidian"],
theme: { typography: { header: "Schibsted Grotesk", body: "Source Sans Pro" } },
links: { markdownLinkResolution: "shortest" },
},
plugins: [
{ source: "@quartz-community/explorer", enabled: true, options: { a: 1, nested: { x: 1 } } },
{
source: "github:quartz-community/graph",
enabled: true,
order: 50,
layout: { position: "right", priority: 10 },
},
{ source: "@quartz-community/comments", enabled: false },
],
layout: { byPageType: { folder: { exclude: ["graph"] } } },
})
describe("deepMerge", () => {
test("objects merge, other values replace, null deletes", () => {
assert.deepStrictEqual(
deepMerge({ a: { b: 1, c: 2 }, l: [1, 2], k: 1 }, { a: { c: 3 }, l: [9], k: null }),
{
a: { b: 1, c: 3 },
l: [9],
},
)
})
test("does not modify its inputs", () => {
const b = { a: { b: 1 } }
deepMerge(b, { a: { b: 2 } })
assert.deepStrictEqual(b, { a: { b: 1 } })
})
})
describe("pluginMatchKey", () => {
test("npm, GitHub, git URL and local sources of one plugin match", () => {
for (const source of [
"@quartz-community/explorer",
"@quartz-community/explorer@^2.0.0",
"github:quartz-community/explorer",
"github:someone/explorer#v2",
"git+https://github.com/quartz-community/explorer.git",
"https://github.com/quartz-community/explorer",
"./plugins/explorer/",
"explorer",
{ repo: "github:quartz-community/plugins", subdir: "x", name: "explorer" },
]) {
assert.strictEqual(pluginMatchKey(source as never), "explorer", JSON.stringify(source))
}
})
})
describe("mergeQuartzConfigs", () => {
test("configuration deep-merges; arrays replace; null resets a key", () => {
const merged = mergeQuartzConfigs(base(), {
configuration: {
pageTitle: "My garden",
ignorePatterns: ["drafts"],
theme: { typography: { header: "Inter" } },
links: null,
},
})
assert.strictEqual(merged.configuration.pageTitle, "My garden")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["drafts"])
assert.deepStrictEqual(merged.configuration.theme, {
typography: { header: "Inter", body: "Source Sans Pro" },
})
assert.ok(!("links" in merged.configuration))
// the base plugins are kept when the overlay lists none
assert.strictEqual(merged.plugins.length, 3)
})
test("plugins match by name; enabled/order/source replace, options/layout merge", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{
source: "github:quartz-community/explorer",
options: { b: 2, nested: { y: 2 } },
} as never,
{ source: "@quartz-community/graph", enabled: false, order: 10, layout: { priority: 1 } },
{ source: "@quartz-community/comments", enabled: true },
],
})
const [explorer, graph, comments] = merged.plugins
assert.strictEqual(explorer.source, "github:quartz-community/explorer")
assert.strictEqual(explorer.enabled, true)
assert.deepStrictEqual(explorer.options, { a: 1, b: 2, nested: { x: 1, y: 2 } })
assert.strictEqual(graph.enabled, false)
assert.strictEqual(graph.order, 10)
assert.deepStrictEqual(graph.layout, { position: "right", priority: 1 })
assert.strictEqual(comments.enabled, true)
assert.strictEqual(merged.plugins.length, 3)
})
test("new plugins are appended as written (no enabled → disabled, as in a full config)", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{ source: "github:me/my-plugin", enabled: true, order: 70 },
{ source: "github:me/other" },
],
})
assert.strictEqual(merged.plugins.length, 5)
assert.deepStrictEqual(merged.plugins[3], {
source: "github:me/my-plugin",
enabled: true,
order: 70,
})
assert.deepStrictEqual(merged.plugins[4], { source: "github:me/other" })
})
test("null removes a plugin's options, layout or order (back to the plugin's defaults)", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{ source: "@quartz-community/graph", layout: null, order: null } as never,
{ source: "@quartz-community/explorer", options: { nested: null } } as never,
],
})
const [explorer, graph] = merged.plugins
assert.ok(!("layout" in graph) && !("order" in graph))
assert.deepStrictEqual(explorer.options, { a: 1 })
})
test("layout merges; arrays like byPageType.*.exclude replace", () => {
const merged = mergeQuartzConfigs(base(), {
layout: { byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } } },
})
assert.deepStrictEqual(merged.layout, {
byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } },
})
})
test("does not modify the base", () => {
const b = base()
const before = JSON.stringify(b)
mergeQuartzConfigs(b, {
configuration: { pageTitle: "x" },
plugins: [{ source: "@quartz-community/explorer", options: { a: 2 } } as never],
})
assert.strictEqual(JSON.stringify(b), before)
})
test("a plugin entry without source is an error", () => {
assert.throws(
() => mergeQuartzConfigs(base(), { plugins: [{ enabled: false } as never] }),
ConfigExtendsError,
)
})
})
describe("resolveExtends", () => {
const files: Record<string, string> = {}
const root = path.resolve("/site")
const readFile = (f: string) => {
const content = files[path.resolve(f)]
if (content === undefined) throw new Error("ENOENT")
return content
}
const put = (rel: string, data: unknown) => {
files[path.join(root, rel)] = YAML.stringify(data)
}
put("quartz.config.default.yaml", base())
test("a config without extends is returned as is", async () => {
const data = { configuration: { pageTitle: "x" }, plugins: [] }
assert.strictEqual(
await resolveExtends(data, path.join(root, "quartz.config.yaml")),
data as never,
)
})
test("extends: default merges onto quartz.config.default.yaml", async () => {
const merged = await resolveExtends(
{
extends: "default",
configuration: { pageTitle: "Mine" },
plugins: [{ source: "@quartz-community/graph", enabled: false }],
},
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Mine")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["private", ".obsidian"])
assert.strictEqual(
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
false,
)
assert.ok(!("extends" in merged))
})
test("relative paths, chains and lists (later wins)", async () => {
put("configs/team.yaml", {
extends: "default",
configuration: { pageTitle: "Team", locale: "cs-CZ" },
})
put("configs/dark.yaml", { configuration: { pageTitle: "Dark" } })
const merged = await resolveExtends(
{
extends: ["./configs/team.yaml", "configs/dark.yaml"],
configuration: { baseUrl: "x.org" },
},
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Dark")
assert.strictEqual(merged.configuration.locale, "cs-CZ")
assert.strictEqual(merged.configuration.baseUrl, "x.org")
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
})
test("cycles and missing files are reported", async () => {
put("a.yaml", { extends: "./b.yaml" })
put("b.yaml", { extends: "./a.yaml" })
await assert.rejects(
() =>
resolveExtends({ extends: "./a.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
/cycle/,
)
await assert.rejects(
() =>
resolveExtends({ extends: "./nope.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
/not found/,
)
await assert.rejects(
() =>
resolveExtends({ extends: 3 }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
ConfigExtendsError,
)
})
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"))
const merged = await resolveExtends({ extends: "default" }, path.resolve("quartz.config.yaml"))
assert.deepStrictEqual(merged, shipped)
})
describe("https bases", () => {
const remote: Record<string, string> = {
"https://cfg.example/base/site.yaml": YAML.stringify({
extends: "./common.yaml",
configuration: { pageTitle: "Remote" },
}),
"https://cfg.example/base/common.yaml": YAML.stringify({
extends: "default",
configuration: { locale: "de-DE" },
}),
}
const fetchRemote = async (url: string) => {
if (!(url in remote)) throw new ConfigExtendsError(`404 ${url}`)
return remote[url]
}
const opts = () => ({ quartzRoot: root, readFile, fetchRemote })
test("a URL base; its relative extends resolve against the URL; default stays local", async () => {
const merged = await resolveExtends(
{ extends: "https://cfg.example/base/site.yaml", configuration: { baseUrl: "me.org" } },
path.join(root, "quartz.config.yaml"),
opts(),
)
assert.strictEqual(merged.configuration.pageTitle, "Remote")
assert.strictEqual(merged.configuration.locale, "de-DE")
assert.strictEqual(merged.configuration.baseUrl, "me.org")
assert.strictEqual(merged.plugins.length, 3) // the local default, via the remote chain
})
test("only https", async () => {
await assert.rejects(
resolveExtends({ extends: "http://cfg.example/x.yaml" }, path.join(root, "q.yaml"), opts()),
/only https/,
)
assert.strictEqual(
resolveTarget("../other.yaml", "https://cfg.example/base/site.yaml", root),
"https://cfg.example/other.yaml",
)
})
})
})
describe("fetchRemoteConfig", () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
const ok = (body: string) =>
(async () => new Response(body, { status: 200 })) as unknown as typeof fetch
const failing = (async () => {
throw new Error("getaddrinfo ENOTFOUND")
}) as unknown as typeof fetch
test("caches a fetched copy and falls back to it when offline or failing", async () => {
const cacheDir = tmp()
const url = "https://cfg.example/a.yaml"
assert.strictEqual(
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 })
assert.strictEqual(
await fetchRemoteConfig(url, {
cacheDir: other,
fetchImpl: failing,
offline: false,
warn: (m) => warnings.push(m),
}),
"a: 1\n",
)
assert.match(warnings[0], /using the cached copy/)
// offline (QUARTZ_EXTENDS_OFFLINE=1, worker threads): the cache only
assert.strictEqual(
await fetchRemoteConfig("https://cfg.example/a.yaml?x", {
cacheDir: other,
offline: true,
}).catch((e: Error) => e.message),
`"extends: https://cfg.example/a.yaml?x": no cached copy in ${other} (offline build). Build once online first.`,
)
})
test("without a cached copy a failed fetch stops the build", async () => {
await assert.rejects(
fetchRemoteConfig("https://cfg.example/b.yaml", {
cacheDir: tmp(),
fetchImpl: failing,
offline: false,
}),
/could not be fetched: getaddrinfo ENOTFOUND/,
)
await assert.rejects(
fetchRemoteConfig("https://cfg.example/c.yaml", { cacheDir: tmp(), offline: true }),
/no cached copy/,
)
})
test("HTTP errors are failures, too", async () => {
const notFound = (async () => new Response("nope", { status: 404 })) as unknown as typeof fetch
await assert.rejects(
fetchRemoteConfig("https://cfg.example/d.yaml", {
cacheDir: tmp(),
fetchImpl: notFound,
offline: false,
}),
/HTTP 404/,
)
})
})
+358
View File
@@ -0,0 +1,358 @@
import fs from "fs"
import path from "path"
import { createHash } from "crypto"
import { isMainThread } from "worker_threads"
import YAML from "yaml"
import type {
PluginJsonEntry,
PluginLayoutDeclaration,
PluginSource,
QuartzPluginsJson,
} from "./types"
/**
* `extends:` in quartz.config.yaml (#2440): start from another config and apply only the
* differences on top.
*
* ```yaml
* extends: default # quartz.config.default.yaml next to quartz.config.yaml's Quartz
* configuration:
* pageTitle: My garden
* plugins:
* - source: "@quartz-community/explorer"
* options: { folderDefaultState: open }
* - source: "@quartz-community/graph"
* enabled: false
* ```
*
* Merge rules (`mergeQuartzConfigs`):
* - `configuration` and `layout`: objects merge key by key, recursively; any other value
* (strings, numbers, arrays such as `ignorePatterns` or `byPageType.*.exclude`) replaces the
* base value; `null` removes the key (back to the built-in default).
* - `plugins`: an entry matches the base entry of the same plugin (by plugin name, so
* `github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the
* same name replaces the original). Of a matched entry, `source`, `enabled` and `order`
* replace the base values, and `options` and `layout` merge like `configuration`. Entries
* that match nothing are appended, as in a full config (so they need `enabled: true`). The base list keeps its order, which only matters as the
* tie-break between plugins with the same `order`.
* - A config without `extends` is used exactly as written, as before.
*/
/** The name `extends: default` stands for. */
export const DEFAULT_EXTENDS = "default"
export const DEFAULT_CONFIG_FILE = "quartz.config.default.yaml"
/** A configuration mistake: reported by its message alone (no stack trace). */
export class ConfigExtendsError extends Error {
constructor(message: string) {
super(message)
this.name = "ConfigExtendsError"
this.stack = `${this.name}: ${message}`
}
}
type PlainObject = Record<string, unknown>
/** A plugin entry in a config that extends another: only `source` is required. */
export interface PluginOverlayEntry {
source: PluginSource
enabled?: boolean
/** Merged into the base entry's options; `null` drops them (the plugin's defaults apply). */
options?: Record<string, unknown> | null
order?: number | null
/** Replace the base entry's constraints; `null` removes them. */
before?: string | string[] | null
after?: string | string[] | null
/** Merged into the base entry's layout; `null` drops it (the plugin's default placement). */
layout?: Partial<PluginLayoutDeclaration> | null
}
/** What a config with `extends` may contain: any part of a full config. */
export interface QuartzConfigOverlay {
$schema?: string
extends?: string | string[] | null
configuration?: Record<string, unknown>
plugins?: PluginOverlayEntry[]
layout?: Record<string, unknown>
}
function isPlainObject(value: unknown): value is PlainObject {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
/** Recursive merge: objects merge, everything else replaces, `null` deletes. */
export function deepMerge(base: unknown, overlay: unknown): unknown {
if (overlay === undefined) return base
if (!isPlainObject(base) || !isPlainObject(overlay)) return overlay
const result: PlainObject = { ...base }
for (const [key, value] of Object.entries(overlay)) {
if (value === null) {
delete result[key]
} else {
result[key] = deepMerge(base[key], value)
}
}
return result
}
/**
* The name a plugin entry is matched by: the last path segment of its package or repository
* (`@quartz-community/explorer`, `github:quartz-community/explorer#v2`, `./plugins/explorer` →
* `explorer`), or the `name` of an object source.
*/
export function pluginMatchKey(source: PluginSource): string {
if (typeof source === "object" && source !== null) {
if (source.name) return source.name
return pluginMatchKey(source.repo)
}
let s = String(source).trim()
s = s.replace(/^git\+/, "").replace(/^github:/, "")
s = s.split("#")[0]
s = s.replace(/\.git$/, "").replace(/\/+$/, "")
// an npm version/range: @scope/name@1.2.3, name@^1
s = s.replace(/(.)@[^/]*$/, "$1")
return s.slice(s.lastIndexOf("/") + 1)
}
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
const merged: PlainObject = { ...base }
for (const [key, value] of Object.entries(overlay)) {
if (value === undefined) continue
if (key === "options" || key === "layout") {
const next = value === null ? undefined : deepMerge(merged[key], value)
if (next === undefined) delete merged[key]
else merged[key] = next
} else if (value === null) {
delete merged[key]
} else {
merged[key] = value
}
}
return merged as unknown as PluginJsonEntry
}
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
export function mergeQuartzConfigs(
base: QuartzPluginsJson,
overlay: QuartzConfigOverlay,
): QuartzPluginsJson {
const { extends: _extends, plugins: overlayPlugins, ...rest } = overlay
const merged = deepMerge(
{ ...base, plugins: undefined },
{ ...rest, plugins: undefined },
) as QuartzPluginsJson
const plugins = (base.plugins ?? []).map((entry) => ({ ...entry }))
for (const entry of overlayPlugins ?? []) {
if (!entry || entry.source === undefined) {
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
}
const key = pluginMatchKey(entry.source)
const index = plugins.findIndex((p) => pluginMatchKey(p.source) === key)
if (index === -1) {
// a new plugin, read like an entry of a full config (no `enabled` → disabled, with a warning)
plugins.push({ ...entry } as PluginJsonEntry)
} else {
plugins[index] = mergePluginEntry(plugins[index], entry)
}
}
merged.plugins = plugins
merged.configuration = (merged.configuration ?? {}) as QuartzPluginsJson["configuration"]
return merged
}
export interface ResolveExtendsOptions {
/** Directory holding quartz.config.default.yaml (`extends: default`). Default: cwd. */
quartzRoot?: string
/** Local file reader, for tests. */
readFile?: (file: string) => string
/** Loader for `https://` bases; default `fetchRemoteConfig` (cached, with a timeout). */
fetchRemote?: (url: string) => Promise<string>
}
/** Where fetched remote bases are kept (offline builds, worker threads). */
export const REMOTE_CACHE_DIR = path.join(".quartz-cache", "extends")
const REMOTE_TIMEOUT_MS = 10_000
const REMOTE_MAX_BYTES = 1024 * 1024
const isUrl = (s: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s)
function remoteCacheFile(url: string, cacheDir: string): string {
return path.join(cacheDir, createHash("sha256").update(url).digest("hex").slice(0, 32) + ".yaml")
}
export interface FetchRemoteOptions {
cacheDir?: string
timeoutMs?: number
/** Only use the cache (QUARTZ_EXTENDS_OFFLINE=1; always in worker threads). */
offline?: boolean
fetchImpl?: typeof fetch
warn?: (message: string) => void
}
const fetched = new Map<string, Promise<string>>()
/**
* Fetch a remote base config: once per process, with a timeout and a size limit. A successful
* fetch is cached in `.quartz-cache/extends/`; when the fetch fails (offline, timeout, HTTP
* error) the cached copy is used with a warning, and without one the build stops. Worker threads
* and `QUARTZ_EXTENDS_OFFLINE=1` read only the cache, so every thread of a build sees the copy
* the main thread fetched.
*/
export function fetchRemoteConfig(url: string, opts: FetchRemoteOptions = {}): Promise<string> {
const cacheDir = opts.cacheDir ?? path.join(process.cwd(), REMOTE_CACHE_DIR)
const key = `${cacheDir}\0${url}`
let pending = fetched.get(key)
if (!pending) {
pending = fetchUncached(url, cacheDir, opts)
fetched.set(key, pending)
pending.catch(() => fetched.delete(key))
}
return pending
}
async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOptions) {
const cacheFile = remoteCacheFile(url, cacheDir)
const cached = () => {
try {
return fs.readFileSync(cacheFile, "utf-8")
} catch {
return undefined
}
}
const offline = opts.offline ?? (process.env.QUARTZ_EXTENDS_OFFLINE === "1" || !isMainThread)
if (offline) {
const copy = cached()
if (copy !== undefined) return copy
throw new ConfigExtendsError(
`"extends: ${url}": no cached copy in ${cacheDir} (offline build). Build once online first.`,
)
}
const warn = opts.warn ?? ((m: string) => console.warn(`⚠ ${m}`))
let failure: string
try {
const res = await (opts.fetchImpl ?? fetch)(url, {
signal: AbortSignal.timeout(opts.timeoutMs ?? REMOTE_TIMEOUT_MS),
headers: { accept: "application/yaml, application/json, text/plain, */*" },
})
if (res.url && !res.url.startsWith("https://")) {
throw new ConfigExtendsError(`"extends: ${url}" redirected to ${res.url}, which is not https`)
}
if (!res.ok) {
failure = `HTTP ${res.status}`
} else {
const text = await res.text()
if (Buffer.byteLength(text) > REMOTE_MAX_BYTES) {
throw new ConfigExtendsError(`"extends: ${url}" is larger than 1 MB`)
}
fs.mkdirSync(cacheDir, { recursive: true })
fs.writeFileSync(cacheFile, text)
return text
}
} catch (err) {
if (err instanceof ConfigExtendsError) throw err
failure = err instanceof Error ? err.message : String(err)
}
const copy = cached()
if (copy !== undefined) {
warn(`"extends: ${url}" could not be fetched (${failure}); using the cached copy.`)
return copy
}
throw new ConfigExtendsError(`"extends: ${url}" could not be fetched: ${failure}`)
}
function parseConfigFile(file: string, raw: string): PlainObject {
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
if (!isPlainObject(data)) {
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
}
return data
}
function extendsTargets(value: unknown, file: string): string[] {
const list = Array.isArray(value) ? value : [value]
for (const item of list) {
if (typeof item !== "string" || item.trim() === "") {
throw new ConfigExtendsError(
`${file}: "extends" must be "${DEFAULT_EXTENDS}", a path to another config file, an https:// URL, or a list of them`,
)
}
}
return list as string[]
}
/**
* Where an `extends` target points, seen from the file (or URL) that names it: `default` is
* the local quartz.config.default.yaml; a URL is used as is; a relative path is resolved
* against the extending file's directory, or against its URL when that file was fetched (a
* remote config cannot reach local files). Only https URLs are allowed. (A future
* `npm:<package>` target would be one more case here.)
*/
export function resolveTarget(target: string, from: string, quartzRoot: string): string {
if (target === DEFAULT_EXTENDS) return path.join(quartzRoot, DEFAULT_CONFIG_FILE)
const resolved = isUrl(target)
? target
: isUrl(from)
? new URL(target, from).href
: path.resolve(path.dirname(from), target)
if (isUrl(resolved) && !resolved.startsWith("https://")) {
throw new ConfigExtendsError(
`${from}: "extends: ${target}" — only https:// URLs can be extended`,
)
}
return resolved
}
/**
* Apply `extends` of `data` (read from `file`, a path or URL): load each base (recursively;
* later entries of an `extends` list win), then merge `data` on top. Returns `data` itself
* when it has no `extends`, so configs without it behave exactly as before.
*/
export async function resolveExtends(
data: PlainObject,
file: string,
options: ResolveExtendsOptions = {},
seen: string[] = [],
): Promise<QuartzPluginsJson> {
if (data.extends === undefined || data.extends === null) {
const { extends: _drop, ...rest } = data
return (data.extends === null ? rest : data) as unknown as QuartzPluginsJson
}
const readFile = options.readFile ?? ((f: string) => fs.readFileSync(f, "utf-8"))
const fetchRemote = options.fetchRemote ?? ((url: string) => fetchRemoteConfig(url))
const quartzRoot = options.quartzRoot ?? process.cwd()
const self = isUrl(file) ? file : path.resolve(file)
const chain = [...seen, self]
let base: QuartzPluginsJson | undefined
for (const target of extendsTargets(data.extends, file)) {
const targetFile = resolveTarget(target, file, quartzRoot)
if (chain.includes(targetFile)) {
throw new ConfigExtendsError(
`"extends" cycle: ${[...chain, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
)
}
let raw: string
if (isUrl(targetFile)) {
raw = await fetchRemote(targetFile)
} else {
try {
raw = readFile(targetFile)
} catch {
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
}
}
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
let parsed: PlainObject
try {
parsed = parseConfigFile(parsePath, raw)
} catch (err) {
throw new ConfigExtendsError(
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
)
}
const resolved = await resolveExtends(parsed, targetFile, options, chain)
base = base ? mergeQuartzConfigs(base, resolved as QuartzConfigOverlay) : resolved
}
return mergeQuartzConfigs(base!, data as QuartzConfigOverlay)
}
@@ -1,8 +1,10 @@
import test, { describe, afterEach } from "node:test"
import assert from "node:assert"
import path from "path"
import {
buildLayoutForEntries,
isExcluded,
resolveConfigPath,
resolveGroups,
validateDependencies,
detectCategoryFromModule,
@@ -13,6 +15,23 @@ import { componentRegistry } from "../../components/registry"
import type { QuartzComponent, QuartzComponentConstructor } from "../../components/types"
import { PluginJsonEntry, LayoutPosition } from "./types"
describe("resolveConfigPath", () => {
afterEach(() => {
delete process.env.QUARTZ_CONFIG_PATH
})
test("QUARTZ_CONFIG_PATH overrides the default lookup", () => {
const custom = path.join("some", "dir", "quartz.config.yaml")
process.env.QUARTZ_CONFIG_PATH = custom
assert.strictEqual(resolveConfigPath(), path.resolve(custom))
})
test("falls back to the cwd default when QUARTZ_CONFIG_PATH is unset", () => {
delete process.env.QUARTZ_CONFIG_PATH
assert.notStrictEqual(resolveConfigPath(), path.resolve("some", "dir", "quartz.config.yaml"))
})
})
const makeComponent = (name: string): QuartzComponent => {
const c = (() => null) as unknown as QuartzComponent
c.displayName = name
+57 -17
View File
@@ -61,6 +61,9 @@ import {
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
import { componentRegistry, RegisteredComponent } from "../../components/registry"
import { frameRegistry } from "../../components/frames/registry"
import { OrderItem, constraintList, normalizePluginName, orderPlugins } from "./plugin-order"
import { resolveExtends } from "./config-extends"
import { setSlugOptions } from "../../util/path"
import { getCondition, getAllConditionNames } from "./conditions"
import {
LAYOUT_SLOTS,
@@ -83,23 +86,27 @@ const DEFAULT_CONFIG_YAML_PATH = path.join(process.cwd(), "quartz.config.default
const LEGACY_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.json")
const LEGACY_DEFAULT_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.default.json")
function resolveConfigPath(): string {
/** @internal Exported for testing only. Honors QUARTZ_CONFIG_PATH, else falls back to cwd. */
export function resolveConfigPath(): string {
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
if (fs.existsSync(CONFIG_YAML_PATH)) return CONFIG_YAML_PATH
if (fs.existsSync(LEGACY_PLUGINS_JSON_PATH)) return LEGACY_PLUGINS_JSON_PATH
if (fs.existsSync(DEFAULT_CONFIG_YAML_PATH)) return DEFAULT_CONFIG_YAML_PATH
if (fs.existsSync(LEGACY_DEFAULT_PLUGINS_JSON_PATH)) return LEGACY_DEFAULT_PLUGINS_JSON_PATH
return CONFIG_YAML_PATH
}
function readPluginsJson(): QuartzPluginsJson | null {
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
const configPath = resolveConfigPath()
if (!fs.existsSync(configPath)) {
return null
}
const raw = fs.readFileSync(configPath, "utf-8")
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
return YAML.parse(raw) as QuartzPluginsJson
}
return JSON.parse(raw) as QuartzPluginsJson
const data =
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
// `extends:` (#2440): merge onto the base config; a config without it is used as written
return data && typeof data === "object" && "extends" in data
? resolveExtends(data, configPath)
: (data as QuartzPluginsJson)
}
function extractPluginName(source: PluginSource): string {
@@ -358,11 +365,12 @@ async function getManifest(source: PluginSource): Promise<PluginManifest | null>
export async function loadQuartzConfig(
configOverrides?: Partial<GlobalConfiguration>,
): Promise<QuartzConfig> {
const json = readPluginsJson()
const json = await readPluginsJson()
if (!json) {
// Fallback: import old-style config directly
const oldConfig = await import("../../../quartz")
setSlugOptions(oldConfig.default?.configuration?.slugs)
return oldConfig.default
}
@@ -370,6 +378,8 @@ export async function loadQuartzConfig(
...(json.configuration as unknown as GlobalConfiguration),
...configOverrides,
}
// before anything computes a slug (this runs in the main thread and in every worker)
setSlugOptions(configuration.slugs)
// Entries of official plugins that are now built into core (crawl-links, remove-draft,
// content-index) are handled by the built-ins below and never installed or loaded.
@@ -654,7 +664,7 @@ export async function loadQuartzConfig(
items: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[],
expectedCategory: ProcessingCategory,
) => {
const instances: { order: number; instance: any }[] = []
const instances: OrderItem<any>[] = []
for (const { entry, manifest } of items) {
try {
const spec = parsePluginSource(entry.source)
@@ -713,7 +723,19 @@ export async function loadQuartzConfig(
issues: manifest?.issues,
quartzVersion: manifest?.quartzVersion,
})
instances.push({ order: entry.order ?? manifest?.defaultOrder ?? 50, instance })
const label = extractPluginName(entry.source)
instances.push({
order: entry.order ?? manifest?.defaultOrder ?? 50,
instance,
label,
names: [
label,
manifest?.name,
typeof instance.name === "string" ? instance.name : "",
].filter((n): n is string => typeof n === "string" && n !== ""),
before: constraintList(entry.before, "before", label),
after: constraintList(entry.after, "after", label),
})
} catch (err) {
pluginLoadFailed(entry, manifest, "was skipped: it failed to initialise", err)
}
@@ -731,15 +753,33 @@ export async function loadQuartzConfig(
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
// Built-in processing steps take their place in plugin order (frontmatter at 0, links at 60 …);
// on equal order a built-in runs before plugins (stable sort, built-ins listed first).
// on equal order a built-in runs before plugins (stable sort, built-ins listed first), unless
// `before`/`after` on an entry say otherwise (see plugin-order.ts).
const knownPluginNames = new Set(
[
...json.plugins.map((e) => extractPluginName(e.source)),
...builtinPlan.builtins.map((b) => b.spec.configKey),
"Frontmatter",
"Links",
"Drafts",
"ContentIndex",
"Fonts",
].map(normalizePluginName),
)
const withBuiltins = <T>(
builtins: { order: number; instance: unknown }[],
instances: { order: number; instance: T }[],
instances: OrderItem<T>[],
): T[] =>
[...builtins, ...instances]
.map((item, index) => ({ ...item, index }))
.sort((a, b) => a.order - b.order || a.index - b.index)
.map((item) => item.instance as T)
orderPlugins(
[
...builtins.map(({ order, instance }) => {
const name = (instance as { name: string }).name
return { order, instance: instance as T, label: name, names: [name] }
}),
...instances,
],
knownPluginNames,
)
const plugins: PluginTypes = {
transformers: withBuiltins(
@@ -758,7 +798,7 @@ export async function loadQuartzConfig(
),
],
pageTypes: [
...(await instantiate(pageTypes, "pageType")).map((item) => item.instance),
...orderPlugins(await instantiate(pageTypes, "pageType"), knownPluginNames),
...builtinPageTypes,
],
}
@@ -1173,7 +1213,7 @@ export function buildQuartzLayout(
* the renderer's layout is updated in place with the overrides applied.
*/
export async function loadQuartzLayout(layoutOverrides?: LayoutOverrides): Promise<QuartzLayout> {
const json = readPluginsJson()
const json = await readPluginsJson()
if (!json) {
// Fallback: import old-style layout directly
+9 -6
View File
@@ -5,8 +5,10 @@ import YAML from "yaml"
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
import type { PluginSource, QuartzPluginsJson } from "./types.js"
import { absorbingBuiltin } from "../builtins/index.js"
import { resolveExtends } from "./config-extends.js"
function resolveConfigPath(): string {
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
const configYamlPath = path.join(process.cwd(), "quartz.config.yaml")
const defaultConfigYamlPath = path.join(process.cwd(), "quartz.config.default.yaml")
const legacyPluginsJsonPath = path.join(process.cwd(), "quartz.plugins.json")
@@ -19,14 +21,15 @@ function resolveConfigPath(): string {
return configYamlPath
}
function readPluginsJson(): QuartzPluginsJson | null {
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
const configPath = resolveConfigPath()
if (!fs.existsSync(configPath)) return null
const raw = fs.readFileSync(configPath, "utf-8")
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
return YAML.parse(raw)
}
return JSON.parse(raw)
const data =
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
return data && typeof data === "object" && "extends" in data
? resolveExtends(data, configPath)
: data
}
async function getExternalPluginSources(): Promise<PluginSource[]> {
@@ -44,7 +47,7 @@ async function getExternalPluginSources(): Promise<PluginSource[]> {
// fall back to config yaml parsing
}
const pluginsJson = readPluginsJson()
const pluginsJson = await readPluginsJson()
const entries = pluginsJson?.plugins ?? []
return entries.filter((entry) => entry.enabled !== false).map((entry) => entry.source)
}
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more