Compare commits

..
Author SHA1 Message Date
saberzero1 28fcb64720 fix: stop esbuild before exiting on a build error 2026-11-09 02:33:30 +01:00
Emile Bangma 8a62b70b1d Merge pull request #2604 from jackyzha0/dev-mode/lockfile-note-properties-1.1.1
chore(deps): note-properties 1.1.1
2026-11-08 18:45:07 +01:00
saberzero1 22c18d1981 chore(deps): note-properties 1.1.1 (refuses JavaScript frontmatter) 2026-11-08 18:37:34 +01:00
Emile Bangma e5332d4491 Merge pull request #2602 from jackyzha0/dev-mode/lockfile-ofm-2.1
chore: lockfile for obsidian-flavored-markdown 2.1.0
2026-11-08 18:18:45 +01:00
Emile Bangma 9f9547eb2d Merge pull request #2603 from jackyzha0/dev-mode/no-js-frontmatter
fix: refuse JavaScript frontmatter instead of executing it
2026-11-08 18:18:27 +01:00
saberzero1 b2da325a32 fix: refuse JavaScript frontmatter instead of executing it; report invalid frontmatter as a content problem 2026-11-08 17:49:08 +01:00
saberzero1 986aa227a8 chore: lockfile for obsidian-flavored-markdown 2.1.0 (highlights keep their formatting; coloured highlights) 2026-11-08 16:47:16 +01:00
Emile Bangma ec1d0b4c06 Merge pull request #2601 from jackyzha0/dev-mode/async-generate
feat: page types may generate virtual pages asynchronously
2026-11-08 16:39:27 +01:00
saberzero1 eab5c532c7 feat: page types may generate virtual pages asynchronously (#2575) 2026-11-08 16:11:50 +01:00
Emile Bangma 6b7bc28912 Merge pull request #2597 from jackyzha0/dev-mode/improvements
Quartz 5.1: built-in processing, plugin capabilities, permalinks, release workflow and fixes
2026-11-08 15:48:42 +01:00
saberzero1 e4ebd28c0d chore: ObsidianFlavoredMarkdown and GitHubFlavoredMarkdown 2.0; lockfile for the released plugins 2026-11-08 15:24:24 +01:00
saberzero1 b7998bbd2d fix(styles): no horizontal scroll on phones (long words break, right sidebar wraps); docs: plugin tag page as tags/plugin/index.md 2026-11-08 02:23:15 +01:00
saberzero1 edfa7f1f1b ci(release): let GitHub create the release tag on the merged commit instead of pushing an unsigned annotated tag (#2455) 2026-11-08 01:50:30 +01:00
saberzero1 c24663f1ab docs: running Quartz with Bun (bun run quartz …) (#2523) 2026-11-08 01:49:35 +01:00
saberzero1 5f503715ab docs(og-image): useGeneratedDescription and the description order (#2470) 2026-11-08 01:48:47 +01:00
saberzero1 6c6aaaa322 chore(deps): minimatch 11 (GHSA-g3hv-75wg-m249) 2026-11-08 01:13:18 +01:00
saberzero1 158a9b5c0f docs: customizing components in v5 (#2444), footer message, theme colors vs configured colors (#2509), per-image styling via alt text and Markdown image sizes (#2494, #2505) 2026-11-08 00:24:01 +01:00
saberzero1 08c2857aa6 feat: layout.sidebars modes (fit, scroll, static) and a docs template 2026-11-08 00:01:29 +01:00
saberzero1 0778a9a157 docs(changeset): permalinked notes stay in their folder in navigation 2026-11-07 23:54:20 +01:00
saberzero1 1f19843db2 feat: content trie places pages by file path, links by slug (permalinked notes stay in their folder) 2026-11-07 23:54:13 +01:00
saberzero1 15b8eeffbf feat: permalinks as in Obsidian Publish — the note's address; its file path redirects there (#2572) 2026-11-07 23:35:44 +01:00
saberzero1 5b6de1fe4c fix(cli): layout.position validation lists the same rendered slots as the schema (no "body") 2026-11-07 22:54:57 +01:00
saberzero1 3e4a50a5ed fix(spa): resolve relative links and push the URL the page was actually served from (after redirects) 2026-11-07 22:50:48 +01:00
saberzero1 5507de3365 fix(i18n): French capitalisation of Vue graphique / Table des matières (#2513) 2026-11-07 22:39:55 +01:00
saberzero1 31bcb34ca7 ci(dependabot): no major bumps of plugin peer dependencies (preact, vfile, unified) (#2586) 2026-11-07 22:24:54 +01:00
saberzero1 671ca4921e chore(deps): sharp 0.35.5, source-map-js 1.2.2, toml 5 (security advisories) 2026-11-07 22:24:54 +01:00
saberzero1 0a475bd328 fix: layout.position schema matches the rendered positions; TUI install hint uses github:quartz-community/tui (#2435) 2026-11-07 22:24:54 +01:00
saberzero1 3103485049 fix(assets): match published (slugified) names, <object data>, srcset and encoded paths for publishAssets: referenced
Follow-up to #2544: references were compared with source paths, so "my photo.png"
(published as my-photo.png) and ofm's <object data> SVG embeds were dropped. The
integration test swapped the repository's own quartz.config.yaml to build a fixture
site; replaced by unit tests of the emitter. Documented publishAssets.
2026-11-07 22:23:03 +01:00
tj2005 63ea0b7190 fix(assets): only copy assets referenced by published pages (#2531)
New opt-in configuration.publishAssets: "referenced" (default "all").

Squashed from #2544 (6 commits).
2026-11-07 22:21:06 +01:00
saberzero1 ab4426337a fix(cli): compare object-form plugin sources by content when detecting a changed source
Follow-up to #2512: `!==` on two objects is always true, so every object-form source
(as read from YAML on each run) counted as changed and was reinstalled every time.
2026-11-07 22:18:49 +01:00
Michel Daviot a78706f710 fix: plugin install --from-config doesn't detect a changed pinned source
handlePluginInstallUnified()'s "already installed" check only verified
that quartz.lock.json had an entry for the plugin's name and that its
directory existed — it never compared the entry's recorded `source`
against the plugin's current source in quartz.config.yaml. So bumping
a plugin's pinned ref (e.g. switching a fork branch, or repointing at
a different fork) was silently ignored whenever the old directory and
lockfile record were still present: the plugin was treated as
up to date and never re-cloned.

This mattered most whenever `.quartz/plugins/` gets reused across
runs instead of rebuilt from scratch — a persistent CI cache, or a
local dev machine re-running `plugin install --from-config` after
editing quartz.config.yaml — since a fresh checkout has no stale
state to miss in the first place. Worse, the existing-directory fast
path re-stamped the lockfile's `source` field to the new value while
leaving `commit` pointing at whatever was actually checked out,
producing a lockfile entry that claimed to be on the new ref while
still serving the old one.

Fixed by extracting the comparison into `pluginSourceChanged()` and
using it in both the "is this missing" filter and the existing-
directory handling: a source mismatch now removes the stale directory
and lets the normal clone path reinstall it, while an unrelated
pre-existing directory (no prior lockfile record at all) is left
alone as before.

Verified: added quartz/cli/plugin-git-handlers.test.js covering the
new helper, `npm test` (167 tests passing) and `npm run check`
(tsc + prettier) both clean.

(cherry picked from commit f933fedca2)
2026-11-07 22:18:36 +01:00
Mark Beznos 3eaf219196 fix(plugins): skip a dependency's peers when building a plugin
(cherry picked from commit 9ce535f8dc)
2026-11-07 22:17:49 +01:00
Mark Beznos 1b4644157b fix(plugins): match excludes by bare name, link local plugins' peers
byPageType.*.exclude compared the full plugin source, so the bare names
the docs and every template use (`reader-mode`) never matched an npm
source (`@quartz-community/reader-mode`). isExcluded matches either.

Local plugins never had their peer dependencies linked at build time,
and when `plugin install --latest` linked them, the relative link was
computed from the path through .quartz/plugins, so it dangled for a
plugin at any other depth. Both copies of the linking code (loader and
CLI) now link from the plugin's real directory, replace dangling links
and a package manager's link to the plugin's own copy, and warn about
an installed copy.

(cherry picked from commit 395a96c86c)
2026-11-07 22:15:39 +01:00
saberzero1andShadorux e44f2b0364 fix(plugins): quartz.ts overrides for npm and component plugins (#2565); one shared plugin index generator
Overrides were registered under a sanitized key (quartz-community__explorer) but looked
up by package name, and component constructors re-exported from a sub-module were not
wrapped at all. Wrappers now also return the original's result. The CLI's copy of the
generator dropped npm plugins from the index; both now use cli/plugin-index.js.

Registry key approach from #2566.

Co-authored-by: Shadorux <208887057+Shadorux@users.noreply.github.com>
2026-11-07 22:13:26 +01:00
saberzero1 76de2838a1 fix(analytics): write config values into generated scripts as JSON string literals (#2571)
Values were spliced into code and, for PostHog/Clarity/Matomo, into script text
nested in a template literal. Those snippets now run directly; every value is
written once with JSON.stringify.
2026-11-07 22:06:40 +01:00
saberzero1 981c64af98 Merge #2541: Configure PostHog init options (@vivekascoder) 2026-11-07 22:04:23 +01:00
saberzero1 4920dae17e Merge #2518: Feat: Allow custom Umami script names (@lfgberg) 2026-11-07 22:04:23 +01:00
saberzero1 7ffd3a818a Merge #2582: docs: fix typos and dead links (@saksham10arora-dotcom) 2026-11-07 22:04:04 +01:00
saberzero1 774f76335a Merge #2578: docs: add DevBook to showcase (@grafanaKibana) 2026-11-07 22:04:04 +01:00
saberzero1 571dde2d86 Merge #2542: docs(community): add Field Notes theme (@oswarren) 2026-11-07 22:04:04 +01:00
saberzero1 fb96a9d8cd Merge #2481: docs: clarify ConditionalRender overrides (@coyaSONG) 2026-11-07 22:04:04 +01:00
saberzero1 114ffc4a86 Merge #2567: fix: clear stale popovers on bfcache restore (@Shadorux) 2026-11-07 22:04:04 +01:00
saberzero1 73a06a0ba8 Merge #2584: fix(analytics): count GoatCounter pageviews once (@IndelibleVivi) 2026-11-07 22:04:04 +01:00
saberzero1 3111df2366 Merge #2524: fix(dev): derive LiveReload WebSocket protocol from the page (@VXNCXNX) 2026-11-07 22:04:04 +01:00
saberzero1 96f62ec88c Merge #2536: fix: remove stale pages after incremental deletes (@ZluxYao) 2026-11-07 22:04:04 +01:00
saberzero1 5c581299a9 Merge #2535: build: improve polling for mounted content (@ZluxYao)
# Conflicts:
#	quartz/build.ts
2026-11-07 22:04:04 +01:00
saberzero1 8f4a816944 Merge #2534: build: clear processed incremental changes (@ZluxYao)
# Conflicts:
#	quartz/build.ts
2026-11-07 22:03:51 +01:00
saberzero1 b6bcd4f6cc Merge #2529: perf: memoize the mkdir in emitter write() (@jackyzha0) 2026-11-07 22:03:28 +01:00
saberzero1 295e822cf9 Merge #2528: fix: mark generated 404 page as unlisted (@paulTroster) 2026-11-07 22:03:28 +01:00
saberzero1 9fa4fa7bf0 Merge #2486: fix(build): clear output dir contents rather than rmdir (@McCio) 2026-11-07 22:03:28 +01:00
saberzero1 7cf595d20a Merge #2533: fix: make asset deletion idempotent (@ZluxYao)
# Conflicts:
#	quartz/plugins/emitters/assets.ts
2026-11-07 22:03:28 +01:00
saberzero1 096350cf0e Merge #2484: fix(assets): silence ENOENT races in watch mode (@McCio) 2026-11-07 22:03:15 +01:00
saberzero1 6e87fda4a5 docs: fontOrigin local loads no fonts — how to provide them with @font-face (#2441) 2026-11-07 21:52:49 +01:00
saberzero1 8eae6a1277 fix(security): run git/npm without a shell, validate refs/commits/URLs/package names, escape generated imports (#2571); fetch pinned commits on update (#2559) 2026-11-07 21:37:20 +01:00
saberzero1 3c18be8c71 feat: quartz.deprecated plugin marker (warned at build, add, doctor); drop deprecated hard-line-breaks from default config and templates 2026-11-07 20:57:30 +01:00
saberzero1 67ae68e9a4 docs: ObsidianFlavoredMarkdown preset, line breaks, inline footnotes; Obsidian math rules 2026-11-07 19:46:07 +01:00
saberzero1 c84f348039 feat(core): plugin assets (externalResources().assets → static/plugins/, window.quartzStaticUrl) 2026-11-07 19:46:07 +01:00
saberzero1 6e9f5c45d8 Merge branch 'pr-2588-pele-docs' into dev-mode/improvements 2026-11-07 19:15:17 +01:00
saberzero1 d66968cd7c feat(cli): upgrade shows release notes and runs the new version's checks; skip built-in plugins in install/restore; bug report asks for quartz info 2026-11-07 17:41:02 +01:00
saberzero1 50203da448 feat(core): report plugins that fail to load, fail CI builds on them; import npm plugin entry modules 2026-11-07 17:41:02 +01:00
saberzero1 ea75b1bdc8 feat(cli): fail builds in CI on plugins that don't support this Quartz version 2026-11-07 15:45:46 +01:00
saberzero1 1cc1439e20 docs: versioning and plugin compatibility, reading build output, ctx.contentIndex, quartz info 2026-11-07 13:53:28 +01:00
saberzero1 f768b1eb7c ci: version Quartz with changesets (release PR, vX.Y.Z tags, GitHub releases) and changesets for unreleased work 2026-11-07 13:53:28 +01:00
saberzero1 18deab128c feat(core): ctx.contentIndex, plugin error attribution, end-of-build diagnostics, enforced plugin quartzVersion, quartz info 2026-11-07 13:53:28 +01:00
saberzero1 13a3d1865c docs: built-in processing (frontmatter, links, drafts, content index), extendContentIndex, migration 2026-11-07 13:15:24 +01:00
saberzero1 052ebb23d5 feat(cli): built-in aware plugin commands, plugin doctor --fix migration, migrated default config and templates 2026-11-07 13:15:24 +01:00
saberzero1 3b8095bdf7 feat(core): built-in frontmatter, links, drafts and content index (configuration.*), absorbing crawl-links/remove-draft/content-index entries; extendContentIndex hook 2026-11-07 13:15:24 +01:00
saberzero1 e49024cca5 fix(layout): working conditions/overrides, layout warnings and --verbose report
- has-backlinks condition computes backlinks from allFiles (was always false)
- byPageType.exclude matches bare package names (npm sources never matched)
- TypeScript layout overrides in quartz.ts are applied (were ignored)
- one deduplicated warning with 'did you mean' for unknown positions, display
  values, frames, byPageType keys/excludes, duplicates, unregistered components;
  missing position/priority fall back to plugin defaults
- unknown-frame warning printed once per frame, not per page
- 'quartz build --verbose' prints a per-page-type layout report
- page-type bodies get component attribution; wire capability and option checks
2026-11-07 03:09:05 +01:00
saberzero1 d2c95da653 feat(components): attribute rendered plugin components
Plugin component roots get data-quartz-plugin / data-quartz-component
attributes so site owners can see which plugin rendered which part of a
page and target it in CSS. Append-only: existing attributes are untouched and
non-element roots (null, fragments, nested components) are left alone.
2026-11-07 03:09:05 +01:00
saberzero1 340672580e feat(plugins): declared plugin capabilities + graceful fetchData
Add an opt-in 'quartz.capabilities' manifest field (provides/requires/optional
for data, dom, globals, events, files, cssVars) and a build-time check that
warns when a required capability has no enabled provider, suggesting which
plugin to enable. Plugins without the field are unaffected.

fetchData now resolves to {} with a console warning instead of rejecting when
contentIndex.json is missing, so search/explorer/graph don't throw uncaught
errors on sites without content-index.
2026-11-07 03:09:05 +01:00
saberzero1 d89a8c76ea feat(cli): harden plugin management workflow
- plugin commands exit non-zero on failure; git errors summarised
- edit quartz.config.yaml in place (comments survive); no stray file creation
- honour lockfile pins in --clean, subdir plugins, build-time installs, ref:
- short names everywhere; list/status show npm and configured-but-missing plugins
- add: duplicate detection, owner/repo shorthand; config --set nested/--unset
- option typo/type validation against plugin defaults; new 'plugin doctor'
- schema: header/footer positions, group wrap/priority, byPageType.template
2026-11-07 03:09:05 +01:00
Aaron Pham e1ab1269f8 docs: shorten Pele opt-in copy 2026-10-20 19:29:18 -04:00
Aaron Pham e31990aaea docs: document opt-in Pele diagram renderer
Match OFM: Mermaid.js stays default; diagramRenderer: pele opts in.
Note Mermaid.js deprecation path toward Pele.
2026-10-20 19:21:11 -04:00
Aaron Pham f3e02aff39 docs: note Pele as the Mermaid diagram renderer
Document that ObsidianFlavoredMarkdown renders Mermaid fences with
Pele instead of Mermaid.js. Companion to quartz-community/obsidian-flavored-markdown#14.
2026-10-20 19:15:06 -04:00
Faye Fang 9eebd805d7 fix(analytics): count GoatCounter pageviews once 2026-10-12 20:12:45 +08:00
Saksham Arora 7e449b8974 docs: fix typos and dead links 2026-10-10 20:43:30 +05:30
saberzero1 09097db511 fix(config): order github-flavored-markdown before obsidian-flavored-markdown
The loader sorts transformers by `order` ascending, and a combined micromark
extension prepends its constructs, so where two plugins claim the same character
the later-registered -- higher `order` -- one wins. With Obsidian at 30 and GFM at
40, GFM owned every shared character and Obsidian's own tokenizers could not run;
`~` is the visible case, since Obsidian's strikethrough closes on the first `~~`,
honours no escape, and has no single-tilde form.

Swaps the two to 30/40 and moves the blocks so the file still reads in ascending
order. Both packages' `quartz.defaultOrder` were swapped to match, so a config that
omits `order` gets the same result.

Measured on remark-obsidian's recorded Obsidian corpus: the reorder alone is
behaviour-neutral, 0 fixed and 0 broken, which clears the risk that both plugins
claim `[`. With it, 21 strikethrough cases match and none regress.
2026-10-06 01:41:18 +02:00
Nikita Reshetnik 461646361b Update DevBook link to Software Engineering Notes 2026-10-02 12:02:23 +03:00
grafanaKibana fbabc76d4a docs: add DevBook to showcase 2026-10-02 11:59:01 +03:00
Shadorux 4ef1814ec1 fix: clear stale popovers on bfcache restore 2026-09-23 17:29:30 -04:00
dependabot[bot] 97a2d05f80 chore(deps): bump the quartz-ecosystem group with 2 updates (#2561)
Bumps the quartz-ecosystem group with 2 updates: [@quartz-community/syntax-highlighting](https://github.com/quartz-community/syntax-highlighting) and [@quartz-community/utils](https://github.com/quartz-community/utils).


Updates `@quartz-community/syntax-highlighting` from 1.0.0 to 1.0.1
- [Release notes](https://github.com/quartz-community/syntax-highlighting/releases)
- [Changelog](https://github.com/quartz-community/syntax-highlighting/blob/main/CHANGELOG.md)
- [Commits](https://github.com/quartz-community/syntax-highlighting/compare/v1.0.0...v1.0.1)

Updates `@quartz-community/utils` from 1.0.0 to 1.0.1
- [Release notes](https://github.com/quartz-community/utils/releases)
- [Changelog](https://github.com/quartz-community/utils/blob/main/CHANGELOG.md)
- [Commits](https://github.com/quartz-community/utils/compare/v1.0.0...v1.0.1)

---
updated-dependencies:
- dependency-name: "@quartz-community/syntax-highlighting"
  dependency-version: 1.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: quartz-ecosystem
- dependency-name: "@quartz-community/utils"
  dependency-version: 1.0.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: quartz-ecosystem
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-20 20:14:52 +00:00
VXNCXNX 5e78078ff7 docs(cli): --remoteDevHost sets a hostname, not a URL
The old wording invited a full URL, which produced ws://https://host:3001. Say hostname, and note that the protocol now follows the page.
2026-09-16 05:46:24 +00:00
VXNCXNX b080c219b9 fix(dev): derive LiveReload WebSocket protocol from the page
--remoteDevHost hardcoded wss://, but the dev server speaks plain ws unless it sits behind a TLS proxy, so LiveReload failed over plain HTTP. Pick ws:/wss: from window.location.protocol instead, which keeps TLS-proxied setups working. Fixes #2510.
2026-09-16 05:46:24 +00:00
saberzero1 3dff48b5df fix: regenerate lockfile for created-modified-date@1.0.1
The production-dependencies bump in #2554 moved @napi-rs/simple-git to 1.x,
which fell outside created-modified-date's peerOptional range and broke
npm install/npm ci with ERESOLVE. Regenerated against the published 1.0.1
that widens the range.
2026-09-15 02:52:01 +02:00
dependabot[bot] 5519ffe5d9 chore(deps): bump the production-dependencies group across 1 directory with 6 updates (#2554)
Bumps the production-dependencies group with 6 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@clack/prompts](https://github.com/bombshell-dev/clack/tree/HEAD/packages/prompts) | `0.11.0` | `1.8.0` |
| [@myriaddreamin/rehype-typst](https://github.com/Myriad-Dreamin/typst.ts) | `0.6.0` | `0.7.0` |
| [@napi-rs/simple-git](https://github.com/Brooooooklyn/simple-git) | `0.1.22` | `1.1.0` |
| [sharp](https://github.com/lovell/sharp) | `0.34.5` | `0.35.4` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.9.6` | `26.5.1` |
| [esbuild](https://github.com/evanw/esbuild) | `0.27.7` | `0.28.2` |



Updates `@clack/prompts` from 0.11.0 to 1.8.0
- [Release notes](https://github.com/bombshell-dev/clack/releases)
- [Changelog](https://github.com/bombshell-dev/clack/blob/main/packages/prompts/CHANGELOG.md)
- [Commits](https://github.com/bombshell-dev/clack/commits/@clack/prompts@1.8.0/packages/prompts)

Updates `@myriaddreamin/rehype-typst` from 0.6.0 to 0.7.0
- [Release notes](https://github.com/Myriad-Dreamin/typst.ts/releases)
- [Changelog](https://github.com/Myriad-Dreamin/typst.ts/blob/main/docs/release-workflows.md)
- [Commits](https://github.com/Myriad-Dreamin/typst.ts/compare/v0.6.0...v0.7.0)

Updates `@napi-rs/simple-git` from 0.1.22 to 1.1.0
- [Release notes](https://github.com/Brooooooklyn/simple-git/releases)
- [Commits](https://github.com/Brooooooklyn/simple-git/compare/v0.1.22...v1.1.0)

Updates `sharp` from 0.34.5 to 0.35.4
- [Release notes](https://github.com/lovell/sharp/releases)
- [Commits](https://github.com/lovell/sharp/compare/v0.34.5...v0.35.4)

Updates `@types/node` from 25.9.6 to 26.5.1
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `esbuild` from 0.27.7 to 0.28.2
- [Release notes](https://github.com/evanw/esbuild/releases)
- [Changelog](https://github.com/evanw/esbuild/blob/main/CHANGELOG.md)
- [Commits](https://github.com/evanw/esbuild/compare/v0.27.7...v0.28.2)

---
updated-dependencies:
- dependency-name: "@clack/prompts"
  dependency-version: 1.8.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: production-dependencies
- dependency-name: "@myriaddreamin/rehype-typst"
  dependency-version: 0.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production-dependencies
- dependency-name: "@napi-rs/simple-git"
  dependency-version: 1.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: production-dependencies
- dependency-name: sharp
  dependency-version: 0.35.4
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production-dependencies
- dependency-name: "@types/node"
  dependency-version: 26.5.1
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: production-dependencies
- dependency-name: esbuild
  dependency-version: 0.28.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: production-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-15 02:44:56 +02:00
saberzero1 afe7e68ff0 ci: isolate typescript into its own dependabot group
PR #2553 failed because the grouped update bumped typescript ^5.9.3 to
^7.0.2, and TypeScript 7 removed moduleResolution=node10, which this repo's
tsconfig still uses. That single breaking change blocked six unrelated
updates from landing.

A compiler major needs its own tsconfig migration and should not ride along
with routine dependency bumps.
2026-09-15 02:40:48 +02:00
saberzero1 4bfe60a28a ci: split dependabot groups and auto-merge ecosystem updates
Every production-dependencies PR for the last ten cycles was closed unmerged.
The group matched '*', so first-party @quartz-community/* updates were bundled
with third-party churn and could not land independently while CI was red.

Splits first-party packages into a quartz-ecosystem group and excludes them
from production-dependencies, so ecosystem updates land on their own.

Adds an auto-merge workflow for that group only. GitHub auto-merge is disabled
on this repository and v5 has no branch protection, so the workflow gates
itself: it runs only after Build and Test succeeds, independently verifies
that every check run on the commit succeeded, refuses major bumps, and only
then squash-merges.
2026-09-15 02:28:33 +02:00
saberzero1 9be7f42b42 fix: regenerate lockfile against published 1.0.0 manifests
The previous regeneration resolved against npm's cached metadata and omitted
dependencies introduced by the 1.0.0 releases, so 'npm ci' failed with
EUSAGE. Regenerated with --prefer-online.
2026-09-15 01:57:22 +02:00
saberzero1 f8b1a4d7aa feat!: adopt 1.0.0 ecosystem
All @quartz-community/* dependencies move to ^1.0.0 and @quartz-themes/core
to ^2.0.0, following the coordinated 1.0 release.

Pre-1.0 caret ranges pinned the minor version, so published fixes to shared
packages could never be resolved. This also eliminates the 46 nested
duplicate copies of @quartz-community/types that the old ranges forced into
the dependency tree.
2026-09-15 01:56:07 +02:00
saberzero1 233a975a32 chore: update lockfile for latest plugin releases 2026-09-15 00:42:16 +02:00
Marco Ciotola f1fba3fc55 fix(schema): allow null for analytics field (#2485) 2026-09-06 13:49:42 +02:00
GlazeSnapandClaude Fable 5 2176a4ae03 docs(community): add Field Notes theme
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-30 17:56:19 -04:00
VivekandCopilot Autofix powered by AI 75f485bd2f Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-30 15:10:37 +05:30
vivekascoder 4ef8d6cbc7 feat: configure PostHog init options 2026-08-30 14:41:12 +05:30
ZluxYao 50227ba2c3 fix: re-emit pages after slug ownership changes 2026-08-27 00:16:36 +08:00
ZluxYao 254af5dcff fix: remove stale pages after incremental deletes 2026-08-27 00:14:53 +08:00
ZluxYao 762f7634b4 build: improve polling for mounted content 2026-08-26 04:04:54 +08:00
ZluxYao f5fa2343a4 fix: clear processed incremental changes 2026-08-26 03:56:35 +08:00
ZluxYao 1930712042 fix: make asset deletion idempotent 2026-08-26 03:53:55 +08:00
paulTroster 631f6b45b5 fix: mark generated 404 page as unlisted
The core-generated 404 page never set the `unlisted` flag on its
vfile data, so any plugin that relies on `unlisted` to exclude pages
from listings (recent-notes, content-index/search, sitemap, RSS)
would incorrectly include the error page.

Unlike tag/folder index pages, which some users may legitimately
want listed, there's no scenario where the 404 page should appear
in search results, feeds, or "recent posts" widgets. Other synthetic/
non-content pages (drafts, encrypted pages, explicitly unlisted notes)
already rely on this same `unlisted` flag, so this brings the 404
page type in line with that existing convention.

Repro: enable @quartz-community/recent-notes with a single content
page and no other config changes - the generated "Not Found" page
shows up in the recent notes list.
2026-08-18 20:15:29 +08:00
lfgberg 990884386a Allow custom umami script names 2026-08-04 22:07:01 -04:00
Marco Ciotola e56ffae883 fix(build): clear output dir contents rather than rmdir, fixes EBUSY on bind mounts 2026-07-19 18:50:55 +02:00
Marco Ciotola b4cb37d8bf fix(assets): silence ENOENT races in watch mode 2026-07-19 18:14:42 +02:00
coyaSONGandOpenAI Codex ca70ffd03b docs: clarify ConditionalRender overrides
Co-Authored-By: OpenAI Codex <noreply@openai.com>
2026-07-14 22:18:41 +09:00
178 changed files with 15558 additions and 4110 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Changesets
Quartz is versioned with [changesets](https://github.com/changesets/changesets). Every pull request that changes how Quartz behaves should include a changeset:
```shell
npx changeset
```
Pick the bump (`patch` for fixes, `minor` for new features and new plugin APIs, `major` for breaking changes) and describe the change for users — the text ends up in `CHANGELOG.md` and the GitHub release notes.
On every push to `v5`, the release workflow opens (or updates) a "chore: release Quartz" pull request that bumps the version in `package.json` and writes `CHANGELOG.md`. Merging it tags the commit `vX.Y.Z` and publishes a GitHub release. Quartz is not published to npm.
See `docs/advanced/versioning.md` for what the version means for users and plugin authors.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
A page type's `generate` can be async: it may return a promise of its virtual pages, which Quartz awaits in full and incremental builds. Page types that create pages from other files (like `.mdx`) can now run content through the site's transformers or bundle with esbuild; previously a promise crashed the build with "virtualPages is not iterable" (#2575).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Clearer failures: errors thrown by a plugin now name the plugin (package, version, source), what it was doing (transforming, filtering, emitting, rendering a component) and the file or page, list problems Quartz already knew about that plugin (incompatible Quartz version, missing required data), and say how to check and where to report it. Plugin stack frames are no longer hidden. Warnings from loading the config are repeated in a summary at the end of the build, together with a note about links to pages that are not on the site (including links to drafts).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Frontmatter parsing, link resolution, draft handling and the content index are now built into Quartz (configured under `configuration.frontmatter`, `.links`, `.drafts` and `.contentIndex`) instead of being plugins that silently broke the site when disabled. Existing `crawl-links`, `remove-draft` and `content-index` entries keep working and are applied automatically; `npx quartz plugin doctor --fix` moves them into `configuration`. Plugins can add fields to `contentIndex.json` with an `extendContentIndex` hook, and emitters can reuse the built index via `ctx.contentIndex`. The effective built-in settings are available to plugins as `ctx.cfg.configuration.<key>`.
+15
View File
@@ -0,0 +1,15 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "v5",
"updateInternalDependencies": "patch",
"privatePackages": {
"version": true,
"tag": true
},
"ignore": []
}
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
When a build stops on an error, Quartz stops esbuild before exiting. esbuild runs as a child process that writes to the same terminal; left running, it could print "fatal error: all goroutines are asleep - deadlock!" and a long goroutine dump after Quartz's error message.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
French: "Vue graphique" and "Table des matières" use French capitalisation (jackyzha0/quartz#2513).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Layout fixes: the `has-backlinks` condition works, `byPageType.exclude` matches npm plugin sources, layout overrides in `quartz.ts` are applied, `position: footer` is accepted by the config schema, and typos in positions, display values, frames or page types produce a "did you mean" warning instead of silently dropping the component. `quartz build --verbose` prints a layout report.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Security updates: `sharp` 0.35.5 (GHSA-wq5f-xc86-pv6w), `toml` 5 (prototype pollution and DoS advisories; TOML frontmatter parses the same, and now also accepts plain dates like `date = 2024-01-02`) and `minimatch` 11 (GHSA-g3hv-75wg-m249; `ignorePatterns` match the same). The plugin schema's `layout.position` lists exactly the positions Quartz renders. `npx quartz tui` points to the right install command (`github:quartz-community/tui`).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Pages no longer scroll sideways on phones: long words (a page title such as "ObsidianFlavoredMarkdown", long inline code) break where they don't fit, and the right sidebar's components (graph, backlinks) wrap below each other when they don't fit side by side.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Security: frontmatter can no longer run code during a build. A note starting with `---js` or `---javascript` had its frontmatter evaluated as JavaScript (gray-matter's default engine), so building content you didn't write, such as a pull request preview, could run arbitrary code. Quartz now refuses JavaScript frontmatter with an error naming the file. Invalid frontmatter (for example broken YAML) is now reported as a problem in that file instead of as a Quartz bug.
@@ -0,0 +1,12 @@
---
"@jackyzha0/quartz": minor
---
Markdown renders as it does in Obsidian: Quartz now uses ObsidianFlavoredMarkdown 2.0 and GitHubFlavoredMarkdown 2.0.
- **Line breaks changed:** a single line break inside a paragraph now renders as `<br>`, as in Obsidian's default reading view. Set `strictLineBreaks: true` in the ObsidianFlavoredMarkdown options to keep the previous behaviour (a space).
- ObsidianFlavoredMarkdown parses with Obsidian's own parser by default (`preset: "legacy"`). Use `preset: "strict"` for TOML (`+++`) frontmatter or plugins that add their own Markdown syntax.
- Also new: callouts parsed like Obsidian, inline footnotes (`text^[note]`), image sizes on Markdown images (`![alt|300](image.png)`), Mermaid diagrams that follow the theme's colours, an opt-in Pele diagram renderer, and inline tags that only link to tag pages that exist.
- GitHubFlavoredMarkdown now runs before ObsidianFlavoredMarkdown (order 30, then 40), as in the default config. If your config sets `order` for either plugin, keep GitHubFlavoredMarkdown first.
See the plugins' changelogs for details.
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Permalinks work as in Obsidian Publish (jackyzha0/quartz#2572): `permalink: page` makes the note's address `/page`, whatever its file path. Links to the note, backlinks, the graph, the sitemap, RSS and the content index use the permalink, links inside the note still resolve relative to its file, and the note's file path redirects to the permalink (with AliasRedirects, like `aliases`). Previously the permalink was only a redirect to the file path. A permalink that is already another page's address is ignored with a warning. In navigation (the content trie used by the explorer, folder pages and breadcrumbs) the note stays in its folder, as on Obsidian Publish sites.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugins can ship files with the site: `externalResources()` may return `assets: [{ from, to }]` (a file or directory on disk), which Quartz copies to `static/plugins/<to>`. Client scripts find them through the new `window.quartzStaticUrl` page global (absolute URL of `static/`, valid across SPA navigations). Use it for large or optional client code loaded with `import()` only where needed, instead of inline scripts, which every page downloads. Invalid or conflicting targets and missing sources are build warnings.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugins can declare what they provide and need (`quartz.capabilities`); the build warns when a required provider is missing (e.g. "backlinks requires data `links` … enable configuration.links"). Rendered plugin components carry `data-quartz-plugin` / `data-quartz-component` attributes, so you can tell which plugin rendered which part of a page. `fetchData` resolves to `{}` instead of rejecting when `contentIndex.json` is missing.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugin management: plugin commands exit non-zero on failure, CLI edits keep comments in `quartz.config.yaml`, lockfile pins are honoured everywhere, npm plugins show up in `plugin list`, `plugin add` detects duplicates, misspelled plugin options are flagged, and the new `plugin doctor` checks config, lockfile and installs. `plugin config --set a.b=1` now writes a nested key.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugins can be marked deprecated with `quartz.deprecated` (a message naming the replacement) in their `package.json`. Quartz warns while a deprecated plugin is enabled — when the build loads the config (repeated in the end-of-build summary), in `plugin add` and in `plugin doctor` — and suggests removing it. The deprecated `hard-line-breaks` plugin is no longer listed in the default config and templates: ObsidianFlavoredMarkdown 2.0+ handles line breaks (`strictLineBreaks`).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugins that fail to load (can't be installed, throw on import, export no plugin) are reported as errors with the plugin, version, the file and line where it failed and what to do, and listed again at the top of the end-of-build summary. Previously some of these failures were silent. Locally the build continues without them; in CI (`CI` set) it fails unless `QUARTZ_ALLOW_BROKEN_PLUGINS=1`. Fixed along the way: the entry module of npm-installed component plugins (and npm plugins without a declared category) was never imported, so their `init(options)` never ran.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
`quartz.ts` overrides (`ExternalPlugin.Explorer({...})`) work for npm plugins and for component plugins (#2565): overrides are registered under the key the loader looks up (the package name for npm plugins), and component constructors re-exported from a plugin's sub-module are wrapped too. The wrapper also returns what the plugin returns, so `ExternalPlugin.X(...)` works both as a statement and as a component in a layout override. `quartz plugin …` commands no longer drop npm plugins from the generated `.quartz/plugins/index.ts`; both generators are now one shared module.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugin version requirements are enforced: a plugin's `quartzVersion` (`package.json` → `quartz.quartzVersion`, any semver range) is checked when the config loads (a warning locally; in CI — `CI` set — the build fails unless `QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS=1`), by `plugin add` and by `plugin doctor`, with a message saying whether to update Quartz or the plugin. Previously the field was never checked (and the old checker read `">=5.0.0"` as `0.0.0`).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
New `configuration.publishAssets: "referenced"` (default `"all"`): only copy the images, PDFs and other files that published pages link to or embed, so files that only unpublished notes use stay private (#2531, from #2544). References are matched against published (slugified) file names and include `<object data>` SVG embeds, `srcset` and URL-encoded paths.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
New `npx quartz info` command: prints the Quartz version (with `git describe`, branch and local changes), Node/npm/OS, the config file, built-ins and every plugin with its version, source and compatibility, as a Markdown block to paste into bug reports. The build banner and `plugin doctor` also show where the checkout is relative to the last release.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Security: plugin commands no longer build shell commands from plugin sources, refs, pinned commits or package names (#2571). git and npm run with argument arrays, refs/commits/URLs/package names are validated (so a value can't be read as an option either), and generated plugin imports are written as escaped string literals. A source such as `github:owner/repo#main;cmd` used to run `cmd`; it is now rejected as an invalid ref. Also fixes restoring a plugin pinned in `quartz.lock.json` to a commit that is no longer its branch tip (#2559).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
New `layout.sidebars` option: how each sidebar handles content taller than the screen. `fit` (default, unchanged) keeps it one screen tall and components shrink and scroll themselves; `scroll` keeps it in view and lets it scroll itself, so nothing is ever out of reach; `static` lets it scroll away with the page. Page types can override it (`byPageType.<type>.sidebars`). New `docs` template for documentation sites (`npx quartz create --template docs`), with both sidebars `static`. Frames receive the modes as a `sidebars` prop and put them on sidebar elements as `data-sidebar-mode`, which plugins can target in CSS.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
SPA navigation follows redirects correctly: when a link is redirected (for example `folder` → `folder/` on static hosts, or an alias page's canonical link), relative links on the new page resolve against where it really is, and the address bar shows that URL. Links on folder pages and parent tag pages reached through slash-less links pointed one level too high.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
`npx quartz upgrade` shows the release notes of every version between the old and the new Quartz, then runs the new version's checks: it restores plugins, runs `plugin doctor` (plugin entries that are built in now, plugins that don't support the new version …) and lists plugin updates. Plugin install/restore skip plugins that are built into Quartz now, and `plugin doctor --fix` also removes their unused lockfile pins.
+12 -6
View File
@@ -28,13 +28,19 @@ You can help speed up fixing the problem by either
1. providing a simple reproduction
2. linking to your Quartz repository where the problem can be observed
**Desktop (please complete the following information):**
**Quartz info**
Run `npx quartz info` in your Quartz folder and paste its output here. It lists your Quartz version, Node/npm/OS and every plugin with its version — no content or site URL is included.
- Quartz Version: [e.g. v4.1.2]
- `node` Version: [e.g. v18.16]
- `npm` version: [e.g. v10.1.0]
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
```
Paste the output of `npx quartz info` here
```
(Quartz older than 5.1 doesn't have `npx quartz info`: give the Quartz version from `package.json` and the output of `git log -1 --format=%h`, plus your `node` and `npm` versions and OS.)
**Browser** (for display problems): [e.g. Firefox 140, Safari on iOS 18]
**Build output**
If the build failed or printed warnings, paste the full output of `npx quartz build`, including the summary at the end.
**Additional context**
Add any other context about the problem here.
+25
View File
@@ -4,11 +4,36 @@ updates:
directory: "/"
schedule:
interval: "weekly"
# Plugins declare these as peer dependencies (preact by 42 plugins, vfile by 15), so a
# major bump here passes `npm ci` but breaks plugins at runtime (#2586). Upgrade them
# deliberately, together with the plugins.
ignore:
- dependency-name: "preact"
update-types: ["version-update:semver-major"]
- dependency-name: "vfile"
update-types: ["version-update:semver-major"]
- dependency-name: "unified"
update-types: ["version-update:semver-major"]
groups:
# Separated so a risky third-party major cannot block ecosystem updates.
quartz-ecosystem:
applies-to: "version-updates"
patterns:
- "@quartz-community/*"
- "@quartz-themes/*"
# Isolated because a compiler major needs a tsconfig migration of its own.
typescript:
applies-to: "version-updates"
patterns:
- "typescript"
production-dependencies:
applies-to: "version-updates"
patterns:
- "*"
exclude-patterns:
- "@quartz-community/*"
- "@quartz-themes/*"
- "typescript"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
+7
View File
@@ -58,6 +58,13 @@ jobs:
- name: Ensure Quartz builds, check bundle info
run: npx quartz build --bundleInfo -d docs
- name: Check for a changeset
if: ${{ github.event_name == 'pull_request' && matrix.os == 'ubuntu-latest' }}
# Non-blocking: docs-only or internal changes don't need one.
run: |
npx changeset status --since=origin/v5 >/dev/null 2>&1 \
|| echo "::warning::No changeset in this PR. If it changes how Quartz behaves, run 'npx changeset' (see .changeset/README.md)."
publish-tag:
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v5' }}
runs-on: ubuntu-latest
@@ -0,0 +1,82 @@
name: Dependabot Auto-merge
on:
workflow_run:
workflows: ["Build and Test"]
types: [completed]
permissions:
contents: write
pull-requests: write
jobs:
auto-merge:
if: >-
github.repository == 'jackyzha0/quartz' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.actor.login == 'dependabot[bot]' &&
contains(github.event.workflow_run.head_branch, 'quartz-ecosystem')
runs-on: ubuntu-latest
steps:
- name: Resolve pull request
id: pr
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
set -euo pipefail
number=$(gh pr list --state open --json number,headRefOid \
--jq "map(select(.headRefOid == \"${HEAD_SHA}\")) | .[0].number // empty")
if [ -z "$number" ]; then
echo "No open PR matches ${HEAD_SHA}; nothing to merge."
echo "found=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "number=${number}" >> "$GITHUB_OUTPUT"
echo "found=true" >> "$GITHUB_OUTPUT"
- name: Require every check on the commit to have succeeded
if: steps.pr.outputs.found == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
set -euo pipefail
runs=$(gh api "repos/${GH_REPO}/commits/${HEAD_SHA}/check-runs" --paginate \
--jq '.check_runs[] | "\(.name)\t\(.status)\t\(.conclusion // "")"')
echo "$runs"
bad=$(printf '%s\n' "$runs" | awk -F'\t' '
$2 != "completed" { print; next }
$3 != "success" && $3 != "neutral" && $3 != "skipped" { print }
')
if [ -n "$bad" ]; then
echo "Refusing to merge - not all checks succeeded:"
printf '%s\n' "$bad"
exit 1
fi
- name: Confirm update is not a major bump
if: steps.pr.outputs.found == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
PR_NUMBER: ${{ steps.pr.outputs.number }}
run: |
set -euo pipefail
title=$(gh pr view "$PR_NUMBER" --json title --jq .title)
echo "PR title: $title"
if printf '%s' "$title" | grep -qiE 'major'; then
echo "Refusing to merge a major update; needs human review."
exit 1
fi
- name: Merge
if: steps.pr.outputs.found == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
PR_NUMBER: ${{ steps.pr.outputs.number }}
run: gh pr merge "$PR_NUMBER" --squash --delete-branch
+67
View File
@@ -0,0 +1,67 @@
name: Release
# Versioning with changesets (see .changeset/README.md):
# 1. While .changeset/*.md files are pending on v5, keep a "chore: release Quartz" PR open that
# bumps package.json and writes CHANGELOG.md.
# 2. When that PR is merged (no pending changesets left), tag the commit vX.Y.Z and publish a
# GitHub release with the CHANGELOG section. Quartz is not published to npm.
on:
push:
branches:
- v5
workflow_dispatch:
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
if: ${{ github.repository == 'jackyzha0/quartz' }}
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions/setup-node@v6
with:
node-version: 24
- run: npm install
- name: Create or update the release PR
id: changesets
uses: changesets/action@v1
with:
version: npm run version-packages
title: "chore: release Quartz"
commit: "chore: release Quartz"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Tag and publish the GitHub release
if: steps.changesets.outputs.hasChangesets == 'false'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
VERSION=$(node -p "require('./package.json').version")
TAG="v$VERSION"
if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
echo "$TAG already exists — nothing to release."
exit 0
fi
# Only versions produced by `changeset version` are released (guards against tagging
# an arbitrary commit with a version that was never released through this workflow).
awk -v v="## $VERSION" '$0 == v {found=1; next} found && /^## / {exit} found' CHANGELOG.md > release-notes.md || true
if [ ! -s release-notes.md ]; then
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
+10
View File
@@ -109,6 +109,16 @@ Component.css = styles
> [!warning]
> Quartz does not use CSS modules so any styles you declare here apply _globally_. If you only want it to apply to your component, make sure you use specific class names and selectors.
#### Source attributes
When Quartz renders a component provided by a plugin, it adds two attributes to the component's root element:
```html
<div class="graph" data-quartz-plugin="graph" data-quartz-component="Graph">…</div>
```
They let site owners and theme authors find out which plugin produced a part of the page (use your browser's inspector) and give a stable hook for styling, e.g. `[data-quartz-plugin="graph"] { … }`. The attributes are only added when your component returns a single HTML element; components returning `null`, text, a fragment or another component are rendered unchanged. Existing attributes are never modified.
### Internationalization
Component plugins should use the i18n pattern for any user-facing strings. See [[making plugins#Internationalization (i18n)]] for the full setup guide.
+1
View File
@@ -8,3 +8,4 @@ This section covers advanced topics for users who want to extend or deeply custo
- **[[making plugins]]** — Build your own transformer, filter, emitter, or component plugin
- **[[creating components]]** — Create custom layout components with JSX
- **[[paths]]** — How Quartz resolves and transforms file paths
- **[[versioning]]** — Version numbers, plugin compatibility (`quartzVersion`) and releases
+100 -2
View File
@@ -61,6 +61,10 @@ my-plugin/
The plugin's `package.json` should declare dependencies on `@quartz-community/types` (for type definitions) and optionally `@quartz-community/utils` (for shared utilities).
If your plugin reads data, DOM elements, globals or files produced by another plugin (or provides them), declare that in `quartz.capabilities` so Quartz can warn when the provider is disabled. See [[plugin capabilities]].
Declare the oldest Quartz version your plugin works with in `quartz.quartzVersion` (a semver range such as `">=5.1.0"`). Quartz checks it when loading the config and in `plugin add` / `plugin doctor`, and mentions it when your plugin throws. See [[versioning#For plugin authors]].
## Plugin Types
## Choosing a Plugin Type
@@ -253,7 +257,7 @@ export type QuartzFilterPluginInstance = {
A filter plugin must define a `name` field and a `shouldPublish` function that takes in a piece of content that has been processed by all the transformers and returns a `true` or `false` depending on whether it should be passed to the emitter plugins or not.
For example, here is the built-in plugin for removing drafts:
For example, here is a filter that removes drafts (Quartz has this [[RemoveDrafts|built in]]):
```ts
import { QuartzFilterPlugin } from "@quartz-community/types"
@@ -387,11 +391,71 @@ export interface QuartzPageTypePluginInstance {
- `priority`: Controls matching order when multiple page types could match a slug. Higher priority page types are checked first. Default: `0`.
- `fileExtensions`: Array of file extensions this page type handles (e.g. `[".canvas"]`, `[".base"]`). Content files (`.md`) are handled by the default content page type.
- `match`: A function that determines whether a given slug/file should be rendered by this page type.
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices).
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices). It receives `{ content, cfg, ctx }` and returns the pages, or (Quartz 5.1+) a promise of them, so it can do async work such as running content through the site's transformers or bundling with esbuild. Page types generate one after another, in priority order. A plugin with an async `generate` should declare `"quartzVersion": ">=5.1.0"`, since older versions don't wait for it.
- `layout`: The layout configuration key (e.g. `"content"`, `"folder"`, `"tag"`). This determines which `byPageType` entry in `quartz.config.yaml` provides the layout overrides for this page type.
- `frame`: The [[layout#Page Frames|page frame]] to use for this page type. Controls the overall HTML structure (e.g. `"default"`, `"full-width"`, `"minimal"`, or a custom frame provided by your plugin). If not set, defaults to `"default"`. Can be overridden per-page-type via `layout.byPageType.<name>.template` in `quartz.config.yaml`.
- `body`: The Quartz component constructor that renders the page body content.
### Extending the content index
Quartz [[ContentIndex|builds `static/contentIndex.json`]] itself — the file search, the explorer, the graph and other client-side components read. Any plugin (transformer, filter, emitter or page type) can add fields to every page's entry by defining `extendContentIndex` on its plugin instance:
```ts
import { QuartzTransformerPlugin } from "@quartz-community/types"
export const ReadingTime: QuartzTransformerPlugin = () => ({
name: "ReadingTime",
markdownPlugins: () => [/* … sets file.data.readingTime … */],
// called once per page when contentIndex.json is written
extendContentIndex({ fileData, entry }) {
return { readingTime: fileData.readingTime as number | undefined }
},
})
```
Client-side code then finds the field next to the core ones:
```ts
const index = await fetchData
index["some/page"].readingTime
```
Rules:
- Return a plain object of JSON-serialisable values, or `undefined` to add nothing. `undefined` values are skipped.
- Core fields (`slug`, `filePath`, `title`, `links`, `tags`, `content`, `richContent`, `date`, `description`) cannot be overridden.
- If two plugins add the same key, the first one in plugin order keeps it; a warning names both. Prefer distinctive or namespaced keys (`"readingTime"`, `"myPlugin:score"` or one nested object).
- `entry` is a read-only copy of the core fields; `fileData` is the page's `file.data`.
- Errors thrown by the hook are reported as a warning and the page keeps its core entry.
- Keep it small: `contentIndex.json` is downloaded by every visitor.
Declare the field in your [[plugin capabilities|capabilities]] (`provides.data`) so other plugins can depend on it.
### Reusing the content index in emitters
Emitters don't need to rebuild the index: `ctx.contentIndex` holds it (a read-only `Map` from slug to entry, virtual pages included, with the same fields as `contentIndex.json` plus `date` and `description`). It is built once per build, after page types generated their pages and before plugin emitters run:
```ts
emit: async (ctx, content) => {
const recent = [...(ctx.contentIndex?.values() ?? [])]
.filter((entry) => entry.date)
.sort((a, b) => b.date!.getTime() - a.date!.getTime())
.slice(0, 20)
// … write a feed, a JSON API, a search index …
}
```
Built-in settings are available too, with defaults and migrated options applied: `ctx.cfg.configuration.links.markdownLinkResolution`, `ctx.cfg.configuration.contentIndex.enableRSS`, … Both need Quartz 5.1+ — declare `"quartzVersion": ">=5.1.0"` (see [[versioning#For plugin authors]]).
### Components in sidebars
Sidebars have three modes ([[layout#Sidebar modes|`layout.sidebars`]]), set on the sidebar element as `data-sidebar-mode`:
- In `fit` (the default) a sidebar is exactly one screen tall and doesn't scroll. A component that can grow (a list, a tree) must be able to shrink: give it `min-height: 0` and its own scroll area (`overflow-y: auto`), or it pushes the components below it out of reach.
- In `scroll` and `static`, core gives every sidebar component its natural height (`flex-shrink: 0`); nothing extra is needed.
To behave differently per mode, target it in your stylesheet, e.g. `.sidebar[data-sidebar-mode="fit"] .my-list { max-height: 40vh; }`. Custom frames with sidebars should put the `sidebars` prop on their sidebar elements the same way.
### Providing Custom Frames
Plugins can ship their own [[layout#Page Frames|page frames]] — custom page layouts that control how the HTML structure (sidebars, header, content area, footer) is arranged. This is useful for page types that need fundamentally different layouts (e.g. a fullscreen canvas, a presentation mode, a dashboard).
@@ -559,6 +623,40 @@ Your plugin's `dist/` directory should be committed to the repository:
If `dist/` is missing or gitignored, Quartz falls back to the full install/build cycle (useful during local development with symlinked plugins).
### Shipping Files with Your Plugin
Since Quartz 5.1, `externalResources()` can return `assets`: files or directories that Quartz copies into the site at `static/plugins/<to>`. Client scripts find them through the `window.quartzStaticUrl` page global (the absolute URL of `static/`, valid across SPA navigations).
Use this for large or optional client code instead of an inline script: Quartz serves inline scripts to **every page**, while an asset is only downloaded where your script imports it.
```ts
import path from "path"
import { createRequire } from "module"
externalResources() {
// resolve a dependency's browser build at build time
const pkg = createRequire(import.meta.url).resolve("my-renderer/package.json")
return {
js: [{ script: loaderScript, loadTime: "afterDOMReady", contentType: "inline", moduleType: "module" }],
assets: [{ from: path.join(path.dirname(pkg), "dist", "esm"), to: "my-plugin/renderer" }],
}
}
```
```ts title="loader.inline.ts"
document.addEventListener("nav", async () => {
const nodes = document.querySelectorAll(".my-widget")
if (nodes.length === 0 || !window.quartzStaticUrl) return // nothing to do on this page
const url = new URL("plugins/my-plugin/renderer/index.js", window.quartzStaticUrl).href
const { render } = await import(url)
for (const node of nodes) render(node)
})
```
- `to` is relative to `static/plugins/`; use your plugin's name as the first segment. Invalid or conflicting targets and missing sources are reported as build warnings.
- An ES module build with relative `import()`s keeps working when served this way, so only the chunks a page needs are downloaded.
- Older Quartz versions ignore `assets` and leave `quartzStaticUrl` undefined. Either require `"quartzVersion": ">=5.1.0"` or fall back (for example to a CDN), as [[ObsidianFlavoredMarkdown]] does for [[Mermaid diagrams|Pele]].
### Plugins with Native Dependencies
Plugins that require native packages (e.g. `sharp` for image processing) cannot bundle those. For these plugins:
+130
View File
@@ -0,0 +1,130 @@
---
title: Plugin capabilities
---
Quartz plugins cooperate through channels the type system can't see:
- `file.data` keys (e.g. built-in [[CrawlLinks|link processing]] writes `links`, [[plugins/Backlinks|backlinks]] reads it),
- DOM classes queried by client scripts (OFM's mermaid script looks for syntax-highlighting's `.clipboard-button`),
- browser globals and document events (`fetchData`, `addCleanup`, `nav`, `themechange`),
- emitted files (`static/contentIndex.json`, read by search, explorer and graph),
- CSS custom properties.
When the provider of one of these is disabled, the consumer usually breaks _silently_: an empty backlinks list, wikilinks that 404, or — worst — `draft: true` pages being published because no plugin parsed the frontmatter. **Capabilities** let a plugin declare what it provides and needs, so `quartz build` can say what is wrong:
```
⚠ Plugin "backlinks" requires data "links", but no enabled plugin provides it — enable "configuration.links". (the backlinks list is always empty)
```
> [!note]
> Capabilities are opt-in and advisory. Plugins without them behave exactly as before, and an unsatisfied requirement is a warning, never a build failure.
## Declaring capabilities
Add `capabilities` to the `quartz` field of your plugin's `package.json`:
```json
{
"quartz": {
"name": "backlinks",
"capabilities": {
"provides": {},
"requires": {
"data": [
{ "name": "links", "from": "crawl-links", "reason": "the backlinks list is always empty" }
]
},
"optional": {
"data": [
{
"name": "frontmatter",
"from": "note-properties",
"reason": "titles fall back to file names"
}
]
}
}
}
}
```
| Section | Meaning | Unsatisfied → |
| ---------- | ------------------------------------------------------------------------- | ---------------------- |
| `provides` | What this plugin makes available. Plain strings. | — |
| `requires` | Needed for the plugin to work correctly. | build warning |
| `optional` | Used when present; the plugin degrades gracefully (you must handle that). | info (not printed yet) |
Each section maps a **kind** to a list:
| Kind | Names | Example |
| --------- | ------------------------------------------------------------- | ---------------------------- |
| `data` | `file.data` / `fileData` keys (vfile `DataMap`) | `"links"` |
| `dom` | CSS selector rendered into pages or added by a script | `".clipboard-button"` |
| `globals` | browser globals defined by scripts | `"fetchData"` |
| `events` | `document` CustomEvents dispatched | `"themechange"` |
| `files` | emitted paths relative to the site root (leading `/` ignored) | `"static/contentIndex.json"` |
| `cssVars` | CSS custom properties defined | `"--secondary"` |
A requirement is either a name, or `{ "name", "from"?, "reason"? }`:
- `from` — plugin name(s) (the manifest `name`, e.g. `"crawl-links"`) known to provide it. It is used for the "enable …" hint, **and** a requirement counts as satisfied whenever a plugin named in `from` is enabled, even if that plugin predates capability declarations. Always set `from` for first-party providers: it keeps new consumers working with old providers.
- `reason` — what breaks without it, appended to the warning.
Names are matched exactly (after trimming). Unknown kinds or malformed entries are ignored and reported, never fatal.
### Provided by Quartz itself
These never need a provider plugin (`coreCapabilities()` in `quartz/plugins/loader/capabilities.ts`):
- data: `slug`, `filePath`, `relativePath`
- dom: `#quartz-body`, `.page`, `.center`, `article`, `.popover-hint`, `.sidebar`
- globals: `fetchData`, `addCleanup`, `spaNavigate`
- events: `nav` (always), `prenav` (only with `enableSPA`)
Note that `fetchData` is a promise for `static/contentIndex.json`, which Quartz emits by default ([[ContentIndex|built-in content index]]). Declare `files: ["static/contentIndex.json"]` if you read it. Since this release `fetchData` resolves to `{}` (with a console warning) when the file is missing, instead of rejecting.
## How the check works
`loadQuartzConfig()` calls `validatePluginCapabilities()` after loading manifests:
1. Collect `provides` of core and every **enabled** plugin.
2. For each enabled plugin with `capabilities`, check each `requires` / `optional` entry. Satisfied if provided, or if a plugin listed in `from` is enabled.
3. Only if something is missing, also read the manifests of **disabled** entries in `quartz.config.yaml` to suggest which one to enable.
4. Warnings are printed once per process (main thread only).
The check is static: it cannot see option-dependent behaviour (e.g. `syntax-highlighting` with `clipboard: false` still "provides" `.clipboard-button`) or pipeline order (see the `dependencies` / `defaultOrder` checks for that).
## Writing robust consumers
Declaring a requirement is not a substitute for handling its absence. For `optional` (and ideally `requires`) capabilities:
- Guard DOM lookups: `const btn = pre.querySelector(".clipboard-button"); if (btn) { … }` — never `getComputedStyle(maybeNull)`.
- Default data: `file.data.links ?? []`, `fileData.dates?.created`.
- Wrap `await fetchData` in `try`/`catch` and accept an empty object.
## Built-ins as providers
Quartz's [[built-in processing]] steps take part in the check like plugins: when enabled, built-in frontmatter provides `frontmatter`, `aliases` and `frontmatterLinks`, built-in links provides `links`, and the built-in content index provides `static/contentIndex.json`. When one is turned off, warnings suggest `configuration.<key>` (and a `from: "crawl-links"` hint is shown as `configuration.links`).
The same declarations decide replacement: an enabled plugin that `provides` `data: ["frontmatter"]`, `data: ["links"]` or `files: ["static/contentIndex.json"]` replaces the matching built-in.
## Migration path
1. **Now (this change):** core checker + declarations on a representative set of first-party plugins: `note-properties`, `crawl-links`, `backlinks`, `description`, `content-index`, `syntax-highlighting`, `obsidian-flavored-markdown`, `remove-draft`, `search`.
2. **Next, first-party plugins** — drafts derived from the workspace catalog (`just catalog show <plugin>` in the dev-mode workspace lists data read/written, DOM classes and scripts):
| Plugin | Draft |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `explicit-publish` | requires data `frontmatter` (built in) |
| `graph`, `explorer` | requires files `static/contentIndex.json` (built in); optional events `themechange` from darkmode |
| `recent-notes`, `content-meta` | optional data `dates` from created-modified-date |
| `alias-redirects` | requires data `aliases` (built in) |
| `table-of-contents` | provides data `toc`, `collapseToc` |
| `created-modified-date` | provides data `dates`, `defaultDateType` |
| `unlisted-pages`, `encrypted-pages` | provide data `unlisted` (encrypted-pages also `encrypted`, events `render`, `content-index-updated`) |
| `darkmode` | provides events `themechange` |
| `og-image`, `folder-page`, `tag-page` | optional data `description` from description, `dates` from created-modified-date |
| `canvas-page`, `obsidian-plugin-excalidraw` | optional dom `.explorer` (they style it) from explorer |
3. **Third-party plugins:** add declarations at their own pace; nothing changes for them otherwise.
4. **Later (proposals, not implemented):** print `optional` infos with `quartz build --verbose`; a `strictCapabilities` option that turns warnings into errors; ordering checks for `data` between transformers (needs a `phase` per provided key); option-aware provides; a `transforms` kind for "rewrites links" style contracts (OFM currently uses crawl-links' `.internal` class as a proxy); exporting these types from `@quartz-community/types`.
+59
View File
@@ -0,0 +1,59 @@
---
title: Versioning and releases
description: What Quartz's version number means, how plugins declare the Quartz versions they support, and how releases are made.
---
Quartz follows [semantic versioning](https://semver.org): `MAJOR.MINOR.PATCH`.
- **patch** (5.1.**1**) — bug fixes.
- **minor** (5.**2**.0) — new features and new APIs for plugins. Existing sites and plugins keep working.
- **major** (**6**.0.0) — breaking changes, with an upgrade guide.
Each release is a git tag (`v5.1.0`) with a [GitHub release](https://github.com/jackyzha0/quartz/releases) listing the changes, also in `CHANGELOG.md`. Quartz itself is not published to npm — your site is a clone of the repository, so its version is the one in `package.json`.
## Which version am I on?
```shell
npx quartz info
```
prints the version, where your checkout is relative to the last release, your environment and your plugins as a block you can paste into an issue or support question. The version shows as e.g. `5.1.0 (v5.1.0-4-g1a2b3c4-dirty)`: 4 commits after the `v5.1.0` release, at commit `1a2b3c4`, with local changes. `npx quartz build` and `npx quartz plugin doctor` print it too.
When asking for help, please include this output — a version number is much more useful than a commit hash of your fork.
## Plugin compatibility
Plugins declare the Quartz versions they work with in their `package.json`:
```json title="package.json"
{
"quartz": {
"quartzVersion": ">=5.1.0"
}
}
```
Any [npm semver range](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#dependencies) works (`>=5.1.0`, `^5.1.0`, `>=5.1.0 <7`). Quartz checks it
- when the build loads your config: locally a warning (repeated in the end-of-build summary); in CI (when the `CI` environment variable is set, as on GitHub Actions, GitLab CI, Netlify, Vercel or Cloudflare Pages) the build fails, so an incompatible plugin doesn't get deployed. Set `QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS=1` to build anyway,
- in `npx quartz plugin add` and `npx quartz plugin doctor` (an error for enabled plugins),
and says whether to update Quartz (`npx quartz upgrade`) or the plugin. If an incompatible plugin later fails, the error message mentions the version mismatch as a likely cause.
### For plugin authors
- Set `quartzVersion` to the **oldest Quartz version your plugin works with**. Raise it when you start using a newer API — for example a plugin that relies on [[built-in processing]] (core-parsed frontmatter, `ctx.contentIndex`, `extendContentIndex`) needs `">=5.1.0"`.
- Prefer a lower bound (`>=5.1.0`) over a caret range: minor Quartz releases don't break plugins, so `^5` would only add an upper bound you'd have to bump at every major release. Add an upper bound when you know a major version breaks you.
- Raising `quartzVersion` is a breaking change for users on older Quartz versions: release it as a new major (or at least minor) version of your plugin and say so in its changelog.
- Pre-releases count: Quartz `5.2.0-beta.1` satisfies `>=5.1.0`.
- To retire a plugin, set `quartz.deprecated` in its `package.json` to a message saying what replaces it (for example `"Line breaks are handled by ObsidianFlavoredMarkdown 2.0+ …"`). Quartz 5.1+ warns when the plugin is enabled (in the build summary, `plugin add` and `plugin doctor`) and suggests removing it; the plugin keeps working.
## Contributing: changesets
Quartz uses [changesets](https://github.com/changesets/changesets). A pull request that changes how Quartz behaves should include one:
```shell
npx changeset
```
Choose `patch`, `minor` or `major` and describe the change for users. On every push to `v5` a "chore: release Quartz" pull request collects the pending changesets, bumps `package.json` and updates `CHANGELOG.md`; merging it tags the release and publishes the GitHub release notes. CI warns (without failing) when a pull request has no changeset.
+11 -10
View File
@@ -6,15 +6,15 @@ The `create` command initializes a new Quartz project. It helps you set up your
## Flags
| Flag | Shorthand | Description |
| ------------- | --------- | --------------------------------------------------------------------- |
| `--template` | `-t` | Configuration template (`default`, `obsidian`, `ttrpg`, or `blog`) |
| `--directory` | `-d` | The directory where Quartz will be initialized |
| `--source` | `-s` | The source directory of your Markdown files |
| `--strategy` | `-X` | How to handle the source files (`new`, `copy`, or `symlink`) |
| `--links` | `-l` | How to resolve internal links (`absolute`, `shortest`, or `relative`) |
| `--baseUrl` | `-b` | Base URL for your site (e.g. `mysite.github.io/quartz`) |
| `--verbose` | `-v` | Enable detailed logging |
| Flag | Shorthand | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| `--template` | `-t` | Configuration template (`default`, `obsidian`, `ttrpg`, `blog`, or `docs`) |
| `--directory` | `-d` | The directory where Quartz will be initialized |
| `--source` | `-s` | The source directory of your Markdown files |
| `--strategy` | `-X` | How to handle the source files (`new`, `copy`, or `symlink`) |
| `--links` | `-l` | How to resolve internal links (`absolute`, `shortest`, or `relative`) |
| `--baseUrl` | `-b` | Base URL for your site (e.g. `mysite.github.io/quartz`) |
| `--verbose` | `-v` | Enable detailed logging |
## Templates
@@ -24,6 +24,7 @@ When you run `quartz create`, you can choose a configuration template that pre-c
- **Obsidian**: Optimized for Obsidian vaults with full Obsidian Flavored Markdown support (wikilinks, callouts, mermaid diagrams, etc.). Automatically sets link resolution to `shortest` and skips the link resolution prompt.
- **TTRPG**: Builds on the Obsidian template with the addition of the [Leaflet bases plugin](https://github.com/Requiae/quartz-leaflet-bases-plugin) and [ITS Theme](https://github.com/saberzero1/quartz-themes) (`its-theme.ttrpg-dnd`). Great for D&D and TTRPG wikis. Also skips the link resolution prompt.
- **Blog**: A blog-focused setup with [recent notes](https://github.com/quartz-community/recent-notes) enabled (showing the 5 most recent posts with tags) and [comments](https://github.com/quartz-community/comments) enabled via giscus. You'll need to fill in the `TODO:` placeholder values in `quartz.config.yaml` with your own giscus repository details.
- **Documentation**: The default setup with both sidebars set to scroll away with the page ([[layout#Sidebar modes|`layout.sidebars`]]: `static`), so long navigation and tables of contents are never cut off.
## Base URL
@@ -56,7 +57,7 @@ Quartz needs to know how to interpret the internal links in your Markdown files:
If you run `npx quartz create` without any arguments, it will guide you through an interactive setup:
1. **Choose a template**: Select a configuration template (`Default`, `Obsidian`, `TTRPG`, or `Blog`).
1. **Choose a template**: Select a configuration template (`Default`, `Obsidian`, `TTRPG`, `Blog`, or `Documentation`).
2. **Select a strategy**: Choose between `new`, `copy`, or `symlink`.
3. **Enter base URL**: Provide the URL where your site will be hosted.
4. **Select link resolution**: Choose how your links are formatted (skipped for Obsidian and TTRPG templates).
+3 -2
View File
@@ -16,15 +16,16 @@ You can run the CLI using `npx quartz`.
| `upgrade` | Upgrade Quartz to the latest version (alias: `update`) | `npx quartz upgrade` |
| `plugin` | Manage Quartz plugins (install, add, remove, etc.) | `npx quartz plugin list` |
| `tui` | Launch the interactive plugin manager | `npx quartz tui` |
| `info` | Print version, environment and plugins for bug reports | `npx quartz info` |
## Commands
- [[create|create]]: Initialize a new Quartz project with a choice of templates (default, obsidian, ttrpg, blog) and base URL configuration.
- [[create|create]]: Initialize a new Quartz project with a choice of templates (default, obsidian, ttrpg, blog, docs) and base URL configuration.
- [[build|build]]: Build your Quartz site into static HTML. Includes a development server.
- [[sync|sync]]: Push and pull changes between your local machine and GitHub.
- [[upgrade|upgrade]]: Upgrade the Quartz framework to the latest version. Also available as `npx quartz update`.
- [[restore|restore]]: Recover your content folder from the local cache.
- [[cli/plugin|plugin]]: Install, add, remove, prune, and configure plugins. Use `plugin install` with flags for lockfile/config sync, updates, and checks.
- [[cli/plugin|plugin]]: Install, add, remove, prune, and configure plugins. Use `plugin install` with flags for lockfile/config sync, updates, and checks, and `plugin doctor` to diagnose plugin problems.
- [[tui|tui]]: Use a terminal interface to manage plugins and layout.
## Global Flags
+84 -16
View File
@@ -4,13 +4,20 @@ title: quartz plugin
The `plugin` command is the heart of the Quartz v5 plugin management system. it allows you to install, configure, and update plugins directly from the command line.
All plugins are stored in the `.quartz/plugins/` directory, and their versions are tracked in `quartz.lock.json`.
Quartz plugins come from two kinds of sources:
- **npm packages** (`@quartz-community/explorer`) — the default plugins. They are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`.
- **Git repositories and local directories** (`github:owner/repo`, `./my-plugin`) — cloned or symlinked into `.quartz/plugins/`. Their exact commits are pinned in `quartz.lock.json`.
Wherever a command takes a plugin name you can use the full name (`@quartz-community/explorer`), the source as written in `quartz.config.yaml`, or the short name (`explorer`). Misspelled names get a "did you mean" suggestion.
Every subcommand exits with a non-zero status when something fails (a clone, a build, an unknown plugin name), so `npx quartz plugin install && npx quartz build` stops in CI instead of building a site with missing plugins.
## Subcommands
### list
List all currently installed plugins and their versions.
List all configured plugins: Git/local plugins with their pinned commit, npm plugins with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
```shell
npx quartz plugin list
@@ -18,10 +25,11 @@ npx quartz plugin list
### add
Add a new plugin from a Git repository.
Add a new plugin from a Git repository. The plugin is installed, pinned in `quartz.lock.json`, and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
```shell
npx quartz plugin add github:username/repo
npx quartz plugin add username/repo # same as github:username/repo
```
To install from a specific branch or ref, append `#ref` to the source:
@@ -44,30 +52,40 @@ Local plugins are symlinked into `.quartz/plugins/`, so any changes you make to
When a branch is specified, it is stored in the lockfile. All subsequent commands (`install`, `prune`) will respect that branch automatically. Use `install --latest` to fetch the latest commit from that branch.
`plugin add` will not create duplicate entries: if a plugin with the same name is already configured (for example `@quartz-community/graph` when you add `github:someone/graph`), it is skipped with a hint. Remove the existing plugin first, or use `--as <name>` to install the second one under a different name. If the plugin is already present in `.quartz/plugins/` but missing from the config (e.g. after you deleted its entry by hand), `add` adds it back to the config without re-cloning.
> [!tip]
> `plugin add` also accepts `--concurrency` / `-c` to limit how many remote repositories are cloned and built at the same time. This is the same flag documented under [[#install]] and is useful when adding several plugins at once on low-end hardware.
### remove
Remove an installed plugin.
Remove a plugin: deletes its entry from `quartz.config.yaml`, and for Git/local plugins also its directory in `.quartz/plugins/` and its lockfile entry.
```shell
npx quartz plugin remove plugin-name
npx quartz plugin remove explorer # short name of @quartz-community/explorer
```
For npm plugins the package stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
### install
Install plugins for your Quartz project. By default, this installs all plugins listed in your `quartz.lock.json` file.
Install plugins for your Quartz project. By default, this installs all plugins listed in your `quartz.lock.json` file, at exactly the pinned commits (including plugins installed from a repository subdirectory).
```shell
npx quartz plugin install
```
If there is no `quartz.lock.json` yet, `install` falls back to installing the Git/local plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists Git plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
> [!note]
> `npx quartz build` also installs any configured Git plugin that is missing from `.quartz/plugins/`, and checks out the commit pinned in `quartz.lock.json` when there is one. Running `plugin install` first is still recommended in CI, because it fails loudly when a plugin cannot be installed.
#### Flags
- `--from-config`: Synchronize plugins with `quartz.config.yaml` instead of the lockfile. This will install missing plugins and prune orphaned ones.
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile.
- `--clean`: Skip existing directories and perform a fresh installation.
- `--clean`: Only restore plugins whose directory is missing; existing directories are left untouched.
- `--dry-run`: Preview the changes without actually installing or removing any files.
- `--concurrency`, `-c`: Maximum number of plugins to clone, fetch, and build in parallel. Defaults to the number of CPU cores. Lower this (e.g. `-c 1` or `-c 2`) on memory- or CPU-constrained machines where the default parallelism causes failures, OOMs, or hangs. See [[#Installing on low-end hardware]] below.
@@ -92,18 +110,59 @@ npx quartz plugin enable plugin-name
npx quartz plugin disable plugin-name
```
The CLI edits `quartz.config.yaml` in place: your comments, quoting and key order are preserved, and the file is only rewritten when something actually changed.
### config
View or modify the configuration for a specific plugin.
View or modify the options of a specific plugin.
```shell
# View config
npx quartz plugin config plugin-name
# View the options you set, plus the plugin defaults you have not overridden
npx quartz plugin config explorer
# Set a value
npx quartz plugin config plugin-name --set key=value
# Set values (repeatable; values are parsed as JSON when possible)
npx quartz plugin config explorer --set folderDefaultState=open --set useSavedState=false
# Nested option keys use dots
npx quartz plugin config graph --set localGraph.depth=2
# Remove an option so the plugin default applies again
npx quartz plugin config explorer --unset folderDefaultState
```
Options are checked against the plugin's documented defaults (the `defaultOptions` and optional `configSchema` in its manifest). A likely typo or a value of the wrong type prints a warning, for example:
```
⚠ @quartz-community/explorer: unknown option "folderDefaultStat" — did you mean "folderDefaultState"?
⚠ @quartz-community/explorer: option "useSavedState" should be a boolean (default: true), got string "yes"
```
The same warnings are printed at the start of `npx quartz build`, along with misspelled entry keys such as `enable:` instead of `enabled:`. They never stop the build.
### doctor
Check your plugin setup without changing anything:
```shell
npx quartz plugin doctor
npx quartz plugin doctor --verbose # also show informational notes
npx quartz plugin doctor --fix # move settings of plugins that are now built into Quartz
```
`doctor` reports, with a suggested fix for each problem:
- YAML syntax errors in `quartz.config.yaml`
- misspelled or invalid entry keys (`enable:`, `option:`, `layout.positon`), non-boolean `enabled` values, and entries without `enabled` (treated as disabled)
- unparseable sources and plugins configured twice
- npm plugins that are not installed, and Git/local plugins that are not installed, not pinned in `quartz.lock.json`, checked out at a different commit than the lockfile pins, or whose source changed
- broken local plugin symlinks and plugins without a built entry point (`dist/`)
- option typos and type mismatches, and declared plugin dependencies that are missing or disabled
- plugins that don't support your Quartz version (their `quartzVersion`, see [[versioning#Plugin compatibility]])
- entries for plugins that are now [[built-in processing|built into Quartz]] (`crawl-links`, `remove-draft`, `content-index`); `--fix` moves their options into `configuration` (keeping your comments) and removes their now unused pins from `quartz.lock.json`
- lockfile entries that are no longer configured (clean up with `prune`)
It exits with status 1 when it finds errors, so it can run as a CI check.
### prune
Remove installed plugins that are no longer referenced in your `quartz.config.yaml`. This is useful for cleaning up after removing plugin entries from your configuration.
@@ -125,10 +184,20 @@ npx quartz plugin prune --dry-run
### Adding and Enabling a Plugin
To add a new plugin and start using it:
`plugin add` installs the plugin and enables it right away (unless the plugin is disabled by default — the command then tells you how to enable it):
1. Add the plugin: `npx quartz plugin add github:quartz-community/example`
2. Enable it: `npx quartz plugin enable example`
```shell
npx quartz plugin add github:quartz-community/example
npx quartz plugin enable example # only needed for plugins that are disabled by default
```
### Something is not working
Start with:
```shell
npx quartz plugin doctor
```
### Updating Everything
@@ -266,7 +335,6 @@ See [[configuration#Advanced Source Options|Advanced Source Options]] for the fu
| `npx quartz plugin check` | `npx quartz plugin install --latest --dry-run` |
| `npx quartz plugin resolve` | `npx quartz plugin install --from-config` |
| `npx quartz plugin resolve --dry-run` | `npx quartz plugin install --from-config --dry-run` |
| `npx quartz update` | `npx quartz plugin install --latest` |
The old commands still work as hidden aliases but will print a deprecation warning.
@@ -278,4 +346,4 @@ Running the plugin command without any subcommand shows a status dashboard of al
npx quartz plugin
```
This displays each plugin with its source, commit, enabled/disabled status, and checks for available updates in parallel. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks Git plugins for available updates in parallel. npm plugins are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
+7 -4
View File
@@ -16,10 +16,13 @@ When you run `npx quartz upgrade`, Quartz performs the following steps:
1. **Backs up your content** — your content folder is cached locally to prevent data loss.
2. **Pulls the latest Quartz code** — fetches and merges from the official upstream repository (`upstream/v5`) using Git.
3. **Shows version changes** — displays the version transition (e.g., `v5.0.0 → v5.1.0`) or confirms you're already up to date.
4. **Updates dependencies** — runs `npm install` to ensure all packages match the new version.
5. **Restores plugins** — reinstalls plugins from `quartz.lock.json` to ensure compatibility.
6. **Checks plugin compatibility** — verifies that installed plugins are compatible with the new Quartz version.
3. **Updates dependencies** — runs `npm install` to ensure all packages match the new version.
4. **Shows what changed** — the version transition (e.g. `5.0.0 → 5.1.0`) and the release notes of every version in between, from `CHANGELOG.md`. Between releases it says how many commits were pulled.
5. **Restores plugins** — reinstalls plugins from `quartz.lock.json`. Plugins that are now [[built-in processing|built into Quartz]] are skipped.
6. **Checks your config and plugins** — runs [[cli/plugin#doctor|`npx quartz plugin doctor`]] for the new version: plugin entries that are built in now (fix with `npx quartz plugin doctor --fix`), plugins that don't support the new Quartz version, lockfile and install problems.
7. **Checks for plugin updates** — lists plugins with newer versions available.
Steps 4–7 run the code of the version you upgraded _to_, so the checks know about that version's changes. (Upgrading _from_ a Quartz older than 5.1 still runs the older steps once.)
## Handling Conflicts
+1 -1
View File
@@ -36,7 +36,7 @@ Custom themes, CSS snippets, and starter templates for Quartz sites.
<!-- Add templates/themes here -->
<!-- Format: - **[Name](link)** — Brief description -->
_No community templates listed yet._
- **[Field Notes](https://github.com/oswarren/quartz-field-notes)** — A warm, single-column reading theme with book margins, a designed dark mode, and a one-command installer that can restore your original files.
## Guides & Tutorials
+29 -3
View File
@@ -31,9 +31,9 @@ This part of the configuration concerns anything that can affect the whole site.
- `null`: don't use analytics;
- `{ provider: 'google', tagId: '<your-google-tag>' }`: use Google Analytics;
- `{ provider: 'plausible' }` (managed) or `{ provider: 'plausible', host: 'https://<your-plausible-host>' }` (self-hosted, make sure to include the `https://` protocol prefix): use [Plausible](https://plausible.io/);
- `{ provider: 'umami', host: '<your-umami-host>', websiteId: '<your-umami-website-id>' }`: use [Umami](https://umami.is/);
- `{ provider: 'umami', host: '<your-umami-host>', websiteId: '<your-umami-website-id>', script: '<your-script-name.js>' }`: use [Umami](https://umami.is/);
- `{ provider: 'goatcounter', websiteId: 'my-goatcounter-id' }` (managed) or `{ provider: 'goatcounter', websiteId: 'my-goatcounter-id', host: 'my-goatcounter-domain.com', scriptSrc: 'https://my-url.to/counter.js' }` (self-hosted) use [GoatCounter](https://goatcounter.com);
- `{ provider: 'posthog', apiKey: '<your-posthog-project-apiKey>', host: '<your-posthog-host>' }`: use [Posthog](https://posthog.com/);
- `{ provider: 'posthog', apiKey: '<your-posthog-project-apiKey>' }` (managed) or `{ provider: 'posthog', apiKey: '<your-posthog-project-apiKey>', apiHost: '<your-posthog-api-host>', uiHost: '<your-posthog-ui-host>', personProfiles: 'identified_only' }` (self-hosted/reverse proxy): use [PostHog](https://posthog.com/). `uiHost` is required when `apiHost` is a reverse proxy. The legacy `host` option is an alias for `apiHost`;
- `{ provider: 'tinylytics', siteId: '<your-site-id>' }`: use [Tinylytics](https://tinylytics.app/);
- `{ provider: 'cabin' }` or `{ provider: 'cabin', host: 'https://cabin.example.com' }` (custom domain): use [Cabin](https://withcabin.com);
- `{provider: 'clarity', projectId: '<your-clarity-id-code' }`: use [Microsoft clarity](https://clarity.microsoft.com/). The project id can be found on top of the overview page.
@@ -45,11 +45,24 @@ This part of the configuration concerns anything that can affect the whole site.
- You will be prompted to set this during [[create|`npx quartz create`]]. The CLI automatically strips any `https://` or `http://` protocol prefixes and trailing slashes for you.
- This should also include the subpath if you are [[hosting]] on GitHub pages without a custom domain. For example, if my repository is `jackyzha0/quartz`, GitHub pages would deploy to `https://jackyzha0.github.io/quartz` and the `baseUrl` would be `jackyzha0.github.io/quartz`.
- Note that Quartz 5 will avoid using this as much as possible and use relative URLs whenever it can to make sure your site works no matter _where_ you end up actually deploying it.
- `publishAssets`: which non-Markdown files (images, PDFs, …) from `content` are copied to the 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.
- `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.
- `"googleFonts"` (default): loads fonts from Google Fonts API. Fastest option, especially with CDN caching enabled.
- `"local"`: downloads fonts and serves them from your site. Fully self-contained with no external requests.
- `"local"`: Quartz loads no fonts at all; you provide them. The `typography` names are still used as the font families, so declare matching `@font-face` rules in `quartz/styles/custom.scss` and put the font files in `quartz/static/fonts/` (served at `static/fonts/`):
```scss title="quartz/styles/custom.scss"
@font-face {
font-family: "Inter";
src: url("static/fonts/Inter.woff2") format("woff2");
font-display: swap;
}
```
Use a path relative to the site root like above (no leading `/`) so it also works when the site is served from a subpath. To have Quartz download Google Fonts at build time and serve them from your site instead, use the [[plugins/Fonts|Fonts]] plugin with `fontOrigin: selfHosted`.
- `cdnCaching`: if `true` (default), use Google CDN to cache the fonts. This will generally be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained.
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here.
- `title`: font for the title of the site (optional, same as `header` by default)
@@ -66,6 +79,19 @@ This part of the configuration concerns anything that can affect the whole site.
- `tertiary`: hover states and visited [[graph view|graph]] nodes
- `highlight`: internal link background, highlighted text, [[syntax highlighting|highlighted lines of code]]
- `textHighlight`: markdown highlighted text background
- `frontmatter`, `links`, `drafts`, `contentIndex`: options for Quartz's [[built-in processing]] — frontmatter parsing ([[Frontmatter]]), link resolution ([[CrawlLinks]]), draft handling ([[RemoveDrafts]]) and the content index, sitemap and RSS feed ([[ContentIndex]]). They are on by default; set e.g. `links: { markdownLinkResolution: relative }` to change an option or `contentIndex: false` to turn one off.
> [!note] Colors with an Obsidian theme
> A theme from [quartz-themes](https://github.com/saberzero1/quartz-themes) (the Obsidian and TTRPG [[create#Templates|templates]] enable one) brings its own color scheme and colors the page through Obsidian's CSS variables (`--text-normal` for most text, `--text-muted` for paragraphs, `--background-primary`, `--interactive-accent`, …). The `colors` above then have little or no effect. To change a theme's colors, override its variables in `quartz/styles/custom.scss`:
>
> ```scss title="quartz/styles/custom.scss"
> html[saved-theme="dark"] body {
> --text-normal: #e0e0e0;
> --text-muted: #a0a0a0;
> }
> ```
>
> (use `html[saved-theme="light"] body` for light mode), or disable the theme to use the `colors` above.
## Plugins
+63
View File
@@ -0,0 +1,63 @@
---
title: Customizing Components
---
In Quartz v4, components such as the footer lived in `quartz/components/` and you customized them by editing their source. In v5, most components are [[configuration#Plugins|community plugins]]: Quartz installs them into `.quartz/plugins/` and runs their **built** code (`dist/`). Editing the files in `.quartz/plugins/` therefore has no effect, and is overwritten the next time the plugin is installed or updated.
There are four ways to change a component, from least to most effort. Try them in this order.
## 1. Options
Most components have options; each plugin's page under [[plugins/index|Plugins]] lists them. Set them in `quartz.config.yaml`:
```yaml title="quartz.config.yaml"
plugins:
- source: github:quartz-community/footer
enabled: true
options:
message: 'Licensed under <a href="/license">CC BY 4.0</a>'
links:
GitHub: https://github.com/you/your-site
```
or from the command line with `npx quartz plugin config footer --set message="Hello"` (see [[cli/plugin|plugin]]).
## 2. Placement
Where a component appears, in which order, on which page types and screen sizes is part of the layout, not the component: `layout.position`, `layout.priority` and `layout.display` per plugin, and `layout.byPageType` to drop or move components on some page types. See [[layout]] and [[layout-components]].
## 3. Styles
Write your own styles in `quartz/styles/custom.scss`. The styles of Quartz, its plugins and themes are in [CSS cascade layers](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) and `custom.scss` is not, so your rules take precedence over theirs whatever their specificity. Find the element's classes with your browser's developer tools, then for example:
```scss title="quartz/styles/custom.scss"
footer {
opacity: 1;
text-align: center;
& ul {
justify-content: center;
}
}
```
For site-wide colors and fonts, use the [[configuration#General Configuration|theme options]] first.
## 4. Your own copy of the plugin
When options and CSS are not enough (you want different markup or behavior), make your own copy of the plugin and use that instead:
1. Copy the plugin's repository (fork it on GitHub, or clone it) into a directory **outside** `.quartz/`, e.g. next to your site: `git clone https://github.com/quartz-community/footer.git ../my-footer`.
2. Change its source (for the footer, `src/components/Footer.tsx`) and build it: `npm install && npm run build` in that directory.
3. Replace the plugin in your site with your copy:
```shell
npx quartz plugin remove footer
npx quartz plugin add ../my-footer
```
Local plugins are symlinked into `.quartz/plugins/`. After further changes, run `npm run build` in your copy again (or `npx quartz plugin install --latest`, which rebuilds local plugins) and rebuild the site.
If you forked on GitHub, you can instead push your changes and add the fork with `npx quartz plugin add github:you/my-footer`, so your site builds in CI too. Note that a local path only works on machines that have that directory.
If you think others would want your change, consider opening a pull request against the original plugin, perhaps as a new option. To write a component from scratch, see [[creating components]].
+1 -1
View File
@@ -4,7 +4,7 @@ tags:
- component
---
Quartz supports rendering [Obsidian Bases](https://obsidian.md/changelog/2025-04-15-desktop-v1.8.0/) (`.base` files) as interactive database-like views. Bases files define queries over your vault's notes and display the results in configurable views such as tables, lists, cards, galleries, and boards.
Quartz supports rendering [Obsidian Bases](https://obsidian.md/help/bases) (`.base` files) as interactive database-like views. Bases files define queries over your vault's notes and display the results in configurable views such as tables, lists, cards, galleries, and boards.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
+2 -7
View File
@@ -59,14 +59,9 @@ Similarly, inline math can be rendered by delimiting math expression with a sing
### Escaping symbols
There will be cases where you may have more than one `$` in a paragraph at once which may accidentally trigger MathJax/Katex.
With [[ObsidianFlavoredMarkdown]], dollar signs follow Obsidian's rules: a `$` followed by a space or a digit after the closing `$` doesn't start or end math, so prices like `I have $1 and you have $2` stay text, as in Obsidian.
To get around this, you can escape the dollar sign by doing `\$` instead.
For example:
- Incorrect: `I have $1 and you have $2` produces I have $1 and you have $2
- Correct: `I have \$1 and you have \$2` produces I have \$1 and you have \$2
If a pair of `$` would still be read as math where you don't want it (for example `$a and b$`), escape the dollar sign as `\$`: `\$a and b\$` produces \$a and b\$.
### Using mhchem
+12 -2
View File
@@ -4,13 +4,23 @@ tags:
- feature/transformer
---
Quartz supports Mermaid which allows you to add diagrams and charts to your notes. Mermaid supports a range of diagrams, such as [flow charts](https://mermaid.js.org/syntax/flowchart.html), [sequence diagrams](https://mermaid.js.org/syntax/sequenceDiagram.html), and [timelines](https://mermaid.js.org/syntax/timeline.html). This is enabled as a part of [[Obsidian compatibility]] and can be configured and enabled/disabled from that plugin.
Quartz supports [Mermaid](https://mermaid.js.org) for diagrams and charts in your notes (flow charts, sequence diagrams, timelines, and so on). This is part of [[Obsidian compatibility]] and can be turned on or off on that plugin.
By default, Quartz will render Mermaid diagrams to match the site theme.
Default renderer is Mermaid.js. Set `diagramRenderer: pele` on [[ObsidianFlavoredMarkdown]] to use [Pele](https://pele.run) instead. Mermaid.js is deprecated; Pele will become the default later.
> [!warning]
> Wondering why Mermaid diagrams may not be showing up even if you have them enabled? You may need to reorder your plugins so that [[ObsidianFlavoredMarkdown]] is _after_ [[SyntaxHighlighting]].
```yaml title="quartz.config.yaml"
plugins:
- source: github:quartz-community/obsidian-flavored-markdown
options:
mermaid: true
diagramRenderer: pele # default: mermaid
```
Both renderers only load on pages that contain a Mermaid diagram. Pele is served from your own site (Quartz 5.1+) and only downloads the code for the diagram types on the page; on older Quartz versions it is loaded from jsDelivr. Mermaid.js is always loaded from a CDN.
## Syntax
To add a Mermaid diagram, create a mermaid code block.
+4 -4
View File
@@ -8,9 +8,9 @@ Quartz was originally designed as a tool to publish Obsidian vaults as websites.
By default, Quartz ships with the [[ObsidianFlavoredMarkdown]] plugin, which is a transformer plugin that adds support for [Obsidian Flavored Markdown](https://help.obsidian.md/Editing+and+formatting/Obsidian+Flavored+Markdown). This includes support for features like [[wikilinks]] and [[Mermaid diagrams]].
It also ships with support for [frontmatter parsing](https://help.obsidian.md/Editing+and+formatting/Properties) with the same fields that Obsidian uses through the [[Frontmatter]] transformer plugin.
It also ships with support for [frontmatter parsing](https://help.obsidian.md/Editing+and+formatting/Properties) with the same fields that Obsidian uses through its built-in [[Frontmatter]] transformer plugin.
Finally, Quartz also provides [[CrawlLinks]] plugin, which allows you to customize Quartz's link resolution behaviour to match Obsidian.
Finally, Quartz's built-in [[CrawlLinks|link processing]] (`configuration.links`) lets you customize link resolution to match Obsidian.
## Supported Features
@@ -123,7 +123,7 @@ Each custom character is preserved as a `data-task` attribute on the rendered el
### Mermaid Diagrams
[[Mermaid diagrams|Mermaid]] code blocks are rendered as diagrams:
[[Mermaid diagrams|Mermaid]] code blocks render as diagrams. Default is Mermaid.js; set `diagramRenderer: pele` for [Pele](https://pele.run):
````markdown
```mermaid
@@ -220,4 +220,4 @@ Quartz focuses on supporting Obsidian's core features. Functionality from Obsidi
## Configuration
This functionality is provided by the [[ObsidianFlavoredMarkdown]], [[Frontmatter]] and [[CrawlLinks]] plugins. See the plugin pages for customization options.
This functionality is provided by the [[ObsidianFlavoredMarkdown]] plugin and Quartz's built-in [[Frontmatter|frontmatter parsing]] and [[CrawlLinks|link processing]]. See those pages for customization options.
+2 -2
View File
@@ -3,8 +3,8 @@ Quartz emits an RSS feed for all the content on your site by generating an `inde
> [!info]
> After deploying, the generated RSS link will be available at `https://${baseUrl}/index.xml` by default.
>
> The `index.xml` path can be customized by passing the `rssSlug` option to the [[ContentIndex]] plugin.
> The `index.xml` path can be customized with `configuration.contentIndex.rssSlug` (see [[ContentIndex]]).
## Configuration
This functionality is provided by the [[ContentIndex]] plugin. See the plugin page for customization options.
This functionality is [[built-in processing|built into Quartz]]. See [[ContentIndex]] for customization options.
+87
View File
@@ -0,0 +1,87 @@
---
title: Built-in processing
description: Frontmatter parsing, link resolution, drafts and the content index are part of Quartz itself.
tags:
- feature
---
Some processing steps are needed by every Quartz site. They are built into Quartz instead of being plugins, so they cannot be removed by accident or run in the wrong order:
| Built-in | Configure under | What it does | Formerly |
| ------------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------- |
| [[Frontmatter\|frontmatter]] | `configuration.frontmatter` | Parses frontmatter: titles, tags, aliases, dates, `draft`, `permalink`, … | the parsing half of `note-properties` |
| [[CrawlLinks\|links]] | `configuration.links` | Makes internal links relative, classifies links, records outgoing links for backlinks and graph | `crawl-links` |
| [[RemoveDrafts\|drafts]] | `configuration.drafts` | Does not publish pages with `draft: true` | `remove-draft` |
| [[ContentIndex\|contentIndex]] | `configuration.contentIndex` | Emits `static/contentIndex.json` (search, explorer, graph, …), `sitemap.xml` and the RSS feed | `content-index` |
Without them a site would silently break: pages titled "Untitled", links that 404 on nested pages, empty backlinks and graph, drafts published, no search.
## Configuration
All built-ins are on by default. Options go under their key in the `configuration` section of `quartz.config.yaml`:
```yaml title="quartz.config.yaml"
configuration:
pageTitle: My garden
frontmatter:
language: yaml # or toml
delimiters: "---"
links:
markdownLinkResolution: shortest # absolute | relative | shortest
prettyLinks: true
openLinksInNewTab: false
lazyLoad: false
externalLinkIcon: true
disableBrokenWikilinks: false
drafts:
publish: false # true = publish drafts anyway (e.g. preview deployments)
contentIndex:
enableSiteMap: true
enableRSS: true
rssLimit: 10
rssFullHtml: false
rssSlug: index
includeEmptyFiles: true
```
Each built-in also accepts:
- `enabled: false` (or the shorthand `links: false`) to turn it off;
- `order` to change where it runs relative to plugins of the same kind (frontmatter runs at `0`, links at `60`, the same scale as plugin `order`).
See the individual pages for every option: [[Frontmatter]], [[CrawlLinks]], [[RemoveDrafts]], [[ContentIndex]].
## Replacing a built-in
A plugin can take over a built-in by declaring that it provides the same thing in its [[plugin capabilities|capabilities]] (`package.json` → `quartz.capabilities.provides`):
| Built-in | Replaced by a plugin that provides |
| ------------ | ------------------------------------- |
| frontmatter | `data: ["frontmatter"]` |
| links | `data: ["links"]` |
| contentIndex | `files: ["static/contentIndex.json"]` |
When such a plugin is enabled, the built-in steps aside (`quartz build --verbose` shows `off — replaced by plugin "…"`). Set `enabled: true` on the built-in to run both.
## Upgrading from the plugins
Existing `quartz.config.yaml` files keep working: entries for `@quartz-community/crawl-links`, `@quartz-community/remove-draft` and `@quartz-community/content-index` are applied to the matching built-in (options, `order` and `enabled: false` carry over) and the packages are no longer loaded. The build prints a notice for each.
To update the file, run:
```shell
npx quartz plugin doctor --fix
```
It moves the options into `configuration`, removes the old entries, and moves note-properties' `delimiters`/`language` options to `configuration.frontmatter`. Comments elsewhere in the file are kept.
> [!note]
> `crawl-links` defaulted to `markdownLinkResolution: absolute`; the built-in defaults to `shortest` (Obsidian's default). Migrated entries keep `absolute` unless you set something else.
The [[Frontmatter#Properties panel|properties panel]] is still a plugin (`note-properties`) — it now only renders the panel.
## For plugin authors
- The data the built-ins produce is unchanged: `file.data.frontmatter`, `aliases`, `frontmatterLinks`, `links`, and the same `contentIndex.json` format. Plugins that read them need no changes.
- Built-ins count as providers for [[plugin capabilities]], so a requirement such as `requires: { data: ["links"] }` is satisfied without any plugin.
- Plugins can add their own fields to `contentIndex.json` — see [[making plugins#Extending the content index]].
+1 -1
View File
@@ -37,7 +37,7 @@ Display names for folders get determined by the `title` frontmatter field in `fo
> [!info]
> The explorer uses local storage by default to save the state of your explorer. This is done to ensure a smooth experience when navigating to different pages.
>
> To clear/delete the explorer state from local storage, delete the `fileTree` entry (guide on how to delete a key from local storage in chromium based browsers can be found [here](https://docs.devolutions.net/kb/general-knowledge-base/clear-browser-local-storage/clear-chrome-local-storage/)). You can disable this by passing `useSavedState: false` as an argument.
> To clear/delete the explorer state from local storage, delete the `fileTree` entry (guide on how to delete a key from local storage in chromium based browsers can be found [here](https://developer.chrome.com/docs/devtools/storage/localstorage)). You can disable this by passing `useSavedState: false` as an argument.
## Customization
+1 -1
View File
@@ -16,7 +16,7 @@ To search content by tags, you can either press `⌘`/`ctrl` + `shift` + `K` or
This component is also keyboard accessible: Tab and Shift+Tab will cycle forward and backward through search results and Enter will navigate to the highlighted result (first result by default). You are also able to navigate search results using `ArrowUp` and `ArrowDown`.
> [!info]
> Search requires the `ContentIndex` emitter plugin to be present in the [[configuration]].
> Search reads `contentIndex.json`, which Quartz emits by default (see [[ContentIndex]]). It has no data if `configuration.contentIndex` is disabled.
### Indexing Behaviour
+1 -1
View File
@@ -38,7 +38,7 @@ By default, the node radius is proportional to the total number of incoming and
Additionally, similar to how browsers highlight visited links a different colour, the graph view will also show nodes that you have visited in a different colour.
> [!info]
> Graph View requires the `ContentIndex` emitter plugin to be present in the [[configuration]].
> Graph View reads `contentIndex.json`, which Quartz emits by default (see [[ContentIndex]]). It is empty if `configuration.contentIndex` is disabled.
## Customization
+1 -1
View File
@@ -10,7 +10,7 @@ Quartz comes with a wide variety of features out of the box. Most features are p
- [[wikilinks]] — Link between notes using `[[wikilinks]]` syntax
- [[callouts]] — Obsidian-style callout blocks
- [[features/Latex|Latex]] — LaTeX math rendering
- [[Mermaid diagrams]] — Diagram support via Mermaid
- [[Mermaid diagrams]] — Mermaid fences (Mermaid.js default, Pele via `diagramRenderer`)
- [[syntax highlighting|Syntax highlighting]] — Code block highlighting with themes
- [[OxHugo compatibility]] — Support for ox-hugo Markdown
- [[Roam Research compatibility]] — Support for Roam Research syntax
+2 -2
View File
@@ -8,12 +8,12 @@ There may be some notes you want to avoid publishing as a website. Quartz suppor
## Filter Plugins
[[making plugins#Filters|Filter plugins]] are plugins that filter out content based off of certain criteria. By default, Quartz uses the [[RemoveDrafts]] plugin which filters out any note that has `draft: true` in the frontmatter.
[[making plugins#Filters|Filter plugins]] are plugins that filter out content based off of certain criteria. By default, Quartz's built-in [[RemoveDrafts|draft handling]] filters out any note that has `draft: true` in the frontmatter.
If you'd like to only publish a select number of notes, you can instead use [[ExplicitPublish]] which will filter out all notes except for any that have `publish: true` in the frontmatter.
> [!warning]
> Regardless of the filter plugin used, **all non-markdown files will be emitted and available publically in the final build.** This includes files such as images, voice recordings, PDFs, etc.
> Regardless of the filter plugin used, **all non-markdown files will be emitted and available publicly in the final build.** This includes files such as images, voice recordings, PDFs, etc.
## `ignorePatterns`
+21 -1
View File
@@ -4,7 +4,7 @@ title: Wikilinks
Wikilinks were pioneered by earlier internet wikis to make it easier to write links across pages without needing to write Markdown or HTML links each time.
Quartz supports Wikilinks by default and these links are resolved by Quartz using the [[CrawlLinks]] plugin. See the [Obsidian Help page on Internal Links](https://help.obsidian.md/Linking+notes+and+files/Internal+links) for more information on Wikilink syntax.
Quartz supports Wikilinks by default and these links are resolved by Quartz's built-in [[CrawlLinks|link processing]]. See the [Obsidian Help page on Internal Links](https://help.obsidian.md/Linking+notes+and+files/Internal+links) for more information on Wikilink syntax.
This is enabled as a part of [[Obsidian compatibility]] and can be configured and enabled/disabled from that plugin.
@@ -21,6 +21,26 @@ Wikilink matching is case-insensitive to mirror Obsidian: `[[My Note]]`, `[[my n
- `![[Path to image]]`: embeds an image into the page
- `![[Path to image|100x145]]`: embeds an image into the page with dimensions 100px by 145px
- `![[Path to image|Alt text|300]]`: embeds an image with alt text and a width of 300px. Markdown images take a size the same way: `![Alt text|300](path/to/image.png)`
- `![[Path to file]]`: transclude an entire page
- `![[Path to file#Anchor]]`: transclude everything under the header `Anchor`
- `![[Path to file#^b15695]]`: transclude block with ID `^b15695`
### Styling individual images
The text between `|`s that isn't a size becomes the image's alt text: `![[diagram.png|invert center|300]]` gives `<img alt="invert center" width="300">` (likewise `![invert center](diagram.png)`). SVG files are embedded as `<object>` and get it as `aria-label`. You can use words in the alt text as flags for styles in `quartz/styles/custom.scss`, for example to invert diagrams in dark mode and to center images:
```scss title="quartz/styles/custom.scss"
// ![[diagram.png|invert]]: invert colors in dark mode (hue-rotate keeps hues roughly the same)
html[saved-theme="dark"] :is(img[alt~="invert"], object[aria-label~="invert"]) {
filter: invert(1) hue-rotate(180deg);
}
// ![[photo.png|center]] or ![[photo.png|center|300]]: center the image
:is(img[alt~="center"], object[aria-label~="center"]) {
display: block;
margin-inline: auto;
}
```
`~=` matches one word of the alt text, so flags combine (`|invert center|`), and an alt text such as `|Network diagram invert|` still describes the image for screen readers.
+3 -3
View File
@@ -31,8 +31,8 @@ Some common frontmatter fields that are natively supported by Quartz:
- `title`: Title of the page. If it isn't provided, Quartz will use the name of the file as the title.
- `description`: Description of the page used for link previews.
- `permalink`: A custom URL for the page that will remain constant even if the path to the file changes.
- `aliases`: Other names for this note. This is a list of strings.
- `permalink`: The page's address on the site, as in Obsidian Publish: `note.md` with `permalink: page` is published at `/page`, whatever its folder or file name. Links to the note (`[[note]]`) point there, and its file path redirects to it. A permalink that is already another page's address is ignored with a warning.
- `aliases`: Other addresses for this note that redirect to it (with the [[AliasRedirects]] plugin), so old links and links from other sites keep working after a note is renamed or moved. This is a list of strings.
- `tags`: Tags for this note.
- `draft`: Whether to publish the page or not. This is one way to make [[private pages|pages private]] in Quartz.
- `date`: A string representing the day the note was published. Normally uses `YYYY-MM-DD` format.
@@ -46,4 +46,4 @@ First, make sure you've [[installation#Setting Up Your GitHub Repository|set up
## Customization
Frontmatter parsing for `title`, `tags`, `aliases` and `cssclasses` is a functionality of the [[Frontmatter]] plugin, `date` is handled by the [[CreatedModifiedDate]] plugin and `description` by the [[Description]] plugin. See the plugin pages for customization options.
Frontmatter parsing for `title`, `tags`, `aliases` and `cssclasses` is built into Quartz (see [[Frontmatter]]), `date` is handled by the [[CreatedModifiedDate]] plugin and `description` by the [[Description]] plugin. See the plugin pages for customization options.
+3
View File
@@ -18,6 +18,9 @@ You need these tools installed before continuing:
> - **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.
> [!tip] Using Bun
> Quartz runs on Node.js, but you can install its dependencies with [Bun](https://bun.sh/) (`bun install`). Bun does not link a package's own commands the way npm does, so `bunx quartz` fails with "could not determine executable to run". Use `bun run quartz` instead, followed by the command, wherever these docs say `npx quartz`: `bun run quartz create`, `bun run quartz build --serve`.
## Setup Steps
Follow these in order:
+1 -1
View File
@@ -58,7 +58,7 @@ npx quartz create
This will prompt you for:
- A **template** (`default`, `obsidian`, `ttrpg`, `blog`) — pick the one that matches your use case. See [[create#Templates]] for details on each.
- A **template** (`default`, `obsidian`, `ttrpg`, `blog`, `docs`) — pick the one that matches your use case. See [[create#Templates]] for details on each.
- A **content strategy** — choose how to populate the `content/` folder:
- **new**: Start with an empty folder
- **copy**: Copy files from an existing folder (e.g. your Obsidian vault)
+7 -5
View File
@@ -57,7 +57,7 @@ npx quartz create
This will prompt you for:
- A **template** (`default`, `obsidian`, `ttrpg`, `blog`) — pick the one closest to your old setup. `obsidian` is recommended if you use an Obsidian vault.
- A **template** (`default`, `obsidian`, `ttrpg`, `blog`, `docs`) — pick the one closest to your old setup. `obsidian` is recommended if you use an Obsidian vault.
- A **content strategy** — choose "Copy" and point it to your backed-up content folder.
If you skipped the `create` wizard or need to restore your content manually:
@@ -117,15 +117,15 @@ Mapping v4 plugin names to v5 equivalents:
| v4 | v5 | Type |
| ----------------------------------- | ------------------------------------------- | --------------------- |
| `Plugin.FrontMatter()` | `ExternalPlugin.NoteProperties()` | Community |
| `Plugin.FrontMatter()` | built in (`configuration.frontmatter`) | Internal |
| `Plugin.CreatedModifiedDate()` | `ExternalPlugin.CreatedModifiedDate()` | Community |
| `Plugin.SyntaxHighlighting()` | `ExternalPlugin.SyntaxHighlighting()` | Community |
| `Plugin.ObsidianFlavoredMarkdown()` | `ExternalPlugin.ObsidianFlavoredMarkdown()` | Community |
| `Plugin.GitHubFlavoredMarkdown()` | `ExternalPlugin.GitHubFlavoredMarkdown()` | Community |
| `Plugin.CrawlLinks()` | `ExternalPlugin.CrawlLinks()` | Community |
| `Plugin.CrawlLinks()` | built in (`configuration.links`) | Internal |
| `Plugin.Description()` | `ExternalPlugin.Description()` | Community |
| `Plugin.Latex()` | `ExternalPlugin.Latex()` | Community |
| `Plugin.RemoveDrafts()` | `ExternalPlugin.RemoveDrafts()` | Community |
| `Plugin.RemoveDrafts()` | built in (`configuration.drafts`) | Internal |
| `Plugin.ContentPage()` | `ExternalPlugin.ContentPage()` | Community (pageTypes) |
| `Plugin.FolderPage()` | `ExternalPlugin.FolderPage()` | Community (pageTypes) |
| `Plugin.TagPage()` | `ExternalPlugin.TagPage()` | Community (pageTypes) |
@@ -134,7 +134,7 @@ Mapping v4 plugin names to v5 equivalents:
| `Plugin.Assets()` | `Plugin.Assets()` (unchanged) | Internal |
| `Plugin.Static()` | `Plugin.Static()` (unchanged) | Internal |
| `Plugin.AliasRedirects()` | `ExternalPlugin.AliasRedirects()` | Community |
| `Plugin.ContentIndex()` | `ExternalPlugin.ContentIndex()` | Community |
| `Plugin.ContentIndex()` | built in (`configuration.contentIndex`) | Internal |
Component layout mapping:
@@ -150,6 +150,8 @@ Component layout mapping:
| `Component.Head()` | `Component.Head()` (unchanged, internal) |
| `Component.Spacer()` | `Plugin.Spacer()` |
If you edited a component's source in `quartz/components/` (for example `Footer.tsx`), that no longer works: components are now installed plugins. See [[customizing components]] for the v5 ways to change them.
## Updating Your CI/CD
Quartz 5 requires plugins to be installed before building. Add a plugin install step and (optionally) caching to your CI pipeline.
+1 -1
View File
@@ -113,7 +113,7 @@ npm install @quartz-community/syntax-highlighting
Or install all default plugins at once:
```bash
npm install @quartz-community/created-modified-date @quartz-community/syntax-highlighting @quartz-community/obsidian-flavored-markdown @quartz-community/github-flavored-markdown @quartz-community/table-of-contents @quartz-community/crawl-links @quartz-community/description @quartz-community/latex @quartz-community/quartz-fonts @quartz-community/remove-draft @quartz-community/alias-redirects @quartz-community/content-index @quartz-community/favicon @quartz-community/og-image @quartz-community/cname @quartz-community/canvas-page @quartz-community/content-page @quartz-community/folder-page @quartz-community/tag-page @quartz-community/explorer @quartz-community/graph @quartz-community/search @quartz-community/backlinks @quartz-community/article-title @quartz-community/content-meta @quartz-community/page-title @quartz-community/darkmode @quartz-community/reader-mode @quartz-community/breadcrumbs @quartz-community/footer @quartz-community/spacer @quartz-community/bases-page @quartz-community/note-properties @quartz-community/unlisted-pages @quartz-community/encrypted-pages
npm install @quartz-community/created-modified-date @quartz-community/syntax-highlighting @quartz-community/obsidian-flavored-markdown @quartz-community/github-flavored-markdown @quartz-community/table-of-contents @quartz-community/description @quartz-community/latex @quartz-community/quartz-fonts @quartz-community/alias-redirects @quartz-community/favicon @quartz-community/og-image @quartz-community/cname @quartz-community/canvas-page @quartz-community/content-page @quartz-community/folder-page @quartz-community/tag-page @quartz-community/explorer @quartz-community/graph @quartz-community/search @quartz-community/backlinks @quartz-community/article-title @quartz-community/content-meta @quartz-community/page-title @quartz-community/darkmode @quartz-community/reader-mode @quartz-community/breadcrumbs @quartz-community/footer @quartz-community/spacer @quartz-community/bases-page @quartz-community/note-properties @quartz-community/unlisted-pages @quartz-community/encrypted-pages
```
### Do I Have to Switch?
+2 -2
View File
@@ -56,7 +56,7 @@ Benefits:
- **No TypeScript knowledge required** for basic customization
- **JSON Schema validation** — editors with YAML support show errors inline
- **Layout defined per-plugin** — each plugin declares its own position and priority
- **Templates** — `npx quartz create` offers preconfigured templates (default, obsidian, ttrpg, blog)
- **Templates** — `npx quartz create` offers preconfigured templates (default, obsidian, ttrpg, blog, docs)
For advanced options that need JavaScript (callbacks, custom components), the `quartz.ts` override system provides full programmatic control.
@@ -70,7 +70,7 @@ Quartz 5 aims for full compatibility with Obsidian's core features:
- **Comments** — `%%hidden comments%%` (inline and block)
- **Tags** — `#tag` and `#nested/tag` with tag pages
- **Custom task characters** — `[?]`, `[!]`, `[>]`, etc. preserved as `data-task` attributes
- **Mermaid diagrams** — rendered with expand button
- **Mermaid diagrams** — Mermaid.js default; [Pele](https://pele.run) via `diagramRenderer: pele`
- **YouTube and Tweet embeds** — via image syntax
- **Block references** — `^block-id` with broad character support
- **Video/audio embeds** — full format support (mp4, webm, ogv, mov, mkv, avi, flac, aac, etc.)
+33 -14
View File
@@ -57,11 +57,14 @@ The `groupOptions` field on each plugin entry supports the following flex item p
The top-level `layout.groups` section configures the flex container itself:
| Option | Type | Description |
| ----------- | -------------------------------------------------------------- | ----------------------------------------- |
| `direction` | `"row"` \| `"row-reverse"` \| `"column"` \| `"column-reverse"` | Flex direction |
| `wrap` | `"nowrap"` \| `"wrap"` \| `"wrap-reverse"` | Flex wrap behavior |
| `gap` | `string` | Gap between flex items (e.g., `"0.5rem"`) |
| Option | Type | Description |
| ----------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `direction` | `"row"` \| `"row-reverse"` \| `"column"` \| `"column-reverse"` | Flex direction |
| `wrap` | `"nowrap"` \| `"wrap"` \| `"wrap-reverse"` | Flex wrap behavior |
| `gap` | `string` | Gap between flex items (e.g., `"0.5rem"`) |
| `priority` | `number` | Position of the whole group in its slot (defaults to its first member's priority) |
Groups work in the `header`, `beforeBody`, `afterBody`, `left` and `right` slots. Groups are formed per slot: members with different `position`s end up in separate groups. Avoid groups in the `footer` slot — the frames place footer components directly in the page grid, and a group wrapper is not assigned to the footer area.
### TS Override
@@ -127,11 +130,13 @@ plugins:
Available `display` values:
| Value | Description |
| -------------- | ------------------------------------- |
| `all` | Visible on all screen sizes (default) |
| `mobile-only` | Only visible on mobile devices |
| `desktop-only` | Only visible on desktop devices |
| Value | Description |
| -------------- | --------------------------------------------------------------------------- |
| `all` | Visible on all screen sizes (default) |
| `mobile-only` | Only visible below the `mobile` breakpoint (800px by default) |
| `desktop-only` | Hidden below the `mobile` breakpoint (visible on tablet and desktop widths) |
Any other value is ignored with a build warning.
### TS Override
@@ -174,15 +179,29 @@ Available built-in conditions:
### TS Override
For custom conditions that aren't covered by the built-in presets, use `Component.ConditionalRender()` in `quartz.ts`:
For custom conditions that aren't covered by the built-in presets, import the internal component utilities and the component you want to wrap in `quartz.ts`. Place `Component.ConditionalRender()` in the layout slot where the wrapped component should appear. For example, this renders Search in the left sidebar only for pages under `notes/`:
```ts title="quartz.ts (override)"
Component.ConditionalRender({
component: Plugin.Search(),
condition: (props) => props.displayClass !== "fullpage",
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
import * as Component from "./quartz/components"
import { Search } from "./.quartz/plugins/search"
const config = await loadQuartzConfig()
export default config
export const layout = await loadQuartzLayout({
defaults: {
left: [
Component.ConditionalRender({
component: Search(),
condition: (props) => props.fileData.slug?.startsWith("notes/") ?? false,
}),
],
},
})
```
The wrapped plugin must be installed and enabled in `quartz.config.yaml`. A TypeScript layout override replaces the selected slot, so include any other components you want to keep in that slot alongside the conditional component.
```typescript
type ConditionalRenderConfig = {
component: QuartzComponent
+76 -7
View File
@@ -7,7 +7,7 @@ Certain emitters may also output [HTML](https://developer.mozilla.org/en-US/docs
In v5, the layout is defined in `quartz.config.yaml`. Each plugin controls its own layout position via `layout.position` and `layout.priority` fields. The top-level `layout` section provides two additional mechanisms:
- `layout.groups` defines flex containers (like `toolbar`) that group multiple components into a single row or column. See [[layout-components]] for details.
- `layout.byPageType` contains per-page-type overrides (content, folder, tag, 404) for beforeBody, left, right sections, and optionally a `template` to control the page's [[#Page Frames|page frame]].
- `layout.byPageType` contains per-page-type overrides (content, folder, tag, 404, …): `exclude` plugins, clear slots with `positions`, and optionally a `template` to control the page's [[#Page Frames|page frame]]. See [[#Per-page-type overrides]].
Each page is composed of multiple different sections which contain `QuartzComponents`. The following code snippet lists all of the valid sections that you can add components to:
@@ -132,10 +132,57 @@ 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 |
| 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`) |
Plugins can register additional conditions. An unknown condition name prints a warning at build time and the component is always shown.
### Plugin layout fields
| Field | Required | Description |
| -------------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `position` | no | `header`, `beforeBody`, `afterBody`, `left`, `right` or `footer`. Defaults to the plugin's `defaultPosition`. |
| `priority` | no | Order within the slot, lower first. Defaults to the plugin's `defaultPriority`, else `50`. |
| `display` | no | `all` (default), `mobile-only`, `desktop-only` — see [[layout-components]]. |
| `condition` | no | One of the conditions above. |
| `group` | no | Name of a flex group from `layout.groups`. Works in every slot except `footer`. |
| `groupOptions` | no | Flex item options inside the group — see [[layout-components]]. |
Because `position` and `priority` fall back to the plugin's defaults, a layout block can contain only what you want to change, e.g. `layout: { condition: has-tags }`. A plugin without a `layout` block is placed at its default position (if it declares one).
Components with equal priority keep the order in which they appear in `quartz.config.yaml`; components placed by their plugin default come after explicitly configured ones.
### Per-page-type overrides
`layout.byPageType.<layout-key>` adjusts the layout for one page type. The key is the page type's layout name (`content`, `folder`, `tag`, `404`, `canvas`, `bases`, …).
| Field | Description |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `exclude` | Plugins to leave out on this page type. Use the plugin name (`reader-mode`); the full source (`@quartz-community/reader-mode`, `github:…/reader-mode`) works too. |
| `positions` | Clear slots: `right: []` removes everything from the right sidebar. Only empty lists are supported. |
| `template` | The [[#Page Frames\|page frame]] to use, e.g. `full-width` or `minimal`. |
Slots that a page type does not change follow the defaults.
### Checking your layout
Layout problems that would otherwise silently drop or misplace a component are reported as `⚠ Layout:` warnings during the build — for example an unknown `position` (with a "did you mean" hint), an unknown `display` or `condition`, a `layout` block for a plugin that provides no component, a plugin listed twice, or a `byPageType` entry that excludes a plugin that doesn't exist.
To see where every component ended up, run the build with `--verbose`:
```bash
npx quartz build --verbose
```
This prints, for the defaults and for each page type, every slot with its components in render order, their priority, whether the position came from your config or the plugin default, and any `display`, `condition` or `group`; plus the frame each page type uses and which slots that frame does not render.
### Mobile layout
On screens narrower than the `mobile` [[#Layout breakpoints|breakpoint]] the left sidebar becomes a single horizontal row at the top of the page — intended for compact components such as the page title, search, darkmode toggle and the explorer menu button. Taller components placed in `left` (recent notes, graph, table of contents, …) get squeezed into that row. Give them `display: desktop-only`, or place them in `right`/`afterBody`, which stack below the content on mobile.
See [[layout-components]] for more details on conditional rendering and display options.
@@ -161,7 +208,12 @@ export const layout = await loadQuartzLayout({
})
```
Fields defined in `defaults` can be overridden by specific entries in `byPageType`.
`loadQuartzConfig()` must be called first (as in the default `quartz.ts`); calling `loadQuartzLayout()` with overrides afterwards applies them to the layout used for rendering. For each slot the precedence is, from highest to lowest:
1. `byPageType` in `quartz.ts`
2. `layout.byPageType` changes in `quartz.config.yaml` (`exclude`, cleared `positions`)
3. `defaults` in `quartz.ts`
4. the layout built from each plugin's `layout` block
Community component plugins are installed via `npx quartz plugin add github:quartz-community/<name>`. See [[layout-components]] for built-in layout utilities (Flex, MobileOnly, DesktopOnly, etc.).
@@ -221,6 +273,23 @@ Frames are applied as a `data-frame` attribute on the `.page` element, which you
Frame CSS should be scoped with `[data-frame="name"]` selectors to avoid conflicts with other frames.
### Sidebar modes
`layout.sidebars` sets how each sidebar handles content taller than the screen:
```yaml title="quartz.config.yaml"
layout:
sidebars:
left: static
right: fit
```
- `fit` (default): the sidebar stays in view and is exactly one screen tall. Its components shrink and scroll themselves (the explorer and table of contents get their own scroll area).
- `scroll`: the sidebar stays in view, and scrolls itself when its components are taller than the screen. Components take their natural height, so nothing can end up out of reach.
- `static`: the sidebar scrolls away with the page, like most documentation sites. The [[create#Templates|docs template]] uses this for both sidebars.
The modes apply where a sidebar is a column: the left sidebar above mobile width, the right sidebar on desktop. A page type can override them with `byPageType.<type>.sidebars`, merged over `layout.sidebars`.
### Layout breakpoints
Quartz has different layouts depending on the width the screen viewing the website.
@@ -245,4 +314,4 @@ Most meaningful style changes like colour scheme and font can be done simply thr
You can see the base style sheet in `quartz/styles/base.scss` and write your own in `quartz/styles/custom.scss`.
> [!note]
> Some components may provide their own styling as well! Community plugins bundle their own styles. If you'd like to customize styling for a specific component, double check the component definition to see how its styles are defined.
> Some components may provide their own styling as well! Community plugins bundle their own styles. If you'd like to customize styling for a specific component, double check the component definition to see how its styles are defined. See also [[customizing components]].
+2
View File
@@ -33,6 +33,8 @@ The emitter supports the following frontmatter fields:
- `aliases`
- `alias`
A note with a `permalink` is published at its permalink, and its file path becomes a redirect as well: `notes/foo.md` with `permalink: foo` lives at `host.me/foo`, and `host.me/notes/foo` redirects there. An alias that is another page's address (or the page's own) is skipped with a warning, so a redirect never replaces a page.
### Case-Preserving Redirects
Quartz v5 normalizes all URLs to lowercase. If you are migrating from v4 (which preserved the original casing), previously indexed URLs containing uppercase letters (e.g. `/Diary/My-Note`) would return 404 errors.
+2 -2
View File
@@ -11,7 +11,7 @@ enabled: true
required: false
---
This plugin provides support for [Obsidian Bases](https://obsidian.md/changelog/2025-04-15-desktop-v1.8.0/) (`.base` files) in Quartz. It reads `.base` files from your vault, resolves matching notes based on the query definition, and renders them as interactive database-like views with support for tables, lists, cards, and maps. It uses the `default` [[layout#Page Frames|page frame]] (three-column layout with sidebars).
This plugin provides support for [Obsidian Bases](https://obsidian.md/help/bases) (`.base` files) in Quartz. It reads `.base` files from your vault, resolves matching notes based on the query definition, and renders them as interactive database-like views with support for tables, lists, cards, and maps. It uses the `default` [[layout#Page Frames|page frame]] (three-column layout with sidebars).
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
@@ -41,7 +41,7 @@ This plugin provides support for [Obsidian Bases](https://obsidian.md/changelog/
This plugin accepts the following configuration options:
- `defaultViewType`: The default view type when none is specified in the `.base` file. Defaults to `"table"`.
- `linkResolution`: How to resolve internal links in view renderers. Should match the `markdownLinkResolution` setting of the [[CrawlLinks]] plugin. Can be `"absolute"`, `"relative"`, or `"shortest"`. Defaults to `"shortest"`.
- `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.
### Default options
+25 -11
View File
@@ -1,22 +1,29 @@
---
title: ContentIndex
description: Generates sitemap, RSS feed, and content index.
description: Built-in content index, sitemap and RSS feed (formerly the content-index plugin). Configured under configuration.contentIndex.
aliases:
- contentIndex
- content-index
tags:
- plugin/emitter
- built-in
image:
repository: "[quartz-community/content-index](https://github.com/quartz-community/content-index)"
enabled: true
required: false
---
This plugin emits both RSS and an XML sitemap for your site. The [[RSS Feed]] allows users to subscribe to content on your site and the sitemap allows search engines to better index your site. The plugin also emits a `contentIndex.json` file which is used by dynamic frontend components like search and graph.
The content index is [[built-in processing|built into Quartz]] (it used to be the `content-index` plugin). It emits both RSS and an XML sitemap for your site. The [[RSS Feed]] allows users to subscribe to content on your site and the sitemap allows search engines to better index your site. It also emits a `contentIndex.json` file which is used by dynamic frontend components like search and graph.
This plugin emits a comprehensive index of the site's content, generating additional resources such as a sitemap, an RSS feed, and a
Configure it under `configuration.contentIndex` in `quartz.config.yaml`:
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
```yaml title="quartz.config.yaml"
configuration:
contentIndex:
enableSiteMap: true
enableRSS: true
```
This plugin accepts the following configuration options:
Options:
- `enableSiteMap`: If `true` (default), generates a sitemap XML file (`sitemap.xml`) listing all site URLs for search engines in content discovery.
- `enableRSS`: If `true` (default), produces an RSS feed (`index.xml`) with recent content updates.
@@ -24,10 +31,17 @@ This plugin accepts the following configuration options:
- `rssFullHtml`: If `true`, the RSS feed includes the full rendered HTML content of each page. Defaults to `false`.
- `rssSlug`: Slug to the generated RSS feed XML file. Defaults to `"index"`.
- `includeEmptyFiles`: If `true` (default), content files with no body text are included in the generated index and resources.
- `enabled`: set to `false` to emit none of these files ([[full-text search|search]], [[features/explorer|explorer]] and the [[graph view]] then have no data).
> [!note]
> An existing `@quartz-community/content-index` entry is applied to `configuration.contentIndex` automatically. Run `npx quartz plugin doctor --fix` to move it.
## Adding fields
Plugins can add their own fields to each entry of `contentIndex.json` with `extendContentIndex` — see [[making plugins#Extending the content index]].
## API
- Category: Emitter
- Function name: `ExternalPlugin.ContentIndex()`.
- Source: [`quartz-community/content-index`](https://github.com/quartz-community/content-index)
- Install: `npx quartz plugin add github:quartz-community/content-index`
- Category: Emitter (built-in)
- Source: [`quartz/plugins/builtins/contentIndex.ts`](https://github.com/jackyzha0/quartz/blob/v5/quartz/plugins/builtins/contentIndex.ts)
- Can be replaced by a plugin that declares `quartz.capabilities.provides.files: ["static/contentIndex.json"]`.
+23 -14
View File
@@ -1,22 +1,30 @@
---
title: CrawlLinks
description: Parses and resolves internal links. Removing it is not recommended.
description: Built-in link resolution (formerly the crawl-links plugin). Configured under configuration.links.
aliases:
- links
- crawl-links
tags:
- plugin/transformer
- built-in
image:
repository: "[quartz-community/crawl-links](https://github.com/quartz-community/crawl-links)"
enabled: true
required: true
---
This plugin parses links and processes them to point to the right places. It is also needed for embedded links (like images). See [[Obsidian compatibility]] for more information.
Link processing is [[built-in processing|built into Quartz]] (it used to be the `crawl-links` plugin). It rewrites links and embedded resources (images, videos, SVG embeds, …) so they point to the right place from any page, adds the `internal` / `external` / `alias` / `broken` classes, and records each page's outgoing links in `file.data.links` — used by [[features/backlinks|backlinks]], the [[graph view]], the content index and the `has-backlinks` layout condition. See [[Obsidian compatibility]] for more information.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
Configure it under `configuration.links` in `quartz.config.yaml`:
This plugin accepts the following configuration options:
```yaml title="quartz.config.yaml"
configuration:
links:
markdownLinkResolution: shortest
```
- `markdownLinkResolution`: Sets the strategy for resolving Markdown paths, can be `"absolute"` (default), `"relative"` or `"shortest"`. You should use the same setting here as in [[Obsidian compatibility|Obsidian]].
Options:
- `markdownLinkResolution`: Sets the strategy for resolving Markdown paths, can be `"absolute"`, `"relative"` or `"shortest"` (default; the `crawl-links` plugin defaulted to `"absolute"`). You should use the same setting here as in [[Obsidian compatibility|Obsidian]].
- `absolute`: Path relative to the root of the content folder.
- `relative`: Path relative to the file you are linking from.
- `shortest`: Name of the file. If this isn't enough to identify the file, use the full absolute path.
@@ -24,14 +32,15 @@ This plugin accepts the following configuration 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 this plugin runs.
- `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.
- `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.
> [!warning]
> Removing this plugin is _not_ recommended and will likely break the page.
> [!note]
> An existing `@quartz-community/crawl-links` entry in `quartz.config.yaml` is applied to `configuration.links` automatically. Run `npx quartz plugin doctor --fix` to move it.
## API
- Category: Transformer
- Function name: `ExternalPlugin.CrawlLinks()`.
- Source: [`quartz-community/crawl-links`](https://github.com/quartz-community/crawl-links)
- Install: `npx quartz plugin add github:quartz-community/crawl-links`
- Category: Transformer (built-in)
- Source: [`quartz/plugins/builtins/links.ts`](https://github.com/jackyzha0/quartz/blob/v5/quartz/plugins/builtins/links.ts)
- Can be replaced by a plugin that declares `quartz.capabilities.provides.data: ["links"]` (see [[built-in processing#Replacing a built-in]]).
+12 -9
View File
@@ -59,15 +59,18 @@ ExternalPlugin.CustomOgImages({
### Configuration Options
| Option | Type | Default | Description |
| -------------------- | --------- | ------------------------- | ----------------------------------------------------------------- |
| `colorScheme` | string | "lightMode" | Theme to use for generating images ("darkMode" or "lightMode") |
| `width` | number | 1200 | Width of the generated image in pixels |
| `height` | number | 630 | Height of the generated image in pixels |
| `excludeRoot` | boolean | false | Whether to exclude the root index page from auto-generated images |
| `defaultTitle` | string | "Untitled" | Fallback title when a page has no title |
| `defaultDescription` | string | "No description provided" | Fallback description when a page has no description |
| `imageStructure` | component | defaultImage | Custom component to use for image generation |
| Option | Type | Default | Description |
| ------------------------- | --------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `colorScheme` | string | "lightMode" | Theme to use for generating images ("darkMode" or "lightMode") |
| `width` | number | 1200 | Width of the generated image in pixels |
| `height` | number | 630 | Height of the generated image in pixels |
| `excludeRoot` | boolean | false | Whether to exclude the root index page from auto-generated images |
| `defaultTitle` | string | "Untitled" | Fallback title when a page has no title |
| `defaultDescription` | string | "No description provided" | Fallback description when a page has no description |
| `useGeneratedDescription` | boolean | true | Use a generated description (the [[Description]] plugin's excerpt of the page) when the frontmatter has none. Set to `false` to show `defaultDescription` instead |
| `imageStructure` | component | defaultImage | Custom component to use for image generation |
The description on an image is, in order: the frontmatter's `socialDescription`, its `description`, the generated description (unless `useGeneratedDescription` is `false`), and finally `defaultDescription`. With the [[Description]] plugin enabled, every page with text has a generated description, so `defaultDescription` mostly shows with `useGeneratedDescription: false`.
## Frontmatter Properties
+3
View File
@@ -16,6 +16,9 @@ This plugin filters content based on an explicit `publish` flag in the frontmatt
This plugin has no configuration options.
> [!tip]
> Images and other files are copied to your site whether or not a published page uses them. Set `configuration.publishAssets: referenced` to only publish the files that published pages link to or embed.
## API
- Category: Filter
+5 -2
View File
@@ -1,6 +1,6 @@
---
title: Footer
description: Page footer with configurable links.
description: Page footer with configurable links and text.
tags:
- plugin/component
image:
@@ -9,7 +9,7 @@ enabled: true
required: false
---
This plugin renders a footer at the bottom of the page with a "Created with Quartz" message and a set of configurable links.
This plugin renders a footer at the bottom of the page with a "Created with Quartz" message, an optional message of your own and a set of configurable links.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
@@ -19,6 +19,9 @@ This plugin renders a footer at the bottom of the page with a "Created with Quar
This plugin accepts the following configuration options:
- `links`: A map of link labels to their URLs to display in the footer. Defaults to `{}`.
- `message`: Extra text shown below the "Created with Quartz" line, e.g. a license notice or contact details. HTML is allowed: `'Licensed under <a href="/license">CC BY 4.0</a>'`. Not set by default.
To change the footer further (styles, different markup), see [[customizing components]].
### Default options
+28 -16
View File
@@ -3,10 +3,11 @@ title: Frontmatter
aliases:
- note-properties
- Note Properties
description: Parses frontmatter and displays note properties in a collapsible panel.
description: Built-in frontmatter parsing, plus the note-properties plugin that displays properties in a collapsible panel.
tags:
- plugin/transformer
- plugin/component
- built-in
publish: true
enableToc: true
image:
@@ -15,24 +16,37 @@ enabled: true
required: true
---
This plugin parses the frontmatter of the page using the [gray-matter](https://github.com/jonschlinkert/gray-matter) library and optionally displays selected properties in a collapsible panel. See [[authoring content#Syntax]], [[Obsidian compatibility]] and [[OxHugo compatibility]] for more information.
Frontmatter parsing is [[built-in processing|built into Quartz]]: every page's frontmatter is parsed with [gray-matter](https://github.com/jonschlinkert/gray-matter) and normalised (see [[#Supported frontmatter]]). Displaying properties on the page is done by the optional `note-properties` plugin ([[#Properties panel]]). See [[authoring content#Syntax]], [[Obsidian compatibility]] and [[OxHugo compatibility]] for more information.
## Parsing (built-in)
Configure it under `configuration.frontmatter` in `quartz.config.yaml`:
- `delimiters`: the delimiters to use for the frontmatter. Can have one value (e.g. `"---"`) or separate values for opening and closing delimiters (e.g. `["---", "~~~"]`). Defaults to `"---"`.
- `language`: the language to use for parsing the frontmatter. Can be `yaml` (default) or `toml`.
- `enabled`: set to `false` to turn parsing off — only useful when a plugin replaces it (see [[built-in processing#Replacing a built-in]]).
```yaml title="quartz.config.yaml"
configuration:
frontmatter:
language: toml
delimiters: "+++"
```
> [!note]
> These two options used to be set on the note-properties plugin. If they are still there, they are applied automatically; `npx quartz plugin doctor --fix` moves them.
## Properties panel plugin (note-properties)
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
> [!warning]
> This plugin must not be removed, otherwise Quartz will break.
The `note-properties` plugin accepts the following configuration options:
## Configuration
This plugin accepts the following configuration options:
- `delimiters`: the delimiters to use for the frontmatter. Can have one value (e.g. `"---"`) or separate values for opening and closing delimiters (e.g. `["---", "~~~"]`). Defaults to `"---"`.
- `language`: the language to use for parsing the frontmatter. Can be `yaml` (default) or `toml`.
- `includeAll`: include all frontmatter properties in the properties panel. When `false`, only `includedProperties` are shown. Defaults to `false`.
- `includedProperties`: properties to include when `includeAll` is `false`. Defaults to `["description", "tags", "aliases"]`.
- `excludedProperties`: properties to always exclude from display, even when `includeAll` is `true`. Defaults to `[]`.
- `hidePropertiesView`: hide the visual properties panel while still processing frontmatter. Useful if you only need frontmatter parsing without the UI. Defaults to `false`.
- `hidePropertiesView`: hide the visual properties panel by default (it can still be shown per note, see [[#Per-note overrides]]). Defaults to `false`. To never show it, disable the plugin — frontmatter is parsed either way.
### Default options
@@ -47,8 +61,6 @@ This plugin accepts the following configuration options:
- aliases
excludedProperties: []
hidePropertiesView: false
delimiters: "---"
language: yaml
```
## Properties panel
@@ -90,7 +102,7 @@ Quartz supports the following frontmatter fields. Where multiple keys are listed
| Description | `description` | Page description for metadata and search. |
| Tags | `tags`, `tag` | Categorization tags. Slugified the same way as file paths: spaces become `-`, `&` becomes `-and-`, `%` becomes `-percent`, and tags are lowercased so that `#MyTag` and `#mytag` resolve to the same tag page (matching Obsidian). |
| Aliases | `aliases`, `alias` | Alternative names for the page, used for link resolution. |
| Permalink | `permalink` | Custom URL slug. Also added to aliases. |
| Permalink | `permalink` | The page's address (Obsidian Publish): published at this path; its file path redirects there. |
| CSS classes | `cssclasses`, `cssclass` | CSS classes applied to the page body. |
| Social image | `socialImage`, `image`, `cover` | Image used for social media previews. |
| Social description | `socialDescription` | Description used specifically for social media previews. |
@@ -105,7 +117,7 @@ Quartz supports the following frontmatter fields. Where multiple keys are listed
## API
- Category: Transformer, Component
- Function name: `ExternalPlugin.NoteProperties()`.
- Parsing: built-in transformer, [`quartz/plugins/builtins/frontmatter.ts`](https://github.com/jackyzha0/quartz/blob/v5/quartz/plugins/builtins/frontmatter.ts)
- Properties panel: Transformer, Component — `ExternalPlugin.NoteProperties()`.
- Source: [`quartz-community/note-properties`](https://github.com/quartz-community/note-properties)
- Install: `npx quartz plugin add github:quartz-community/note-properties`
+4 -1
View File
@@ -9,7 +9,10 @@ enabled: false
required: false
---
This plugin automatically converts single line breaks in Markdown text into hard line breaks in the HTML output. This plugin is not enabled by default as this doesn't follow the semantics of actual Markdown but you may enable it if you'd like parity with [[Obsidian compatibility|Obsidian]].
> [!warning] Deprecated
> Line breaks are handled by [[ObsidianFlavoredMarkdown]] 2.0+: a single line break renders as a `<br>` by default (`preset: "legacy"`), as in Obsidian. Set its `strictLineBreaks` option to `true` to render it as a space instead. Remove this plugin (`npx quartz plugin remove hard-line-breaks`) unless your site doesn't use ObsidianFlavoredMarkdown; Quartz warns while it is enabled.
This plugin converts single line breaks in Markdown text into hard line breaks in the HTML output.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
+1 -1
View File
@@ -7,7 +7,7 @@ image:
new-in-v5: true
repository: "[quartz-community/note-properties](https://github.com/quartz-community/note-properties)"
enabled: true
required: true
required: false
---
The NoteProperties plugin is documented under [[Frontmatter]].
+9 -2
View File
@@ -16,11 +16,16 @@ This plugin provides support for [[Obsidian compatibility]].
This plugin accepts the following configuration options:
- `preset`: How Markdown is parsed (via [remark-obsidian](https://github.com/quartz-community/remark-obsidian)).
- `"legacy"` (default) parses exactly as Obsidian does, so pages render as they do in the app. It replaces Quartz's Markdown parser, so syntax extensions added by other plugins are not consulted, and only YAML (`---`) [[Frontmatter|frontmatter]] is recognized.
- `"strict"` parses CommonMark and GFM as specified, plus Obsidian's syntax, and keeps other plugins' syntax extensions working. Use it for TOML (`+++`) or custom frontmatter delimiters, or plugins that add Markdown syntax.
- `strictLineBreaks`: Obsidian's "Strict line breaks" setting. `false` (the default under `preset: "legacy"`) renders a single line break inside a paragraph as a `<br>`, as in Obsidian's default reading view. `true` (the default under `preset: "strict"`) renders it as a space, as CommonMark does. This replaces the deprecated [[HardLineBreaks]] plugin.
- `comments`: If `true` (default), enables parsing of `%%` style Obsidian comment blocks.
- `highlight`: If `true` (default), enables parsing of `==` style highlights within content.
- `wikilinks`:If `true` (default), turns [[wikilinks]] into regular links.
- `callouts`: If `true` (default), adds support for [[callouts|callout]] blocks for emphasizing content.
- `mermaid`: If `true` (default), enables [[Mermaid diagrams|Mermaid diagram]] rendering within Markdown files.
- `mermaid`: If `true` (default), enables [[Mermaid diagrams|Mermaid diagram]] parsing within Markdown files.
- `diagramRenderer`: `"mermaid"` (default) or `"pele"`. Which engine draws Mermaid fences. [Pele](https://pele.run) is opt-in; Mermaid.js is deprecated.
- `parseTags`: If `true` (default), parses and links tags within the content.
- `parseBlockReferences`: If `true` (default), handles block references, linking to specific content blocks.
- `enableInHtmlEmbed`: If `true`, allows embedding of content directly within HTML. Defaults to `false`.
@@ -30,8 +35,10 @@ This plugin accepts the following configuration options:
- `enableCheckbox`: If `true`, adds support for interactive checkboxes in content, including custom task characters (e.g. `- [?]`, `- [!]`, `- [/]`). Defaults to `false`.
- `enableObsidianUri`: If `true` (default), marks `obsidian://` protocol links with a CSS class and data attribute for custom styling.
Inline footnotes (`text^[note]`) are numbered together with regular footnotes.
> [!note]
> The `disableBrokenWikilinks` option previously lived on this plugin. It has moved to [[CrawlLinks]], which owns link resolution and can honor the configured `markdownLinkResolution` strategy when deciding whether a link is broken. Users upgrading from earlier Quartz v5 betas should move the option from `ObsidianFlavoredMarkdown` to `CrawlLinks`.
> The `disableBrokenWikilinks` option previously lived on this plugin. It has moved to the built-in [[CrawlLinks|link processing]] (`configuration.links.disableBrokenWikilinks`), which owns link resolution and can honor the configured `markdownLinkResolution` strategy when deciding whether a link is broken. Users upgrading from earlier Quartz v5 betas should move the option from `ObsidianFlavoredMarkdown` to `CrawlLinks`.
> [!warning]
> Don't remove this plugin if you're using [[Obsidian compatibility|Obsidian]] to author the content!
+1 -1
View File
@@ -25,7 +25,7 @@ This plugin accepts the following configuration options:
> [!warning]
> While you can use this together with [[ObsidianFlavoredMarkdown]], it's not recommended because it might mutate the file in unexpected ways. Use with caution.
>
> If you use `toml` frontmatter, make sure to configure the [[Frontmatter]] plugin accordingly. See [[OxHugo compatibility]] for an example.
> If you use `toml` frontmatter, make sure to set `configuration.frontmatter` accordingly (see [[Frontmatter]]). See [[OxHugo compatibility]] for an example.
## API
+21 -9
View File
@@ -1,24 +1,36 @@
---
title: RemoveDrafts
description: Filters out pages marked as drafts.
description: Built-in draft handling (formerly the remove-draft plugin). Pages with draft true are not published.
aliases:
- drafts
- remove-draft
tags:
- plugin/filter
- built-in
image:
repository: "[quartz-community/remove-draft](https://github.com/quartz-community/remove-draft)"
enabled: true
required: false
---
This plugin filters out content from your vault, so that only finalized content is made available. This prevents [[private pages]] from being published. By default, it filters out all pages with `draft: true` in the frontmatter and leaves all other pages intact.
Draft handling is [[built-in processing|built into Quartz]] (it used to be the `remove-draft` plugin): pages with `draft: true` in their frontmatter are not published. This prevents [[private pages]] from being published. All other pages are left intact.
Configure it under `configuration.drafts` in `quartz.config.yaml`:
- `publish`: set to `true` to publish drafts anyway, e.g. for a preview deployment. Defaults to `false`.
- `enabled`: `false` has the same effect as `publish: true`.
```yaml title="quartz.config.yaml"
configuration:
drafts:
publish: false
```
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
> An existing `@quartz-community/remove-draft` entry is handled automatically (a disabled entry means drafts are published). Run `npx quartz plugin doctor --fix` to move it.
This plugin has no configuration options.
For the opposite approach — only publish pages marked `publish: true` — enable [[ExplicitPublish]].
## API
- Category: Filter
- Function name: `ExternalPlugin.RemoveDrafts()`.
- Source: [`quartz-community/remove-draft`](https://github.com/quartz-community/remove-draft)
- Install: `npx quartz plugin add github:quartz-community/remove-draft`
- Category: Filter (built-in)
- Source: [`quartz/plugins/builtins/drafts.ts`](https://github.com/jackyzha0/quartz/blob/v5/quartz/plugins/builtins/drafts.ts)
+3 -3
View File
@@ -19,9 +19,9 @@ This plugin accepts the following configuration options:
- `orComponent`: If `true` (default), converts Roam `{{ or:ONE|TWO|THREE }}` shortcodes into HTML Dropdown options.
- `TODOComponent`: If `true` (default), converts Roam `{{[[TODO]]}}` shortcodes into HTML check boxes.
- `DONEComponent`: If `true` (default), converts Roam `{{[[DONE]]}}` shortcodes into checked HTML check boxes.
- `videoComponent`: If `true` (default), converts Roam `{{[[video]]:URL}}` shortcodes into embeded HTML video.
- `audioComponent`: If `true` (default), converts Roam `{{[[audio]]:URL}}` shortcodes into embeded HTML audio.
- `pdfComponent`: If `true` (default), converts Roam `{{[[pdf]]:URL}}` shortcodes into embeded HTML PDF viewer.
- `videoComponent`: If `true` (default), converts Roam `{{[[video]]:URL}}` shortcodes into embedded HTML video.
- `audioComponent`: If `true` (default), converts Roam `{{[[audio]]:URL}}` shortcodes into embedded HTML audio.
- `pdfComponent`: If `true` (default), converts Roam `{{[[pdf]]:URL}}` shortcodes into embedded HTML PDF viewer.
- `blockquoteComponent`: If `true` (default), converts Roam `{{[[>]]}}` shortcodes into Quartz blockquotes.
- `tableComponent`: If `true` (default), converts Roam table syntax into HTML tables.
- `attributeComponent`: If `true` (default), converts Roam attribute syntax into rendered attributes.
+1
View File
@@ -21,3 +21,4 @@ Want to see what Quartz can do? Here are some cool community gardens:
- [Ellie's Notes](https://ellie.wtf)
- [Eledah's Crystalline](https://blog.eledah.ir/)
- [🌓 Projects & Privacy - FOSS, tech, law](https://be-far.com)
- [Software Engineering Notes - DevBook](https://devbook.zip/)
File renamed without changes.
+45 -7
View File
@@ -4,6 +4,14 @@ title: Troubleshooting
Common issues and solutions when working with Quartz.
## Reading build output
- **Errors from plugins** say which plugin failed (name, version, source), what it was doing ("while transforming the Markdown of `notes/x.md`", "component Backlinks while rendering `features/x`"), any problems Quartz already knew about that plugin, and where to report it. To confirm a plugin is the cause, disable it (`npx quartz plugin disable <name>`) and build again.
- **Plugins that fail to load** (can't be installed, their code throws on import, no plugin found in the package) are marked `✗` with the file and line where it failed. Locally the build continues without them so you can check the rest of the site; they are listed again at the top of the end-of-build summary. In CI (`CI` set, e.g. GitHub Actions, Netlify, Vercel, Cloudflare Pages) the build fails instead, so a site with a missing feature isn't deployed — set `QUARTZ_ALLOW_BROKEN_PLUGINS=1` to deploy anyway.
- **Warnings** printed while loading the config (plugins that need a newer Quartz, plugins missing data they need, layout typos, plugin entries that are now built in) are repeated in a summary at the end of the build.
- **Notes** in that summary point out links to pages that are not on your site — including links to [[RemoveDrafts|drafts]], which are the usual cause of "this link 404s". `npx quartz build --verbose` lists every such link, the order plugins run in, the built-ins and the layout of each page type.
- **Which version am I on?** `npx quartz info` prints your Quartz version, environment and plugins — include it when asking for help (see [[versioning]]).
## Build Errors
### `Could not resolve ...` or missing module errors
@@ -34,12 +42,20 @@ The default uses all available CPU cores. If you're on a memory-constrained envi
## Plugin Issues
> [!tip]
> `npx quartz plugin doctor` checks your whole plugin setup — config typos, plugins that are not installed or not built, lockfile mismatches, option typos — and suggests a fix for each problem. Run it first.
### Plugin not loading after installation
1. Verify the plugin appears in `quartz.config.yaml` under `plugins:`
2. Check that `enabled: true` is set
3. Run `npx quartz plugin list` to confirm it's installed
4. Run `npx quartz plugin install --latest --dry-run` to verify plugin health
1. Run `npx quartz plugin doctor`
2. Verify the plugin appears in `quartz.config.yaml` under `plugins:`
3. Check that `enabled: true` is set (spelled `enabled`, as a boolean — `enable: true` or `enabled: "true"` do not work as expected)
4. Run `npx quartz plugin list` to confirm it's installed
5. Run `npx quartz plugin install --latest --dry-run` to check for updates
### Which plugin rendered this part of the page?
Open your browser's developer tools and inspect the element. Components provided by plugins carry `data-quartz-plugin` (the plugin name) and `data-quartz-component` (the component name) attributes on their root element. Look for the nearest ancestor with these attributes.
### Plugin options not taking effect
@@ -53,7 +69,7 @@ plugins:
myOption: value # correct: nested under options
```
A common mistake is putting options at the wrong indentation level.
A common mistake is putting options at the wrong indentation level. Misspelled option names are reported as warnings at the start of `npx quartz build` (e.g. `unknown option "folderDefaultStat" — did you mean "folderDefaultState"?`); `npx quartz plugin config <name>` shows the options you set next to the plugin's defaults.
### `ExternalPlugin.X is not a function`
@@ -109,7 +125,7 @@ If `plugin install` consistently fails near the same plugin with `-c 1`, the iss
### Notes not showing up
- Check that the file is in the `content/` folder
- Check that `draft: true` is not set in the frontmatter (the [[RemoveDrafts]] plugin filters these out)
- Check that `draft: true` is not set in the frontmatter (drafts are not published — see [[RemoveDrafts|built-in draft handling]]; `configuration.drafts.publish: true` publishes them)
- If using [[ExplicitPublish]], make sure `publish: true` is set in frontmatter
- Check your [[configuration]] `ignorePatterns` to make sure the file path is not excluded
@@ -155,7 +171,28 @@ If you want to start over, run `npx quartz restore` to recover your content from
- Make sure you're using `--serve` mode: `npx quartz build --serve`
- Check that port 3001 (WebSocket) is not blocked — this is the default `--wsPort` used for hot reload notifications
- If developing remotely, use `--remoteDevHost` to set the correct WebSocket URL
- If developing remotely, use `--remoteDevHost` to set the WebSocket hostname (the protocol follows the page: `wss` on HTTPS, `ws` otherwise)
### Changes on mounted or network content are not detected
Some network filesystems and Docker bind mounts do not forward directory change events. Enable
Chokidar polling so Quartz watches existing content files directly and periodically scans for added
or deleted files:
```shell
CHOKIDAR_USEPOLLING=true CHOKIDAR_INTERVAL=1000 npx quartz build --serve
```
In PowerShell:
```powershell
$env:CHOKIDAR_USEPOLLING = "true"
$env:CHOKIDAR_INTERVAL = "1000"
npx quartz build --serve
```
Polling uses more CPU and filesystem I/O than native events. Increase `CHOKIDAR_INTERVAL` when
watching a large content directory or when immediate updates are not required.
### Port already in use
@@ -170,3 +207,4 @@ npx quartz build --serve --port 3000
- Check the [GitHub Issues](https://github.com/jackyzha0/quartz/issues) for similar problems
- Ask in the [Discord Community](https://discord.gg/cRFFHYye7t)
- Run your command with `--verbose` for more detailed error output
- Include the output of `npx quartz info` in your question
+2581 -2618
View File
File diff suppressed because it is too large. Load diff
+64 -55
View File
@@ -19,7 +19,9 @@
"test": "tsx --test",
"profile": "0x -D prof ./quartz/bootstrap-cli.mjs build --concurrency=1",
"install-plugins": "npx tsx ./quartz/plugins/loader/install-plugins.ts",
"prebuild": "npm run install-plugins"
"prebuild": "npm run install-plugins",
"changeset": "changeset",
"version-packages": "changeset version && npm install --package-lock-only --ignore-scripts --no-audit --no-fund"
},
"engines": {
"npm": ">=10.9.2",
@@ -37,78 +39,82 @@
"quartz": "./quartz/bootstrap-cli.mjs"
},
"dependencies": {
"@clack/prompts": "^0.11.0",
"@clack/prompts": "^1.8.0",
"@floating-ui/dom": "^1.7.4",
"@myriaddreamin/rehype-typst": "^0.6.0",
"@napi-rs/simple-git": "0.1.22",
"@quartz-community/alias-redirects": "^0.1.0",
"@quartz-community/article-title": "^0.1.0",
"@quartz-community/backlinks": "^0.1.0",
"@quartz-community/bases-page": "^0.2.0",
"@quartz-community/breadcrumbs": "^0.1.0",
"@quartz-community/canvas-page": "^0.1.0",
"@quartz-community/citations": "^0.1.0",
"@quartz-community/cname": "^0.1.0",
"@quartz-community/comments": "^0.1.0",
"@quartz-community/content-index": "^0.1.0",
"@quartz-community/content-meta": "^0.1.0",
"@quartz-community/content-page": "^0.1.0",
"@quartz-community/crawl-links": "^0.1.0",
"@quartz-themes/core": "^1.0.0",
"@quartz-community/created-modified-date": "^0.1.0",
"@quartz-community/darkmode": "^0.1.0",
"@quartz-community/description": "^0.1.0",
"@quartz-community/encrypted-pages": "^0.1.0",
"@quartz-community/explicit-publish": "^0.1.0",
"@quartz-community/explorer": "^0.1.0",
"@quartz-community/favicon": "^0.1.1",
"@quartz-community/folder-page": "^0.1.0",
"@quartz-community/footer": "^0.1.0",
"@quartz-community/github-flavored-markdown": "^0.1.0",
"@quartz-community/graph": "^0.1.0",
"@quartz-community/hard-line-breaks": "^0.1.0",
"@quartz-community/latex": "^0.1.0",
"@quartz-community/note-properties": "^0.1.0",
"@quartz-community/obsidian-flavored-markdown": "^0.1.1",
"@quartz-community/og-image": "^0.1.1",
"@quartz-community/ox-hugo": "^0.1.0",
"@quartz-community/page-title": "^0.1.0",
"@quartz-community/quartz-fonts": "^0.1.1",
"@quartz-community/reader-mode": "^0.1.0",
"@quartz-community/recent-notes": "^0.1.0",
"@quartz-community/remove-draft": "^0.1.0",
"@quartz-community/roam": "^0.1.0",
"@quartz-community/search": "^0.1.0",
"@quartz-community/spacer": "^0.1.0",
"@quartz-community/stacked-pages": "^0.1.0",
"@quartz-community/syntax-highlighting": "^0.1.0",
"@quartz-community/table-of-contents": "^0.1.0",
"@quartz-community/tag-list": "^0.1.0",
"@quartz-community/tag-page": "^0.1.0",
"@quartz-community/unlisted-pages": "^0.1.0",
"@myriaddreamin/rehype-typst": "^0.7.0",
"@napi-rs/simple-git": "1.1.0",
"@quartz-community/alias-redirects": "^1.0.0",
"@quartz-community/article-title": "^1.0.0",
"@quartz-community/backlinks": "^1.0.0",
"@quartz-community/bases-page": "^1.0.0",
"@quartz-community/breadcrumbs": "^1.0.0",
"@quartz-community/canvas-page": "^1.0.0",
"@quartz-community/citations": "^1.0.0",
"@quartz-community/cname": "^1.0.0",
"@quartz-community/comments": "^1.0.0",
"@quartz-community/content-meta": "^1.0.0",
"@quartz-community/content-page": "^1.0.0",
"@quartz-community/created-modified-date": "^1.0.0",
"@quartz-community/darkmode": "^1.0.0",
"@quartz-community/description": "^1.0.0",
"@quartz-community/encrypted-pages": "^1.0.0",
"@quartz-community/explicit-publish": "^1.0.0",
"@quartz-community/explorer": "^1.0.0",
"@quartz-community/favicon": "^1.0.0",
"@quartz-community/folder-page": "^1.0.0",
"@quartz-community/footer": "^1.0.0",
"@quartz-community/github-flavored-markdown": "^2.0.0",
"@quartz-community/graph": "^1.0.0",
"@quartz-community/hard-line-breaks": "^1.0.0",
"@quartz-community/latex": "^1.0.0",
"@quartz-community/note-properties": "^1.1.1",
"@quartz-community/obsidian-flavored-markdown": "^2.0.0",
"@quartz-community/og-image": "^1.0.0",
"@quartz-community/ox-hugo": "^1.0.0",
"@quartz-community/page-title": "^1.0.0",
"@quartz-community/quartz-fonts": "^1.0.0",
"@quartz-community/reader-mode": "^1.0.0",
"@quartz-community/recent-notes": "^1.0.0",
"@quartz-community/roam": "^1.0.0",
"@quartz-community/search": "^1.0.0",
"@quartz-community/spacer": "^1.0.0",
"@quartz-community/stacked-pages": "^1.0.0",
"@quartz-community/syntax-highlighting": "^1.0.1",
"@quartz-community/table-of-contents": "^1.0.0",
"@quartz-community/tag-list": "^1.0.0",
"@quartz-community/tag-page": "^1.0.0",
"@quartz-community/unlisted-pages": "^1.0.0",
"@quartz-themes/core": "^2.0.0",
"ansi-truncate": "^1.4.0",
"async-mutex": "^0.5.0",
"chokidar": "^5.0.0",
"esbuild-sass-plugin": "^3.6.0",
"github-slugger": "^2.0.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-jsx-runtime": "^2.3.6",
"is-absolute-url": "^4.0.1",
"isomorphic-git": "^1.36.3",
"js-yaml": "^4.1.0",
"lightningcss": "^1.31.1",
"micromorph": "^0.4.5",
"minimatch": "^10.1.1",
"minimatch": "^11.0.5",
"preact": "^10.28.2",
"preact-render-to-string": "^6.6.5",
"pretty-bytes": "^7.1.0",
"pretty-time": "^1.1.0",
"remark-frontmatter": "^5.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"rfdc": "^1.4.1",
"semver": "^7.7.3",
"serve-handler": "^6.1.6",
"sharp": "^0.34.5",
"sharp": "^0.35.4",
"source-map-support": "^0.5.21",
"to-vfile": "^8.0.0",
"toml": "^5.0.1",
"unified": "^11.0.5",
"unist-util-visit": "^5.1.0",
"vfile": "^6.0.3",
@@ -118,15 +124,18 @@
"yargs": "^18.0.0"
},
"devDependencies": {
"@quartz-community/types": "^0.3.0",
"@quartz-community/utils": "^0.1.0",
"@changesets/cli": "^2.29.2",
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.0.1",
"@types/hast": "^3.0.4",
"@types/node": "^25.0.10",
"@types/js-yaml": "^4.0.9",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
"@types/semver": "^7.7.1",
"@types/source-map-support": "^0.5.10",
"@types/ws": "^8.18.1",
"@types/yargs": "^17.0.35",
"esbuild": "^0.27.2",
"esbuild": "^0.28.2",
"prettier": "^3.8.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
+8 -20
View File
@@ -40,6 +40,11 @@ configuration:
tertiary: "#84a59d"
highlight: rgba(143, 159, 169, 0.15)
textHighlight: "#b3aa0288"
links:
markdownLinkResolution: shortest
contentIndex:
enableSiteMap: true
enableRSS: true
plugins:
- source: "@quartz-community/created-modified-date"
enabled: true
@@ -58,14 +63,14 @@ plugins:
dark: github-dark
keepBackground: false
order: 20
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 30
- source: "@quartz-community/obsidian-flavored-markdown"
enabled: true
options:
enableInHtmlEmbed: false
enableCheckbox: true
order: 30
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 40
- source: "@quartz-community/table-of-contents"
enabled: true
@@ -73,11 +78,6 @@ plugins:
layout:
position: right
priority: 30
- source: "@quartz-community/crawl-links"
enabled: true
options:
markdownLinkResolution: shortest
order: 60
- source: "@quartz-community/description"
enabled: true
order: 70
@@ -89,9 +89,6 @@ plugins:
- source: "@quartz-community/citations"
enabled: false
order: 85
- source: "@quartz-community/hard-line-breaks"
enabled: false
order: 90
- source: "@quartz-community/ox-hugo"
enabled: false
order: 91
@@ -105,17 +102,10 @@ plugins:
options:
theme: tokyo-night
mode: both
- source: "@quartz-community/remove-draft"
enabled: true
- source: "@quartz-community/explicit-publish"
enabled: false
- source: "@quartz-community/alias-redirects"
enabled: true
- source: "@quartz-community/content-index"
enabled: true
options:
enableSiteMap: true
enableRSS: true
- source: "@quartz-community/favicon"
enabled: true
- source: "@quartz-community/og-image"
@@ -232,8 +222,6 @@ plugins:
- aliases
excludedProperties: []
hidePropertiesView: false
delimiters: ---
language: yaml
order: 5
layout:
position: beforeBody
+60 -4
View File
@@ -27,6 +27,7 @@ import {
handlePluginDisable,
handlePluginConfig,
handlePluginPrune,
handlePluginDoctor,
} from "./cli/plugin-git-handlers.js"
import { CommonArgv, BuildArgv, CreateArgv, SyncArgv } from "./cli/args.js"
import { version } from "./cli/constants.js"
@@ -39,8 +40,9 @@ async function launchTui() {
if (!existsSync(tuiPath)) {
console.error(
// installed from GitHub into .quartz/plugins (it is not published to npm)
"TUI plugin not installed. Install with:\n" +
" npx quartz plugin add @quartz-community/tui\n",
" npx quartz plugin add github:quartz-community/tui\n",
)
process.exit(1)
}
@@ -101,6 +103,15 @@ yargs(hideBin(process.argv))
.command("build", "Build Quartz into a bundle of static HTML files", BuildArgv, async (argv) => {
await handleBuild(argv)
})
.command(
"info",
"Print Quartz version, environment and plugins (paste it into bug reports)",
{ json: { boolean: true, default: false, describe: "Print JSON instead of Markdown" } },
async (argv) => {
const { handleInfo } = await import("./cli/info.js")
await handleInfo({ json: argv.json })
},
)
.command("tui", "Launch interactive plugin manager", CommonArgv, async () => {
await launchTui()
})
@@ -194,16 +205,39 @@ yargs(hideBin(process.argv))
)
.command(
"config <name>",
"View or set plugin configuration",
"View or set plugin options",
{
...CommonArgv,
set: {
string: true,
describe: "Set a config value (key=value)",
array: true,
describe:
"Set an option (key=value; value is parsed as JSON when possible; nested keys with a.b=value). Repeatable",
},
unset: {
string: true,
array: true,
describe: "Remove an option so the plugin default applies. Repeatable",
},
},
async (argv) => {
await handlePluginConfig(argv.name, { set: argv.set })
await handlePluginConfig(argv.name, { set: argv.set, unset: argv.unset })
},
)
.command(
"doctor",
"Check plugin config, lockfile and installs for problems",
{
...CommonArgv,
fix: {
boolean: true,
default: false,
describe:
"Rewrite quartz.config.yaml for plugins that are now built into Quartz (keeps comments)",
},
},
async (argv) => {
await handlePluginDoctor({ verbose: argv.verbose, fix: argv.fix })
},
)
.command(
@@ -274,6 +308,28 @@ yargs(hideBin(process.argv))
)
},
async (argv) => {
if (argv.subcommand !== undefined) {
const known = [
"install",
"add",
"remove",
"list",
"enable",
"disable",
"config",
"prune",
"doctor",
]
const { suggestClosest } = await import("./cli/plugin-validation.js")
const suggestion = suggestClosest(String(argv.subcommand), known)
console.error(
`Unknown plugin command "${argv.subcommand}".` +
(suggestion ? ` Did you mean "quartz plugin ${suggestion}"?` : "") +
`\nRun 'npx quartz plugin --help' to see all commands.`,
)
process.exitCode = 1
return
}
if (!argv._.includes("plugin") || argv._.length > 1) return
await handlePluginStatus()
},
+144 -19
View File
@@ -1,8 +1,9 @@
import sourceMapSupport from "source-map-support"
sourceMapSupport.install(options)
import path from "path"
import fs from "fs"
import { PerfTimer } from "./util/perf"
import { rm } from "fs/promises"
import { rm, readdir } from "fs/promises"
import { GlobbyFilterFunction, isGitIgnored } from "globby"
import { styleText } from "util"
import { parseMarkdown } from "./processors/parse"
@@ -22,6 +23,43 @@ import { getStaticResourcesFromPlugins } from "./plugins"
import { randomIdNonSecure } from "./util/random"
import { ChangeEvent } from "./plugins/types"
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 { collectPermalinks } from "./util/permalinks"
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
import { diffContentFiles, pollingEnabled } from "./util/contentWatcher"
/**
* Every page's address: permalinks (frontmatter `permalink`, read up front so links can resolve
* to them) and the slugified paths of all files. A permalinked note's file path stays in
* `allSlugs`: it becomes a redirect to the permalink.
*/
function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
const frontmatter = ctx.cfg.configuration.frontmatter
const enabled =
frontmatter !== false && (typeof frontmatter !== "object" || frontmatter.enabled !== false)
const options = typeof frontmatter === "object" ? frontmatter : {}
ctx.permalinks = enabled
? collectPermalinks({
files: allFiles.filter((fp) => fp.endsWith(".md")),
permalinkOf: (fp) => {
const source = fs.readFileSync(path.join(ctx.argv.directory, fp))
if (!source.includes("permalink")) return undefined
try {
return readFrontmatterData(source, options).permalink
} catch {
return undefined // reported when the file is parsed
}
},
warn: (message) => warn({ area: "permalinks", message }),
})
: {}
const pathSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
}
function reportSlugCollisions(content: ProcessedContent[]): void {
const collisions = detectSlugCollisions(content)
@@ -45,7 +83,7 @@ type BuildData = {
ignored: GlobbyFilterFunction
mut: Mutex
contentMap: ContentMap
changesSinceLastBuild: Record<FilePath, ChangeEvent["type"]>
changesSinceLastBuild: ChangeRecord
lastBuildMs: number
}
@@ -72,11 +110,36 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
console.log(` Filters: ${pluginNames("filters").join(", ")}`)
console.log(` Emitters: ${pluginNames("emitters").join(", ")}`)
console.log(` PageTypes: ${pluginNames("pageTypes").join(", ")}`)
const builtinPlan = getBuiltinPlan()
if (builtinPlan) {
console.log(` Built-ins:`)
for (const b of builtinPlan.builtins) {
const state = b.enabled ? `on (order ${b.order})` : `off — ${b.note ?? "disabled"}`
const from = b.absorbed?.enabled ? " · options from its former plugin entry" : ""
console.log(` configuration.${b.spec.configKey}: ${state}${b.enabled ? from : ""}`)
}
}
const pageTypes = (cfg.plugins.pageTypes ?? []).map((pt) => {
const { name, layout, frame } = pt as { name: string; layout?: unknown; frame?: unknown }
return {
name,
layout: typeof layout === "string" ? layout : name,
frame: typeof frame === "string" ? frame : undefined,
}
})
console.log(formatLayoutReport(getLayoutReport(), pageTypes))
}
const release = await mut.acquire()
perf.addEvent("clean")
await rm(output, { recursive: true, force: true })
try {
const entries = await readdir(output)
await Promise.all(
entries.map((e) => rm(path.join(output, e), { recursive: true, force: true })),
)
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err
}
console.log(`Cleaned output directory \`${output}\` in ${perf.timeSince("clean")}`)
perf.addEvent("glob")
@@ -88,7 +151,7 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
const filePaths = markdownPaths.map((fp) => joinSegments(argv.directory, fp) as FilePath)
ctx.allFiles = allFiles
ctx.allSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
updateSlugs(ctx, allFiles)
const parsedFiles = await parseMarkdown(ctx, filePaths)
reportSlugCollisions(parsedFiles)
@@ -98,6 +161,8 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
console.log(
styleText("green", `Done processing ${markdownPaths.length} files in ${perf.timeSince()}`),
)
// Repeat warnings from config loading (they scrolled away) and notes about the output.
printDiagnosticsSummary({ verbose: argv.verbose })
release()
if (argv.watch) {
@@ -157,10 +222,16 @@ async function startWatching(
lastBuildMs: 0,
}
const watcher = chokidar.watch(".", {
const contentRoot = path.resolve(argv.directory)
const usePerFilePolling = pollingEnabled(process.env.CHOKIDAR_USEPOLLING)
const knownFiles = new Set(allFiles.map((fp) => toPosixPath(fp.toString()) as FilePath))
const watcherTargets = usePerFilePolling
? Array.from(knownFiles, (fp) => path.resolve(contentRoot, fp))
: ["."]
const watcher = chokidar.watch(watcherTargets, {
awaitWriteFinish: { stabilityThreshold: 250 },
persistent: true,
cwd: argv.directory,
...(usePerFilePolling ? {} : { cwd: argv.directory }),
ignoreInitial: true,
})
@@ -175,27 +246,79 @@ async function startWatching(
})
}, 100)
}
const recordChange = (fp: string, type: ChangeEvent["type"]) => {
const relativePath = toPosixPath(
path.isAbsolute(fp) ? path.relative(contentRoot, fp) : fp,
) as FilePath
if (relativePath.startsWith("../") || buildData.ignored(relativePath)) return
if (type === "add") knownFiles.add(relativePath)
if (type === "delete") knownFiles.delete(relativePath)
changes.push({ path: relativePath, type })
scheduleRebuild()
}
watcher
.on("add", (fp) => {
fp = toPosixPath(fp)
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "add" })
scheduleRebuild()
recordChange(fp, "add")
})
.on("change", (fp) => {
fp = toPosixPath(fp)
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "change" })
scheduleRebuild()
recordChange(fp, "change")
})
.on("unlink", (fp) => {
fp = toPosixPath(fp)
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "delete" })
scheduleRebuild()
recordChange(fp, "delete")
})
let discoveryTimer: ReturnType<typeof setInterval> | undefined
if (usePerFilePolling) {
if (watcherTargets.length > 0) {
await new Promise<void>((resolve, reject) => {
watcher.once("ready", resolve)
watcher.once("error", reject)
})
}
const configuredInterval = Number.parseInt(process.env.CHOKIDAR_INTERVAL ?? "", 10)
const discoveryInterval = Math.max(
Number.isFinite(configuredInterval) && configuredInterval > 0 ? configuredInterval : 100,
1000,
)
let scanInProgress = false
const reconcileFileList = async () => {
if (scanInProgress) return
scanInProgress = true
try {
const scannedFiles = await glob("**/*.*", argv.directory, cfg.configuration.ignorePatterns)
const currentFiles = new Set(scannedFiles)
const { added, deleted } = diffContentFiles(knownFiles, currentFiles)
for (const fp of added) {
watcher.add(path.resolve(contentRoot, fp))
recordChange(fp, "add")
}
for (const fp of deleted) {
await watcher.unwatch(path.resolve(contentRoot, fp))
recordChange(fp, "delete")
}
} finally {
scanInProgress = false
}
}
discoveryTimer = setInterval(() => {
reconcileFileList().catch((err) => {
console.error(styleText("red", "Content scan failed:"), err.message ?? err)
})
}, discoveryInterval)
console.log(
`Watching ${knownFiles.size} content files in \`${contentRoot}\` using polling (ready)`,
)
}
return async () => {
if (discoveryTimer) clearInterval(discoveryTimer)
await watcher.close()
}
}
@@ -283,7 +406,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
// update allFiles and then allSlugs with the consistent view of content map
ctx.allFiles = Array.from(contentMap.keys())
ctx.allSlugs = ctx.allFiles.map((fp) => slugifyFilePath(fp as FilePath))
updateSlugs(ctx, ctx.allFiles)
const markdownContent = Array.from(contentMap.values())
.filter((file) => file.type === "markdown")
@@ -321,6 +444,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
// Phase 2: Run all other emitters with content extended by virtual pages
const contentWithVirtual =
ctx.virtualPages.length > 0 ? [...processedFiles, ...ctx.virtualPages] : processedFiles
prepareContentIndex(ctx, contentWithVirtual)
for (const emitter of cfg.plugins.emitters) {
if (emitter.name === "PageTypeDispatcher") continue
// Try to use partialEmit if available, otherwise assume the output is static
@@ -353,6 +477,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince("rebuild")}`,
)
console.log(styleText("green", `Done rebuilding in ${perf.timeSince()}`))
clearChangeRecord(changesSinceLastBuild)
changes.splice(0, numChangesInBuild)
clientRefresh()
} finally {
+83
View File
@@ -18,6 +18,7 @@ export type Analytics =
provider: "umami"
websiteId: string
host?: string
script?: string
}
| {
provider: "goatcounter"
@@ -28,6 +29,10 @@ export type Analytics =
| {
provider: "posthog"
apiKey: string
apiHost?: string
uiHost?: string
personProfiles?: "always" | "never" | "identified_only"
/** @deprecated Use `apiHost` instead. */
host?: string
}
| {
@@ -81,6 +86,69 @@ export interface GlobalConfiguration {
* Region Codes: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
*/
locale: ValidLocale
/** Built-in frontmatter parsing (title, tags, aliases, dates, …). See docs/features/built-in processing. */
frontmatter?: FrontmatterConfig | boolean
/** Built-in link resolution (relative hrefs, `file.data.links` for backlinks/graph). */
links?: LinksConfig | boolean
/** Built-in draft handling: pages with `draft: true` are not published. */
drafts?: DraftsConfig | boolean
/** Built-in content index: `static/contentIndex.json`, sitemap and RSS. */
contentIndex?: ContentIndexConfig | boolean
/**
* Controls which assets are copied to public/
* - "all": Copy all non-markdown files (backwards compatible, default)
* - "referenced": Only copy assets referenced by published pages
*/
publishAssets?: "all" | "referenced"
}
/** Shared by every built-in: `enabled: false` turns it off (e.g. to replace it with a plugin). */
interface BuiltinToggle {
enabled?: boolean
/** Position among plugins of the same category (same scale as plugin `order`). */
order?: number
}
export interface FrontmatterConfig extends BuiltinToggle {
/** Frontmatter delimiters. Default `"---"`. */
delimiters?: string | [string, string]
/** Frontmatter language. Default `"yaml"`. */
language?: "yaml" | "toml"
}
export interface LinksConfig extends BuiltinToggle {
/** How to resolve Markdown link paths. Default `"shortest"` (Obsidian's default). */
markdownLinkResolution?: "absolute" | "relative" | "shortest"
/** Strip folders from link text (`folder/note` → `note`). Default `true`. */
prettyLinks?: boolean
/** Open external links in a new tab. Default `false`. */
openLinksInNewTab?: boolean
/** Add `loading="lazy"` to images, videos, audio and iframes. Default `false`. */
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`. */
disableBrokenWikilinks?: boolean
}
export interface DraftsConfig extends BuiltinToggle {
/** Publish pages marked `draft: true` anyway. Default `false`. */
publish?: boolean
}
export interface ContentIndexConfig extends BuiltinToggle {
/** Emit `sitemap.xml`. Default `true`. */
enableSiteMap?: boolean
/** Emit an RSS feed. Default `true`. */
enableRSS?: boolean
/** Maximum number of RSS items. Default `10`. */
rssLimit?: number
/** Put the full page HTML in RSS items instead of the description. Default `false`. */
rssFullHtml?: boolean
/** Slug of the RSS feed (`index` → `index.xml`). Default `"index"`. */
rssSlug?: string
/** Include pages without text content. Default `true`. */
includeEmptyFiles?: boolean
}
export interface QuartzConfig {
@@ -100,6 +168,21 @@ export interface FullPageLayout {
footer: QuartzComponent[]
/** Page frame name (e.g. "default", "full-width", "minimal"). Defaults to "default". */
frame?: string
/** How each sidebar handles content taller than the screen (`layout.sidebars`). */
sidebars?: SidebarModes
}
/**
* - `fit` (default): the sidebar stays in view and is exactly one screen tall; components shrink
* and scroll themselves.
* - `scroll`: the sidebar stays in view and scrolls itself; components take their natural height.
* - `static`: the sidebar scrolls away with the page.
*/
export type SidebarMode = "fit" | "scroll" | "static"
export const SIDEBAR_MODES: readonly SidebarMode[] = ["fit", "scroll", "static"]
export interface SidebarModes {
left?: SidebarMode
right?: SidebarMode
}
export type PageLayout = Pick<FullPageLayout, "beforeBody" | "left" | "right">
+3 -2
View File
@@ -23,7 +23,7 @@ export const CreateArgv = {
template: {
string: true,
alias: ["t"],
choices: ["default", "obsidian", "ttrpg", "blog"],
choices: ["default", "obsidian", "ttrpg", "blog", "docs"],
describe: "template to use for initial configuration",
},
source: {
@@ -110,7 +110,8 @@ export const BuildArgv = {
remoteDevHost: {
string: true,
default: "",
describe: "A URL override for the websocket connection if you are not developing on localhost",
describe:
"hostname to use for the hot-reload WebSocket connection if you are not developing on localhost",
},
bundleInfo: {
boolean: true,
+181
View File
@@ -0,0 +1,181 @@
/**
* Migrate quartz.config.yaml entries of plugins that are now built into Quartz core
* (see quartz/plugins/builtins/index.ts):
*
* @quartz-community/crawl-links → configuration.links
* @quartz-community/remove-draft → configuration.drafts
* @quartz-community/content-index → configuration.contentIndex
* note-properties `delimiters` / `language` options → configuration.frontmatter
*
* Pure: takes the parsed config, returns a migrated copy and a list of human-readable changes.
* Used by `quartz plugin doctor --fix`. The build applies the same mapping on the fly
* (planBuiltins), so un-migrated configs keep working — this only makes it explicit.
*/
const ABSORBED = {
"crawl-links": {
key: "links",
defaultOrder: 60,
// crawl-links defaulted to "absolute"; the built-in defaults to "shortest"
legacyDefaults: { markdownLinkResolution: "absolute" },
},
"remove-draft": { key: "drafts", defaultOrder: 50, legacyDefaults: {} },
"content-index": { key: "contentIndex", defaultOrder: 50, legacyDefaults: {} },
}
const FRONTMATTER_DEFAULTS = { delimiters: "---", language: "yaml" }
/** Short name of an official quartz-community plugin source, else undefined (mirrors core). */
export function officialPluginName(source) {
if (source && typeof source === "object") return officialPluginName(source.repo)
if (typeof source !== "string") return undefined
const npm = source.match(/^@quartz-community\/([a-z0-9-]+)(?:@.*)?$/)
if (npm) return npm[1]
const github = source.match(
/^(?:github:|git\+https:\/\/github\.com\/|https:\/\/github\.com\/)quartz-community\/([a-z0-9-]+?)(?:\.git)?(?:#.*)?$/,
)
return github?.[1]
}
/** Entries that `migrateBuiltinEntries` would change (for doctor's report). */
export function findBuiltinMigrations(data) {
const plugins = Array.isArray(data?.plugins) ? data.plugins : []
const found = []
for (const entry of plugins) {
const name = officialPluginName(entry?.source)
if (name && ABSORBED[name]) {
found.push({ name, key: ABSORBED[name].key, entry })
} else if (name === "note-properties") {
const opts = entry?.options ?? {}
if ("delimiters" in opts || "language" in opts) {
found.push({ name, key: "frontmatter", entry })
}
}
}
return found
}
function isPlainObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value)
}
export function migrateBuiltinEntries(input) {
const data = structuredClone(input ?? {})
const changes = []
if (!Array.isArray(data.plugins)) return { data, changes }
data.configuration = isPlainObject(data.configuration) ? data.configuration : {}
const cfg = data.configuration
const kept = []
for (const entry of data.plugins) {
const name = officialPluginName(entry?.source)
const absorbed = name ? ABSORBED[name] : undefined
if (absorbed) {
const existing = cfg[absorbed.key]
const target = isPlainObject(existing)
? existing
: typeof existing === "boolean"
? { enabled: existing }
: {}
const moved = []
if (entry.enabled === false) {
if (absorbed.key === "drafts") {
if (target.publish === undefined && target.enabled === undefined) {
target.publish = true
moved.push("publish: true")
}
} else if (target.enabled === undefined) {
target.enabled = false
moved.push("enabled: false")
}
} else {
const options = { ...absorbed.legacyDefaults, ...(entry.options ?? {}) }
for (const [key, value] of Object.entries(options)) {
if (target[key] === undefined) {
target[key] = value
moved.push(key)
}
}
}
if (typeof entry.order === "number" && entry.order !== absorbed.defaultOrder) {
if (target.order === undefined) {
target.order = entry.order
moved.push("order")
}
}
if (Object.keys(target).length > 0) cfg[absorbed.key] = target
changes.push(
`${name}: removed from plugins (built into Quartz)` +
(moved.length > 0 ? `; moved ${moved.join(", ")} to configuration.${absorbed.key}` : ""),
)
continue
}
if (name === "note-properties" && isPlainObject(entry.options)) {
const moved = []
const target = isPlainObject(cfg.frontmatter) ? cfg.frontmatter : {}
for (const key of ["delimiters", "language"]) {
if (!(key in entry.options)) continue
const value = entry.options[key]
delete entry.options[key]
if (value === FRONTMATTER_DEFAULTS[key] || target[key] !== undefined) {
moved.push(`dropped ${key} (default or already set)`)
continue
}
target[key] = value
moved.push(`moved ${key} to configuration.frontmatter`)
}
if (Object.keys(target).length > 0) cfg.frontmatter = target
if (moved.length > 0) changes.push(`note-properties: ${moved.join(", ")}`)
}
kept.push(entry)
}
data.plugins = kept
return { data, changes }
}
/**
* When a CLI command names a plugin that is built into core now (by short name or official
* source), the configuration key to point the user to; otherwise undefined.
*/
export function builtinKeyFor(nameOrSource) {
// object sources: { repo: "github:quartz-community/crawl-links", … }
if (typeof nameOrSource?.repo === "string") nameOrSource = nameOrSource.repo
if (typeof nameOrSource !== "string") return undefined
const name = officialPluginName(nameOrSource) ?? nameOrSource
return ABSORBED[name]?.key
}
/** One-line explanation for CLI commands that target a built-in. */
export function builtinMessage(nameOrSource) {
const key = builtinKeyFor(nameOrSource)
if (!key) return undefined
if (typeof nameOrSource?.repo === "string") nameOrSource = nameOrSource.repo
const name = officialPluginName(nameOrSource) ?? nameOrSource
const toggle = key === "drafts" ? "publish: true" : "enabled: false"
return (
`${name} is built into Quartz now — configure it under configuration.${key} in quartz.config.yaml ` +
`(e.g. \`${key}: { ${toggle} }\`). See https://quartz.jzhao.xyz/features/built-in-processing`
)
}
/** Summary of the built-ins for `quartz plugin list`. */
export function describeBuiltins(configuration = {}) {
const rows = [
["frontmatter", "frontmatter parsing (titles, tags, aliases, dates)"],
["links", "link resolution, backlinks/graph data (was crawl-links)"],
["drafts", "hides `draft: true` pages (was remove-draft)"],
["contentIndex", "contentIndex.json, sitemap, RSS (was content-index)"],
]
return rows.map(([key, description]) => {
const value = configuration?.[key]
const enabled =
value === false || (isPlainObject(value) && value.enabled === false)
? false
: key === "drafts" && isPlainObject(value) && value.publish === true
? false
: true
return { key, description, enabled }
})
}
+152
View File
@@ -0,0 +1,152 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import YAML from "yaml"
import {
builtinKeyFor,
builtinMessage,
describeBuiltins,
findBuiltinMigrations,
migrateBuiltinEntries,
} from "./builtin-migration.js"
import { stringifyConfigYaml } from "./plugin-data.js"
const legacyConfig = () => ({
configuration: { pageTitle: "Site" },
plugins: [
{
source: "@quartz-community/note-properties",
enabled: true,
options: { includeAll: true, delimiters: "---", language: "toml" },
order: 5,
},
{
source: "@quartz-community/crawl-links",
enabled: true,
options: { lazyLoad: true },
order: 60,
},
{ source: "@quartz-community/remove-draft", enabled: true },
{ source: "@quartz-community/content-index", enabled: false },
{ source: "@quartz-community/graph", enabled: true },
],
})
describe("migrateBuiltinEntries", () => {
test("moves absorbed plugins into configuration and removes their entries", () => {
const { data, changes } = migrateBuiltinEntries(legacyConfig())
assert.deepStrictEqual(
data.plugins.map((p) => p.source),
["@quartz-community/note-properties", "@quartz-community/graph"],
)
// crawl-links' old default (absolute) is made explicit so behaviour does not change
assert.deepStrictEqual(data.configuration.links, {
markdownLinkResolution: "absolute",
lazyLoad: true,
})
assert.strictEqual(data.configuration.drafts, undefined) // enabled remove-draft = default
assert.deepStrictEqual(data.configuration.contentIndex, { enabled: false })
// note-properties keeps its view options; frontmatter options move, defaults are dropped
assert.deepStrictEqual(data.plugins[0].options, { includeAll: true })
assert.deepStrictEqual(data.configuration.frontmatter, { language: "toml" })
assert.strictEqual(changes.length, 4)
})
test("disabled remove-draft becomes drafts.publish: true; custom order is kept", () => {
const { data } = migrateBuiltinEntries({
plugins: [
{ source: "@quartz-community/remove-draft", enabled: false },
{ source: "github:quartz-community/crawl-links", enabled: true, order: 75 },
],
})
assert.deepStrictEqual(data.configuration.drafts, { publish: true })
assert.deepStrictEqual(data.configuration.links, {
markdownLinkResolution: "absolute",
order: 75,
})
})
test("existing configuration values win", () => {
const { data } = migrateBuiltinEntries({
configuration: { links: { markdownLinkResolution: "shortest" } },
plugins: [
{
source: "@quartz-community/crawl-links",
enabled: true,
options: { markdownLinkResolution: "relative" },
},
],
})
assert.strictEqual(data.configuration.links.markdownLinkResolution, "shortest")
})
test("leaves forks alone and does not mutate its input", () => {
const input = { plugins: [{ source: "github:someone/crawl-links", enabled: true }] }
const { data, changes } = migrateBuiltinEntries(input)
assert.deepStrictEqual(data.plugins, input.plugins)
assert.deepStrictEqual(changes, [])
const legacy = legacyConfig()
migrateBuiltinEntries(legacy)
assert.strictEqual(legacy.plugins.length, 5)
})
test("keeps comments when written back in place", () => {
const raw = [
"configuration:",
" pageTitle: Site # my title",
"plugins:",
" # links",
' - source: "@quartz-community/crawl-links"',
" enabled: true",
" # graph view",
' - source: "@quartz-community/graph"',
" enabled: true",
"",
].join("\n")
const { data } = migrateBuiltinEntries(YAML.parse(raw))
const out = stringifyConfigYaml(data, raw)
assert.match(out, /pageTitle: Site # my title/)
assert.match(out, /# graph view/)
assert.doesNotMatch(out, /crawl-links/)
assert.match(out, /links:\n\s+markdownLinkResolution: absolute/)
})
})
describe("built-in helpers", () => {
test("findBuiltinMigrations lists absorbed entries and note-properties frontmatter options", () => {
assert.deepStrictEqual(
findBuiltinMigrations(legacyConfig()).map((m) => [m.name, m.key]),
[
["note-properties", "frontmatter"],
["crawl-links", "links"],
["remove-draft", "drafts"],
["content-index", "contentIndex"],
],
)
})
test("builtinKeyFor / builtinMessage recognise names and official sources", () => {
assert.strictEqual(builtinKeyFor("crawl-links"), "links")
assert.strictEqual(builtinKeyFor("@quartz-community/content-index"), "contentIndex")
assert.strictEqual(builtinKeyFor("graph"), undefined)
assert.match(builtinMessage("remove-draft"), /configuration\.drafts.*publish: true/)
assert.strictEqual(builtinKeyFor({ repo: "github:quartz-community/crawl-links" }), "links")
assert.match(
builtinMessage({ repo: "github:quartz-community/crawl-links" }),
/^crawl-links is built into Quartz/,
)
assert.strictEqual(builtinKeyFor({ repo: "github:me/crawl-links-fork" }), undefined)
})
test("describeBuiltins reflects configuration", () => {
const rows = describeBuiltins({ links: false, drafts: { publish: true } })
assert.deepStrictEqual(
rows.map((r) => [r.key, r.enabled]),
[
["frontmatter", true],
["links", false],
["drafts", false],
["contentIndex", true],
],
)
})
})
+36
View File
@@ -0,0 +1,36 @@
export type RequirementStatus = "ok" | "incompatible" | "invalid" | "unknown" | "none"
export interface RequirementResult {
status: RequirementStatus
range: string | undefined
version: string | undefined
}
export interface QuartzCheckout {
describe?: string
commit?: string
branch?: string
dirty?: boolean
upstream?: string
origin?: string
}
export function readQuartzVersion(root?: string): string | undefined
export function checkQuartzRequirement(
range: unknown,
version: string | undefined,
): RequirementResult
export function describeRequirementProblem(
pluginName: string,
result: RequirementResult,
pluginVersion?: string,
): { message: string; hint: string } | undefined
export function describeDeprecation(
pluginName: string,
deprecated: unknown,
): { message: string; hint: string } | undefined
export function describeQuartzCheckout(root?: string): QuartzCheckout
export function formatQuartzVersion(version: string | undefined, checkout?: QuartzCheckout): string
export function incompatiblePluginsFailBuild(env?: Record<string, string | undefined>): boolean
export function brokenPluginsFailBuild(env?: Record<string, string | undefined>): boolean
export function isCI(env?: Record<string, string | undefined>): boolean
+142
View File
@@ -0,0 +1,142 @@
/**
* Quartz version and plugin compatibility helpers, shared by the CLI (plain Node) and the build
* (TypeScript, see compat.d.ts).
*
* Plugins declare the Quartz versions they work with in `package.json`:
*
* "quartz": { "quartzVersion": ">=5.1.0" }
*
* Any npm semver range works (`^5.1.0`, `>=5.1.0 <7`). Quartz checks it when loading the config
* (build, `plugin doctor`, `plugin add/install`) and names the requirement in error messages.
*/
import fs from "node:fs"
import path from "node:path"
import { execFileSync } from "node:child_process"
import semver from "semver"
const QUARTZ_PACKAGE = "@jackyzha0/quartz"
/** Version from Quartz's package.json (cwd = Quartz root for every CLI command). */
export function readQuartzVersion(root = process.cwd()) {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"))
if (pkg?.name === QUARTZ_PACKAGE && typeof pkg.version === "string") return pkg.version
} catch {}
return undefined
}
/**
* Check a plugin's `quartzVersion` range against the running Quartz version.
* Returns { status: "ok" | "incompatible" | "invalid" | "unknown" | "none", range, version }.
* Prereleases of a satisfying version count as satisfying (5.1.0-beta.1 satisfies >=5.1.0-0 and
* >=5.0.0), so pre-release testing works.
*/
export function checkQuartzRequirement(range, version) {
if (range === undefined || range === null || range === "") {
return { status: "none", range: undefined, version }
}
if (typeof range !== "string" || semver.validRange(range) === null) {
return { status: "invalid", range: String(range), version }
}
if (!version || semver.valid(version) === null) return { status: "unknown", range, version }
const ok = semver.satisfies(version, range, { includePrerelease: true })
return { status: ok ? "ok" : "incompatible", range, version }
}
/** One-line explanation + fix for an incompatible or invalid requirement (undefined when fine). */
export function describeRequirementProblem(pluginName, result, pluginVersion) {
const label = pluginVersion ? `${pluginName}@${pluginVersion}` : pluginName
if (result.status === "invalid") {
return {
message: `${label} declares quartzVersion "${result.range}", which is not a valid semver range (ignored).`,
hint: `Plugin authors: use e.g. ">=5.1.0" in package.json → quartz.quartzVersion.`,
}
}
if (result.status !== "incompatible") return undefined
const min = semver.minVersion(result.range)
const newer = min && semver.gt(min, result.version)
return {
message: `${label} requires Quartz ${result.range}, but this is Quartz ${result.version}.`,
hint: newer
? `Update Quartz (npx quartz upgrade), or use an older version of ${pluginName} that supports ${result.version}.`
: `${pluginName} does not support this Quartz version yet — check for a newer release of the plugin.`,
}
}
/**
* Whether incompatible plugins fail the build: in CI (`CI` set, as GitHub Actions, GitLab CI,
* Netlify, Vercel, Cloudflare Pages… do) unless QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS=1. Locally they
* only warn, so a site keeps building while you sort out versions.
*/
export function incompatiblePluginsFailBuild(env = process.env) {
if (env.QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS === "1") return false
return isCI(env)
}
/**
* Whether plugins that fail to load fail the build: in CI unless QUARTZ_ALLOW_BROKEN_PLUGINS=1.
* Locally the build continues without them (and says so), so the rest of the site can be checked.
*/
export function brokenPluginsFailBuild(env = process.env) {
if (env.QUARTZ_ALLOW_BROKEN_PLUGINS === "1") return false
return isCI(env)
}
/** `CI` set to anything but "", "0" or "false". */
export function isCI(env = process.env) {
const ci = env.CI
return ci !== undefined && ci !== "" && ci !== "0" && ci.toLowerCase() !== "false"
}
/**
* A plugin's `quartz.deprecated` message (a string, ideally naming its replacement) as a warning
* with a fix; undefined when the plugin isn't deprecated.
*/
export function describeDeprecation(pluginName, deprecated) {
if (typeof deprecated !== "string" || deprecated.trim() === "") return undefined
return {
message: `${pluginName} is deprecated: ${deprecated.trim()}`,
hint: `Remove it when you have switched: npx quartz plugin remove ${pluginName}`,
}
}
function git(root, args) {
try {
return execFileSync("git", args, {
cwd: root,
encoding: "utf8",
timeout: 3000,
stdio: ["ignore", "pipe", "ignore"],
}).trim()
} catch {
return undefined
}
}
/**
* Where this Quartz checkout is, in version terms: `git describe` against release tags
* (e.g. "v5.1.0", "v5.1.0-3-g1a2b3c4", "v5.1.0-3-g1a2b3c4-dirty"), plus commit and branch.
* All fields are undefined outside a git checkout.
*/
export function describeQuartzCheckout(root = process.cwd()) {
const describe = git(root, ["describe", "--tags", "--match", "v*", "--always", "--dirty"])
const commit = git(root, ["rev-parse", "--short", "HEAD"])
const branch = git(root, ["rev-parse", "--abbrev-ref", "HEAD"])
const dirtyFiles = git(root, ["status", "--porcelain", "--untracked-files=no"])
return {
describe,
commit,
branch: branch === "HEAD" ? undefined : branch,
dirty: dirtyFiles === undefined ? undefined : dirtyFiles.length > 0,
upstream: git(root, ["config", "--get", "remote.upstream.url"]),
origin: git(root, ["config", "--get", "remote.origin.url"]),
}
}
/** "5.1.0" or "5.1.0 (v5.1.0-3-g1a2b3c4-dirty)" when the checkout is not exactly a release. */
export function formatQuartzVersion(version, checkout) {
const v = version ?? "unknown"
const d = checkout?.describe
if (!d || d === `v${v}`) return v
return `${v} (${d})`
}
+148
View File
@@ -0,0 +1,148 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import {
checkQuartzRequirement,
describeDeprecation,
describeRequirementProblem,
formatQuartzVersion,
brokenPluginsFailBuild,
incompatiblePluginsFailBuild,
readQuartzVersion,
} from "./compat.js"
import { redactRemote, formatInfoMarkdown } from "./info.js"
describe("checkQuartzRequirement", () => {
test("real semver ranges", () => {
assert.strictEqual(checkQuartzRequirement(">=5.0.0", "5.0.0").status, "ok")
assert.strictEqual(checkQuartzRequirement(">=5.1.0", "5.0.0").status, "incompatible")
assert.strictEqual(checkQuartzRequirement("^5.1.0", "6.0.0").status, "incompatible")
assert.strictEqual(checkQuartzRequirement(">=5.1.0 <7", "6.2.0").status, "ok")
})
test("prereleases of a satisfying version count", () => {
assert.strictEqual(checkQuartzRequirement(">=5.0.0", "5.1.0-beta.1").status, "ok")
})
test("missing, invalid and unknown", () => {
assert.strictEqual(checkQuartzRequirement(undefined, "5.0.0").status, "none")
assert.strictEqual(checkQuartzRequirement("five", "5.0.0").status, "invalid")
assert.strictEqual(checkQuartzRequirement(">=5.0.0", undefined).status, "unknown")
})
})
describe("describeRequirementProblem", () => {
test("too old Quartz → suggests upgrading Quartz", () => {
const p = describeRequirementProblem(
"graph",
checkQuartzRequirement(">=5.1.0", "5.0.0"),
"2.0.0",
)
assert.match(p.message, /graph@2\.0\.0 requires Quartz >=5\.1\.0, but this is Quartz 5\.0\.0/)
assert.match(p.hint, /npx quartz upgrade/)
})
test("too new Quartz → suggests a newer plugin", () => {
const p = describeRequirementProblem("graph", checkQuartzRequirement("^5.0.0", "6.0.0"))
assert.match(p.hint, /newer release of the plugin/)
})
test("nothing to say when compatible", () => {
assert.strictEqual(
describeRequirementProblem("graph", checkQuartzRequirement(">=5.0.0", "5.0.0")),
undefined,
)
})
})
describe("incompatiblePluginsFailBuild", () => {
test("fails in CI, warns locally, can be overridden", () => {
assert.strictEqual(incompatiblePluginsFailBuild({}), false)
assert.strictEqual(incompatiblePluginsFailBuild({ CI: "true" }), true)
assert.strictEqual(incompatiblePluginsFailBuild({ CI: "1" }), true)
assert.strictEqual(incompatiblePluginsFailBuild({ CI: "false" }), false)
assert.strictEqual(incompatiblePluginsFailBuild({ CI: "0" }), false)
assert.strictEqual(
incompatiblePluginsFailBuild({ CI: "true", QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: "1" }),
false,
)
})
test("broken plugins have their own override", () => {
assert.strictEqual(brokenPluginsFailBuild({}), false)
assert.strictEqual(brokenPluginsFailBuild({ CI: "true" }), true)
assert.strictEqual(
brokenPluginsFailBuild({ CI: "true", QUARTZ_ALLOW_BROKEN_PLUGINS: "1" }),
false,
)
assert.strictEqual(
brokenPluginsFailBuild({ CI: "true", QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: "1" }),
true,
)
})
})
describe("describeDeprecation", () => {
test("turns quartz.deprecated into a warning with a fix", () => {
const d = describeDeprecation("hard-line-breaks", " Use OFM's strictLineBreaks. ")
assert.strictEqual(d.message, "hard-line-breaks is deprecated: Use OFM's strictLineBreaks.")
assert.match(d.hint, /npx quartz plugin remove hard-line-breaks/)
assert.strictEqual(describeDeprecation("x", undefined), undefined)
assert.strictEqual(describeDeprecation("x", ""), undefined)
assert.strictEqual(describeDeprecation("x", true), undefined)
})
})
describe("version display", () => {
test("readQuartzVersion reads this checkout's package.json", () => {
assert.match(readQuartzVersion() ?? "", /^\d+\.\d+\.\d+/)
})
test("formatQuartzVersion adds git describe only off a release", () => {
assert.strictEqual(formatQuartzVersion("5.1.0", { describe: "v5.1.0" }), "5.1.0")
assert.strictEqual(
formatQuartzVersion("5.1.0", { describe: "v5.1.0-3-g1a2b3c4-dirty" }),
"5.1.0 (v5.1.0-3-g1a2b3c4-dirty)",
)
assert.strictEqual(formatQuartzVersion(undefined, {}), "unknown")
})
})
describe("quartz info", () => {
test("redacts credentials in remote URLs", () => {
assert.strictEqual(
redactRemote("https://ghp_secret@github.com/me/quartz.git"),
"https://github.com/me/quartz.git",
)
assert.strictEqual(redactRemote("git@github.com:me/quartz.git"), "git@github.com:me/quartz.git")
})
test("markdown lists incompatible plugins prominently", () => {
const md = formatInfoMarkdown({
quartz: { display: "5.0.0 (abc1234-dirty)", branch: "main", modified: true },
environment: { node: "v22.0.0", npm: "10.0.0", os: "linux" },
config: { file: "quartz.config.yaml", plugins: 2, enabled: 2 },
builtins: [{ key: "links", enabled: true }],
plugins: [
{
name: "graph",
enabled: true,
version: "2.0.0",
source: "@quartz-community/graph",
quartzVersion: ">=5.1.0",
compatibility: "incompatible",
},
{
name: "mine",
enabled: true,
version: "0.1.0",
commit: "1a2b3c4",
source: "github:me/mine",
compatibility: "none",
},
],
})
assert.match(md, /\*\*Quartz:\*\* 5\.0\.0 \(abc1234-dirty\) — branch `main`, local changes/)
assert.match(md, /\*\*Incompatible plugins:\*\* graph \(needs Quartz >=5\.1\.0\)/)
assert.match(md, /\| mine \| yes \| 0\.1\.0 @1a2b3c4 \| github:me\/mine \| – \|/)
})
})
+68 -32
View File
@@ -9,12 +9,15 @@ import { rm } from "fs/promises"
import chokidar from "chokidar"
import prettyBytes from "pretty-bytes"
import { execSync, spawnSync } from "child_process"
import { pathToFileURL } from "url"
import http from "http"
import serveHandler from "serve-handler"
import { WebSocketServer } from "ws"
import { randomUUID } from "crypto"
import { Mutex } from "async-mutex"
import { CreateArgv } from "./args.js"
import { describeQuartzCheckout } from "./compat.js"
import { git } from "./subprocess.js"
import { globby } from "globby"
import {
exitIfCancel,
@@ -35,7 +38,6 @@ import {
createConfigFromTemplate,
readPluginsJson,
writePluginsJson,
extractPluginName,
updateGlobalConfig,
LOCKFILE_PATH,
} from "./plugin-data.js"
@@ -145,6 +147,11 @@ export async function handleCreate(argv) {
label: "Blog",
hint: "recent notes and comments enabled for blogging",
},
{
value: "docs",
label: "Documentation",
hint: "sidebars scroll with the page, for long navigation and tables of contents",
},
],
}),
)
@@ -283,19 +290,18 @@ See the [documentation](https://quartz.jzhao.xyz) for how to get started.
console.log(styleText("green", "Created quartz.config.yaml from defaults"))
}
// Update markdownLinkResolution in the crawl-links plugin options via YAML config
// Link resolution is built into Quartz (configuration.links)
const json = readPluginsJson()
if (json?.plugins) {
const crawlLinksIndex = json.plugins.findIndex(
(p) => extractPluginName(p.source) === "crawl-links",
)
if (crawlLinksIndex !== -1) {
json.plugins[crawlLinksIndex].options = {
...json.plugins[crawlLinksIndex].options,
markdownLinkResolution: linkResolutionStrategy,
}
writePluginsJson(json)
if (json) {
const links =
json.configuration?.links && typeof json.configuration.links === "object"
? json.configuration.links
: {}
json.configuration = {
...json.configuration,
links: { ...links, markdownLinkResolution: linkResolutionStrategy },
}
writePluginsJson(json)
}
// Update baseUrl in configuration
@@ -305,9 +311,7 @@ See the [documentation](https://quartz.jzhao.xyz) for how to get started.
await handlePluginResolve()
// setup remote
execSync(`git remote show upstream || git remote add upstream ${QUARTZ_SOURCE_REPO}`, {
stdio: "ignore",
})
ensureUpstreamRemote()
outro(`You're all set! Not sure what to do next? Try:
• Customizing Quartz a bit more by editing \`quartz.config.yaml\`
@@ -330,7 +334,12 @@ export async function handleBuild(argv) {
argv.watch = true
}
console.log(`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)} \n`)
// " 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 : ""
console.log(
`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)} ${describe ? styleText("gray", describe) : ""}\n`,
)
const ctx = await esbuild.context({
entryPoints: [fp],
outfile: cacheFile,
@@ -419,6 +428,8 @@ export async function handleBuild(argv) {
`${styleText("red", "Failed to build Quartz.")} Check for syntax errors in your configuration or plugins.`,
)
console.log(`Reason: ${styleText("gray", err.message ?? String(err))}`)
// stop esbuild's child process first: it shares our stderr and outlives us otherwise
void esbuild.stop()
process.exit(1)
})
release()
@@ -606,6 +617,15 @@ export async function handleBuild(argv) {
}
}
/** Add the `upstream` remote (the official Quartz repository) unless it exists. */
function ensureUpstreamRemote() {
try {
git(["remote", "get-url", UPSTREAM_NAME])
} catch {
git(["remote", "add", UPSTREAM_NAME, QUARTZ_SOURCE_REPO])
}
}
/**
* Handles `npx quartz upgrade`
* Upgrades the Quartz framework itself by pulling latest changes from upstream.
@@ -614,8 +634,9 @@ export async function handleBuild(argv) {
export async function handleUpgrade(argv) {
const contentFolder = resolveContentPath(argv.directory)
console.log(`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)} \n`)
const fromCommit = describeQuartzCheckout().commit
console.log("Backing up your content")
execSync(`git remote show upstream || git remote add upstream ${QUARTZ_SOURCE_REPO}`)
ensureUpstreamRemote()
await stashContentFolder(contentFolder)
const lockfileBackup = LOCKFILE_PATH + ".bak"
@@ -636,7 +657,7 @@ export async function handleUpgrade(argv) {
if (hasLockfile) {
try {
fs.copyFileSync(lockfileBackup, LOCKFILE_PATH)
execSync(`git add ${LOCKFILE_PATH}`)
git(["add", "--", LOCKFILE_PATH])
const remaining = execSync("git diff --name-only --diff-filter=U", {
encoding: "utf-8",
}).trim()
@@ -668,15 +689,6 @@ export async function handleUpgrade(argv) {
await popContentFolder(contentFolder)
// Read the new version after pulling
const newPkg = JSON.parse(fs.readFileSync("./package.json").toString())
const newVersion = newPkg.version
if (newVersion !== version) {
console.log(styleText("cyan", `Upgraded Quartz: v${version} → v${newVersion}`))
} else {
console.log(styleText("gray", `Quartz is already up to date (v${version})`))
}
console.log("Ensuring dependencies are up to date")
/*
@@ -706,11 +718,35 @@ export async function handleUpgrade(argv) {
)
}
console.log("Restoring plugins from lockfile...")
await handlePluginRestore()
console.log("Checking plugin compatibility...")
await handlePluginCheck()
// Finish with the *new* code (release notes, plugin restore, doctor) — see cli/upgrade.js.
// This process is still running the Quartz that was checked out before the pull.
const finishScript = path.resolve("quartz/cli/upgrade.js")
if (fs.existsSync(finishScript)) {
const script =
`import(${JSON.stringify(pathToFileURL(finishScript).href)})` +
`.then((m) => m.finishUpgrade(${JSON.stringify({ fromVersion: version, fromCommit })}))` +
`.catch((err) => { console.error(err); process.exitCode = 1 })`
const res = spawnSync(process.execPath, ["--input-type=module", "-e", script], {
stdio: "inherit",
timeout: 15 * 60 * 1000,
})
if (res.status !== 0) {
console.log(
styleText("yellow", "Some checks reported problems (see above).") +
" Run `npx quartz plugin doctor` after fixing them.",
)
process.exitCode = 1
return
}
} else {
// Upgraded to a Quartz without cli/upgrade.js (e.g. a downgrade): use this version's steps.
const newVersion = JSON.parse(fs.readFileSync("./package.json").toString()).version
console.log(styleText("cyan", `Quartz v${version} → v${newVersion}`))
console.log("Restoring plugins from lockfile...")
await handlePluginRestore()
console.log("Checking plugin compatibility...")
await handlePluginCheck()
}
console.log(styleText("green", "Done!"))
}
+186
View File
@@ -0,0 +1,186 @@
/**
* `quartz info`: everything needed to answer "which Quartz are you on?" in one paste.
*
* Prints a Markdown block for issues / Discord: Quartz version and where the checkout is relative
* to release tags (`git describe`), Node/npm/OS, the config file, built-ins, and every configured
* plugin with its installed version, source, commit (git plugins) and whether it supports this
* Quartz version. `--json` prints the same data as JSON.
*
* No content, baseUrl or option values are included.
*/
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { execFileSync } from "node:child_process"
import { styleText } from "node:util"
import {
checkQuartzRequirement,
describeQuartzCheckout,
formatQuartzVersion,
readQuartzVersion,
} from "./compat.js"
import { builtinKeyFor, describeBuiltins } from "./builtin-migration.js"
import { shortPluginName } from "./plugin-validation.js"
import {
readConfigWithDiagnostics,
readLockfile,
extractPluginName,
formatSource,
parseGitSource,
resolvePluginDir,
} from "./plugin-data.js"
function commandVersion(cmd, args = ["--version"]) {
try {
return execFileSync(cmd, args, {
encoding: "utf8",
timeout: 5000,
stdio: ["ignore", "pipe", "ignore"],
}).trim()
} catch {
return undefined
}
}
/** Strip credentials from remote URLs (https://token@github.com/… → https://github.com/…). */
export function redactRemote(url) {
if (!url) return url
return url.replace(/^(\w+:\/\/)[^@/]+@/, "$1")
}
function readPackage(dir) {
try {
return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"))
} catch {
return undefined
}
}
export function collectInfo(root = process.cwd()) {
const version = readQuartzVersion(root)
const checkout = describeQuartzCheckout(root)
const config = readConfigWithDiagnostics()
const lockfile = readLockfile()
const entries = Array.isArray(config.data?.plugins) ? config.data.plugins : []
const plugins = entries.map((entry) => {
const name = (() => {
try {
return shortPluginName(extractPluginName(entry.source))
} catch {
return String(entry?.source)
}
})()
const builtinNow =
builtinKeyFor(typeof entry?.source === "string" ? entry.source : entry?.source?.repo) !==
undefined
let installedVersion
let quartzVersion
let commit
if (!builtinNow) {
const dir = resolvePluginDir(entry.source)
const pkg = dir ? readPackage(dir) : undefined
installedVersion = pkg?.version
quartzVersion = pkg?.quartz?.quartzVersion
try {
const parsed = parseGitSource(entry.source)
if (!parsed.npmPackage) commit = lockfile?.plugins?.[parsed.name]?.commit?.slice(0, 7)
} catch {}
}
return {
name,
source: formatSource(entry.source),
enabled: entry.enabled === true,
version: installedVersion,
commit,
quartzVersion,
compatibility: builtinNow
? "built-in now"
: checkQuartzRequirement(quartzVersion, version).status,
}
})
return {
quartz: {
version,
display: formatQuartzVersion(version, checkout),
describe: checkout.describe,
commit: checkout.commit,
branch: checkout.branch,
modified: checkout.dirty,
origin: redactRemote(checkout.origin),
upstream: redactRemote(checkout.upstream),
},
environment: {
node: process.version,
npm: commandVersion("npm"),
os: `${os.platform()} ${os.release()} (${os.arch()})`,
},
config: {
file: config.exists ? path.basename(config.path) : null,
error: config.error ?? undefined,
plugins: entries.length,
enabled: plugins.filter((p) => p.enabled).length,
},
builtins: describeBuiltins(config.data?.configuration),
plugins,
}
}
const COMPAT_LABEL = {
ok: "✓",
none: "–",
unknown: "?",
invalid: "invalid range",
incompatible: "✗ incompatible",
"built-in now": "built in now",
}
export function formatInfoMarkdown(info) {
const q = info.quartz
const lines = []
lines.push("### Quartz info", "")
const where = [q.branch && `branch \`${q.branch}\``, q.modified && "local changes"]
.filter(Boolean)
.join(", ")
lines.push(`- **Quartz:** ${q.display}${where ? ` — ${where}` : ""}`)
if (q.origin)
lines.push(`- **Repository:** ${q.origin}${q.upstream ? ` (upstream ${q.upstream})` : ""}`)
lines.push(
`- **Environment:** Node ${info.environment.node}${info.environment.npm ? `, npm ${info.environment.npm}` : ""}, ${info.environment.os}`,
)
lines.push(
`- **Config:** ${info.config.file ?? "none"}${info.config.error ? ` (parse error: ${info.config.error})` : ""} — ${info.config.enabled} of ${info.config.plugins} plugins enabled`,
)
lines.push(
`- **Built-ins:** ${info.builtins.map((b) => `${b.key} ${b.enabled ? "on" : "off"}`).join(", ")}`,
)
const incompatible = info.plugins.filter((p) => p.enabled && p.compatibility === "incompatible")
if (incompatible.length > 0) {
lines.push(
`- **Incompatible plugins:** ${incompatible.map((p) => `${p.name} (needs Quartz ${p.quartzVersion})`).join(", ")}`,
)
}
lines.push("", "<details><summary>Plugins</summary>", "")
lines.push("| Plugin | Enabled | Version | Source | Supports this Quartz |")
lines.push("| --- | --- | --- | --- | --- |")
for (const p of info.plugins) {
const version = [p.version, p.commit && `@${p.commit}`].filter(Boolean).join(" ") || "–"
const compat = COMPAT_LABEL[p.compatibility] ?? p.compatibility
lines.push(
`| ${p.name} | ${p.enabled ? "yes" : "no"} | ${version} | ${p.source} | ${compat}${p.quartzVersion ? ` (${p.quartzVersion})` : ""} |`,
)
}
lines.push("", "</details>")
return lines.join("\n")
}
export async function handleInfo({ json = false } = {}) {
const info = collectInfo()
if (json) {
console.log(JSON.stringify(info, null, 2))
return
}
console.log(formatInfoMarkdown(info))
console.error(styleText("gray", "\nPaste the block above into your issue or support question."))
}
+198 -12
View File
@@ -1,7 +1,7 @@
import fs from "fs"
import path from "path"
import { execSync } from "child_process"
import YAML from "yaml"
import YAML, { isMap, isNode, isScalar, isSeq } from "yaml"
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
@@ -39,23 +39,163 @@ function readFileAsData(filePath) {
}
}
function writeDataToFile(filePath, data) {
const YAML_SCHEMA_HEADER =
"# yaml-language-server: $schema=./quartz/plugins/quartz-plugins.schema.json\n"
function isPlainObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value)
}
/** Identity used to match plugin entries between the old and new document. */
function sequenceItemKey(value) {
if (isPlainObject(value) && "source" in value) return JSON.stringify(value.source)
return null
}
function pairKey(pair) {
return isScalar(pair.key) ? pair.key.value : pair.key
}
/**
* Update an existing YAML node in place so that it represents `value`, keeping
* comments, quoting style and key order of everything that did not change.
* Returns the node to use (a new node when the shape changed).
*/
function syncYamlNode(doc, node, value) {
if (isPlainObject(value) && isMap(node)) {
for (const pair of [...node.items]) {
const key = pairKey(pair)
if (!Object.prototype.hasOwnProperty.call(value, key) || value[key] === undefined) {
node.delete(key)
}
}
for (const [key, child] of Object.entries(value)) {
if (child === undefined) continue
const pair = node.items.find((p) => pairKey(p) === key)
if (pair) {
pair.value = syncYamlNode(doc, pair.value, child)
} else {
node.add(doc.createPair(key, child))
}
}
return node
}
if (Array.isArray(value) && isSeq(node)) {
const oldItems = [...node.items]
const oldKeys = oldItems.map((item) => sequenceItemKey(isNode(item) ? item.toJS(doc) : item))
const newKeys = value.map(sequenceItemKey)
if (oldKeys.every((k) => k !== null) && newKeys.every((k) => k !== null)) {
// Plugin-entry style lists: match by `source` so removals/insertions
// keep the comments attached to the surviving entries.
const used = new Set()
node.items = value.map((child, i) => {
const idx = oldKeys.findIndex((k, j) => k === newKeys[i] && !used.has(j))
if (idx === -1) return doc.createNode(child)
used.add(idx)
return syncYamlNode(doc, oldItems[idx], child)
})
return node
}
node.items = value.map((child, i) =>
i < oldItems.length ? syncYamlNode(doc, oldItems[i], child) : doc.createNode(child),
)
return node
}
if (isScalar(node) && !isPlainObject(value) && !Array.isArray(value) && node.value === value) {
return node
}
const created = doc.createNode(value)
if (isNode(node)) {
if (node.comment) created.comment = node.comment
if (node.commentBefore) created.commentBefore = node.commentBefore
}
return created
}
/**
* Serialize `data` as YAML. When `existingRaw` (the current file contents) is
* given, the existing document is updated in place so user comments and
* formatting survive CLI edits.
*/
export function stringifyConfigYaml(data, existingRaw) {
if (typeof existingRaw === "string" && existingRaw.trim() !== "") {
const doc = YAML.parseDocument(existingRaw)
if (doc.errors.length === 0 && isMap(doc.contents)) {
doc.contents = syncYamlNode(doc, doc.contents, data)
const out = doc.toString({ lineWidth: 120 })
return out.includes("yaml-language-server:") ? out : YAML_SCHEMA_HEADER + out
}
}
return YAML_SCHEMA_HEADER + YAML.stringify(data, { lineWidth: 120 })
}
function writeDataToFile(filePath, data, baseRaw) {
if (filePath.endsWith(".yaml") || filePath.endsWith(".yml")) {
const header = "# yaml-language-server: $schema=./quartz/plugins/quartz-plugins.schema.json\n"
fs.writeFileSync(filePath, header + YAML.stringify(data, { lineWidth: 120 }))
fs.writeFileSync(filePath, stringifyConfigYaml(data, baseRaw))
} else {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n")
}
}
let reportedParseError = false
export function readPluginsJson() {
const configPath = resolveConfigPath()
return readFileAsData(configPath)
const data = readFileAsData(configPath)
if (data === null && fs.existsSync(configPath) && !reportedParseError) {
// Don't let a syntax error masquerade as "no config found".
const { error } = readConfigWithDiagnostics()
if (error) {
reportedParseError = true
console.error(`✗ Could not parse ${path.basename(configPath)}: ${error}`)
process.exitCode = 1
}
}
return data
}
/** Path of the config file the CLI reads from (may be a default/legacy file). */
export function getConfigReadPath() {
return resolveConfigPath()
}
/**
* Parse the config file and report YAML/JSON syntax errors instead of
* swallowing them. Returns { path, exists, data, error }.
*/
export function readConfigWithDiagnostics() {
const configPath = resolveConfigPath()
if (!fs.existsSync(configPath))
return { path: configPath, exists: false, data: null, error: null }
const raw = fs.readFileSync(configPath, "utf-8")
try {
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
const doc = YAML.parseDocument(raw)
if (doc.errors.length > 0) {
return { path: configPath, exists: true, data: null, error: doc.errors[0].message }
}
return { path: configPath, exists: true, data: doc.toJS(), error: null }
}
return { path: configPath, exists: true, data: JSON.parse(raw), error: null }
} catch (err) {
return { path: configPath, exists: true, data: null, error: String(err?.message ?? err) }
}
}
export function writePluginsJson(data) {
const { $schema, ...rest } = data
writeDataToFile(CONFIG_YAML_PATH, rest)
// Edit the user's file in place; when it does not exist yet, start from the
// file we read the config from (e.g. quartz.config.default.yaml) so its
// comments carry over.
let baseRaw
const basePath = fs.existsSync(CONFIG_YAML_PATH) ? CONFIG_YAML_PATH : resolveConfigPath()
if (fs.existsSync(basePath) && (basePath.endsWith(".yaml") || basePath.endsWith(".yml"))) {
baseRaw = fs.readFileSync(basePath, "utf-8")
}
writeDataToFile(CONFIG_YAML_PATH, rest, baseRaw)
}
function readDefaultPluginsJson() {
@@ -149,9 +289,44 @@ export function extractPluginName(source) {
const match = cleaned.match(/\/([^/]+?)(?:\.git)?(?:#|$)/)
return match?.[1] ?? url
}
if (isGithubShorthand(url)) {
return url.split("#")[0].split("/")[1]
}
return url
}
/** "owner/repo" or "owner/repo#ref" (GitHub shorthand without the `github:` prefix). */
function isGithubShorthand(url) {
return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(#.+)?$/.test(url) && !url.startsWith(".")
}
/** Valid source formats, used in error messages. */
export const SOURCE_FORMATS_HELP = [
"github:owner/repo[#ref] (or just owner/repo)",
"https://host/owner/repo.git[#ref]",
"git+https://host/owner/repo.git[#ref]",
"@scope/package (npm package)",
"./path, ../path, /abs/path (local directory)",
]
/**
* Directory a configured plugin lives in: node_modules for npm packages,
* .quartz/plugins/<name> for everything else. Returns null when unparseable.
*/
export function resolvePluginDir(source) {
let parsed
try {
parsed = parseGitSource(source)
} catch {
return null
}
if (parsed.npmPackage) {
const pkgName = getSourceUrl(source)
return path.join(process.cwd(), "node_modules", ...pkgName.split("/"))
}
return path.join(PLUGINS_DIR, parsed.name)
}
export function readManifestFromPackageJson(pluginDir) {
const pkgPath = path.join(pluginDir, "package.json")
if (!fs.existsSync(pkgPath)) return null
@@ -166,36 +341,47 @@ export function readManifestFromPackageJson(pluginDir) {
export function parseGitSource(source) {
const url = getSourceUrl(source)
const subdir = getSourceSubdir(source)
// Object sources may pin a ref with a dedicated `ref` field (takes precedence over #ref).
const objectRef =
typeof source === "object" && source !== null && typeof source.ref === "string"
? source.ref
: undefined
if (isLocalSource(url)) {
const resolved = path.resolve(url)
const name = typeof source === "object" && source.name ? source.name : path.basename(resolved)
return { name, url: resolved, ref: undefined, local: true, subdir }
}
if (url.startsWith("github:")) {
if (url.startsWith("github:") || isGithubShorthand(url)) {
const [repoPath, ref] = url.replace("github:", "").split("#")
const [owner, repo] = repoPath.split("/")
if (!owner || !repo) {
throw new Error(`Invalid GitHub source "${url}". Expected github:owner/repo`)
}
const name = typeof source === "object" && source.name ? source.name : repo
return { name, url: `https://github.com/${owner}/${repo}.git`, ref, subdir }
return { name, url: `https://github.com/${owner}/${repo}.git`, ref: objectRef ?? ref, subdir }
}
if (url.startsWith("git+")) {
const raw = url.replace("git+", "")
const [parsed, ref] = raw.split("#")
const name =
typeof source === "object" && source.name ? source.name : path.basename(parsed, ".git")
return { name, url: parsed, ref, subdir }
return { name, url: parsed, ref: objectRef ?? ref, subdir }
}
if (url.startsWith("https://")) {
const [parsed, ref] = url.split("#")
const name =
typeof source === "object" && source.name ? source.name : path.basename(parsed, ".git")
return { name, url: parsed, ref, subdir }
return { name, url: parsed, ref: objectRef ?? ref, subdir }
}
// Handle npm scoped packages
if (typeof url === "string" && url.startsWith("@") && url.includes("/") && !url.includes(":")) {
const name = typeof source === "object" && source.name ? source.name : url
return { name, url: "", npmPackage: true, subdir }
}
throw new Error(`Cannot parse plugin source: ${formatSource(source)}`)
throw new Error(
`Cannot parse plugin source "${formatSource(source)}". Supported formats:\n` +
SOURCE_FORMATS_HELP.map((f) => ` ${f}`).join("\n"),
)
}
export function getGitCommit(pluginDir) {
@@ -276,7 +462,7 @@ export function createConfigFromDefault() {
return rest
}
const VALID_TEMPLATES = ["default", "obsidian", "ttrpg", "blog"]
const VALID_TEMPLATES = ["default", "obsidian", "ttrpg", "blog", "docs"]
export function createConfigFromTemplate(templateName) {
if (!VALID_TEMPLATES.includes(templateName)) {
+94
View File
@@ -0,0 +1,94 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import YAML from "yaml"
import { stringifyConfigYaml, parseGitSource, extractPluginName } from "./plugin-data.js"
const ORIGINAL = `# yaml-language-server: $schema=./quartz/plugins/quartz-plugins.schema.json
configuration:
pageTitle: "My Garden" # site title
plugins:
# keep explorer first
- source: "@quartz-community/explorer" # inline note
enabled: true
layout:
position: left
priority: 50
# graph, tweaked
- source: "@quartz-community/graph"
enabled: true
options:
localGraph: { depth: 2 }
`
describe("stringifyConfigYaml", () => {
test("round-trips an unchanged document byte for byte", () => {
assert.strictEqual(stringifyConfigYaml(YAML.parse(ORIGINAL), ORIGINAL), ORIGINAL)
})
test("keeps comments and quoting when a value changes", () => {
const data = YAML.parse(ORIGINAL)
data.plugins[0].enabled = false
const out = stringifyConfigYaml(data, ORIGINAL)
assert.match(out, /# keep explorer first/)
assert.match(out, /"@quartz-community\/explorer" # inline note/)
assert.match(out, /pageTitle: "My Garden" # site title/)
assert.match(out, /# graph, tweaked/)
assert.deepStrictEqual(YAML.parse(out), data)
})
test("removing an entry keeps the comments of the others", () => {
const data = YAML.parse(ORIGINAL)
data.plugins.splice(0, 1)
const out = stringifyConfigYaml(data, ORIGINAL)
// (a comment directly above the first list item belongs to the list and is kept)
assert.doesNotMatch(out, /@quartz-community\/explorer/)
assert.match(out, /# graph, tweaked/)
assert.match(out, /localGraph: \{ depth: 2 \}/)
assert.deepStrictEqual(YAML.parse(out), data)
})
test("adds new entries and options", () => {
const data = YAML.parse(ORIGINAL)
data.plugins[0].options = { folderDefaultState: "open" }
data.plugins.push({ source: "github:me/thing", enabled: true })
const out = stringifyConfigYaml(data, ORIGINAL)
assert.deepStrictEqual(YAML.parse(out), data)
assert.match(out, /# keep explorer first/)
})
test("writes a schema header for brand-new files", () => {
const out = stringifyConfigYaml({ configuration: {}, plugins: [] })
assert.ok(out.startsWith("# yaml-language-server: $schema="))
})
test("falls back to a fresh document when the old one is invalid", () => {
const data = { configuration: { pageTitle: "x" }, plugins: [] }
const out = stringifyConfigYaml(data, "plugins: [\n")
assert.deepStrictEqual(YAML.parse(out), data)
})
})
describe("parseGitSource", () => {
test("accepts owner/repo shorthand like the build loader", () => {
const parsed = parseGitSource("quartz-community/spacer#dev")
assert.strictEqual(parsed.name, "spacer")
assert.strictEqual(parsed.url, "https://github.com/quartz-community/spacer.git")
assert.strictEqual(parsed.ref, "dev")
assert.strictEqual(extractPluginName("quartz-community/spacer"), "spacer")
})
test("uses the ref field of object sources", () => {
const parsed = parseGitSource({ repo: "github:me/mono", subdir: "pkg", ref: "v2" })
assert.strictEqual(parsed.ref, "v2")
assert.strictEqual(parsed.subdir, "pkg")
})
test("still treats @scope/name as npm", () => {
assert.strictEqual(parseGitSource("@quartz-community/explorer").npmPackage, true)
})
test("explains supported formats for unknown sources", () => {
assert.throws(() => parseGitSource("explorer"), /Supported formats/)
assert.throws(() => parseGitSource("github:onlyowner"), /Expected github:owner\/repo/)
})
})
File diff suppressed because it is too large. Load diff
+163
View File
@@ -0,0 +1,163 @@
import test, { describe, beforeEach, afterEach } from "node:test"
import assert from "node:assert"
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"
let root
let hostPreact
beforeEach(() => {
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "quartz-peers-test-")))
hostPreact = path.join(root, "quartz", "node_modules", "preact")
fs.mkdirSync(hostPreact, { recursive: true })
fs.writeFileSync(path.join(hostPreact, "package.json"), `{ "name": "preact" }`)
})
afterEach(() => {
fs.rmSync(root, { recursive: true, force: true })
})
describe("linkPeerPlugins", () => {
// outside the checkout, at a different depth from .quartz/plugins
function makeLocalPlugin() {
const source = path.join(root, "dev", "work", "my-plugin")
fs.mkdirSync(source, { recursive: true })
const pkg = { name: "my-plugin", peerDependencies: { preact: "^10.0.0" } }
fs.writeFileSync(path.join(source, "package.json"), JSON.stringify(pkg))
const pluginDir = path.join(root, "quartz", ".quartz", "plugins", "my-plugin")
fs.mkdirSync(path.dirname(pluginDir), { recursive: true })
fs.symlinkSync(source, pluginDir, "dir")
return { pluginDir, peer: path.join(source, "node_modules", "preact") }
}
test("links a local plugin's peer to Quartz's copy", () => {
const plugin = makeLocalPlugin()
linkPeerPlugins(plugin.pluginDir)
assert.strictEqual(fs.realpathSync(plugin.peer), hostPreact)
})
test("replaces a dangling link", () => {
const plugin = makeLocalPlugin()
fs.mkdirSync(path.dirname(plugin.peer), { recursive: true })
fs.symlinkSync(path.join(root, "missing"), plugin.peer, "dir")
linkPeerPlugins(plugin.pluginDir)
assert.strictEqual(fs.realpathSync(plugin.peer), hostPreact)
})
test("replaces a package manager's link to the plugin's own copy", () => {
const plugin = makeLocalPlugin()
const store = path.join(root, "store", "preact")
fs.mkdirSync(store, { recursive: true })
fs.mkdirSync(path.dirname(plugin.peer), { recursive: true })
fs.symlinkSync(store, plugin.peer, "dir")
linkPeerPlugins(plugin.pluginDir)
assert.strictEqual(fs.realpathSync(plugin.peer), hostPreact)
})
test("leaves an installed copy in place, and warns", (t) => {
const plugin = makeLocalPlugin()
fs.mkdirSync(plugin.peer, { recursive: true })
const warn = t.mock.method(console, "warn", () => {})
linkPeerPlugins(plugin.pluginDir)
assert.ok(!fs.lstatSync(plugin.peer).isSymbolicLink())
assert.strictEqual(warn.mock.callCount(), 1)
})
})
describe("buildPluginAsync", () => {
// a tarball npm installs offline; npm resolves no peers for a linked directory
function pack(pkg) {
const dir = path.join(root, "dev", pkg.name)
fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify(pkg))
execSync("npm pack --silent", { cwd: dir, stdio: "pipe" })
return path.join(dir, `${pkg.name}-${pkg.version}.tgz`)
}
// a cloned plugin built from source, with a dev copy of preact and a dependency that peers on
// it, as @quartz-community/utils does
function makeClonedPlugin() {
const pluginDir = path.join(root, "quartz", ".quartz", "plugins", "my-plugin")
fs.mkdirSync(pluginDir, { recursive: true })
const spec = (tarball) => `file:${path.relative(pluginDir, tarball).replaceAll(path.sep, "/")}`
const pkg = {
name: "my-plugin",
// a real entry point: an empty dist/ is reported as a failed build
scripts: {
build: `node -e "require('fs').mkdirSync('dist');require('fs').writeFileSync('dist/index.js','')"`,
},
dependencies: {
utils: spec(
pack({ name: "utils", version: "1.0.0", peerDependencies: { preact: "^10.0.0" } }),
),
},
peerDependencies: { preact: "^10.0.0" },
devDependencies: { preact: spec(pack({ name: "preact", version: "10.0.0" })) },
}
fs.writeFileSync(path.join(pluginDir, "package.json"), JSON.stringify(pkg))
fs.writeFileSync(path.join(pluginDir, ".gitignore"), "dist\n")
fs.writeFileSync(
path.join(pluginDir, ".npmrc"),
"audit=false\nfund=false\nupdate-notifier=false\n",
)
return { pluginDir, peer: path.join(pluginDir, "node_modules", "preact") }
}
test("links a cloned plugin's peers when npm did not start Quartz", async (t) => {
const plugin = makeClonedPlugin()
t.mock.method(console, "log", () => {})
// npm passes Quartz's .npmrc on to the commands it runs; a plain `node` launch does not
const legacyPeerDeps = process.env.npm_config_legacy_peer_deps
delete process.env.npm_config_legacy_peer_deps
try {
assert.ok(await buildPluginAsync(plugin.pluginDir, "my-plugin"))
} finally {
if (legacyPeerDeps !== undefined) process.env.npm_config_legacy_peer_deps = legacyPeerDeps
}
assert.strictEqual(fs.realpathSync(plugin.peer), hostPreact)
})
})
describe("pluginSourceChanged", () => {
test("is false when there is no prior lockfile record", () => {
// First-ever install: nothing to compare against, so this alone must not
// force a reinstall of an unrelated pre-existing directory.
assert.strictEqual(pluginSourceChanged(undefined, "github:owner/repo#main"), false)
})
test("is false when the source is unchanged", () => {
const priorEntry = { source: "github:owner/repo#main", resolved: "...", commit: "abc123" }
assert.strictEqual(pluginSourceChanged(priorEntry, "github:owner/repo#main"), false)
})
test("is true when the pinned ref changed", () => {
// This is the case `plugin install --from-config` used to miss entirely:
// the directory and lockfile entry both already exist, so the plugin was
// treated as "already installed" and never re-cloned even though its
// configured ref moved to a different branch.
const priorEntry = { source: "github:owner/repo#old-branch", resolved: "...", commit: "abc123" }
assert.strictEqual(pluginSourceChanged(priorEntry, "github:owner/repo#new-branch"), true)
})
test("object sources compare by content, not identity", () => {
const priorEntry = { source: { repo: "github:owner/repo", ref: "main" }, commit: "abc123" }
// read from YAML on every run, so never the same object as the lockfile's
assert.strictEqual(
pluginSourceChanged(priorEntry, { ref: "main", repo: "github:owner/repo" }),
false,
)
assert.strictEqual(
pluginSourceChanged(priorEntry, { repo: "github:owner/repo", ref: "dev" }),
true,
)
assert.strictEqual(pluginSourceChanged(priorEntry, "github:owner/repo#main"), true)
})
test("is true when the repo itself changed", () => {
const priorEntry = { source: "github:owner/old-repo", resolved: "...", commit: "abc123" }
assert.strictEqual(pluginSourceChanged(priorEntry, "github:owner/new-repo"), true)
})
})
+28
View File
@@ -0,0 +1,28 @@
export interface PluginIndexEntry {
overridable: string[]
passthrough: string[]
types: string[]
importPath: string
registryKey: string
}
export function parseExportsFromDts(content: string): string[]
export function isOverridableExport(
name: string,
dtsContent: string,
dtsPath?: string,
depth?: number,
): boolean
export function collectPluginExports(options: {
pluginsDir: string
npmPackages?: string[]
verbose?: boolean
}): Map<string, PluginIndexEntry>
export function renderPluginIndex(
entries: Map<string, PluginIndexEntry>,
options?: { warn?: (message: string) => void },
): string
export function writePluginIndex(options: {
pluginsDir: string
npmPackages?: string[]
verbose?: boolean
}): Map<string, PluginIndexEntry>
+230
View File
@@ -0,0 +1,230 @@
/**
* The generated plugin index (`.quartz/plugins/index.ts`), shared by `quartz plugin …` commands
* and the install step before a build (which used to keep two diverging copies of this code).
*
* `quartz.ts` imports it as `ExternalPlugin`. Every plugin factory or component constructor is
* wrapped: calling `ExternalPlugin.Explorer({...})` records the options as overrides (merged over
* the YAML options when Quartz instantiates the plugin) AND returns what the original returns, so
* it works both as a statement and as a component inside a layout override.
*
* Overrides are registered under the key the config loader looks them up by: the npm package name
* for npm plugins, the directory name for Git/local plugins (#2565).
*/
import fs from "node:fs"
import path from "node:path"
import { styleText } from "node:util"
import { isIdentifier, jsString } from "./subprocess.js"
const INTERNAL_EXPORTS = new Set(["manifest", "default"])
const PLUGIN_TYPE_PATTERN =
/Quartz(?:Emitter|Transformer|Filter|PageType)Plugin|QuartzComponentConstructor|\(.*\)\s*=>\s*QuartzComponent\b/
/** Exported names of a `.d.ts` (types prefixed with "type "), excluding external re-exports. */
export function parseExportsFromDts(content) {
const exports = []
const exportMatches = content.matchAll(/export\s*{\s*([^}]+)\s*}(?:\s*from\s*['"]([^'"]+)['"])?/g)
for (const match of exportMatches) {
const fromModule = match[2]
if (fromModule?.startsWith("@")) continue
const names = match[1]
.split(",")
.map((n) => n.trim())
.filter(Boolean)
for (const name of names) {
const cleanName = name.split(" as ").pop()?.trim() || name.trim()
if (cleanName && !cleanName.startsWith("_") && !INTERNAL_EXPORTS.has(cleanName)) {
const finalName = cleanName.replace(/^type\s+/, "")
exports.push(name.includes("type ") ? `type ${finalName}` : finalName)
}
}
}
return exports
}
function resolveOriginalName(exportName, dtsContent) {
const match = dtsContent.match(new RegExp(`(\\w+)\\s+as\\s+${exportName}\\b`))
return match ? match[1] : exportName
}
/**
* Whether an export is a plugin factory or component constructor. Follows relative re-exports
* (`export { Explorer } from './components/index.js'`), which is how most component plugins
* expose their constructor.
*/
export function isOverridableExport(name, dtsContent, dtsPath, depth = 0) {
const declName = resolveOriginalName(name, dtsContent)
const declPattern = new RegExp(`declare\\s+const\\s+${declName}\\s*:\\s*(.+?)(?:;|$)`, "m")
const match = dtsContent.match(declPattern)
if (match) return PLUGIN_TYPE_PATTERN.test(match[1])
if (!dtsPath || depth >= 4) return false
for (const reexport of dtsContent.matchAll(
/export\s*{\s*([^}]+)\s*}\s*from\s*['"](\.[^'"]+)['"]/g,
)) {
const entry = reexport[1]
.split(",")
.map((n) => n.trim().replace(/^type\s+/, ""))
.find((n) => (n.split(/\s+as\s+/).pop() ?? "").trim() === name)
if (!entry) continue
const original = entry.split(/\s+as\s+/)[0].trim()
const target = path.resolve(path.dirname(dtsPath), reexport[2].replace(/\.js$/, ".d.ts"))
if (!fs.existsSync(target)) return false
return isOverridableExport(original, fs.readFileSync(target, "utf-8"), target, depth + 1)
}
return false
}
/** Names `export { … }`-ed by the built JavaScript entry (to tell values from type-only names). */
function jsExportNames(jsIndex) {
const names = new Set()
if (!fs.existsSync(jsIndex)) return names
for (const m of fs.readFileSync(jsIndex, "utf-8").matchAll(/export\s*{\s*([^}]+)\s*}/g)) {
for (const n of m[1].split(",")) {
const clean = n
.trim()
.split(/\s+as\s+/)
.pop()
?.trim()
if (clean) names.add(clean)
}
}
return names
}
function classify(distIndex) {
const dtsContent = fs.readFileSync(distIndex, "utf-8")
const exported = parseExportsFromDts(dtsContent)
const dtsTypes = exported.filter((e) => e.startsWith("type ")).map((e) => e.slice(5))
const dtsNamed = exported.filter((e) => !e.startsWith("type "))
const jsExports = jsExportNames(path.join(path.dirname(distIndex), "index.js"))
const named = jsExports.size > 0 ? dtsNamed.filter((n) => jsExports.has(n)) : dtsNamed
const extraTypes = jsExports.size > 0 ? dtsNamed.filter((n) => !jsExports.has(n)) : []
const overridable = named.filter((n) => isOverridableExport(n, dtsContent, distIndex))
return {
overridable: overridable.filter(isIdentifier),
passthrough: named.filter((n) => !overridable.includes(n)).filter(isIdentifier),
types: [...dtsTypes, ...extraTypes].filter(isIdentifier),
}
}
/**
* Collect the exports of the installed Git/local plugins (`<pluginsDir>/<name>/dist`) and of the
* given npm packages. Returns entries keyed for the generated `plugins` map.
*/
export function collectPluginExports({ pluginsDir, npmPackages = [], verbose = false }) {
const entries = new Map()
const add = (key, info) => {
const { overridable, passthrough, types } = info
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) entries.set(key, info)
}
const dirs = fs.existsSync(pluginsDir)
? fs.readdirSync(pluginsDir).filter((n) => fs.statSync(path.join(pluginsDir, n)).isDirectory())
: []
for (const name of dirs) {
const distIndex = path.join(pluginsDir, name, "dist", "index.d.ts")
if (!fs.existsSync(distIndex)) {
if (verbose)
console.log(styleText("yellow", `⚠`), `Skipping ${name}: no dist/index.d.ts found`)
continue
}
add(name, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
}
for (const pkg of npmPackages) {
let distIndex
try {
const pkgJson = new URL(import.meta.resolve(`${pkg}/package.json`)).pathname
distIndex = path.join(path.dirname(decodeURIComponent(pkgJson)), "dist", "index.d.ts")
} catch {
if (verbose) console.log(styleText("yellow", `⚠`), `Skipping npm package ${pkg}: not found`)
continue
}
if (!fs.existsSync(distIndex)) {
if (verbose)
console.log(styleText("yellow", `⚠`), `Skipping npm package ${pkg}: no dist/index.d.ts`)
continue
}
const key = pkg.replace(/^@/, "").replace(/\//g, "__")
add(key, { ...classify(distIndex), importPath: pkg, registryKey: pkg })
}
return entries
}
/** Source of the generated index for collected entries. */
export function renderPluginIndex(entries, { warn = () => {} } = {}) {
const nameCount = new Map()
for (const { overridable, passthrough } of entries.values()) {
for (const n of [...overridable, ...passthrough]) nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
}
const unique = (n) => (nameCount.get(n) ?? 0) === 1
const lines = [`import { componentRegistry } from "../../quartz/components/registry"`, ""]
for (const { types, importPath } of entries.values()) {
if (types.length > 0)
lines.push(`export type { ${types.join(", ")} } from ${jsString(importPath)}`)
}
for (const { passthrough, importPath } of entries.values()) {
const names = passthrough.filter(unique)
if (names.length > 0) lines.push(`export { ${names.join(", ")} } from ${jsString(importPath)}`)
}
// The originals of wrapped exports, imported under collision-free local names
const alias = new Map()
let index = 0
for (const [key, { overridable, importPath }] of entries) {
if (overridable.length === 0) continue
const specifiers = overridable.map((n) => {
const local = `__quartzPlugin${index}_${n}`
alias.set(`${key}\u0000${n}`, local)
return `${n} as ${local}`
})
lines.push(`import { ${specifiers.join(", ")} } from ${jsString(importPath)}`)
index++
}
lines.push("")
lines.push(`type AnyFn = (...args: unknown[]) => unknown`)
lines.push(`export const plugins: Record<string, Record<string, AnyFn>> = {`)
for (const [key, { overridable, registryKey }] of entries) {
if (overridable.length === 0) continue
lines.push(` ${jsString(key)}: {`)
for (const n of overridable) {
lines.push(
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides(${jsString(registryKey)}, args[0] as Record<string, unknown>); return (${alias.get(`${key}\u0000${n}`)} as unknown as AnyFn)(...args) },`,
)
}
lines.push(` },`)
}
lines.push(`}`, "")
for (const [key, { overridable }] of entries) {
for (const n of overridable) {
if (unique(n)) {
lines.push(
`export const ${n} = plugins[${jsString(key)}].${n} as unknown as typeof ${alias.get(`${key}\u0000${n}`)}`,
)
} else {
warn(
`Export "${n}" conflicts across plugins — use plugins[${jsString(key)}].${n} in quartz.ts`,
)
}
}
}
lines.push("")
return lines.join("\n")
}
/** Collect, render and write `<pluginsDir>/index.ts`. */
export function writePluginIndex({ pluginsDir, npmPackages = [], verbose = false }) {
fs.mkdirSync(pluginsDir, { recursive: true })
const entries = collectPluginExports({ pluginsDir, npmPackages, verbose })
const source = renderPluginIndex(entries, {
warn: (message) => {
if (verbose) console.warn(styleText("yellow", `⚠`), message)
},
})
fs.writeFileSync(path.join(pluginsDir, "index.ts"), source)
return entries
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more