Compare commits

..
Author SHA1 Message Date
Emile Bangma 51bfc8f9e3 feat(explorer): Add active class to current folder in explorer 2025-11-06 21:40:15 +01:00
403 changed files with 14057 additions and 36675 deletions

No files matched your search

-13
View File
@@ -1,13 +0,0 @@
# 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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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>`.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
A plugin that lists a plugin now built into Quartz in `quartz.dependencies` (`@quartz-community/crawl-links`, `remove-draft` or `content-index`) no longer fails the build with "requires crawl-links. Run: npx quartz plugin add …". The built-in (`configuration.links`, `drafts`, `contentIndex`) satisfies the dependency. A warning is shown when that built-in is disabled. `npx quartz plugin doctor` checks the same way.
-15
View File
@@ -1,15 +0,0 @@
{
"$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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
More build errors caused by content are reported as content problems ("fix the file and build again") instead of "This is likely a Quartz bug": frontmatter that holds a single value or a list instead of properties, Markdown files and assets Quartz can't read (permission denied, a directory named like a note). Plugins can do the same by throwing an `Error` with `quartzContent = true` (see "Reporting problems in content" in Making plugins).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugins can declare `window.quartzStaticUrl` and `window.quartzPrefetch` in `capabilities.requires.globals` without a false "nothing provides it" warning: Quartz counts both as its own (`quartzPrefetch` unless `prefetch` is off).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
A plugin whose dependency is configured but disabled gets the intended warning ("depends on X which is disabled") instead of failing the build with "requires X. Run: npx quartz plugin add X".
-5
View File
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
The folder hierarchy used by folder pages and breadcrumbs now includes the pages of page types that render files (`.base`, `.canvas`, …): folder pages list them, and a folder that holds only such pages has its own node (#2576). Documented that while a page type's `generate` runs, `ctx.virtualPages` holds the virtual pages of the page types before it.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
French: "Vue graphique" and "Table des matières" use French capitalisation (jackyzha0/quartz#2513).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Embedding a section by the anchor Obsidian writes for its heading works when that anchor differs from the heading's id: `![[note#Colon unspaced]]` now embeds `## Colon:unspaced`. It needs GitHubFlavoredMarkdown 2.1.0 or later, which marks those anchors on the heading.
-5
View File
@@ -1,5 +0,0 @@
---
"@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.
-10
View File
@@ -1,10 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Links as in Obsidian 1.15.0:
- A Markdown link whose path is not valid percent-encoding (`[x](%zz)`, `[x](a%E2.md)`) is an external link. Before, it failed the whole build with `URI malformed`.
- Link paths are NFC-normalized, so a link spelled with a decomposed `é` reaches `café.md`.
- An image of a file the site doesn't have, with no alt text, gets its percent-decoded path as alt (`![](missing%20pic.png)` → “missing pic.png”), as Obsidian names a missing embed.
- A wikilink's `^id` no longer names its paragraph (Obsidian Flavored Markdown).
-5
View File
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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.
@@ -1,12 +0,0 @@
---
"@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.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugin option checks use the option schemas first-party plugins ship. These are declared as `quartz.optionSchema`, the name Quartz Syncer reads, as a flat map of option to type (`{ limit: { type: "number" }, mode: { type: "enum", values: [...] } }`). Before, only a JSON Schema in `quartz.configSchema` was read, so no first-party plugin's schema was used. A misspelled option, an enum value that isn't allowed, or a value of the wrong type is now a warning. A value of the same type as the plugin's default is always accepted, even where a schema disagrees.
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Tag pages honour the TagPage `numPages` and `sort` options (tag-page 1.0.4); before, they always used the defaults. Plugin client scripts can use `window.quartzStaticUrl` and `window.quartzPrefetch` with the declarations in `@quartz-community/types` 1.3.1.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
On Windows, regenerating `.quartz/plugins/index.ts` (`npm run install-plugins`, which also runs before every `npm run build`) no longer skips npm plugins with "dist/index.d.ts could not be found", which left exports such as `ExternalPlugin.Explorer` undefined. The package's location was read from a `file:` URL's pathname (`/C:/…`), which is not a Windows path.
-5
View File
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugin fixes for Windows: relative aliases (`./old`, `../x`) redirect to the right page (alias-redirects 1.0.3), and git dates of notes in folders are read from git instead of the filesystem (created-modified-date 1.0.3).
-12
View File
@@ -1,12 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Updated default plugins (see each plugin's changelog for details):
- **Changed heading ids:** with SmartyPants on (the default), a heading containing `--` now gets the same id as on GitHub: `## Range 1--2` → `range-1--2` (was `range-12`). Links that hard-code the old id need updating; `[[page#Range 1--2]]` keeps working. Links Obsidian writes to headings containing `:`, `|`, `^`, `#` or `\` now reach them, and heading ids, links and table-of-contents entries share one slug function (GitHubFlavoredMarkdown 2.1.0, TableOfContents, CrawlLinks, utils 1.1).
- **Bases now behave as in Obsidian 1.15** (BasesPage 1.2.0, checked against real Obsidian): subtracting dates gives a duration (`(due - today()).days`); nested tags match (`file.tags.contains("#project")` finds `#project/x`); dates display in the site's locale, and `date()` reads only ISO-style dates; cards use Obsidian's aspect ratio and layout; `link()` with any URL is an external link; a base opens on its first view; tags link to their tag pages; `this.<property>` in an embedded base reads the embedding note. Base views also list canvas and Excalidraw files with their real paths, `this` in an embedded base is that note, and Quartz's generated pages (404, tags, folder listings) no longer appear as notes. **Changed:** `file.tags` keeps `#` and the original case, the `tags` property no longer includes inline tags, `hasTag(a, b)` matches any of its tags, the root folder is `/`, text `contains` ignores case, and the cards' `imageAspectRatio` is height/width (it was inverted). `file.name` is as in Obsidian: a Markdown note's name has no extension (`Note`), other files keep theirs (`Plan.canvas`); `file.fullname` has the extension for every file.
- Folder pages list folders that hold only canvas, base or other generated pages (FolderPage).
- A footnote referenced only from a table cell past the table's columns is rendered, as in Obsidian (ObsidianFlavoredMarkdown 2.1.1, with remark-obsidian 2.2.0: faster parsing and fixes for deeply nested notes and `\r\n` line endings).
- A short wikilink to an Obsidian folder note (`[[Topic]]` for `Topic/Topic.md`) reaches the folder page (utils 1.1).
- NoteProperties no longer bundles gray-matter's `eval`-based JavaScript frontmatter engine.
-5
View File
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugins use Quartz's own Preact instead of each bundling a copy, so components can use hooks and context across plugins (a component using `preact/hooks` with another plugin's components crashed), and plugin bundles are smaller. The default plugins and the plugin template are updated; a third-party plugin made from the template before this release still bundles its own copy until it updates its `tsup.config.ts` (see quartz-community/plugin-template).
-11
View File
@@ -1,11 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Prefetching: Quartz fetches pages before their links are followed, so they open at once. New `configuration.prefetch`:
- `viewport` (default): links on screen are fetched while the browser is idle, and links pointed at, focused or touched first.
- `hover`: only links pointed at, focused or touched.
- `"off"`.
It works with and without SPA routing. With SPA routing, fetched pages are kept in memory (five minutes, at most 40) and used by both page navigation and popover previews, which no longer download a page the router fetches again. Without it, Quartz asks the browser to prefetch (Speculation Rules, or `<link rel="prefetch">`). Nothing is prefetched from links to other sites, files, or pages the site doesn't have, or with Data Saver on or a 2G connection (except links pointed at). Add `data-no-prefetch` to a link to exclude it. See https://quartz.jzhao.xyz/features/prefetching
-5
View File
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
The Roam Research plugin works with ObsidianFlavoredMarkdown on, as in the default config (roam 1.1.0). `{{[[TODO]]}}`, `{{[[DONE]]}}`, `[[>]]` and `{{[[video]]: …}}` no longer render as wikilinks, and `__italic__` is italic instead of bold.
-5
View File
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@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
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Sites created with `npx quartz create` from a template (default, blog, docs, obsidian, ttrpg) run GitHubFlavoredMarkdown before ObsidianFlavoredMarkdown (orders 30 and 40), as the default config does and 5.1 requires. The templates still had the old orders (40 and 30). The obsidian and ttrpg templates no longer set `parseArrows`, which ObsidianFlavoredMarkdown doesn't have.
-5
View File
@@ -1,5 +0,0 @@
---
"@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.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Pages that page types render from files (`.base`, `.canvas`, Excalidraw drawings) follow the site's publish filters (quartz-community/bases-page#11). The filters see each such page with the frontmatter its page type gives it and `file.data.referencedBy`, the published pages that link to it; a page a filter rejects is not emitted and not listed in the content index, sitemap, RSS, folder pages, explorer or search, and can't be embedded. Before, every such file was published regardless of the filters. New transformer hook `virtualPageHtmlPlugins(ctx, content)`: rehype plugins run on these pages' rendered bodies, which never pass through `htmlPlugins`, so plugins such as encrypted-pages can encrypt them.
@@ -1,7 +0,0 @@
---
"@jackyzha0/quartz": patch
---
A local plugin source written with Windows separators (`.\my-plugin`, `..\plugins\my-plugin`) is recognised as a local path. Before, it was read as a git or npm source and failed with "Expected github:owner/repo".
Pretty links shorten link text the same way on every OS: Windows also cut it at a backslash (`[[a\b]]` showed `b`).
+6 -12
View File
@@ -28,19 +28,13 @@ 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
**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.
**Desktop (please complete the following information):**
```
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.
- 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]
**Additional context**
Add any other context about the problem here.
-25
View File
@@ -4,36 +4,11 @@ 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:
+4 -15
View File
@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
name: Build Preview
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v5
with:
fetch-depth: 0
@@ -21,25 +21,14 @@ jobs:
node-version: 22
- name: Cache dependencies
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Cache Quartz plugins
uses: actions/cache@v5
with:
path: .quartz/plugins
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
restore-keys: |
${{ runner.os }}-plugins-
- run: npm install
- name: Install Quartz plugins
run: npx quartz plugin install
- run: npm ci
- name: Check types and style
run: npm run check
@@ -48,7 +37,7 @@ jobs:
run: npx quartz build -d docs -v
- name: Upload build artifact
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v5
with:
name: preview-build
path: public
+9 -27
View File
@@ -3,10 +3,10 @@ name: Build and Test
on:
pull_request:
branches:
- v5
- v4
push:
branches:
- v5
- v4
workflow_dispatch:
jobs:
@@ -19,35 +19,24 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version: 24
node-version: 22
- name: Cache dependencies
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Cache Quartz plugins
uses: actions/cache@v5
with:
path: .quartz/plugins
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
restore-keys: |
${{ runner.os }}-plugins-
- run: npm install
- name: Install Quartz plugins
run: npx quartz plugin install
- run: npm ci
- name: Check types and style
run: npm run check
@@ -58,26 +47,19 @@ 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' }}
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v4' }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version: 24
node-version: 22
- name: Get package version
run: node -p -e '`PACKAGE_VERSION=${require("./package.json").version}`' >> $GITHUB_ENV
- name: Create release tag
@@ -1,82 +0,0 @@
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
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
name: Deploy Preview to Cloudflare Pages
steps:
- name: Download build artifact
uses: actions/download-artifact@v8
uses: actions/download-artifact@v6
id: preview-build-artifact
with:
name: preview-build
-64
View File
@@ -1,64 +0,0 @@
name: Deploy v5 Preview
on:
push:
branches:
- v5
workflow_dispatch:
permissions:
contents: read
deployments: write
jobs:
deploy-v5:
if: ${{ github.repository == 'jackyzha0/quartz' }}
runs-on: ubuntu-latest
name: Deploy v5 to Cloudflare Pages
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version: 24
- name: Cache dependencies
uses: actions/cache@v5
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Cache Quartz plugins
uses: actions/cache@v5
with:
path: .quartz/plugins
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
restore-keys: |
${{ runner.os }}-plugins-
- run: npm install
- name: Install Quartz plugins
run: npx quartz plugin install
- name: Check types and style
run: npm run check
- name: Build Quartz
run: npx quartz build -d docs -v
- name: Deploy to Cloudflare Pages
uses: AdrianGonz97/refined-cf-pages-action@v1
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
githubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: quartz
deploymentName: v5 Branch Preview
branch: v5
directory: public
+11 -11
View File
@@ -2,10 +2,10 @@ name: Docker build & push image
on:
push:
branches: [v5]
branches: [v4]
tags: ["v*"]
pull_request:
branches: [v5]
branches: [v4]
paths:
- .github/workflows/docker-build-push.yaml
- quartz/**
@@ -21,15 +21,15 @@ jobs:
echo "OWNER_LOWERCASE=${OWNER,,}" >> ${GITHUB_ENV}
env:
OWNER: "${{ github.repository_owner }}"
- uses: actions/checkout@v6
- uses: actions/checkout@v5
with:
fetch-depth: 1
- name: Inject slug/short variables
uses: rlespinasse/github-slug-action@v5.6.0
uses: rlespinasse/github-slug-action@v5.3.0
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
with:
install: true
driver-opts: |
@@ -37,9 +37,9 @@ jobs:
network=host
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@v4.1.2
uses: sigstore/cosign-installer@v4.0.0
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
if: github.event_name != 'pull_request'
with:
registry: ghcr.io
@@ -49,7 +49,7 @@ jobs:
- name: Extract metadata tags and labels on PRs
if: github.event_name == 'pull_request'
id: meta-pr
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ env.OWNER_LOWERCASE }}/quartz
tags: |
@@ -59,7 +59,7 @@ jobs:
- name: Extract metadata tags and labels for main, release or tag
if: github.event_name != 'pull_request'
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
with:
flavor: |
latest=auto
@@ -76,7 +76,7 @@ jobs:
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@v7
uses: docker/build-push-action@v6
with:
push: ${{ github.event_name != 'pull_request' }}
build-args: |
-67
View File
@@ -1,67 +0,0 @@
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
-3
View File
@@ -9,6 +9,3 @@ tsconfig.tsbuildinfo
private/
.replit
replit.nix
.quartz/
quartz/cli/tui/dist/
.turbo/
-1
View File
@@ -1,2 +1 @@
engine-strict=true
legacy-peer-deps=true
+1 -15
View File
@@ -3,19 +3,5 @@
"quoteProps": "as-needed",
"trailingComma": "all",
"tabWidth": 2,
"semi": false,
"overrides": [
{
"files": "*.canvas",
"options": {
"parser": "json"
}
},
{
"files": "*.base",
"options": {
"parser": "yaml"
}
}
]
"semi": false
}
+1 -8
View File
@@ -1,15 +1,8 @@
FROM node:22-slim AS builder
# install git to install plugins
RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
WORKDIR /usr/src/app
COPY package.json .
COPY package-lock.json* .
COPY .npmrc* .
COPY quartz/ ./quartz/
COPY quartz.lock.json* .
RUN npm install; npx quartz plugin install
RUN npm ci
FROM node:22-slim
WORKDIR /usr/src/app
+2 -1
View File
@@ -1,8 +1,9 @@
# Quartz v5
# Quartz v4
> “[One] who works with the door open gets all kinds of interruptions, but [they] also occasionally gets clues as to what the world is and what might be important.” — Richard Hamming
Quartz is a set of tools that helps you publish your [digital garden](https://jzhao.xyz/posts/networked-thought) and notes as a website for free.
Quartz v4 features a from-the-ground rewrite focusing on end-user extensibility and ease-of-use.
🔗 Read the documentation and get started: https://quartz.jzhao.xyz/
-135
View File
@@ -1,135 +0,0 @@
filters:
and:
- file.ext == "md"
formulas:
doc_type: |
if(file.hasTag("plugin/transformer"), "transformer",
if(file.hasTag("plugin/emitter"), "emitter",
if(file.hasTag("plugin/filter"), "filter",
if(file.hasTag("component"), "component",
if(file.inFolder("features"), "feature",
if(file.inFolder("advanced"), "advanced",
if(file.inFolder("plugins"), "plugin",
if(file.inFolder("getting-started"), "getting-started",
if(file.inFolder("cli"), "cli", "guide")))))))))
last_modified: file.mtime.relative()
section: |
if(file.inFolder("plugins"), "plugins",
if(file.inFolder("features"), "features",
if(file.inFolder("advanced"), "advanced",
if(file.inFolder("getting-started"), "getting-started",
if(file.inFolder("cli"), "cli",
if(file.inFolder("tags"), "tags", "core"))))))
properties:
title:
displayName: Title
formula.doc_type:
displayName: Type
formula.last_modified:
displayName: Updated
formula.section:
displayName: Section
views:
- type: table
name: All Documentation
groupBy:
property: formula.section
direction: ASC
order:
- file.name
- title
- formula.doc_type
- formula.section
- formula.last_modified
sort:
- property: formula.doc_type
direction: ASC
- property: file.name
direction: ASC
columnSize:
file.name: 185
note.title: 268
formula.doc_type: 146
formula.section: 276
- type: table
name: Plugins
filters:
or:
- file.hasTag("plugin/transformer")
- file.hasTag("plugin/emitter")
- file.hasTag("plugin/filter")
groupBy:
property: formula.doc_type
direction: ASC
order:
- file.name
- title
- formula.doc_type
- formula.last_modified
- type: table
name: Components & Features
filters:
or:
- file.hasTag("component")
- file.inFolder("features")
order:
- file.name
- title
- formula.doc_type
- formula.last_modified
- type: list
name: Recently Updated
order:
- file.name
- formula.last_modified
limit: 15
- type: table
name: Core Guides
filters:
not:
- file.inFolder("plugins")
- file.inFolder("features")
- file.inFolder("advanced")
- file.inFolder("getting-started")
- file.inFolder("cli")
- file.inFolder("tags")
order:
- file.name
- title
- formula.last_modified
- type: board
name: By Type (Board)
groupBy:
property: formula.doc_type
direction: ASC
order:
- file.name
- title
- formula.last_modified
- type: gallery
name: Gallery
order:
- title
- formula.doc_type
- formula.section
limit: 30
- type: cards
name: Cards
order:
- file.name
- title
- formula.doc_type
- formula.section
- formula.last_modified
limit: 24
- type: cards
name: Image Cards
filters:
and:
- file.folder == "plugins"
- "!image.isEmpty()"
order:
- file.name
image: note.image
cardSize: 220
imageAspectRatio: 1
-321
View File
@@ -1,321 +0,0 @@
{
"nodes": [
{
"id": "group-node-types",
"type": "group",
"x": -30,
"y": 260,
"width": 1220,
"height": 460,
"color": "6",
"label": "Node Types"
},
{
"id": "group-config",
"type": "group",
"x": -30,
"y": 1180,
"width": 1220,
"height": 360,
"color": "2",
"label": "Configuration"
},
{
"id": "group-colors",
"type": "group",
"x": -30,
"y": 790,
"width": 1220,
"height": 320,
"color": "4",
"label": "Preset Colors"
},
{
"id": "group-edges",
"type": "group",
"x": -30,
"y": 1610,
"width": 1220,
"height": 320,
"color": "3",
"label": "Edges & Connections"
},
{
"id": "title",
"type": "text",
"text": "# CanvasPage Plugin\n\nThis plugin renders [JSON Canvas](https://jsoncanvas.org) (`.canvas`) files as interactive, pannable and zoomable canvas pages. It supports the full [JSON Canvas 1.0 spec](https://jsoncanvas.org/spec/1.0/).\n\nInstall: `npx quartz plugin add github:quartz-community/canvas-page`",
"x": 0,
"y": 0,
"width": 560,
"height": 200,
"color": "5"
},
{
"id": "text-node-demo",
"type": "text",
"text": "## Text Nodes\n\nText nodes render **Markdown** content with GFM support:\n\n- **Bold** and *italic* text\n- ~~Strikethrough~~ text\n- [External links](https://jsoncanvas.org)\n- `Inline code` blocks\n- Lists (like this one)\n\n### Headings Work Too\n\nAll standard Markdown syntax is rendered at build time.",
"x": 0,
"y": 300,
"width": 360,
"height": 280,
"color": "1"
},
{
"id": "file-node-info",
"type": "text",
"text": "## File Nodes\n\nFile nodes reference other pages in your vault. They appear as clickable links and support **popover previews** on hover.\n\nThe node below links to the CanvasPage documentation:",
"x": 400,
"y": 300,
"width": 360,
"height": 160,
"color": "2"
},
{
"id": "file-node-demo",
"type": "file",
"file": "plugins/CanvasPage.md",
"x": 400,
"y": 500,
"width": 360,
"height": 80,
"color": "4"
},
{
"id": "link-node-info",
"type": "text",
"text": "## Link Nodes\n\nLink nodes reference external URLs. The node below links to the JSON Canvas specification:",
"x": 800,
"y": 300,
"width": 360,
"height": 120,
"color": "3"
},
{
"id": "link-node-demo",
"type": "link",
"url": "https://jsoncanvas.org/spec/1.0/",
"x": 800,
"y": 460,
"width": 360,
"height": 80,
"color": "5"
},
{
"id": "color-1",
"type": "text",
"text": "**Color 1** — Red",
"x": 0,
"y": 830,
"width": 180,
"height": 80,
"color": "1"
},
{
"id": "color-2",
"type": "text",
"text": "**Color 2** — Orange",
"x": 200,
"y": 830,
"width": 180,
"height": 80,
"color": "2"
},
{
"id": "color-3",
"type": "text",
"text": "**Color 3** — Yellow",
"x": 400,
"y": 830,
"width": 180,
"height": 80,
"color": "3"
},
{
"id": "color-4",
"type": "text",
"text": "**Color 4** — Green",
"x": 600,
"y": 830,
"width": 180,
"height": 80,
"color": "4"
},
{
"id": "color-5",
"type": "text",
"text": "**Color 5** — Cyan",
"x": 800,
"y": 830,
"width": 180,
"height": 80,
"color": "5"
},
{
"id": "color-6",
"type": "text",
"text": "**Color 6** — Purple",
"x": 1000,
"y": 830,
"width": 180,
"height": 80,
"color": "6"
},
{
"id": "color-custom",
"type": "text",
"text": "**Custom hex color** — `#ff6600`",
"x": 400,
"y": 950,
"width": 380,
"height": 80,
"color": "#ff6600"
},
{
"id": "config-options",
"type": "text",
"text": "## Configuration Options\n\n- `enableInteraction` — Enable pan and zoom. Default: `true`\n- `initialZoom` — Initial zoom level. Default: `1`\n- `minZoom` — Minimum zoom level. Default: `0.1`\n- `maxZoom` — Maximum zoom level. Default: `5`\n- `defaultFullscreen` — Start in fullscreen mode. Default: `false`\n\nConfigure in `quartz.config.yaml`:\n\n```\nCanvasPage({ defaultFullscreen: false, initialZoom: 1 })\n```",
"x": 0,
"y": 1220,
"width": 560,
"height": 280
},
{
"id": "config-fullscreen",
"type": "text",
"text": "## Fullscreen Mode\n\nClick the **expand button** (top-right corner) to toggle fullscreen mode. The canvas fills the entire viewport.\n\n- Press **Escape** to exit fullscreen\n- Set `defaultFullscreen: true` to start in fullscreen\n- The toggle button switches between expand and collapse icons\n\n## Quartz Integration\n\n- **Popover previews**: Hover over file nodes to see a preview\n- **Internal links**: File nodes link to pages in your vault\n- **Dark mode**: Canvas adapts to your theme settings",
"x": 600,
"y": 1220,
"width": 560,
"height": 280
},
{
"id": "edge-source",
"type": "text",
"text": "## Edges\n\nEdges connect nodes with SVG paths. They support **labels**, **arrows**, and **colors**.",
"x": 0,
"y": 1650,
"width": 300,
"height": 120,
"color": "1"
},
{
"id": "edge-labeled",
"type": "text",
"text": "This edge has a **label** and an arrow marker.",
"x": 450,
"y": 1650,
"width": 260,
"height": 80,
"color": "4"
},
{
"id": "edge-colored",
"type": "text",
"text": "This edge has a **custom color** (`#ff6600`).",
"x": 450,
"y": 1780,
"width": 260,
"height": 80,
"color": "2"
},
{
"id": "edge-preset",
"type": "text",
"text": "Edges can use the same **preset colors** (1–6) as nodes, or custom **hex colors** like `#ff6600`.",
"x": 850,
"y": 1650,
"width": 300,
"height": 120,
"color": "6"
},
{
"id": "api-info",
"type": "text",
"text": "## API\n\n- **Category**: Page Type\n- **Function name**: `ExternalPlugin.CanvasPage()`\n- **Source**: [quartz-community/canvas-page](https://github.com/quartz-community/canvas-page)\n- **Install**: `npx quartz plugin add github:quartz-community/canvas-page`",
"x": 0,
"y": 2000,
"width": 560,
"height": 180
},
{
"id": "spec-info",
"type": "text",
"text": "## JSON Canvas Spec\n\nThis plugin implements the [JSON Canvas 1.0](https://jsoncanvas.org/spec/1.0/) specification — an open file format for infinite canvas data.\n\nCanvas files use the `.canvas` extension and are standard JSON. They are natively supported by [Obsidian](https://obsidian.md).",
"x": 600,
"y": 2000,
"width": 560,
"height": 180
}
],
"edges": [
{
"id": "edge-title-to-types",
"fromNode": "title",
"fromSide": "bottom",
"toNode": "group-node-types",
"toSide": "top",
"label": "supports"
},
{
"id": "edge-info-to-file",
"fromNode": "file-node-info",
"fromSide": "bottom",
"toNode": "file-node-demo",
"toSide": "top",
"color": "4"
},
{
"id": "edge-info-to-link",
"fromNode": "link-node-info",
"fromSide": "bottom",
"toNode": "link-node-demo",
"toSide": "top",
"color": "5"
},
{
"id": "edge-types-to-colors",
"fromNode": "group-node-types",
"fromSide": "bottom",
"toNode": "group-colors",
"toSide": "top"
},
{
"id": "edge-colors-to-config",
"fromNode": "group-colors",
"fromSide": "bottom",
"toNode": "group-config",
"toSide": "top"
},
{
"id": "edge-config-to-edges",
"fromNode": "group-config",
"fromSide": "bottom",
"toNode": "group-edges",
"toSide": "top"
},
{
"id": "edge-labeled-demo",
"fromNode": "edge-source",
"fromSide": "right",
"toNode": "edge-labeled",
"toSide": "left",
"label": "labeled edge"
},
{
"id": "edge-colored-demo",
"fromNode": "edge-source",
"fromSide": "right",
"toNode": "edge-colored",
"toSide": "left",
"color": "#ff6600"
},
{
"id": "edge-preset-demo",
"fromNode": "edge-labeled",
"fromSide": "right",
"toNode": "edge-preset",
"toSide": "left",
"color": "6"
}
]
}
+16 -119
View File
@@ -11,7 +11,7 @@ This question is best answered by tracing what happens when a user (you!) runs `
1. After running `npx quartz build`, npm will look at `package.json` to find the `bin` entry for `quartz` which points at `./quartz/bootstrap-cli.mjs`.
2. This file has a [shebang](<https://en.wikipedia.org/wiki/Shebang_(Unix)>) line at the top which tells npm to execute it using Node.
3. `bootstrap-cli.mjs` is responsible for a few things:
1. Parsing the command-line arguments using [yargs](http://yargs.js.org/). The `plugin` subcommand is also handled here for managing external plugins.
1. Parsing the command-line arguments using [yargs](http://yargs.js.org/).
2. Transpiling and bundling the rest of Quartz (which is in Typescript) to regular JavaScript using [esbuild](https://esbuild.github.io/). The `esbuild` configuration here is slightly special as it also handles `.scss` file imports using [esbuild-sass-plugin v2](https://www.npmjs.com/package/esbuild-sass-plugin). Additionally, we bundle 'inline' client-side scripts (any `.inline.ts` file) that components declare using a custom `esbuild` plugin that runs another instance of `esbuild` which bundles for the browser instead of `node`. Modules of both types are imported as plain text.
3. Running the local preview server if `--serve` is set. This starts two servers:
1. A WebSocket server on port 3001 to handle hot-reload signals. This tracks all inbound connections and sends a 'rebuild' message a server-side change is detected (either content or configuration).
@@ -21,135 +21,32 @@ This question is best answered by tracing what happens when a user (you!) runs `
4. In `build.ts`, we start by installing source map support manually to account for the query string cache busting hack we introduced earlier. Then, we start processing content:
1. Clean the output directory.
2. Recursively glob all files in the `content` folder, respecting the `.gitignore`.
3. Collect every page's slug (`ctx.allSlugs`), taking frontmatter `permalink`s into account, so links can be resolved while parsing.
4. Parse the Markdown files.
3. Parse the Markdown files.
1. Quartz detects the number of threads available and chooses to spawn worker threads if there are >128 pieces of content to parse (rough heuristic). If it needs to spawn workers, it will invoke esbuild again to transpile the worker script `quartz/worker.ts`. Then, a work-stealing [workerpool](https://www.npmjs.com/package/workerpool) is then created and batches of 128 files are assigned to workers.
2. Each worker (or just the main thread if there is no concurrency) creates a [unified](https://github.com/unifiedjs/unified) parser based off of the plugins defined in the [[configuration]].
3. Parsing has these steps:
3. Parsing has three steps:
1. Read the file into a [vfile](https://github.com/vfile/vfile).
2. Applied plugin-defined text transformations over the content.
3. Slugify the file path (or use its `permalink`) and store it in the data for the file. See the page on [[paths]] for more details about how path logic works in Quartz (spoiler: its complicated).
3. Slugify the file path and store it in the data for the file. See the page on [[paths]] for more details about how path logic works in Quartz (spoiler: its complicated).
4. Markdown parsing using [remark-parse](https://www.npmjs.com/package/remark-parse) (text to [mdast](https://github.com/syntax-tree/mdast)).
5. Apply the transformers' Markdown-to-Markdown transformations, in plugin order. The [[built-in processing|built-in]] frontmatter parsing runs among them at order 0 and sets `file.data.frontmatter`.
5. Apply plugin-defined Markdown-to-Markdown transformations.
6. Convert Markdown into HTML using [remark-rehype](https://github.com/remarkjs/remark-rehype) ([mdast](https://github.com/syntax-tree/mdast) to [hast](https://github.com/syntax-tree/hast)).
7. Apply the transformers' HTML-to-HTML transformations, in plugin order. The built-in link processing runs among them at order 60: it rewrites internal links and records `file.data.links`.
5. Filter out unwanted content using filter plugins and the built-in drafts filter.
6. Emit files using emitters, in three phases (`quartz/processors/emit.ts`):
1. Gather all the static resources (e.g. external CSS, JS modules, etc.) that transformers and emitters declare. The `ComponentResources` emitter runs first and writes the site's CSS and scripts:
1. CSS is minified and transformed using [Lightning CSS](https://github.com/parcel-bundler/lightningcss) to add vendor prefixes and do syntax lowering. Quartz's and the components' styles are put in the `quartz-base` cascade layer.
7. Apply plugin-defined HTML-to-HTML transformations.
4. Filter out unwanted content using plugins.
5. Emit files using plugins.
1. Gather all the static resources (e.g. external CSS, JS modules, etc.) each emitter plugin declares.
2. Emitters that emit HTML files do a bit of extra work here as they need to transform the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX. This is done using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime. Finally, the JSX is rendered to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) which statically renders the JSX to HTML (i.e. doesn't care about `useState`, `useEffect`, or any other React/Preact interactive bits). Here, we also do a bunch of fun stuff like assemble the page [[layout]] from `quartz.layout.ts`, assemble all the inline scripts that actually get shipped to the client, and all the transpiled styles. The bulk of this logic can be found in `quartz/components/renderPage.tsx`. Other fun things of note:
1. CSS is minified and transformed using [Lightning CSS](https://github.com/parcel-bundler/lightningcss) to add vendor prefixes and do syntax lowering.
2. Scripts are split into `beforeDOMLoaded` and `afterDOMLoaded` and are inserted in the `<head>` and `<body>` respectively.
2. The `PageTypeDispatcher` emitter renders the HTML pages (`quartz/plugins/pageTypes/dispatcher.ts`):
1. Each page type's `generate` runs, one after another in priority order, and returns virtual pages (folder and tag pages, `.base` and `.canvas` pages, …). They are collected in `ctx.virtualPages`. Pages that stand for a file (page types with `fileExtensions`) first go through the site's filters, with `file.data.referencedBy` set to the pages that link to them.
2. The bodies of the virtual pages are rendered (so they can be embedded), and the transformers' `virtualPageHtmlPlugins` run on those of file-backed pages.
3. Every content page is rendered by the first page type (highest priority) whose `match` accepts it, and every virtual page by the page type that generated it. Rendering transforms the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime, applies the page types' `treeTransforms`, assembles the page [[layout]] and [[layout#Page Frames|frame]], and renders the JSX to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) (statically: `useState`, `useEffect` and other interactive bits don't run). The bulk of this logic can be found in `quartz/components/renderPage.tsx`.
3. The content index is built once from the published and virtual pages (`ctx.contentIndex`), then all other emitters run in parallel over the same content (virtual pages included). The built-in content index emitter writes `static/contentIndex.json`, the sitemap and the RSS feed; plugin emitters write their own files.
7. If the `--serve` flag was detected, we also set up another file watcher to detect content changes (only `.md` files). We keep a content map that tracks the parsed AST and plugin data for each slug and update this on file changes. Newly added or modified paths are rebuilt and added to the content map. Then, all the filters and emitters are run over the resulting content map. This file watcher is debounced with a threshold of 250ms. On success, we send a client refresh signal using the passed in callback function.
3. Finally, each emitter plugin is responsible for emitting and writing it's own emitted files to disk.
6. If the `--serve` flag was detected, we also set up another file watcher to detect content changes (only `.md` files). We keep a content map that tracks the parsed AST and plugin data for each slug and update this on file changes. Newly added or modified paths are rebuilt and added to the content map. Then, all the filters and emitters are run over the resulting content map. This file watcher is debounced with a threshold of 250ms. On success, we send a client refresh signal using the passed in callback function.
## On the client
1. The browser opens a Quartz page and loads the HTML. The `<head>` also links to page styles (emitted to `public/index-<hash>.css`, plus a file per component stylesheet) and page-critical JS (emitted to `public/prescript-<hash>.js`). With `--serve`, the names have no hash.
2. Then, once the body is loaded, the browser loads the non-critical JS (`public/postscript-<hash>.js`). In a production build it imports each component's `afterDOMLoaded` script (`static/scripts/`) in parallel, then the SPA router; with `--serve` it holds all of them.
1. The browser opens a Quartz page and loads the HTML. The `<head>` also links to page styles (emitted to `public/index.css`) and page-critical JS (emitted to `public/prescript.js`)
2. Then, once the body is loaded, the browser loads the non-critical JS (emitted to `public/postscript.js`)
3. Once the page is done loading, the page will then dispatch a custom synthetic browser event `"nav"`. This is used so client-side scripts declared by components can 'setup' anything that requires access to the page DOM.
1. If the [[SPA Routing|enableSPA option]] is enabled in the [[configuration]], this `"nav"` event is also fired on any client-navigation to allow for components to unregister and reregister any event handlers and state.
2. If it's not, we wire up the `"nav"` event to just be fired a single time after page load to allow for consistency across how state is setup across both SPA and non-SPA contexts.
3. A separate `"render"` event can be dispatched when the DOM is updated in-place without a full navigation (e.g. after content decryption). Components that attach listeners to content elements should listen for both `"nav"` and `"render"`.
## Community Package Layering
Quartz v5 separates shared code into three community packages, each with a distinct responsibility:
- **`@quartz-community/types`** — Type definitions, interfaces, and the canonical `vfile` DataMap augmentation. This is the "contract" between Quartz and plugins. It has no runtime dependencies.
- **`@quartz-community/utils`** — Shared utility functions (path manipulation, DOM helpers, sorting, date formatting, JSX conversion, etc.). Depends on `@quartz-community/types`.
- **`@quartz-community/runtime`** — Browser-only utilities for client-side scripts (event handling, navigation, storage, script loading). Depends on both `types` and `utils`.
```
types (no deps)
↑
utils (depends on types)
↑
runtime (depends on types + utils)
↑
plugins (depend on any combination)
```
Plugins should import types from `@quartz-community/types`, utility functions from `@quartz-community/utils`, and browser utilities from `@quartz-community/runtime`. This layering ensures plugins don't depend on Quartz core.
## Plugin System
Quartz v5 introduces a community plugin system. Plugins are standalone packages: the default plugins are npm packages (dependencies of Quartz, installed in `node_modules`), other plugins can also be Git repositories or local folders, which are installed into `.quartz/plugins/`. Their named exports are re-exported through an auto-generated index file at `.quartz/plugins/index.ts`, which you import in a `quartz.ts` override as `ExternalPlugin`.
### Plugin Types
There are four processing plugin categories, plus Bases views:
- **Transformers**: Map over content (generate descriptions, syntax highlighting, Obsidian syntax)
- **Filters**: Filter content (explicit publish, unlisted pages)
- **Emitters**: Reduce over content (generate RSS, sitemaps, alias redirects, OG images)
- **Page Types**: Define how pages are rendered. Each page type handles a specific kind of page (content notes, folder listings, tag listings, 404). Page types are ordinary entries in the `plugins` list of `quartz.config.yaml` whose manifest has the category `pageType`. The `PageTypeDispatcher` emitter routes pages to the appropriate page type plugin based on the content.
- **Bases Views**: Custom view renderers for the `bases-page` plugin's database-like view system. Plugins can register new view types (e.g., timeline, kanban) via the `ViewRegistry`. See [[making plugins#Bases Views]] for details.
Frontmatter parsing, link processing, drafts and the content index are not plugins but [[built-in processing]].
Plugins can also provide components and frames. These roles are **not mutually exclusive** — a single plugin can be a transformer AND provide components (e.g., `table-of-contents`), or be a page type AND provide custom frames (e.g., `canvas-page`).
### Plugin Resolution
When a Git plugin is installed, e.g. with `npx quartz plugin add github:your-name/my-plugin`:
1. The repository is cloned into `.quartz/plugins/my-plugin/`
2. If it ships a pre-built `dist/` (not gitignored), that is used as is and only its peer dependencies are linked to the site's `node_modules`. Otherwise its dependencies are installed and it is built using `tsup` (defined in the plugin's `tsup.config.ts`)
3. An auto-generated `.quartz/plugins/index.ts` re-exports all installed plugins
4. The plugin's commit hash is recorded in `quartz.lock.json`
npm plugins (such as the default `@quartz-community/explorer`) are imported from `node_modules` and are not cloned or built.
### Plugin CLI Commands
- `npx quartz plugin add github:quartz-community/<name>` — Install a community plugin
- `npx quartz plugin install --latest` — Update all plugins to latest commits
- `npx quartz plugin install` — Install plugins at the commits locked in `quartz.lock.json` (used in CI/CD); `--clean` only restores plugins whose directory is missing
- `npx quartz plugin remove <name>` — Remove an installed plugin
### Plugin Structure
Each community plugin repository contains:
- `src/index.ts` — Plugin entry point exporting the plugin function
- `tsup.config.ts` — Build configuration using tsup
- `package.json` — Declares dependencies on `@quartz-community/types` and `@quartz-community/utils`, and the [[plugin manifest]] in its `quartz` field
The architecture and design of the plugin system was intentionally left pretty vague here as this is described in much more depth in the guide on [[making plugins|creating plugins]].
## Page Frames
Page frames control the inner HTML structure of each page. While the outer shell (`<html>`, `<head>`, `<body>`, `#quartz-root`) is always the same (required for [[SPA Routing]]), the frame determines how layout slots are arranged inside the page.
The frame system lives in `quartz/components/frames/` and consists of:
- `types.ts` — Defines the `PageFrame` and `PageFrameProps` interfaces
- `DefaultFrame.tsx` — Three-column layout (left sidebar, center, right sidebar, footer)
- `FullWidthFrame.tsx` — No sidebars, single center column
- `MinimalFrame.tsx` — No sidebars, no header/beforeBody, just content and footer
- `registry.ts` — `FrameRegistry` singleton for plugin-registered frames
- `index.ts` — `resolveFrame()` function and built-in frame registry
### Frame Registry
The `FrameRegistry` (`quartz/components/frames/registry.ts`) is a singleton that stores frames registered by community plugins. It mirrors the design of the `ComponentRegistry`. Plugins declare frames in their `package.json` manifest under the `"quartz"."frames"` field, and these are loaded by `quartz/plugins/loader/frameLoader.ts` during plugin initialization.
### Frame Resolution
The rendering pipeline in `quartz/components/renderPage.tsx` delegates to the resolved frame's `render()` function. Frame resolution happens in the `PageTypeDispatcher` emitter (`quartz/plugins/pageTypes/dispatcher.ts`) using this priority:
1. YAML config: `layout.byPageType.<name>.template`
2. Plugin-registered frame: looked up by name in the `FrameRegistry`
3. Built-in frame: looked up by name in the `builtinFrames` map
4. Fallback: `"default"`
The active frame name is set as a `data-frame` attribute on the `.page` element, enabling frame-specific CSS overrides in `quartz/styles/base.scss`.
### Plugin-Provided Frames
Community plugins can ship their own frames by exporting them from a `./frames` subpath and declaring them in the plugin manifest. For example, the `canvas-page` plugin provides a `"canvas"` frame with a fullscreen layout and togglable sidebar. See [[making plugins#Providing Custom Frames]] for implementation details.
See [[layout#Page Frames]] for user-facing documentation and [[making plugins#Page Types]] for how to set frames in page type plugins.
The architecture and design of the plugin system was intentionally left pretty vague here as this is described in much more depth in the guide on [[making plugins|making your own plugin]].
+152 -264
View File
@@ -1,5 +1,5 @@
---
title: Creating Component Plugins
title: Creating your own Quartz components
---
> [!warning]
@@ -20,341 +20,229 @@ However, HTML doesn't let you create reusable templates. If you wanted to create
In effect, components allow you to write a JavaScript function that takes some data and produces HTML as an output. **While Quartz doesn't use React, it uses the same component concept to allow you to easily express layout templates in your Quartz site.**
## Community Component Plugins
## An Example Component
In v5, most components are community plugins — standalone repositories that export a `QuartzComponent`. These plugins are decoupled from the core Quartz repository, allowing for easier maintenance and sharing.
### Constructor
### Getting Started
Component files are written in `.tsx` files that live in the `quartz/components` folder. These are re-exported in `quartz/components/index.ts` so you can use them in layouts and other components more easily.
To create a new component plugin, you can use the official plugin template:
Each component file should have a default export that satisfies the `QuartzComponentConstructor` function signature. It's a function that takes in a single optional parameter `opts` and returns a Quartz Component. The type of the parameters `opts` is defined by the interface `Options` which you as the component creator also decide.
```shell
git clone https://github.com/quartz-community/plugin-template.git my-component
cd my-component
npm install
```
In your component, you can use the values from the configuration option to change the rendering behaviour inside of your component. For example, the component in the code snippet below will not render if the `favouriteNumber` option is below 0.
### Plugin Structure
A component is a constructor: a function that takes the user's options and returns a `QuartzComponent`. Put it in `src/components/`:
```tsx title="src/components/MyComponent.tsx"
import type { QuartzComponent, QuartzComponentConstructor } from "@quartz-community/types"
export interface MyComponentOptions {
```tsx {11-17}
interface Options {
favouriteNumber: number
}
const defaultOptions: MyComponentOptions = {
const defaultOptions: Options = {
favouriteNumber: 42,
}
export default ((userOpts?: Partial<MyComponentOptions>) => {
const opts = { ...defaultOptions, ...userOpts }
export default ((userOpts?: Options) => {
const opts = { ...userOpts, ...defaultOpts }
function YourComponent(props: QuartzComponentProps) {
if (opts.favouriteNumber < 0) {
return null
}
const Component: QuartzComponent = () => {
if (opts.favouriteNumber < 0) return null
return <p class="my-component">My favourite number is {opts.favouriteNumber}</p>
return <p>My favourite number is {opts.favouriteNumber}</p>
}
return Component
}) satisfies QuartzComponentConstructor<Partial<MyComponentOptions>>
```
Quartz loads components from the package's **`./components`** export, by the names listed in the manifest — not from the entry module, and not from a `default` export:
```ts title="src/components/index.ts"
export { default as MyComponent } from "./MyComponent"
export type { MyComponentOptions } from "./MyComponent"
```
```json title="package.json"
{
"exports": {
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
"./components": {
"types": "./dist/components/index.d.ts",
"import": "./dist/components/index.js"
}
},
"quartz": {
"category": "component",
"components": {
"MyComponent": {
"displayName": "My Component",
"defaultPosition": "right",
"defaultPriority": 50
}
}
}
}
```
The key in `quartz.components` must match the export name in `src/components/index.ts`; `defaultPosition` and `defaultPriority` place the component when the user's config doesn't (see [[plugin manifest#components]]). The plugin template's `tsup.config.ts` already builds the `components/index` entry.
Also re-export the constructor by name from the entry module, so users can call it in `quartz.ts` overrides (`ExternalPlugin.MyComponent(…)`, see [[#Installing Your Component]]). The generated `.quartz/plugins/index.ts` re-exports your entry module's named exports; `default` exports are left out.
```ts title="src/index.ts"
export { MyComponent } from "./components"
export type { MyComponentOptions } from "./components"
return YourComponent
}) satisfies QuartzComponentConstructor
```
### Props
The Quartz component itself (lines 11-17 highlighted above) looks like a React component. It takes in properties (sometimes called [props](https://react.dev/learn/passing-props-to-a-component)) and returns JSX.
All Quartz components accept the same set of props:
```tsx
```tsx title="quartz/components/types.ts"
// simplified for sake of demonstration
export type QuartzComponentProps = {
ctx: unknown
externalResources: StaticResources
fileData: QuartzPluginData & Record<string, unknown>
fileData: QuartzPluginData
cfg: GlobalConfiguration
children: unknown
tree: unknown
allFiles: (QuartzPluginData & Record<string, unknown>)[]
tree: Node<QuartzPluginData>
allFiles: QuartzPluginData[]
displayClass?: "mobile-only" | "desktop-only"
[key: string]: unknown
}
```
- `ctx`: the [[making plugins|`BuildCtx`]] of the build (typed `unknown`; cast it to `BuildCtx` to read it).
- `externalResources`: the page's CSS, scripts and head elements.
- `fileData`: Any metadata plugins may have added to the current page.
- `fileData`: Any metadata [[making plugins|plugins]] may have added to the current page.
- `fileData.slug`: slug of the current page.
- `fileData.frontmatter`: any frontmatter parsed.
- `cfg`: The `configuration` field in `quartz.config.yaml`.
- `children`: child components, for components that wrap others (e.g. `Flex`).
- `tree`: the resulting [HTML AST](https://github.com/syntax-tree/hast) (a hast `Root`) after processing and transforming the file.
- `allFiles`: Metadata for all published pages, virtual pages included. Useful for doing page listings or figuring out the overall site structure.
- `displayClass`: a utility class that indicates a preference from the user about how to render it in a mobile or desktop setting.
- `cfg`: The `configuration` field in `quartz.config.ts`.
- `tree`: the resulting [HTML AST](https://github.com/syntax-tree/hast) after processing and transforming the file. This is useful if you'd like to render the content using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) (you can find an example of this in `quartz/components/pages/Content.tsx`).
- `allFiles`: Metadata for all files that have been parsed. Useful for doing page listings or figuring out the overall site structure.
- `displayClass`: a utility class that indicates a preference from the user about how to render it in a mobile or desktop setting. Helpful if you want to conditionally hide a component on mobile or desktop.
### Styling
In community plugins, styles are bundled with the plugin. You can define styles using the `.css` property on the component:
Quartz components can also define a `.css` property on the actual function component which will get picked up by Quartz. This is expected to be a CSS string which can either be inlined or imported from a `.scss` file.
```tsx
Component.css = `
.my-component { color: red; }
`
Note that inlined styles **must** be plain vanilla CSS:
```tsx {6-10} title="quartz/components/YourComponent.tsx"
export default (() => {
function YourComponent() {
return <p class="red-text">Example Component</p>
}
YourComponent.css = `
p.red-text {
color: red;
}
`
return YourComponent
}) satisfies QuartzComponentConstructor
```
For SCSS, you can import it and assign it to the `.css` property. The build system will handle the transformation:
Imported styles, however, can be from SCSS files:
```tsx
import styles from "./styles.scss"
Component.css = styles
```tsx {1-2,9} title="quartz/components/YourComponent.tsx"
// assuming your stylesheet is in quartz/components/styles/YourComponent.scss
import styles from "./styles/YourComponent.scss"
export default (() => {
function YourComponent() {
return <p>Example Component</p>
}
YourComponent.css = styles
return YourComponent
}) satisfies QuartzComponentConstructor
```
> [!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.
Quartz puts component CSS in the `quartz-base` [cascade layer](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer), like its own base styles, so a site's `custom.scss` (unlayered) overrides it without needing more specific 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.
Quick reference:
```tsx
import { i18n } from "../i18n"
const MyComponent: QuartzComponent = ({ cfg }) => {
const t = i18n(cfg.locale ?? "en-US").components.myComponent
return <h2>{t.title}</h2>
}
```
Always provide at least an `en-US` locale as the fallback. Additional locales are optional but encouraged for international reach.
### Scripts and Interactivity
For interactivity, you can declare `.beforeDOMLoaded` and `.afterDOMLoaded` properties on the component. These should be strings containing the JavaScript to be executed in the browser.
What about interactivity? Suppose you want to add an-click handler for example. Like the `.css` property on the component, you can also declare `.beforeDOMLoaded` and `.afterDOMLoaded` properties that are strings that contain the script.
- `.beforeDOMLoaded`: Executed _before_ the page is done loading (from `<head>`), for early initialization such as applying a saved theme before the page is painted.
- `.afterDOMLoaded`: Executed once the page has been completely loaded.
```tsx title="quartz/components/YourComponent.tsx"
export default (() => {
function YourComponent() {
return <button id="btn">Click me</button>
}
Each script runs once per full page load, not on every SPA navigation. Don't rely on scripts sharing a scope or running in a particular order:
YourComponent.beforeDOMLoaded = `
console.log("hello from before the page loads!")
`
- In a production build, each `afterDOMLoaded` script is a separate ES module, and all of them are imported in parallel; only the SPA router (which dispatches the first `nav`) is imported after them.
- In `quartz build --serve`, all `afterDOMLoaded` scripts are bundled into one file, each wrapped in its own function.
YourComponent.afterDOMLoaded = `
document.getElementById('btn').onclick = () => {
alert('button clicked!')
}
`
return YourComponent
}) satisfies QuartzComponentConstructor
```
Share state between components through `window` or DOM attributes, and do page setup in a `nav` listener rather than at the top level.
> [!hint]
> For those coming from React, Quartz components are different from React components in that it only uses JSX for templating and layout. Hooks like `useEffect`, `useState`, etc. are not rendered and other properties that accept functions like `onClick` handlers will not work. Instead, do it using a regular JS script that modifies the DOM element directly.
If you need to create an `afterDOMLoaded` script that depends on page-specific elements that may change when navigating, listen for the `"nav"` event:
As the names suggest, the `.beforeDOMLoaded` scripts are executed _before_ the page is done loading so it doesn't have access to any elements on the page. This is mostly used to prefetch any critical data.
The `.afterDOMLoaded` script executes once the page has been completely loaded. This is a good place to setup anything that should last for the duration of a site visit (e.g. getting something saved from local storage).
If you need to create an `afterDOMLoaded` script that depends on _page specific_ elements that may change when navigating to a new page, you can listen for the `"nav"` event that gets fired whenever a page loads (which may happen on navigation if [[SPA Routing]] is enabled).
```ts
document.addEventListener("nav", () => {
// do page specific logic here
// e.g. attach event listeners
const toggleSwitch = document.querySelector("#switch") as HTMLInputElement
if (toggleSwitch) {
toggleSwitch.addEventListener("change", switchTheme)
window.addCleanup(() => toggleSwitch.removeEventListener("change", switchTheme))
}
toggleSwitch.addEventListener("change", switchTheme)
window.addCleanup(() => toggleSwitch.removeEventListener("change", switchTheme))
})
```
You can also use the `"prenav"` event, which fires before the page is replaced during SPA navigation.
The `"render"` event fires when the DOM has been updated in-place without a full navigation — for example, after content decryption or dynamic DOM modifications by other plugins. If your component attaches event listeners to content elements, listen for `"render"` in addition to `"nav"` to ensure re-initialization:
You can also add the equivalent of a `beforeunload` event for [[SPA Routing]] via the `prenav` event.
```ts
function setupMyComponent() {
const elements = document.querySelectorAll(".my-interactive")
for (const el of elements) {
el.addEventListener("click", handleClick)
window.addCleanup(() => el.removeEventListener("click", handleClick))
}
}
document.addEventListener("nav", setupMyComponent)
document.addEventListener("render", setupMyComponent)
```
It is best practice to track any event handlers via `window.addCleanup` to prevent memory leaks during SPA navigation.
Quartz itself never dispatches `"render"`; plugins that change the page do (e.g. encrypted pages after decryption). Since other components re-run their setup on it, make your `render` handler safe to run more than once.
#### Links your script adds
[[prefetching|Prefetching]] and [[popover previews]] look for links on `nav`, and again on `render`. If your script inserts links after `nav` (lists built from `contentIndex.json`, content fetched later), dispatch `render` once they are in the page so they are prefetched and get popovers. Mark links with
- `data-no-prefetch` to keep them from being prefetched,
- `data-router-ignore` to make them full page loads instead of SPA navigations (they aren't prefetched either),
- `data-no-popover="true"` to give them no popover.
When your script needs another page's HTML, get it through the prefetch cache with `window.quartzPrefetch?.load(url)` (set unless prefetching is off; declared in the globals of `@quartz-community/types` 1.3.1+), so a page the reader is about to open is fetched once:
```ts title="related.inline.ts"
import { normalizeRelativeURLs } from "@quartz-community/utils/dom"
async function pageHtml(url: URL): Promise<string | undefined> {
// with prefetching on, use its cache (or fetch through it, so the page is fetched once)
if (window.quartzPrefetch) return (await window.quartzPrefetch.load(url))?.text
const res = await fetch(url)
return res.ok ? await res.text() : undefined
}
document.addEventListener("nav", async () => {
const container = document.querySelector<HTMLElement>(".my-related")
if (!container?.dataset.src) return
const url = new URL(container.dataset.src, window.location.href)
const html = await pageHtml(url)
if (!html) return
const doc = new DOMParser().parseFromString(html, "text/html")
normalizeRelativeURLs(doc, url.toString()) // its links are relative to that page
container.replaceChildren(...doc.querySelectorAll("article a.internal"))
// the links were added after `nav`: let prefetching and popovers pick them up
document.dispatchEvent(new CustomEvent("render", { detail: {} }))
document.addEventListener("prenav", () => {
// executed after an SPA navigation is triggered but
// before the page is replaced
// one usage pattern is to store things in sessionStorage
// in the prenav and then conditionally load then in the consequent
// nav
})
```
It is best practice to track any event handlers via `window.addCleanup` to prevent memory leaks.
This will get called on page navigation.
#### Importing Code
In community plugins, TypeScript scripts should be transpiled at build time. The plugin template includes an `inlineScriptPlugin` in `tsup.config.ts` that automatically transpiles `.inline.ts` files imported as text:
Of course, it isn't always practical (nor desired!) to write your code as a string literal in the component.
```tsx title="src/index.ts"
import script from "./script.inline.ts"
Quartz supports importing component code through `.inline.ts` files.
const Component: QuartzComponent = (props) => {
return <button id="btn">Click me</button>
}
Component.afterDOMLoaded = script
```
```tsx title="quartz/components/YourComponent.tsx"
// @ts-ignore: typescript doesn't know about our inline bundling system
// so we need to silence the error
import script from "./scripts/graph.inline"
The `inlineScriptPlugin` handles transpiling TypeScript to browser-compatible JavaScript during the build step, allowing you to write type-safe client-side code.
### Installing Your Component
Once your component is published (e.g., to GitHub or npm), users can install it using the Quartz CLI:
```shell
npx quartz plugin add github:your-username/my-component
```
Then, they can add it to their `quartz.config.yaml`:
```yaml title="quartz.config.yaml"
plugins:
- source: github:your-username/my-component
enabled: true
options:
favouriteNumber: 42
layout:
position: left
priority: 60
```
For advanced usage via the TS override in `quartz.ts`:
```ts title="quartz.ts (override)"
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
import * as ExternalPlugin from "./.quartz/plugins"
const config = await loadQuartzConfig()
export default config
export const layout = await loadQuartzLayout({
byPageType: {
content: {
left: [ExternalPlugin.MyComponent({ favouriteNumber: 42 })],
},
},
})
```
### Receiving YAML Options in Component-Only Plugins
Component plugins that also belong to a processing category (transformer, filter, emitter, page type) receive options through their factory function automatically. However, **component-only plugins** — those whose manifest declares only `"category": ["component"]` — are loaded via side-effect import and don't go through the factory path.
To receive YAML options in a component-only plugin, export an `init` function from your entry point:
```ts title="src/index.ts"
export function init(options?: Record<string, unknown>): void {
// options contains merged defaultOptions + user's YAML options
const myFlag = (options?.myFlag as boolean) ?? false
// Use options to configure registrations, global state, etc.
}
```
Quartz's config-loader calls `init()` after importing the module, passing the merged result of your manifest's `defaultOptions` and the user's `options` from `quartz.config.yaml`. The merge follows the same `{ ...defaultOptions, ...userOptions }` pattern used for processing plugins — user values take precedence.
Declare your defaults in `package.json`:
```json title="package.json"
{
"quartz": {
"category": ["component"],
"defaultOptions": {
"myFlag": false
}
export default (() => {
function YourComponent() {
return <button id="btn">Click me</button>
}
YourComponent.afterDOMLoaded = script
return YourComponent
}) satisfies QuartzComponentConstructor
```
```ts title="quartz/components/scripts/graph.inline.ts"
// any imports here are bundled for the browser
import * as d3 from "d3"
document.getElementById("btn").onclick = () => {
alert("button clicked!")
}
```
If your plugin does not export `init`, it continues to work as a pure side-effect import — this is fully backward compatible.
Additionally, like what is shown in the example above, you can import packages in `.inline.ts` files. This will be bundled by Quartz and included in the actual script.
## Internal Components
### Using a Component
Quartz also has internal components that provide layout utilities. These live in `quartz/components/` and are primarily used for structural purposes:
After creating your custom component, re-export it in `quartz/components/index.ts`:
- `Component.Head()` — renders the `<head>` tag
- `Component.Spacer()` — adds flexible space
- `Component.Flex()` — flexible layout container
- `Component.MobileOnly()` — shows component only on mobile
- `Component.DesktopOnly()` — shows component only on desktop
- `Component.ConditionalRender()` — conditionally renders based on page data
```ts title="quartz/components/index.ts" {4,10}
import ArticleTitle from "./ArticleTitle"
import Content from "./pages/Content"
import Darkmode from "./Darkmode"
import YourComponent from "./YourComponent"
See [[layout-components]] for more details on these utilities.
export { ArticleTitle, Content, Darkmode, YourComponent }
```
Then, you can use it like any other component in `quartz.layout.ts` via `Component.YourComponent()`. See the [[configuration#Layout|layout]] section for more details.
As Quartz components are just functions that return React components, you can compositionally use them in other Quartz components.
```tsx title="quartz/components/AnotherComponent.tsx"
import YourComponentConstructor from "./YourComponent"
export default (() => {
const YourComponent = YourComponentConstructor()
function AnotherComponent(props: QuartzComponentProps) {
return (
<div>
<p>It's nested!</p>
<YourComponent {...props} />
</div>
)
}
return AnotherComponent
}) satisfies QuartzComponentConstructor
```
> [!hint]
> Look at existing community plugins like [Explorer](https://github.com/quartz-community/explorer) or [Darkmode](https://github.com/quartz-community/darkmode) for real-world examples.
> Look in `quartz/components` for more examples of components in Quartz as reference for your own components!
-10
View File
@@ -1,13 +1,3 @@
---
title: "Advanced"
---
This section covers advanced topics for users who want to extend or deeply customize Quartz.
- **[[architecture]]** — How Quartz works under the hood: the parse, filter, and emit pipeline
- **[[making plugins]]** — Build your own transformer, filter, emitter, page type, or component plugin
- **[[plugin manifest]]** — Reference for the `quartz` field of a plugin's `package.json`
- **[[plugin capabilities]]** — Declare what a plugin provides to and needs from other plugins
- **[[creating components]]** — Create custom layout components with JSX
- **[[paths]]** — How Quartz resolves and transforms file paths
- **[[versioning]]** — Version numbers, plugin compatibility (`quartzVersion`) and releases
+122 -768
View File
@@ -18,85 +18,20 @@ type QuartzPluginInstance =
| QuartzTransformerPluginInstance
| QuartzFilterPluginInstance
| QuartzEmitterPluginInstance
| QuartzPageTypePluginInstance
```
The following sections will go into detail for what methods can be implemented for each plugin type. Before we do that, let's clarify a few more ambiguous types:
- `BuildCtx` is defined in `@quartz-community/types`. It consists of
- `buildId`: a random id for this build
- `argv`: The command line arguments passed to the Quartz [[build]] command (`argv.output` is the output folder)
- `cfg`: The full Quartz [[configuration]]; `cfg.configuration` holds the `configuration` section of `quartz.config.yaml`
- `BuildCtx` is defined in `quartz/ctx.ts`. It consists of
- `argv`: The command line arguments passed to the Quartz [[build]] command
- `cfg`: The full Quartz [[configuration]]
- `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a slug is)
- `allFiles`: the paths of all files in the content folder, relative to it
- `incremental`: `true` while `quartz build --serve` rebuilds after a change
- `contentIndex` (Quartz 5.1+): the site's content index, see [[#Reusing the content index in emitters]]
- Quartz's own `BuildCtx` has more fields that `@quartz-community/types` doesn't declare: `virtualPages` (the pages page types generated, see [[#Page Types]]), `trie` (the folder tree, set by the page-type dispatcher) and `permalinks` (content file → slug for notes with a `permalink` in their frontmatter). Read them through a cast and expect them to be missing.
- `StaticResources` is defined in `@quartz-community/types`. It consists of
- `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type. It accepts either a source URL or the inline content of the stylesheet.
- `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script.
- `StaticResources` is defined in `quartz/resources.tsx`. It consists of
- `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type which is also defined in `quartz/resources.tsx`. It accepts either a source URL or the inline content of the stylesheet.
- `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type which is also defined in `quartz/resources.tsx`. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script.
- `additionalHead`: a list of JSX elements or functions that return JSX elements to be added to the `<head>` tag of the page. Functions receive the page's data as an argument and can conditionally render elements.
- `assets` (Quartz 5.1+): files and directories to copy into the site, see [[#Shipping Files with Your Plugin]].
## Getting Started
In v5, plugins are standalone repositories. The easiest way to create one is using the plugin template:
```shell
# Use the plugin template to create a new repository on GitHub
# Then clone it locally
git clone https://github.com/your-username/my-plugin.git
cd my-plugin
npm install
```
The template provides the build configuration (`tsup.config.ts`), TypeScript setup, and correct package structure. It depends on `@quartz-community/types` and `@quartz-community/utils`; the examples on this page need types 1.3.0 and utils 1.2.0 or later.
## Plugin Structure
The basic file structure of a plugin is as follows:
```
my-plugin/
├── src/
│ └── index.ts # Plugin entry point
├── tsup.config.ts # Build configuration
├── package.json # Dependencies and exports
└── tsconfig.json # TypeScript configuration
```
Component plugins also have `src/components/index.ts` (built to the `./components` export) and plugins with frames `src/frames/index.ts` (`./frames`).
The plugin's `package.json` should declare dependencies on `@quartz-community/types` (for type definitions) and optionally `@quartz-community/utils` (for shared utilities).
Its `quartz` field — the **manifest** — tells Quartz what the plugin is: its category, where it runs (`defaultOrder`), its default options and option schema, the components and frames it ships, the plugins it depends on, and the Quartz versions it works with. Every field is described in the [[plugin manifest]] reference. In particular:
- 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]].
- 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]].
- If your plugin must run after another one, set `defaultOrder` (and `dependencies` for a plugin that must be installed); see [[plugin manifest#defaultOrder|the order table]].
A plugin that fails to load (can't be installed, throws on import, exports no plugin) is reported as an error naming the plugin and where it failed. Locally the build continues without it; in CI the build fails unless `QUARTZ_ALLOW_BROKEN_PLUGINS=1` is set. To retire a plugin, set `quartz.deprecated` (see [[plugin manifest#deprecated]]).
## Choosing a Plugin Type
Quartz has four processing plugin types — transformers, filters, emitters and page types — and plugins can also provide components, frames and Bases views. A single plugin can combine several of them.
| I want to... | Plugin Type |
| ------------------------------------------------ | ----------- |
| Transform Markdown/HTML content | Transformer |
| Decide which pages to publish | Filter |
| Generate output files (RSS, sitemaps, manifests) | Emitter |
| Define how a category of pages renders | Page Type |
| Add a UI component to the layout | Component |
| Add a custom view to the Bases database system | Bases View |
These are **not mutually exclusive**. For example:
- `table-of-contents` is both a **transformer** (collects the headings) and provides a **component** (renders them)
- `canvas-page` is a **page type** that also provides a custom **frame**
- A plugin could be a **transformer** that adds metadata AND a **component** that displays it
### Transformers
## Transformers
Transformers **map** over content, taking a Markdown file and outputting modified content or adding metadata to the file itself.
@@ -106,9 +41,7 @@ export type QuartzTransformerPluginInstance = {
textTransform?: (ctx: BuildCtx, src: string) => string
markdownPlugins?: (ctx: BuildCtx) => PluggableList
htmlPlugins?: (ctx: BuildCtx) => PluggableList
virtualPageHtmlPlugins?: (ctx: BuildCtx, content: ProcessedContent[]) => PluggableList
externalResources?: (ctx: BuildCtx) => Partial<StaticResources> | undefined
extendContentIndex?: ContentIndexExtension // any plugin type, see below
externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
}
```
@@ -117,20 +50,17 @@ All transformer plugins must define at least a `name` field to register the plug
- `textTransform` performs a text-to-text transformation _before_ a file is parsed into the [Markdown AST](https://github.com/syntax-tree/mdast).
- `markdownPlugins` defines a list of [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md). `remark` is a tool that transforms Markdown to Markdown in a structured way.
- `htmlPlugins` defines a list of [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md). Similar to how `remark` works, `rehype` is a tool that transforms HTML to HTML in a structured way.
- `virtualPageHtmlPlugins` (Quartz 5.1+) defines rehype plugins for the pages that page types render from files (`.base`, `.canvas`, Excalidraw drawings). Those pages are rendered when emitting and never pass through `htmlPlugins`, so a plugin that should also act on them (e.g. encryption) registers its rehype plugin here too. They run on the page's rendered body, with the page's vfile (`file.data.frontmatter`, `file.data.referencedBy`), after the filters published the page; the page then shows the resulting tree. `content` is the published content.
- `externalResources` defines any external resources the plugin may need to load on the client-side for it to work properly.
Transformers run in plugin order (see [[plugin manifest#defaultOrder]]); the built-in frontmatter parsing runs at order 0 and the built-in link processing, which sets `file.data.links`, at 60.
Normally for both `remark` and `rehype`, you can find existing plugins that you can use to . If you'd like to create your own `remark` or `rehype` plugin, checkout the [guide to creating a plugin](https://unifiedjs.com/learn/guide/create-a-plugin/) using `unified` (the underlying AST parser and transformer library).
Normally for both `remark` and `rehype`, you can find existing plugins that you can use. If you'd like to create your own `remark` or `rehype` plugin, checkout the [guide to creating a plugin](https://unifiedjs.com/learn/guide/create-a-plugin/) using `unified` (the underlying AST parser and transformer library).
A good example of a transformer plugin that borrows from the `remark` and `rehype` ecosystems is the [[plugins/Latex|Latex]] plugin:
A good example of a transformer plugin that borrows from the `remark` and `rehype` ecosystems is the [[plugins/Latex|Latex]] plugin (simplified):
```ts
```ts title="quartz/plugins/transformers/latex.ts"
import remarkMath from "remark-math"
import rehypeKatex from "rehype-katex"
import rehypeMathjax from "rehype-mathjax/svg"
import type { QuartzTransformerPlugin } from "@quartz-community/types"
import { QuartzTransformerPlugin } from "../types"
interface Options {
renderEngine: "katex" | "mathjax"
@@ -158,13 +88,13 @@ export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
css: [
{
// base css
content: "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css",
content: "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css",
},
],
js: [
{
// fix copy behaviour: https://github.com/KaTeX/KaTeX/blob/main/contrib/copy-tex/README.md
src: "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/copy-tex.min.js",
src: "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/contrib/copy-tex.min.js",
loadTime: "afterDOMReady",
contentType: "external",
},
@@ -179,19 +109,17 @@ export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
Another common thing that transformer plugins will do is parse a file and add extra data for that file:
```ts
import type { QuartzTransformerPlugin } from "@quartz-community/types"
export const AddWordCount: QuartzTransformerPlugin = () => {
return {
name: "AddWordCount",
markdownPlugins() {
return [
() => {
return (_tree, file) => {
// _tree is an `mdast` root element
// file is a `vfile`; its value is a string or a Uint8Array
const text = file.toString()
const words = text.split(/\s+/).filter(Boolean).length
return (tree, file) => {
// tree is an `mdast` root element
// file is a `vfile`
const text = file.value
const words = text.split(" ").length
file.data.wordcount = words
}
},
@@ -212,53 +140,45 @@ declare module "vfile" {
Finally, you can also perform transformations over Markdown or HTML ASTs using the `visit` function from the `unist-util-visit` package or the `findAndReplace` function from the `mdast-util-find-and-replace` package.
```ts
import { SKIP, visit } from "unist-util-visit"
import { findAndReplace } from "mdast-util-find-and-replace"
import type { QuartzTransformerPlugin } from "@quartz-community/types"
import type { Root } from "mdast"
export const TextTransforms: QuartzTransformerPlugin = () => {
return {
name: "TextTransforms",
markdownPlugins() {
return [
() => {
return (tree: Root) => {
// replace _text_ with the italics version
findAndReplace(tree, [
/_(.+?)_/g,
(_value: string, inner: string) => {
// inner is the text inside of the () of the regex
// return an mdast node
// https://github.com/syntax-tree/mdast
return {
type: "emphasis",
children: [{ type: "text", value: inner }],
}
},
])
return [() => {
return (tree, file) => {
// replace _text_ with the italics version
findAndReplace(tree, /_(.+)_/, (_value: string, ...capture: string[]) => {
// inner is the text inside of the () of the regex
const [inner] = capture
// return an mdast node
// https://github.com/syntax-tree/mdast
return {
type: "emphasis",
children: [{ type: 'text', value: inner }]
}
})
// remove all links (replace each with its content)
// match by 'type' field on an mdast node
// https://github.com/syntax-tree/mdast#link in this example
visit(tree, "link", (link, index, parent) => {
if (parent === undefined || index === undefined) return
// the visitor's return value controls traversal; to change the
// tree, mutate the parent
parent.children.splice(index, 1, ...link.children)
return [SKIP, index]
})
}
},
]
},
// remove all links (replace with just the link content)
// match by 'type' field on an mdast node
// https://github.com/syntax-tree/mdast#link in this example
visit(tree, "link", (link: Link) => {
return {
type: "paragraph"
children: [{ type: 'text', value: link.title }]
}
})
}
}]
}
}
}
```
All transformer plugins can be found under `quartz/plugins/transformers`. If you decide to write your own transformer plugin, don't forget to re-export it under `quartz/plugins/transformers/index.ts`
A parting word: transformer plugins are quite complex so don't worry if you don't get them right away. Take a look at the built in transformers and see how they operate over content to get a better sense for how to accomplish what you are trying to do.
### Filters
## Filters
Filters **filter** content, taking the output of all the transformers and determining what files to actually keep and what to discard.
@@ -273,26 +193,24 @@ 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. A page is published only if every filter returns `true`.
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.
Filters also see the pages that page types render from files (Quartz 5.1+; page types that declare `fileExtensions`, e.g. `.base` and `.canvas` pages), with the frontmatter the page type gives them and `file.data.referencedBy`: the published pages that link to them. A page a filter rejects is not emitted, listed or embeddable. Such files may have no frontmatter (`.base`, `.canvas`): [[ExplicitPublish]] publishes them when a published page links to them.
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]], and a plugin can't replace it (it would run in addition); the built-in is configured under `configuration.drafts`.
```ts title="quartz/plugins/filters/draft.ts"
import { QuartzFilterPlugin } from "../types"
```ts
import type { QuartzFilterPlugin } from "@quartz-community/types"
export const RemoveDrafts: QuartzFilterPlugin = () => ({
export const RemoveDrafts: QuartzFilterPlugin<{}> = () => ({
name: "RemoveDrafts",
shouldPublish(_ctx, [_tree, vfile]) {
// uses frontmatter parsed by Quartz; `draft` may be a boolean or a string
const draft = vfile.data.frontmatter?.draft
return !(draft === true || draft === "true")
// uses frontmatter parsed from transformers
const draftFlag: boolean = vfile.data?.frontmatter?.draft ?? false
return !draftFlag
},
})
```
### Emitters
## Emitters
Emitters **reduce** over content, taking in a list of all the transformed and filtered content and creating output files.
@@ -314,651 +232,87 @@ export type QuartzEmitterPluginInstance = {
resources: StaticResources,
changeEvents: ChangeEvent[],
): Promise<FilePath[]> | AsyncGenerator<FilePath> | null
getQuartzComponents?(ctx: BuildCtx): QuartzComponent[]
externalResources?(ctx: BuildCtx): Partial<StaticResources> | undefined
extendContentIndex?: ContentIndexExtension // see below
getQuartzComponents(ctx: BuildCtx): QuartzComponent[]
}
```
An emitter plugin must define a `name` field and an `emit` function. Everything else is optional.
An emitter plugin must define a `name` field, an `emit` function, and a `getQuartzComponents` function. It can optionally implement a `partialEmit` function for incremental builds.
- `emit` is responsible for looking at all the parsed and filtered content and then appropriately creating files and returning a list of paths to files the plugin created (or yielding them one by one from an async generator).
- `partialEmit` enables incremental rebuilds in `quartz build --serve`. It receives information about which files have changed (`changeEvents`) and can selectively rebuild only the necessary files. If `partialEmit` is undefined, Quartz calls `emit` again.
- `getQuartzComponents` declares Quartz components the emitter uses, so their CSS and scripts are included in the site.
- `externalResources` adds CSS, scripts or [[#Shipping Files with Your Plugin|assets]] to every page, like a transformer's.
- `emit` is responsible for looking at all the parsed and filtered content and then appropriately creating files and returning a list of paths to files the plugin created.
- `partialEmit` is an optional function that enables incremental builds. It receives information about which files have changed (`changeEvents`) and can selectively rebuild only the necessary files. This is useful for optimizing build times in development mode. If `partialEmit` is undefined, it will default to the `emit` function.
- `getQuartzComponents` declares which Quartz components the emitter uses to construct its pages.
`content` holds the published pages, including the virtual pages that [[#Page Types|page types]] generated (folder and tag pages, `.base` and `.canvas` pages, …). Emitters run after the page types have rendered their pages, **in parallel**, so don't rely on another emitter's output, and treat `ctx` and `content` as read-only. `ctx.contentIndex` is ready by then ([[#Reusing the content index in emitters|see below]]).
Create files with Node's [fs module](https://nodejs.org/api/fs.html) and write them below `ctx.argv.output`. `@quartz-community/utils` has no `write` helper, so plugins define a small one, as in this emitter that writes a JSON list of all pages:
Creating new files can be done via regular Node [fs module](https://nodejs.org/api/fs.html) (i.e. `fs.cp` or `fs.writeFile`) or via the `write` function in `quartz/plugins/emitters/helpers.ts` if you are creating files that contain text. `write` has the following signature:
```ts
import path from "node:path"
import fs from "node:fs/promises"
import type {
BuildCtx,
FilePath,
FullSlug,
ProcessedContent,
QuartzEmitterPlugin,
} from "@quartz-community/types"
import { joinSegments } from "@quartz-community/types"
export type WriteOptions = (data: {
// the build context
ctx: BuildCtx
// the name of the file to emit (not including the file extension)
slug: FullSlug
// the file extension
ext: `.${string}` | ""
// the file content to add
content: string
}) => Promise<FilePath>
```
// write a text file below the output folder, creating directories as needed
const write = async (
ctx: BuildCtx,
slug: FullSlug,
ext: `.${string}` | "",
content: string,
): Promise<FilePath> => {
const fp = joinSegments(ctx.argv.output, slug + ext)
await fs.mkdir(path.dirname(fp), { recursive: true })
await fs.writeFile(fp, content)
return fp
}
This is a thin wrapper around writing to the appropriate output folder and ensuring that intermediate directories exist. If you choose to use the native Node `fs` APIs, ensure you emit to the `argv.output` folder as well.
interface Options {
slug: string
}
If you are creating an emitter plugin that needs to render components, there are three more things to be aware of:
export const PageList: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
const slug = (opts?.slug ?? "pages") as FullSlug
const emitList = async (ctx: BuildCtx, content: ProcessedContent[]) => {
const pages = content.map(([_tree, file]) => ({
slug: file.data.slug,
title: file.data.frontmatter?.title,
}))
return [await write(ctx, slug, ".json", JSON.stringify(pages))]
- Your component should use `getQuartzComponents` to declare a list of `QuartzComponents` that it uses to construct the page. See the page on [[creating components]] for more information.
- You can use the `renderPage` function defined in `quartz/components/renderPage.tsx` to render Quartz components into HTML.
- If you need to render an HTML AST to JSX, you can use the `htmlToJsx` function from `quartz/util/jsx.ts`. An example of this can be found in `quartz/components/pages/Content.tsx`.
For example, the following is a simplified version of the content page plugin that renders every single page.
```tsx title="quartz/plugins/emitters/contentPage.tsx"
export const ContentPage: QuartzEmitterPlugin = () => {
// construct the layout
const layout: FullPageLayout = {
...sharedPageComponents,
...defaultContentPageLayout,
pageBody: Content(),
}
const { head, header, beforeBody, pageBody, afterBody, left, right, footer } = layout
return {
name: "PageList",
emit: (ctx, content) => emitList(ctx, content),
// rebuild the whole file on every change in `quartz build --serve`
partialEmit: (ctx, content) => emitList(ctx, content),
}
}
```
An emitter that wants to render HTML pages with the site's layout should be a [[#Page Types|page type]] instead: Quartz's page renderer isn't exported to plugins. To turn an HTML AST into JSX (e.g. inside a component), use `htmlToJsx` from `@quartz-community/utils`.
### Page Types
Page types define how a category of pages is rendered. They are the primary way to add support for new file types or virtual pages in Quartz.
```ts
export interface QuartzPageTypePluginInstance {
name: string
priority?: number
fileExtensions?: string[]
match: PageMatcher
generate?: PageGenerator
layout: string
frame?: string
body: QuartzComponentConstructor
treeTransforms?: (ctx: BuildCtx) => TreeTransform[]
}
```
- `name`: A unique identifier for this page type.
- `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. The pages of such a page type stand for files: Quartz runs the site's filters on them (Quartz 5.1+), so give each page the file's `filePath` / `relativePath` and, if the file has frontmatter, that frontmatter.
- `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). 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, and while one generates, `ctx.virtualPages` (a Quartz field not declared in `@quartz-community/types`) holds the virtual pages of the page types before it. 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.
- `treeTransforms`: Optional functions `(root, slug, componentData) => void` that change a page's HTML tree when it is rendered, when all pages (`componentData.allFiles`) are known — e.g. to resolve embeds. Quartz applies the transforms of every page type to every page it renders, so check that a node is yours before changing it.
`match` is only asked about content files; a virtual page is rendered by the page type that generated it. All page types run inside one built-in emitter, the page-type dispatcher, which runs before the plugins' emitters. A minimal page type that adds one page per author:
```tsx
import type {
FullSlug,
QuartzComponent,
QuartzComponentConstructor,
QuartzPageTypePlugin,
VirtualPage,
} from "@quartz-community/types"
import { slugifyPath } from "@quartz-community/utils"
const AuthorBody: QuartzComponentConstructor = () => {
const Body: QuartzComponent = ({ fileData, allFiles }) => {
const author = fileData.author as string
const pages = allFiles.filter((f) => f.frontmatter?.author === author)
return (
<ul>
{pages.map((f) => (
<li>{f.frontmatter?.title}</li>
))}
</ul>
)
}
return Body
}
export const AuthorPage: QuartzPageTypePlugin = () => ({
name: "AuthorPage",
// checked before the content page type (priority 0)
priority: 10,
// notes you write under authors/ are rendered by this page type too
match: ({ slug }) => slug.startsWith("authors/"),
generate({ content }) {
const authors = new Set<string>()
for (const [, file] of content) {
const author = file.data.frontmatter?.author
if (typeof author === "string") authors.add(author)
}
return [...authors].map((author): VirtualPage => ({
slug: `authors/${slugifyPath(author)}` as FullSlug,
title: author,
data: { author },
}))
},
layout: "author", // layout.byPageType.author in quartz.config.yaml
body: AuthorBody,
})
```
### 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 type { 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 }) {
return { readingTime: fileData.readingTime }
},
})
declare module "vfile" {
interface DataMap {
readingTime: number
}
}
```
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: Quartz 5.1 sets `ctx.cfg.configuration.links`, `.frontmatter`, `.drafts` and `.contentIndex` to objects with every option (`enabled`, `order`, `markdownLinkResolution`, `enableRSS`, …). Their type also allows `boolean` (what a user may write in YAML) and `undefined` (older Quartz), so narrow before reading an option:
```ts
const links = ctx.cfg.configuration.links
const resolution =
(typeof links === "object" ? links.markdownLinkResolution : undefined) ?? "shortest"
```
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).
To provide a custom frame:
**1. Create the frame file:**
```tsx title="src/frames/MyFrame.tsx"
import type { PageFrame, PageFrameProps } from "@quartz-community/types"
import type { ComponentChildren } from "preact"
export const MyFrame: PageFrame = {
name: "my-frame",
css: `
.page[data-frame="my-frame"] > #quartz-body {
grid-template-columns: 1fr;
grid-template-areas: "center";
}
`,
render({ componentData, pageBody: Content, footer: Footers }: PageFrameProps): unknown {
return (
<div class="center">
{Content(componentData) as ComponentChildren}
{Footers.map((Footer) => Footer(componentData) as ComponentChildren)}
</div>
)
},
}
```
Key requirements:
- `name`: A unique string identifier. This is what page types and YAML config reference.
- `render()`: Receives all layout slots (header, sidebars, content, footer) and returns JSX for the inner page structure. Note that `footer` is a `QuartzComponent[]` (an array) — frames should iterate over it with `.map()` to render all footer components.
- `css` (optional): Frame-specific CSS. Scope it with `.page[data-frame="my-frame"]` selectors to avoid conflicts.
**2. Re-export the frame:**
```ts title="src/frames/index.ts"
export { MyFrame } from "./MyFrame"
```
**3. Declare the frame in `package.json`:**
```json title="package.json"
{
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
name: "ContentPage",
getQuartzComponents() {
return [head, ...header, ...beforeBody, pageBody, ...afterBody, ...left, ...right, footer]
},
async emit(ctx, content, resources, emit): Promise<FilePath[]> {
const cfg = ctx.cfg.configuration
const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data)
for (const [tree, file] of content) {
const slug = canonicalizeServer(file.data.slug!)
const externalResources = pageResources(slug, file.data, resources)
const componentData: QuartzComponentProps = {
fileData: file.data,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await emit({
content,
slug: file.data.slug!,
ext: ".html",
})
fps.push(fp)
}
return fps
},
"./frames": {
"import": "./dist/frames/index.js",
"types": "./dist/frames/index.d.ts"
}
},
"quartz": {
"frames": {
"MyFrame": { "exportName": "MyFrame" }
}
}
}
```
The `"frames"` field in the `"quartz"` manifest maps export names to frame metadata. The key (e.g. `"MyFrame"`) must match the export name in `src/frames/index.ts`.
Note that it takes in a `FullPageLayout` as the options. It's made by combining a `SharedLayout` and a `PageLayout` both of which are provided through the `quartz.layout.ts` file.
**4. Add the frame entry point to your build config:**
```ts title="tsup.config.ts"
export default defineConfig({
entry: {
index: "src/index.ts",
"frames/index": "src/frames/index.ts",
},
// ...
})
```
**5. Reference the frame in your page type:**
```ts
export const MyPageType: QuartzPageTypePlugin = () => ({
name: "MyPageType",
frame: "my-frame", // References the frame by its name property
// ...
})
```
When a user installs your plugin, Quartz automatically loads the frame from the `./frames` export and registers it in the Frame Registry. The frame is then available by name in any page type or YAML config override.
> [!tip]
> See the [`canvas-page`](https://github.com/quartz-community/canvas-page) plugin for a complete real-world example of a plugin-provided frame.
### Bases Views
The `bases-page` plugin provides a database-like view system similar to Obsidian Bases. Other plugins can register custom view types via the `ViewRegistry`:
```tsx
import { viewRegistry } from "@quartz-community/bases-page"
viewRegistry.register({
id: "timeline",
name: "Timeline",
icon: "git-branch",
render: ({ entries }) => (
<div class="bases-timeline">
{entries.map((entry) => (
<div>{entry.title}</div>
))}
</div>
),
css: `.bases-timeline { display: flex; flex-direction: column; }`,
afterDOMLoaded: `document.addEventListener("nav", () => { /* setup */ })`,
})
```
Each view registration includes:
- `id`: Unique identifier (e.g., `"timeline"`, `"kanban"`)
- `name`: Display name shown in the view selector
- `icon`: Optional Lucide icon name
- `render`: Function that receives `ViewRendererProps` and returns Preact JSX
- `css`: Optional CSS string (deduplicated by view ID)
- `afterDOMLoaded`: Optional client-side script (same lifecycle as component scripts)
- `options`: Optional configuration passed to every render invocation
The `ViewRegistry` is a global singleton (via `Symbol.for`) ensuring all copies of the module share the same registry.
### Reporting problems in content
When your plugin fails because of a file's content rather than a bug in your code — a `.canvas` file that isn't valid JSON, a property with a value your plugin can't use, a file it can't read — throw an `Error` with `quartzContent` set to `true` and a message that names the problem:
```ts
const err = new Error(`Invalid canvas: ${parseError.message}`)
;(err as Error & { quartzContent?: boolean }).quartzContent = true
throw err
```
Quartz then reports it as a problem in the file's content ("fix it and build again") instead of asking the user to report a bug in your plugin, and leaves out the stack trace. Errors from transformers name the file being processed; from an emitter or a page type's `generate`, put the file's path in your message. Quartz checks the property, not the class, so plugins don't need to import anything from Quartz; it also finds the property on an error's `cause`. Only use it when the content is at fault — a wrong guess sends users looking for a problem in their notes that isn't there.
## Building and Distribution
Quartz v5 plugins ship pre-built `dist/` in their repositories. When a user installs your plugin, Quartz detects the pre-built output and skips the install/build cycle entirely — making installation near-instant.
### Build Configuration
The plugin template's `tsup.config.ts` bundles all dependencies by default. Only **singleton externals** — packages that must be the same instance across all plugins — are left unbundled:
```ts
const SINGLETON_EXTERNALS = [
"preact",
"preact/hooks",
"preact/jsx-runtime",
"preact/compat",
"@jackyzha0/quartz",
"@jackyzha0/quartz/*",
"vfile",
"vfile/*",
"unified",
]
export default defineConfig({
entry: {
index: "src/index.ts",
types: "src/types.ts",
"components/index": "src/components/index.ts",
},
// ...
noExternal: [/.*/], // Bundle everything
external: SINGLETON_EXTERNALS, // Except singletons
esbuildOptions(options) {
options.jsx = "automatic"
options.jsxImportSource = "preact"
// noExternal: [/.*/] overrides `external`, so set it on esbuild directly
options.external = SINGLETON_EXTERNALS
},
})
```
This means your plugin's `dist/` is self-contained — no `npm install` needed at install time. The three entries build the `.`, `./types` and `./components` exports of the template's `package.json`; Quartz loads components from `./components` (see [[creating components]]).
The singletons are left out so that every plugin uses the same copy. List `preact` (and `vfile` if you use it) in `peerDependencies`, as the template does: Quartz links a plugin's peer dependencies to the site's own `node_modules`, so all plugins share Quartz's Preact and hooks and context work across components of different plugins.
> [!warning] Plugins made from an older template
> Before Quartz 5.1, the template's `tsup.config.ts` set only `external`, which `noExternal: [/.*/]` overrides: those plugins bundle their own Preact, and a component using `preact/hooks` can crash next to other plugins' components. Copy the `esbuildOptions` above (`options.external = SINGLETON_EXTERNALS`) from the current [plugin template](https://github.com/quartz-community/plugin-template), move `preact` to `peerDependencies` and rebuild.
### Shipping Pre-built Output
Your plugin's `dist/` directory should be committed to the repository:
1. **Do NOT add `dist/` to `.gitignore`**
2. Run `npm run build` before committing
The template's CI workflow runs typecheck, lint, format check, tests and a build, then checks `dist/index.js` for imports of packages that are neither bundled, built into Node, shared singletons nor peer dependencies (they would fail at runtime). It does not check that the committed `dist/` matches the source, so rebuild before every commit.
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 "node:path"
import { createRequire } from "node: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<HTMLElement>(".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)
})
```
`window.quartzStaticUrl` is declared in the browser globals of `@quartz-community/types` from 1.3.1 on; the template's `types/globals.d.ts` references them (`/// <reference path="../node_modules/@quartz-community/types/globals.d.ts" />`).
- `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:
1. Set `"requiresInstall": true` in your `package.json` quartz manifest
2. Declare the native package as a `peerDependency`
3. Quartz installs it into the site when it installs your plugin from Git
```shell
# Build the plugin
npm run build
# or
npx tsup
```
## What to Import from Where
| You need... | Import from |
| ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Type definitions (`QuartzTransformerPlugin`, `QuartzComponent`, `BuildCtx`, `FilePath`, etc.) | `@quartz-community/types` |
| Browser globals (`fetchData`, `window.addCleanup`, `window.quartzStaticUrl`, the `nav` / `render` events, …) | `@quartz-community/types/globals.d.ts` (types only, see above) |
| Path utilities (`simplifySlug`, `resolveRelative`, `pathToRoot`, `slugifyFilePath`, `joinSegments`) | `@quartz-community/utils/path` |
| Links: `transformLink` (resolve a link like Quartz does), `splitAnchor`, `linkPathDecodes` | `@quartz-community/utils/path` |
| Heading ids and anchors: `slugHeading`, `HeadingSlugger`, `obsidianHeadingAnchor`, `resolveAnchorHref`; tags: `slugTag` | `@quartz-community/utils/path` |
| DOM utilities (`removeAllChildren`, `registerEscapeHandler`, `normalizeRelativeURLs`) | `@quartz-community/utils/dom` |
| JSX conversion (`htmlToJsx`) | `@quartz-community/utils/jsx` |
| Language utilities (`classNames`, `capitalize`) | `@quartz-community/utils/lang` |
| Date/sort utilities (`formatDate`, `getDate`, `byDateAndAlphabetical`) | `@quartz-community/utils/date` and `@quartz-community/utils/sort` |
| HTML escaping (`escapeHTML`, `unescapeHTML`) | `@quartz-community/utils/escape` |
| Emoji utilities (`getIconCode`) | `@quartz-community/utils/emoji` |
| Browser runtime (`onNav`, `onRender`, `fetchContentIndex`) | `@quartz-community/runtime` |
All utilities are also exported from `@quartz-community/utils` itself. The tables assume `@quartz-community/types` 1.3.0+ and `@quartz-community/utils` 1.2.0+.
A plugin that gives headings ids, or writes links to headings, must use the heading helpers: they make the same ids as GitHub Flavored Markdown and the table of contents (`HeadingSlugger` numbers repeated headings `foo`, `foo-1`, …), so anchors written in Obsidian resolve. See [[paths#Headings and anchors]].
Do **not** import from `@jackyzha0/quartz`: plugins run against whichever Quartz version the site uses. Use the community packages instead. Import `vfile` only for types, such as the `declare module "vfile"` block that adds your `file.data` fields; it is a shared package, so list it in `peerDependencies` rather than bundling it.
## Internationalization (i18n)
Plugins should provide their own translations for user-facing strings. Do **not** hardcode strings in components.
### Setting Up i18n
Create the following structure:
```
src/i18n/
├── index.ts
└── locales/
└── en-US.ts
```
**`src/i18n/locales/en-US.ts`** (required base locale):
```ts
export default {
components: {
myPlugin: {
title: "My Plugin",
description: "A description",
itemCount: ({ count }: { count: number }) => (count === 1 ? "1 item" : `${count} items`),
},
},
}
```
**`src/i18n/index.ts`**:
```ts
import enUS from "./locales/en-US"
const locales: Record<string, typeof enUS> = {
"en-US": enUS,
}
export function i18n(locale: string) {
return locales[locale] || enUS
}
```
### Using i18n in Components
```tsx
import { i18n } from "../i18n"
const MyComponent: QuartzComponent = ({ cfg }) => {
const locale = cfg.locale ?? "en-US"
const t = i18n(locale).components.myPlugin
return <h2>{t.title}</h2>
}
```
### Adding Translations
To add a new locale, copy `en-US.ts`, translate the strings, and register it:
```ts
// src/i18n/locales/fr-FR.ts
export default {
components: {
myPlugin: {
title: "Mon Plugin",
description: "Une description",
itemCount: ({ count }: { count: number }) =>
count === 1 ? "1 élément" : `${count} éléments`,
},
},
}
```
```ts
// src/i18n/index.ts
import enUS from "./locales/en-US"
import frFR from "./locales/fr-FR"
const locales: Record<string, typeof enUS> = {
"en-US": enUS,
"fr-FR": frFR,
}
```
Use [BCP 47](https://en.wikipedia.org/wiki/IETF_language_tag) locale codes (e.g., `en-US`, `de-DE`, `ja-JP`, `zh-CN`). For dynamic content, use function-based translations as shown with `itemCount` above.
## Installing Your Plugin
```shell
# In your Quartz project
npx quartz plugin add github:your-username/my-plugin
```
This clones the plugin and adds it to both `quartz.config.yaml` and `quartz.lock.json`. If the plugin ships pre-built `dist/` (recommended), installation completes in seconds with no build step. You can then configure it in your config:
```yaml title="quartz.config.yaml"
plugins:
- source: github:your-username/my-plugin
enabled: true
```
For options that require JavaScript callback functions (not expressible in YAML), use the TS override in `quartz.ts`:
```ts title="quartz.ts (override)"
import * as ExternalPlugin from "./.quartz/plugins"
// Must be placed before loadQuartzConfig()
ExternalPlugin.MyPlugin({
customFn: (data) => {
// ...
},
})
```
Options set via `quartz.ts` are merged with YAML options at instantiation time, with `quartz.ts` overrides taking precedence. These calls must be placed **before** `loadQuartzConfig()` in your `quartz.ts`.
### Development Workflow
During plugin development, you'll frequently install and uninstall your plugin to test changes. The following commands help manage this cycle:
```shell
# Remove your plugin and clean up
npx quartz plugin remove my-plugin
# Re-add after making changes
npx quartz plugin add github:your-username/my-plugin
```
If you've updated your `quartz.config.yaml` to reference a plugin that isn't installed yet, you can install it without manually running `add`:
```shell
# Install all config-referenced plugins missing from the lockfile
npx quartz plugin install --from-config
# Preview first without making changes
npx quartz plugin install --from-config --dry-run
```
To clean up plugins that are installed but no longer referenced in your config:
```shell
# Remove orphaned plugins
npx quartz plugin prune
# Preview first without making changes
npx quartz plugin prune --dry-run
```
> [!tip]
> Both `install --from-config` and `prune` fall back to `quartz.config.default.yaml` if no `quartz.config.yaml` is present. This is useful for CI environments where the default config is the source of truth. See [[cli/plugin#install|install]] and [[cli/plugin#prune|prune]] for full details.
## Component Plugins
For plugins that provide visual components (like Explorer, Graph, Search), see the [[creating components|creating component plugins]] guide.
Quartz loads components from your package's `./components` export by the names listed in `quartz.components` (see [[plugin manifest#components]]). Component-only plugins (those with `"category": ["component"]` in their manifest) are loaded via side-effect import rather than a factory function. If your component-only plugin needs to receive user options from `quartz.config.yaml`, export an `init(options)` function — see [[creating components#Receiving YAML Options in Component-Only Plugins|receiving YAML options]] for details.
> [!hint]
> Look in `quartz/plugins` for more examples of plugins in Quartz as reference for your own plugins!
+2 -20
View File
@@ -15,7 +15,7 @@ Luckily, we can mimic nominal typing using [brands](https://www.typescriptlang.o
type FullSlug = string
// we do
type FullSlug = string & { _brand: "FullSlug" }
type FullSlug = string & { __brand: "full" }
// that way, the following will fail typechecking
const slug: FullSlug = "some random string"
@@ -25,7 +25,7 @@ While this prevents most typing mistakes _within_ our nominal typing system (e.g
Thus, we still need to be careful when casting from a string to one of these nominal types in the 'entrypoints', illustrated with hexagon shapes in the diagram below.
The following diagram draws the relationships between all the path sources, nominal path types, and what functions convert between them. In Quartz core they live in `quartz/util/path.ts`; plugins import the same functions from `@quartz-community/utils` (the types `FilePath`, `FullSlug` and `SimpleSlug` from `@quartz-community/types`).
The following diagram draws the relationships between all the path sources, nominal path types, and what functions in `quartz/path.ts` convert between them.
```mermaid
graph LR
@@ -49,21 +49,3 @@ Here are the main types of slugs with a rough description of each type of path:
- `RelativeURL`: must start with `.` or `..` to indicate it's a relative URL. Shouldn't have `/index` as an ending or a file extension but can contain a trailing slash.
To get a clearer picture of how these relate to each other, take a look at the path tests in `quartz/util/path.test.ts`.
## A page's slug
`slugifyFilePath()` lowercases, replaces spaces with `-` and normalizes Unicode to NFC (so `café.md` written in NFD, as macOS does, gets the same slug). But a page isn't always published at the slug of its file path: a note with a `permalink` in its frontmatter is published at that address instead (see [[built-in processing]]). Always use `file.data.slug` (or `fileData.slug` in components) for a page's address, and `file.data.relativePath` / `filePath` for its file; don't recompute the slug from the path.
## Links
To resolve a link the way Quartz does, use `transformLink(src, target, { strategy, allSlugs })`: `src` is the current page's slug, `strategy` is the site's `configuration.links.markdownLinkResolution` (`absolute`, `relative` or `shortest`) and `allSlugs` is `ctx.allSlugs`. It decodes percent-encoding, applies the same slug rules as `slugifyFilePath()` and resolves folder notes. A Markdown link whose path doesn't percent-decode (`[x](%zz)`) is external in Obsidian and in Quartz; check with `linkPathDecodes(link)` before treating a link as internal. `splitAnchor(link)` splits off the `#anchor` and slugs it as a heading anchor.
## Headings and anchors
Heading ids follow the GitHub rule (`github-slugger`, as `rehype-slug` and the table of contents use): lowercase, punctuation removed, spaces replaced by `-`, other letters and digits kept. Plugins that give headings ids or link to headings must use the helpers from `@quartz-community/utils`, so ids and anchors match:
- `slugHeading(text)`: the id of a heading with this text;
- `HeadingSlugger`: slugs all headings of one page in order and numbers repeats (`foo`, `foo-1`, …) — create one per page;
- `obsidianHeadingAnchor(text)`: the anchor Obsidian writes for a heading (it replaces `:`, `|`, `^`, `#` and `\` with spaces); slug it with `slugHeading` and add it as an extra id when it differs;
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, a block reference `#^name`, or a heading's text);
- `slugTag(tag)`: the slug of a tag, as used for tag pages.
-119
View File
@@ -1,119 +0,0 @@
---
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": "quartz:links",
"reason": "the backlinks list is always empty"
}
]
},
"optional": {
"data": [
{
"name": "frontmatter",
"from": "quartz:frontmatter",
"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. `"syntax-highlighting"`) 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. [[built-in processing|Built-ins]] are named `quartz:frontmatter`, `quartz:links`, `quartz:drafts` and `quartz:contentIndex` (the names of the plugins they replaced, `crawl-links`, `remove-draft` and `content-index`, work too).
- `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`, `quartzStaticUrl`, `quartzPrefetch` (the last is only set while [[prefetching]] is on)
- 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 Quartz 5.1, `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: for that, set [[plugin manifest#defaultOrder|`defaultOrder`]] (and [[plugin manifest#dependencies|`dependencies`]]: a missing dependency or one ordered after your plugin fails the build, a disabled one is a warning).
## 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`. Built-in links also provides the DOM classes `.internal`, `.external` and `.broken`, and the content index `sitemap.xml`. When one is turned off, warnings suggest `configuration.<key>` (a `from: "crawl-links"` or `"quartz: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. Built-in drafts can't be replaced.
## Who declares capabilities
In Quartz 5.1, these first-party plugins declare capabilities: `backlinks`, `description`, `syntax-highlighting`, `obsidian-flavored-markdown` and `search` (and the plugins replaced by built-ins: `note-properties`, `crawl-links`, `remove-draft`, `content-index`). Plugins without declarations are never checked and never cause warnings, so third-party plugins can add them at their own pace.
Not implemented (yet): printing unsatisfied `optional` requirements, turning warnings into errors, ordering checks between transformers, and option-aware `provides`. The capability types are not exported from `@quartz-community/types`; the schema above is the contract.
-160
View File
@@ -1,160 +0,0 @@
---
title: Plugin manifest
---
The `quartz` field of a plugin's `package.json` is its **manifest**: it tells Quartz what kind of plugin it is, where it runs in the pipeline, which components and frames it ships and what it needs. Quartz reads it from the installed package (`node_modules/<package>/package.json` for npm plugins, `.quartz/plugins/<name>/package.json` for Git and local plugins). See [[making plugins]] for how to write the plugin itself.
```json title="package.json"
{
"name": "@you/my-plugin",
"version": "1.2.0",
"description": "Adds reading times",
"exports": {
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
"./components": {
"types": "./dist/components/index.d.ts",
"import": "./dist/components/index.js"
}
},
"quartz": {
"name": "my-plugin",
"displayName": "My Plugin",
"category": ["transformer", "component"],
"quartzVersion": ">=5.1.0",
"defaultOrder": 70,
"defaultEnabled": true,
"defaultOptions": { "wordsPerMinute": 200 },
"configSchema": {
"type": "object",
"properties": { "wordsPerMinute": { "type": "number" } },
"additionalProperties": false
},
"components": {
"ReadingTime": {
"displayName": "Reading time",
"description": "Shows how long a page takes to read",
"defaultPosition": "beforeBody",
"defaultPriority": 40
}
},
"capabilities": {
"provides": { "data": ["readingTime"] }
}
}
}
```
## Fields
| Field | Type | Default |
| ----------------- | -------------------------------------- | ------------------------------- |
| `name` | `string` | the package / directory name |
| `displayName` | `string` | `name` |
| `description` | `string` | the package's `description` |
| `category` | category, or an array of categories | detected from the entry module |
| `quartzVersion` | semver range | none (works with every version) |
| `deprecated` | `string` | none |
| `dependencies` | `string[]` (plugin sources) | `[]` |
| `defaultOrder` | `number` | `50` |
| `defaultEnabled` | `boolean` | `true` |
| `defaultOptions` | object | `{}` |
| `configSchema` | JSON Schema of the options object | none |
| `components` | `{ [exportName]: { displayName, … } }` | none |
| `frames` | `{ [exportName]: { exportName } }` | none |
| `requiresInstall` | `boolean` | `false` |
| `capabilities` | `{ provides?, requires?, optional? }` | none |
`author` and `homepage` fall back to the package's own fields; the bug-report link Quartz prints when a plugin fails comes from the package's `bugs` or `repository` field.
### `name`, `displayName`, `description`
`name` is the short name Quartz uses in error messages and that other plugins name in the `from` of their [[plugin capabilities|capability]] requirements. `displayName` (used in dependency errors) and `description` describe the plugin to people, e.g. in the TUI.
### Version
Quartz uses the package's `version`. A `quartz.version` field (the plugin template used to ship one) is only used when the package has no `version`, so you don't need to keep it in sync.
### `category`
One of `"transformer"`, `"filter"`, `"emitter"`, `"pageType"` or `"component"`, or an array for a plugin that is several things at once (e.g. `["transformer", "component"]`). For each processing category (everything except `component`), Quartz looks for the plugin's factory in the entry module (`.`): the `default` export, else a `plugin` export, else the only exported function, else the exported function that returns an instance with that category's methods when called without options. A plugin with several processing categories should therefore not have a `default` export, since Quartz would use it for every category.
A plugin whose categories are all `"component"` is loaded differently: Quartz imports its entry module for its side effects, calls its `init(options)` export if there is one (see [[creating components#Receiving YAML Options in Component-Only Plugins|receiving YAML options]]) and loads its components.
Without a `category`, Quartz tries to detect it from the entry module; if it can't and the plugin declares no components, the plugin is skipped with an error. Set it.
### `quartzVersion`
The Quartz versions the plugin works with, as a semver range (`">=5.1.0"`). Locally a mismatch is a warning; in CI the build fails. See [[versioning#For plugin authors]].
### `deprecated`
A message saying why the plugin is deprecated and what replaces it. Quartz 5.1+ warns while the plugin is enabled (during the build, in `plugin add` and in `plugin doctor`); the plugin keeps working.
### `dependencies`
Other plugins that must run for this one to work, as plugin sources. Each one is matched **exactly** against the `source` of the entries in `quartz.config.yaml`: `"@quartz-community/foo"` doesn't match an entry `github:quartz-community/foo`, so use the form the default config uses (the npm package name for official plugins). The build **fails** when a dependency isn't in the config at all, when it runs later than the plugin (its order is higher), or when dependencies form a cycle. A dependency that is in the config but disabled is a warning.
Don't declare `crawl-links`, `remove-draft` or `content-index`: they are [[built-in processing]] since Quartz 5.1, which treats such a dependency as satisfied by the built-in, but Quartz 5.0 fails the build when the plugin is not in the config. Declare what you need from them as [[plugin capabilities|capabilities]] instead (`requires: { data: ["links"] }`), and order your plugin after them with `defaultOrder`.
### `defaultOrder`
Where the plugin runs among plugins of the same category, lower first, when the user's config entry sets no `order`. Built-ins take part in the same scale (on equal order a built-in runs first). For transformers:
| Order | Transformer |
| ----- | ---------------------------------------------- |
| 0 | built-in frontmatter (`file.data.frontmatter`) |
| 10 | `created-modified-date` |
| 20 | `syntax-highlighting` |
| 30 | `github-flavored-markdown` |
| 40 | `obsidian-flavored-markdown` |
| 50 | default |
| 60 | built-in links (`file.data.links`) |
| 70 | `description` |
A transformer that reads `file.data.links` must do so in `htmlPlugins` (it isn't set yet while `markdownPlugins` run) and have an order above 60. Filters and emitters run in order too (the built-in drafts filter and content index emitter are at 50), although emitters run in parallel.
### `defaultEnabled`, `defaultOptions`
`npx quartz plugin add` writes the plugin's entry with `enabled: defaultEnabled`, `order: defaultOrder` and `options: defaultOptions`, so a later change to `defaultOrder` only reaches entries without an `order`. When Quartz loads the plugin, it merges the options as `{ ...defaultOptions, ...options from quartz.config.yaml, ...options from quartz.ts }` and passes the result to the factory (or to `init`).
### `configSchema`
A JSON Schema for the options object. Quartz warns about likely mistakes in a plugin's `options` when it loads the config and in `npx quartz plugin doctor`:
- an option name that looks like a typo of a known one (`did you mean …?`), or any unknown option when the schema sets `"additionalProperties": false`;
- a value of the wrong type (`properties.<name>.type`, with `"integer"` counted as a number);
- a value not in `properties.<name>.enum`.
Options are known from `properties` and from the keys of `defaultOptions`; without a schema, types are inferred from `defaultOptions`, and a value of the same type as an option's default is always accepted.
First-party plugins declare their options as `optionSchema` instead, a flat map of option name to type that [Quartz Syncer](https://github.com/saberzero1/quartz-syncer) also uses for its settings. Quartz reads it the same way, with `"enum"` plus `values` for a choice:
```json title="package.json"
"optionSchema": {
"limit": { "type": "number", "description": "How many notes to list" },
"mode": { "type": "enum", "values": ["light", "dark"] },
"showTags": { "type": "boolean" }
}
```
### `components`
The components the plugin provides, keyed by export name. Quartz imports them from the package's **`./components`** export (not the entry module) and registers each name it finds there; a name missing from `./components` is reported as a warning. Each entry can set:
- `displayName`, `description`: describe the component, e.g. in the TUI;
- `defaultPosition`: the layout slot used when the user's `layout:` block has no `position` (`header`, `left`, `right`, `beforeBody`, `afterBody` or `footer`). Without either, the component isn't placed;
- `defaultPriority`: the order within that slot when the user sets none (default 50, lower first).
See [[creating components]].
### `frames`
[[layout#Page Frames|Page frames]] the plugin provides, keyed by export name, loaded from the package's `./frames` export. See [[making plugins#Providing Custom Frames]].
### `requiresInstall`
Set it when the plugin needs native packages that can't be bundled (e.g. `sharp`). Quartz then installs the plugin's `peerDependencies` (except the packages it shares with plugins, like Preact) into the site when it installs the plugin from Git. See [[making plugins#Plugins with Native Dependencies]].
### `capabilities`
What the plugin provides to and needs from other plugins (`file.data` keys, DOM classes, globals, events, files, CSS variables), so Quartz can warn when a provider is missing. See [[plugin capabilities]].
-59
View File
@@ -1,59 +0,0 @@
---
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`), an async page type `generate`, `virtualPageHtmlPlugins`, `assets` or `window.quartzStaticUrl` needs `">=5.1.0"`. The [plugin template](https://github.com/quartz-community/plugin-template) starts with `">=5.0.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.
+47
View File
@@ -0,0 +1,47 @@
---
title: Authoring Content
---
All of the content in your Quartz should go in the `/content` folder. The content for the home page of your Quartz lives in `content/index.md`. If you've [[index#🪴 Get Started|setup Quartz]] already, this folder should already be initialized. Any Markdown in this folder will get processed by Quartz.
It is recommended that you use [Obsidian](https://obsidian.md/) as a way to edit and maintain your Quartz. It comes with a nice editor and graphical interface to preview, edit, and link your local files and attachments.
Got everything setup? Let's [[build]] and preview your Quartz locally!
## Syntax
As Quartz uses Markdown files as the main way of writing content, it fully supports Markdown syntax. By default, Quartz also ships with a few syntax extensions like [Github Flavored Markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) (footnotes, strikethrough, tables, tasklists) and [Obsidian Flavored Markdown](https://help.obsidian.md/Editing+and+formatting/Obsidian+Flavored+Markdown) ([[callouts]], [[wikilinks]]).
Additionally, Quartz also allows you to specify additional metadata in your notes called **frontmatter**.
```md title="content/note.md"
---
title: Example Title
draft: false
tags:
- example-tag
---
The rest of your content lives here. You can use **Markdown** here :)
```
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.
- `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.
See [[Frontmatter]] for a complete list of frontmatter.
## Syncing your Content
When your Quartz is at a point you're happy with, you can save your changes to GitHub.
First, make sure you've [[setting up your GitHub repository|already setup your GitHub repository]] and then do `npx quartz sync`.
## 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.
+27
View File
@@ -0,0 +1,27 @@
---
title: "Building your Quartz"
---
Once you've [[index#🪴 Get Started|initialized]] Quartz, let's see what it looks like locally:
```bash
npx quartz build --serve
```
This will start a local web server to run your Quartz on your computer. Open a web browser and visit `http://localhost:8080/` to view it.
> [!hint] Flags and options
> For full help options, you can run `npx quartz build --help`.
>
> Most of these have sensible defaults but you can override them if you have a custom setup:
>
> - `-d` or `--directory`: the content folder. This is normally just `content`
> - `-v` or `--verbose`: print out extra logging information
> - `-o` or `--output`: the output folder. This is normally just `public`
> - `--serve`: run a local hot-reloading server to preview your Quartz
> - `--port`: what port to run the local preview server on
> - `--concurrency`: how many threads to use to parse notes
> [!warning] Not to be used for production
> Serve mode is intended for local previews only.
> For production workloads, see the page on [[hosting]].
-92
View File
@@ -1,92 +0,0 @@
---
title: quartz build
aliases:
- build
---
The `build` command transforms your Markdown content into a static HTML website. It processes your files through the configured plugins and outputs the final site to a directory of your choice.
## Flags
| Flag | Shorthand | Description | Default |
| ----------------- | --------- | ---------------------------------------------------------------------------------- | ------------------ |
| `--directory` | `-d` | The content folder | `content` |
| `--verbose` | `-v` | Print detailed build information (see [[#Verbose output]]) | `false` |
| `--output` | `-o` | The directory where the built site will be saved | `public` |
| `--serve` | | Start a local development server | `false` |
| `--watch` | | Rebuild the site when files change | `false` |
| `--port` | | The port for the development server | `8080` |
| `--wsPort` | | The port for the WebSocket hot-reload server | `3001` |
| `--baseDir` | | Base path the development server serves the site under | `""` (none) |
| `--remoteDevHost` | | Hostname for the hot-reload WebSocket when not developing on localhost | `""` (`localhost`) |
| `--bundleInfo` | | Print an analysis of Quartz's own esbuild bundle (files and sizes) to the terminal | `false` |
| `--concurrency` | `-c` | Number of worker threads to use for building | CPU core count |
## Examples
### Basic Build
Generate your site into the `public` folder.
```shell
npx quartz build
```
### Development Mode
Start a local server and watch for changes. This is the most common way to preview your site while writing.
```shell
npx quartz build --serve
```
### Custom Output and Port
Build to a specific folder and run the server on a different port.
```shell
npx quartz build --serve --output dist --port 3000
```
### Performance Tuning
If you have a very large vault, you can limit the number of concurrent workers to save memory.
```shell
npx quartz build --concurrency 2
```
### Verbose output
`npx quartz build --verbose` also prints:
- the plugins loaded, in the order they run (transformers, filters, emitters, page types)
- the [[built-in processing|built-ins]] and whether each is on (with its order) or off, and why
- a layout report: which components each page type renders in each slot (see [[layout#Checking your layout]])
- every link to a page that is not on the site (including links to drafts) — without `--verbose` the end-of-build summary counts them and shows a few examples
- every file each emitter writes
### In CI
When the `CI` environment variable is set (GitHub Actions, Cloudflare Pages, Netlify, Vercel, … set it), the build fails on plugins that fail to load or that need a newer Quartz, instead of warning. Set `QUARTZ_ALLOW_BROKEN_PLUGINS=1` or `QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS=1` to build anyway. See [[troubleshooting#Reading build output]].
## Serve vs Watch
The `--serve` and `--watch` flags control different behaviors:
- **`--serve`** starts a local development server AND automatically watches for changes (implies `--watch`). This is the recommended mode for local development.
- **`--watch`** only watches for file changes and rebuilds automatically, without starting a server. This is useful for CI pipelines or custom server setups where you want automatic rebuilds but handle serving separately.
In most cases, you want `--serve`:
```shell
npx quartz build --serve
```
## Development Server
The `--serve` flag starts a local web server. This server is intended for development and previewing only. It is not designed for production use. For information on how to deploy your site, see [[hosting]].
### Hot Reloading
When running with `--serve`, Quartz automatically enables `--watch`. It uses a WebSocket connection (on the port specified by `--wsPort`) to notify your browser when a file has changed. The browser will then automatically refresh to show the latest version of your content.
-84
View File
@@ -1,84 +0,0 @@
---
title: quartz create
---
The `create` command initializes a new Quartz project. It helps you set up your content folder, choose a configuration template, set your site's base URL, and configure how Quartz should handle your Markdown files.
## Flags
| Flag | Shorthand | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| `--template` | `-t` | Configuration template (`default`, `obsidian`, `ttrpg`, `blog`, or `docs`) |
| `--directory` | `-d` | The content folder to set up (default: `content`) |
| `--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
When you run `quartz create`, you can choose a configuration template that pre-configures Quartz for your use case. The selected template always overwrites `quartz.config.yaml`, even if one already exists. After applying the template, Quartz automatically runs plugin resolution to install any plugins the template requires and remove any that are no longer referenced.
- **Default**: A clean Quartz setup with sensible defaults. Best for starting from scratch.
- **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
During setup, Quartz will ask for the base URL of your site. This is the URL where your site will be deployed (e.g. `mysite.github.io/quartz`).
- Do **not** include the protocol (`https://`) — if you do, it will be automatically stripped.
- Trailing slashes are also removed automatically.
- See [[configuration]] for more details on how `baseUrl` is used.
## Strategies
When you run `quartz create`, you must choose a strategy for your content:
- **new**: Creates a fresh, empty content folder. Use this if you are starting a new project from scratch.
- **copy**: Copies all files from your source directory into the Quartz content folder. This is the safest option for existing vaults as it doesn't touch your original files.
- **symlink**: Creates a symbolic link from the Quartz content folder to your source directory. Any changes you make in your source directory (e.g. in Obsidian) will be immediately reflected in Quartz.
## Link Resolution
Quartz needs to know how to interpret the internal links in your Markdown files:
- **shortest**: Resolves links to the closest matching file name. This is the default for Obsidian.
- **absolute**: Resolves links relative to the root of your content folder.
- **relative**: Resolves links relative to the current file's location.
> [!note]
> When using the **Obsidian** or **TTRPG** templates, link resolution is automatically set to `shortest` and the prompt is skipped.
## Interactive Walkthrough
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`, `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).
5. **Finish**: Quartz will set up the directory structure, create your configuration, and automatically install any plugins referenced in the template.
## Example: Importing an Obsidian Vault
To create a Quartz project that links directly to an existing Obsidian vault:
```shell
npx quartz create --template obsidian --strategy symlink --source ~/Documents/MyVault
```
This command tells Quartz to use the Obsidian template (with full OFM support and shortest link resolution), look at your vault in `~/Documents/MyVault`, and use symbolic links so changes are synced.
## Example: Setting Up a Blog
To quickly set up a blog with recent notes and comments:
```shell
npx quartz create --template blog --strategy new --baseUrl myblog.github.io
```
After setup, edit `quartz.config.yaml` to fill in your giscus repository details in the comments plugin section.
-57
View File
@@ -1,57 +0,0 @@
---
title: CLI Reference
---
The Quartz CLI is the primary way to interact with your Quartz project. It provides commands for creating new projects, building static sites, syncing with GitHub, and managing plugins.
You can run the CLI using `npx quartz`.
## Quick Reference
| Command | Description | Example |
| --------- | ------------------------------------------------------- | ------------------------ |
| `create` | Initialize a new Quartz project with template selection | `npx quartz create` |
| `build` | Generate static HTML files | `npx quartz build` |
| `sync` | Sync content with GitHub | `npx quartz sync` |
| `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, 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, and `plugin doctor` to diagnose plugin problems.
- [[tui|tui]]: Use a terminal interface to manage plugins and layout.
- `info`: Print your Quartz version (with its git state), 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. See [[versioning]].
## Global Flags
These flags are accepted by every Quartz command:
| Flag | Shorthand | Description | Default |
| --------------- | --------- | ------------------------------------------------------------------------------------------------------- | -------------- |
| `--directory` | `-d` | The content folder (relative to your Quartz project) | `content` |
| `--verbose` | `-v` | Enable detailed logging for debugging | `false` |
| `--concurrency` | `-c` | Max parallel workers for operations that run in parallel (e.g. `build`, `plugin install`, `plugin add`) | CPU core count |
Commands that don't perform parallel work accept `-c` as a no-op, so it's always safe to pass. See [[build#Performance Tuning|build]] and [[cli/plugin#Installing on low-end hardware|plugin]] for practical examples.
## Help and Versioning
To see a full list of available flags for any command, use the `--help` flag.
```shell
npx quartz --help
npx quartz build --help
```
To check which version of Quartz you are currently running, use the `--version` flag.
```shell
npx quartz --version
```
-351
View File
@@ -1,351 +0,0 @@
---
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.
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 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
```
### add
Add a new plugin from npm or a Git repository. The plugin is installed (Git plugins are pinned in `quartz.lock.json`, npm packages recorded in `package.json`), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
```shell
npx quartz plugin add @quartz-community/graph # an npm package, as the default config uses
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:
```shell
npx quartz plugin add github:username/repo#my-branch
npx quartz plugin add git+https://github.com/username/repo.git#my-branch
npx quartz plugin add https://github.com/username/repo.git#my-branch
```
You can also add a plugin from a local directory. This is useful for local development or airgapped environments:
```shell
npx quartz plugin add ./path/to/my-plugin
npx quartz plugin add ../sibling-plugin
npx quartz plugin add /absolute/path/to/plugin
```
Local plugins are symlinked into `.quartz/plugins/`, so any changes you make to the source directory are reflected immediately without re-installing.
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 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, 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`: 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.
#### Positional Arguments
- `[names..]`: Optional list of specific plugin names to install or update.
```shell
# Update specific plugins to latest
npx quartz plugin install --latest plugin-a plugin-b
# Preview what would be installed from config
npx quartz plugin install --from-config --dry-run
```
### enable / disable
Toggle a plugin's status in your `quartz.config.yaml` without removing its files.
```shell
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 options of a specific plugin.
```shell
# View the options you set, plus the plugin defaults you have not overridden
npx quartz plugin config explorer
# 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]])
- deprecated plugins (their `quartz.deprecated` message names the replacement)
- entries for plugins that are now [[built-in processing|built into Quartz]] (`crawl-links`, `remove-draft`, `content-index`) and note-properties' `delimiters`/`language` options; `--fix` moves them into `configuration` (`links`, `drafts`, `contentIndex`, `frontmatter`), keeping your comments, and removes the 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.
> [!note]
> Running `plugin install --from-config` also removes orphaned plugins as part of its synchronization. Use `prune` when you only want to clean up without installing anything new.
```shell
npx quartz plugin prune
```
Use `--dry-run` to preview which plugins would be removed without making changes:
```shell
npx quartz plugin prune --dry-run
```
## Common Workflows
### Adding and Enabling a Plugin
`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):
```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
To keep your plugins fresh:
```shell
npx quartz plugin install --latest
```
### Installing on low-end hardware
By default, `plugin install` and `plugin add` clone, fetch, and build plugins in parallel across all your CPU cores. On memory-constrained machines (low-end laptops, Raspberry Pi, small VPS instances, restrictive CI runners) this can exhaust RAM or overwhelm the system because each worker may kick off its own `npm install` / `npm run build` at the same time.
> [!note]
> Most community plugins now ship with a pre-built `dist/` directory. When Quartz finds this, it skips the installation and build steps entirely, making the process much faster and lighter on resources. This section is primarily relevant for plugins in development or those that don't provide pre-built distribution.
If `plugin install` fails, hangs, or OOMs on your machine, lower the concurrency with `--concurrency` / `-c`:
```shell
# Install one plugin at a time (safest, slowest)
npx quartz plugin install --latest -c 1
# Two at a time — usually a good balance on 4 GB machines
npx quartz plugin install --latest --concurrency 2
```
The same flag works on `plugin add` and the other plugin subcommands that perform parallel work:
```shell
npx quartz plugin add github:quartz-community/some-plugin -c 1
```
### Managing Configuration
If you want to change a plugin setting without opening the YAML file:
```shell
npx quartz plugin config explorer --set useSavedState=true
```
### Cleaning Up Unused Plugins
If you've removed plugins from your config and want to clean up leftover files:
```shell
npx quartz plugin prune --dry-run # preview first
npx quartz plugin prune # remove orphaned plugins
```
### Setting Up from Config
When setting up on a new machine or in CI, `install --from-config` ensures your installed plugins match your config — installing missing plugins and removing any that are no longer referenced:
```shell
npx quartz plugin install --from-config
```
### Testing with Branches
If a plugin author has a fix or feature on a separate branch, you can install it directly without waiting for a release to the default branch:
```shell
# Install from a feature branch
npx quartz plugin add github:username/repo#fix/some-bug
# Later, switch back to the default branch by re-adding without a ref
npx quartz plugin remove repo
npx quartz plugin add github:username/repo
```
The branch ref is tracked in `quartz.lock.json`, so `install --latest` will continue to follow the specified branch until the plugin is re-added without one.
Both `prune` and `install --from-config` will fall back to `quartz.config.default.yaml` if no `quartz.config.yaml` is present.
### Local Plugin Development
For local plugin development or airgapped environments, you can add a plugin from a local directory:
```shell
npx quartz plugin add ./my-local-plugin
```
Local plugins are symlinked into `.quartz/plugins/`, so changes reflect immediately. When you run `install --latest`, local plugins are rebuilt (npm install + npm run build) without any git operations.
> [!note]
> Local symlinked plugins typically use this build-on-install fallback because the `dist/` directory is usually gitignored during development.
The `install --latest --dry-run` command will show local plugins with a "local" status instead of checking for remote updates.
To switch a local plugin back to a git source:
```shell
npx quartz plugin remove my-local-plugin
npx quartz plugin add github:username/my-local-plugin
```
### Subdirectory (Monorepo) Plugins
Some plugins live in a subdirectory of a larger repository rather than at the root. For these, you can specify the plugin source as an object in `quartz.config.yaml` with a `subdir` field:
```yaml title="quartz.config.yaml"
plugins:
- source:
repo: "https://github.com/username/monorepo.git"
subdir: plugin
enabled: true
```
This tells Quartz to clone the full repository but install only the contents of the specified subdirectory.
You can combine `subdir` with `ref` to pin a branch or tag, and `name` to override the plugin directory name:
```yaml title="quartz.config.yaml"
plugins:
- source:
repo: "https://github.com/username/monorepo.git"
subdir: packages/my-plugin
ref: v2.0
name: my-plugin
enabled: true
```
See [[configuration#Advanced Source Options|Advanced Source Options]] for the full reference on object source fields.
> [!note]
> The `plugin add` CLI command works with string sources. To use the object source format with `subdir`, edit `quartz.config.yaml` directly, then run `npx quartz plugin install --from-config` to install it.
## Migration from Deprecated Commands
| Old command | New equivalent |
| ------------------------------------- | --------------------------------------------------- |
| `npx quartz plugin restore` | `npx quartz plugin install --clean` |
| `npx quartz plugin update` | `npx quartz plugin install --latest` |
| `npx quartz plugin update my-plugin` | `npx quartz plugin install --latest my-plugin` |
| `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` |
The old commands still work as hidden aliases but will print a deprecation warning.
## Plugin Status
Running the plugin command without any subcommand shows a status dashboard of all installed plugins, including whether updates are available:
```shell
npx quartz plugin
```
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.
-31
View File
@@ -1,31 +0,0 @@
---
title: quartz restore
---
The `restore` command is a safety mechanism that allows you to recover your **content folder** from a local cache. This command only affects your Markdown files and does not restore plugins or configuration.
To restore plugins to a specific state, use [[cli/plugin|npx quartz plugin install]].
## When to Use
You should use `restore` if:
- A `quartz upgrade` failed and corrupted your content.
- You accidentally deleted files in your content folder.
- You encountered complex merge conflicts that you want to undo.
## How it Works
Quartz maintains a hidden cache of your content folder. Every time you run certain commands, Quartz ensures that a backup of your Markdown files exists. The `restore` command simply copies these files back into your main content directory.
```shell
npx quartz restore
```
## Example Workflow
If an update fails and leaves your project in a broken state:
1. **Restore**: Run `npx quartz restore` to bring back your content.
2. **Clean**: Use Git to reset any other broken code files.
3. **Retry**: Attempt the update again or manually apply the changes you need.
-76
View File
@@ -1,76 +0,0 @@
---
title: quartz sync
---
The `sync` command automates the process of pushing your local changes to GitHub and pulling updates from your remote repository. It simplifies the Git workflow for users who want to keep their site updated without running manual Git commands.
## Flags
| Flag | Shorthand | Description | Default |
| ------------- | --------- | ----------------------------------- | -------------------------- |
| `--directory` | `-d` | The content folder | `content` |
| `--verbose` | `-v` | Enable detailed logging | `false` |
| `--commit` | | Whether to commit changes | `true` |
| `--no-commit` | | Skip committing changes | `false` |
| `--message` | `-m` | Custom commit message | `Quartz sync: <date time>` |
| `--push` | | Whether to (force-)push to remote | `true` |
| `--no-push` | | Skip pushing changes | `false` |
| `--pull` | | Whether to pull changes from remote | `true` |
| `--no-pull` | | Skip pulling changes | `false` |
## Workflow
When you run `npx quartz sync`, Quartz performs the following steps:
1. **Commit**: It stages all new and modified files in your project (`git add .`) and commits them.
2. **Pull**: It merges the `v5` branch of your repository (`origin`) into your branch.
3. **Push**: It force-pushes your current branch to `origin` (`git push -uf`).
> [!warning] `sync` force-pushes
> The push overwrites the remote branch with your local one. If you skip the pull (`--no-pull`) while the remote has commits you don't have — for example from another device or a GitHub edit — those commits are lost on the remote.
## Common Workflows
### Regular Sync
The most common usage is to simply run the command with no flags. This commits, pulls, and pushes everything.
```shell
npx quartz sync
```
### First Sync
If you have just set up a new repository and haven't pushed anything yet, you might want to skip the pull step.
```shell
npx quartz sync --no-pull
```
### Custom Commit Message
You can provide a more descriptive message for your changes.
```shell
npx quartz sync --message "add new notes about gardening"
```
### Sync from Another Device
If you are working on a different computer and just want to get the latest changes without pushing anything back yet.
```shell
npx quartz sync --no-push --no-commit
```
## Troubleshooting
### Git Buffer
If you have a very large number of changes, Git might occasionally fail due to buffer limits. If this happens, try syncing smaller batches of files or increasing your Git post buffer size.
### Autostash
Quartz pulls with `git pull --no-rebase --autostash --no-edit --allow-unrelated-histories`: remote changes are merged (not rebased) without opening an editor, and uncommitted changes (e.g. with `--no-commit`) are set aside during the pull and brought back afterwards. If a conflict occurs, resolve it with standard Git tools, commit, and run `npx quartz sync --no-pull`.
For more information on initial setup, see [[installation]].
-64
View File
@@ -1,64 +0,0 @@
---
title: quartz tui
---
The `tui` command launches an interactive terminal user interface for managing your Quartz project. It provides a visual way to manage plugins, arrange your site layout, and edit general settings.
## Prerequisites
To use the TUI, you must have the following:
1. **Bun**: The TUI requires the Bun runtime. You can find installation instructions at [bun.sh](https://bun.sh/docs/installation).
2. **TUI Plugin**: You must install the TUI plugin in your Quartz project.
### Installation
Run the following command to add the TUI plugin:
```shell
npx quartz plugin add github:quartz-community/tui
```
## Interface Panels
The TUI is divided into three main panels that you can navigate between.
### Plugins Panel
This panel allows you to browse all available and installed plugins. You can:
- Enable or disable plugins with a single keystroke.
- Configure plugin-specific settings.
- Install new plugins from the community or remove existing ones.
### Layout Panel
The Layout panel is where you define where components appear on your site. You can:
- Move components between different sections (e.g. `left`, `right`, `beforeBody`).
- Reorder components within a section to change their vertical stack.
- Set priorities for components to control their placement.
### Settings Panel
This panel provides a central place to edit your `quartz.config.yaml` settings. You can update:
- `pageTitle`
- Theme colors and fonts
- Analytics configuration
- Deployment settings
## Navigation
The TUI uses standard terminal navigation keys:
- **Arrow Keys**: Move between items and panels.
- **Enter**: Select an item or confirm a change.
- **Esc**: Go back or cancel an action.
- **Tab**: Cycle through different interface elements.
## Important Note
All changes made within the TUI are written directly to your `quartz.config.yaml` file. It is a good practice to have a clean Git state before using the TUI so you can easily review and undo any changes it makes.
For command-line based plugin management, see [[cli/plugin|quartz plugin]].
-51
View File
@@ -1,51 +0,0 @@
---
title: quartz upgrade
---
The `upgrade` command upgrades the Quartz framework itself to the latest version by pulling changes from the official Quartz repository.
## Usage
```shell
npx quartz upgrade
```
## How it Works
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. **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
Because Quartz allows you to customize almost every part of the code, upgrades can sometimes result in merge conflicts. This happens if you have modified a file that the Quartz team has also updated.
Quartz automatically handles merge conflicts in `quartz.lock.json` by backing up your lockfile before pulling and restoring it afterward. This prevents the most common source of conflicts during upgrades.
For other files, if a conflict occurs:
1. Git will mark the conflicting sections in the affected files.
2. You will need to open these files and manually choose which changes to keep.
3. After resolving the conflicts, you can commit the changes.
## Recovery
If an upgrade goes wrong or leaves your project in an unusable state, you can use the [[restore|restore]] command to recover your content from the local cache.
## Flags
The `upgrade` command supports the standard [[cli/index|common flags]] (`--directory`, `--verbose`).
## See Also
- [[cli/plugin|quartz plugin install --latest]] — update installed plugins
- [[upgrading|Upgrading Quartz]] — detailed upgrading guide
- [[restore|quartz restore]] — recover content from cache
-60
View File
@@ -1,60 +0,0 @@
---
title: Community
---
Quartz has a vibrant community of users and contributors. This page highlights community-created plugins, tools, and resources that extend Quartz.
> [!tip] Contributing
> Know of a great community resource? Submit a pull request to add it to this page!
## Community Plugins
Third-party plugins that extend Quartz functionality. Install them with the [[cli/plugin|plugin CLI]]:
```bash
npx quartz plugin add <github-url>
```
<!-- Add community plugins here as they become available -->
<!-- Format: - **[Plugin Name](link)** — Brief description -->
_No community plugins listed yet. Be the first to share yours!_
## Tools & Integrations
Tools, scripts, and integrations built by the community to work with Quartz.
<!-- Add tools here -->
<!-- Format: - **[Tool Name](link)** — Brief description -->
_No community tools listed yet._
## Templates & Themes
Custom themes, CSS snippets, and starter templates for Quartz sites.
<!-- Add templates/themes here -->
<!-- Format: - **[Name](link)** — Brief description -->
- **[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
Community-written guides, blog posts, and tutorials about using Quartz.
<!-- Add guides here -->
<!-- Format: - **[Title](link)** by Author — Brief description -->
_No community guides listed yet._
## Related Projects
Projects and tools in the digital garden / PKM ecosystem that pair well with Quartz.
- **[Obsidian](https://obsidian.md/)** — Knowledge base and note-taking app (recommended editor for Quartz content)
---
Looking to see sites built with Quartz? Check out the [[showcase|Quartz Showcase]].
Want to chat with other Quartz users? [Join the Discord community](https://discord.gg/cRFFHYye7t).
+62 -292
View File
@@ -2,27 +2,20 @@
title: Configuration
---
Quartz is meant to be extremely configurable, even if you don't know any coding. Most of the configuration you should need can be done by just editing `quartz.config.yaml`.
Quartz is meant to be extremely configurable, even if you don't know any coding. Most of the configuration you should need can be done by just editing `quartz.config.ts` or changing [[layout|the layout]] in `quartz.layout.ts`.
> [!tip]
> If you edit `quartz.config.yaml` using a text-editor with YAML language support like VSCode, it will warn you when you've made an error in your configuration, helping you avoid configuration mistakes!
> If you edit Quartz configuration using a text-editor that has TypeScript language support like VSCode, it will warn you when you you've made an error in your configuration, helping you avoid configuration mistakes!
The configuration of Quartz can be broken down into three parts:
The configuration of Quartz can be broken down into two main parts:
```yaml title="quartz.config.yaml"
configuration:
pageTitle: "My Site"
# ... general configuration
plugins:
- source: "@quartz-community/explorer"
enabled: true
# ... plugin entries
layout:
# ... groups and per-page-type layout overrides
```ts title="quartz.config.ts"
const config: QuartzConfig = {
configuration: { ... },
plugins: { ... },
}
```
`configuration` and `plugins` are described below; the `layout` section (component groups, `byPageType` overrides, sidebar modes) is described in [[layout]].
## General Configuration
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
@@ -31,51 +24,32 @@ This part of the configuration concerns anything that can affect the whole site.
- `pageTitleSuffix`: a string added to the end of the page title. This only applies to the browser tab title, not the title shown at the top of the page.
- `enableSPA`: whether to enable [[SPA Routing]] on your site.
- `enablePopovers`: whether to enable [[popover previews]] on your site.
- `prefetch`: fetch pages before their links are followed, so they open at once ([[prefetching]]): `viewport` (default, links on screen and links pointed at), `hover` (only links pointed at) or `"off"`. Works with and without SPA routing.
- `analytics`: what to use for analytics on your site. Values can be
- `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>', script: '<your-script-name.js>' }`: use [Umami](https://umami.is/);
- `{ provider: 'umami', host: '<your-umami-host>', websiteId: '<your-umami-website-id>' }`: 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>' }` (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: 'posthog', apiKey: '<your-posthog-project-apiKey>', host: '<your-posthog-host>' }`: use [Posthog](https://posthog.com/);
- `{ 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.
- `{ provider: 'matomo', siteId: '<your-matomo-id-code', host: 'matomo.example.com' }`: use [Matomo](https://matomo.org/), without protocol.
- `{ provider: 'vercel' }`: use [Vercel Web Analytics](https://vercel.com/docs/concepts/analytics).
- `{ provider: 'rybbit', siteId: 'my-rybbit-id' }` (managed) or `{ provider: 'rybbit', siteId: 'my-rybbit-id', host: 'my-rybbit-domain.com' }` (self-hosted) use [Rybbit](https://rybbit.com);
- `locale`: used for [[i18n]] and date formatting
- `baseUrl`: this is used for sitemaps and RSS feeds that require an absolute URL to know where the canonical 'home' of your site lives. This is normally the deployed URL of your site (e.g. `quartz.jzhao.xyz` for this site). Do not include the protocol (i.e. `https://`) or any leading or trailing slashes.
- 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.
- Files that Quartz renders as pages themselves (e.g. `.base` and `.canvas` files) are never copied as raw assets.
- Note that Quartz 4 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.
- `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.
- `defaultDateType`: whether to use created, modified, or published as the default date to display on pages and page listings.
- `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"`: 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)
- `header`: font to use for headers
- `code`: font for inline and block quotes
- `body`: font for everything
- `colors`: controls the theming of the site. It has two color schemes, `lightMode` and `darkMode`, each with the same keys:
- `colors`: controls the theming of the site.
- `light`: page background
- `lightgray`: borders
- `gray`: graph links, heavier borders
@@ -85,34 +59,6 @@ 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. Each takes an object of options (plus `enabled` and `order`) or a boolean shorthand: set e.g. `links: { markdownLinkResolution: relative }` to change an option or `contentIndex: false` to turn one off.
- `links.markdownLinkResolution` defaults to `shortest` (Obsidian's default). An old `crawl-links` plugin entry that Quartz migrates keeps that plugin's default, `absolute`, unless it sets another value.
```yaml title="quartz.config.yaml"
configuration:
theme:
colors:
lightMode:
light: "#faf8f8"
secondary: "#284b63"
# ... the other keys
darkMode:
light: "#161618"
secondary: "#7b97aa"
# ... the other keys
```
> [!note] Colors with an Obsidian theme
> A theme from [quartz-themes](https://github.com/saberzero1/quartz-themes) (the [[ThemesCore|@quartz-themes/core]] plugin; 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
@@ -120,203 +66,47 @@ You can think of Quartz plugins as a series of transformations over content.
![[quartz transform pipeline.png]]
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/created-modified-date"
enabled: true
order: 10 # controls execution order
- source: "@quartz-community/syntax-highlighting"
enabled: true
order: 20
# ... more plugins
```ts title="quartz.config.ts"
plugins: {
transformers: [...],
filters: [...],
emitters: [...],
}
```
Plugins are categorized by their type (transformer, filter, emitter, pageType) based on their manifest. The `order` field controls execution order within each category.
> [!note]
> For advanced TS override of plugin configuration, you can modify `quartz.ts`:
>
> ```ts title="quartz.ts"
> import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
>
> const config = await loadQuartzConfig({
> // override any configuration field here
> })
> export default config
> export const layout = await loadQuartzLayout()
> ```
- [[tags/plugin/transformer|Transformers]] **map** over content (e.g. parsing frontmatter, generating a description)
- [[tags/plugin/filter|Filters]] **filter** content (e.g. hiding [[UnlistedPages|unlisted pages]]; dropping drafts is [[built-in processing|built in]])
- [[tags/plugin/filter|Filters]] **filter** content (e.g. filtering out drafts)
- [[tags/plugin/emitter|Emitters]] **reduce** over content (e.g. creating an RSS feed or pages that list all files with a specific tag)
- **Page Types** define how different types of pages are rendered (content pages, folder listings, tag listings). Each page type can use a different [[layout#Page Frames|page frame]] to control its overall HTML structure.
The `layout.byPageType` section in `quartz.config.yaml` can also set a `template` field to override the page frame for a specific page type:
```yaml title="quartz.config.yaml"
layout:
byPageType:
canvas:
template: minimal # Override the page frame for canvas pages
```
See [[layout#Page Frames]] for details on available frames and how frame resolution works.
### Internal vs External Plugins
Quartz distinguishes between processing that is built into Quartz and plugins that are installed separately.
In `quartz.config.yaml`, the official plugins are referenced by their npm package name (this is what the default config uses); other plugins can also be referenced by a Git source such as `github:org/repo`:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
- source: "@quartz-community/syntax-highlighting"
enabled: true
options:
theme:
light: github-light
dark: github-dark
```
Frontmatter parsing, link resolution, drafts and the content index are not plugins: they are [[built-in processing|built into Quartz]] and configured under `configuration.frontmatter`, `.links`, `.drafts` and `.contentIndex`. Everything else is a plugin, referenced by its source: npm plugins (all the default ones) are installed in `node_modules`, Git and local plugins in `.quartz/plugins/`.
### Community Plugins
To install a community plugin, you can use the following command:
```shell
npx quartz plugin add @quartz-community/explorer # an npm package
npx quartz plugin add github:username/repo # a Git repository
```
This adds the plugin to `quartz.config.yaml` and installs it to `.quartz/plugins/`.
To install all plugins referenced in your config that aren't yet installed (useful when cloning a project or setting up CI):
```shell
npx quartz plugin install --from-config
```
To remove installed plugins that are no longer in your config:
```shell
npx quartz plugin prune
```
Both commands support `--dry-run` to preview changes. See [[cli/plugin|the plugin CLI reference]] for full details.
### Advanced Source Options
The `source` field for a plugin can be either a simple string or an object with additional options. The string form is the most common:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
- source: github:username/repo
enabled: true
```
For plugins that live in a subdirectory of a repository (monorepo-style), or when you need to pin to a specific branch or tag, use the object form:
```yaml title="quartz.config.yaml"
plugins:
- source:
repo: "https://github.com/user/repo.git"
subdir: plugin
ref: main
name: my-plugin
enabled: true
```
The object form supports the following fields:
| Field | Required | Description |
| -------- | :------: | --------------------------------------------------------------------------------------------------------- |
| `repo` | ✅ | Git repository URL (e.g. `https://github.com/user/repo.git`). |
| `subdir` | ❌ | Subdirectory within the repository that contains the plugin. Used for monorepo-style plugin repositories. |
| `ref` | ❌ | Git ref (branch or tag) to pin to. Equivalent to the `#ref` suffix on string sources. |
| `name` | ❌ | Override the directory name used in `.quartz/plugins/`. Defaults to the repository name. |
> [!example] Example
> A plugin in the `plugin/` subdirectory of a repository, pinned to a tag:
>
> ```yaml title="quartz.config.yaml"
> plugins:
> - source:
> name: my-plugin
> repo: "https://github.com/user/repo.git"
> subdir: plugin
> ref: v1.0.0
> enabled: true
> ```
>
> Themes from [quartz-themes](https://github.com/saberzero1/quartz-themes) don't need this: they are published to npm as `@quartz-themes/core` and the default config already has a (disabled) entry for it:
>
> ```yaml title="quartz.config.yaml"
> plugins:
> - source: "@quartz-themes/core"
> enabled: true
> options:
> theme: tokyo-night
> mode: both
> ```
> [!tip]
> The string form `github:user/repo#branch` and the object form `{ repo, ref }` are equivalent ways to specify a branch. Use the object form when you also need `subdir` or `name`, or when you prefer a more readable configuration.
### Usage
You can customize the behaviour of Quartz by adding, removing and reordering plugins in `quartz.config.yaml`. Each plugin entry specifies its source, whether it's enabled, execution order, and any options:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/note-properties"
enabled: true
options:
includeAll: false
includedProperties:
- description
- tags
- aliases
order: 5
- source: "@quartz-community/created-modified-date"
enabled: true
options:
priority:
- frontmatter
- git
- filesystem
order: 10
- source: "@quartz-community/latex"
enabled: true
options:
renderEngine: katex
order: 80
```
You can customize the behaviour of Quartz by adding, removing and reordering plugins in the `transformers`, `filters` and `emitters` fields.
> [!note]
> Some plugin options require JavaScript callback functions (e.g. custom sort, filter, or map functions) that can't be expressed in YAML. For these, use the TS override in `quartz.ts`:
>
> ```ts title="quartz.ts"
> import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
> import * as ExternalPlugin from "./.quartz/plugins"
>
> ExternalPlugin.Explorer({
> mapFn: (node) => {
> node.displayName = node.displayName.toUpperCase()
> return node
> },
> })
>
> const config = await loadQuartzConfig()
> export default config
> export const layout = await loadQuartzLayout()
> ```
>
> Options set in `quartz.ts` are merged with YAML options and take precedence. Plugin overrides must be placed **before** `loadQuartzConfig()` so they are applied when components are instantiated during config loading. See the plugin-specific documentation for available callback options.
> Each node is modified by every transformer _in order_. Some transformers are position sensitive, so you may need to pay particular attention to whether they need to come before or after certain other plugins.
You should take care to add the plugin to the right entry corresponding to its plugin type. For example, to add the [[ExplicitPublish]] plugin (a [[tags/plugin/filter|Filter]]), you would add the following line:
```ts title="quartz.config.ts"
filters: [
...
Plugin.ExplicitPublish(),
...
],
```
To remove a plugin, you should remove all occurrences of it in the `quartz.config.ts`.
To customize plugins further, some plugins may also have their own configuration settings that you can pass in. If you do not pass in a configuration, the plugin will use its default settings.
For example, the [[plugins/Latex|Latex]] plugin allows you to pass in a field specifying the `renderEngine` to choose between Katex and MathJax.
```ts title="quartz.config.ts"
transformers: [
Plugin.FrontMatter(), // use default options
Plugin.Latex({ renderEngine: "katex" }), // set some custom options
]
```
Some plugins are included by default in the [`quartz.config.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz.config.ts), but there are more available.
You can see a list of all plugins and their configuration options [[tags/plugin|here]].
@@ -324,42 +114,22 @@ If you'd like to make your own plugins, see the [[making plugins|making custom p
## Fonts
Fonts can be specified as a simple string or with advanced options in `quartz.config.yaml`:
Fonts can be specified as a `string` or a `FontSpecification`:
```yaml title="quartz.config.yaml"
configuration:
theme:
typography:
title: Schibsted Grotesk # optional, defaults to header font
header: Schibsted Grotesk
body: Source Sans Pro
code: IBM Plex Mono
```
```ts
// string
typography: {
header: "Schibsted Grotesk",
...
}
> [!note]
> Quartz uses `title`, but the config's JSON schema doesn't list it yet, so an editor with YAML validation may flag it. The warning can be ignored.
For more control over font weights and italics, use the TS override in `quartz.ts`:
```ts title="quartz.ts"
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
const config = await loadQuartzConfig({
theme: {
typography: {
header: {
name: "Schibsted Grotesk",
weights: [400, 700],
includeItalic: true,
},
body: "Source Sans Pro",
code: "IBM Plex Mono",
},
// FontSpecification
typography: {
header: {
name: "Schibsted Grotesk",
weights: [400, 700],
includeItalic: true,
},
})
export default config
export const layout = await loadQuartzLayout()
...
}
```
> [!tip]
> For per-heading font control, self-hosted fonts, or Obsidian theme font bridging, see the [[plugins/Fonts|Fonts]] plugin. It can download Google Fonts at build time and serve them locally with `fontOrigin: selfHosted`, making your site fully self-contained.
-63
View File
@@ -1,63 +0,0 @@
---
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]], and Quartz runs their **built** code (`dist/`). The default plugins are npm packages in `node_modules/@quartz-community/`; plugins installed from Git live in `.quartz/plugins/`. Editing either copy is the wrong approach: changes to the source have no effect until it is rebuilt, and both are 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]].
-36
View File
@@ -1,36 +0,0 @@
---
title: Bases Support
tags:
- component
---
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.
Bases support is provided by the [[BasesPage]] plugin, which is enabled by default. See the plugin page for configuration options, built-in views, notes on the expression language, and how to extend with custom views.
## Changed in Quartz 5.1 (bases-page 1.2)
Bases now behave like Obsidian's in many details. If you upgrade, check filters and formulas that rely on the old behaviour:
- A base opens on its **first view** (it used to open on the first table view); `defaultViewType` has no default.
- `file.name` of a Markdown note has no extension (`Note`); other files keep it (`Plan.canvas`). `file.fullname` always has it.
- `file.tags` keeps `#` and the tags' original case; the `tags` property holds only frontmatter tags. `hasTag()` matches nested tags and is true if **any** of the given tags match.
- Dates display in the site's locale; `date()` only parses ISO-style strings. Subtracting dates gives a duration (`9 days`) with `.days`, `.hours`, … fields.
- `imageAspectRatio` is height / width; `file.folder` of a root file is `/`; `contains()` on text ignores case.
- `this` in an embedded base refers to the embedding note.
- Tags link to tag pages; links to missing notes are marked broken.
- `.base` pages follow the site's publish filters, such as [[ExplicitPublish]].
See [[BasesPage#Obsidian compatibility]] for details.
## Demo
![[Base.base]]
## Customization
- Install: `npx quartz plugin add @quartz-community/bases-page`
- Source: [`quartz-community/bases-page`](https://github.com/quartz-community/bases-page)
-21
View File
@@ -1,21 +0,0 @@
---
title: Canvas Support
tags:
- component
---
Quartz supports rendering [JSON Canvas](https://jsoncanvas.org) (`.canvas`) files as interactive, pannable and zoomable canvas pages. This brings your Obsidian canvas files to the web, preserving text nodes, file references, link nodes, group nodes, and edges with full visual fidelity.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
Canvas support is provided by the [[CanvasPage]] plugin, which is enabled by default. See the plugin page for configuration options and a full list of supported features.
## Demo
![[Canvas.canvas]]
## Customization
- Install: `npx quartz plugin add @quartz-community/canvas-page`
- Source: [`quartz-community/canvas-page`](https://github.com/quartz-community/canvas-page)
-10
View File
@@ -1,9 +1,3 @@
---
title: "Docker Support"
tags:
- feature
---
Quartz comes shipped with a Docker image that will allow you to preview your Quartz locally without installing Node.
You can run the below one-liner to run Quartz in Docker.
@@ -11,7 +5,3 @@ You can run the below one-liner to run Quartz in Docker.
```sh
docker run --rm -itp 8080:8080 -p 3001:3001 -v ./content:/usr/src/app/content $(docker build -q .)
```
> [!warning] Not to be used for production
> Serve mode is intended for local previews only.
> For production workloads, see the page on [[hosting]].
+11 -5
View File
@@ -4,7 +4,7 @@ tags:
- feature/transformer
---
Quartz uses [Katex](https://katex.org/) by default to typeset both inline and block math expressions at build time. [MathJax](https://www.mathjax.org/) and [Typst](https://typst.app/) are available with the [[plugins/Latex|Latex]] plugin's `renderEngine` option (`katex`, `mathjax` or `typst`).
Quartz uses [Katex](https://katex.org/) by default to typeset both inline and block math expressions at build time.
## Syntax
@@ -59,15 +59,21 @@ Similarly, inline math can be rendered by delimiting math expression with a sing
### Escaping symbols
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.
There will be cases where you may have more than one `$` in a paragraph at once which may accidentally trigger MathJax/Katex.
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\$.
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
### Using mhchem
If you are using the community Latex plugin, you can add `mhchem` support by forking the plugin repository and adding the following import to the top of `src/index.ts` (before all the other imports):
Add the following import to the top of `quartz/plugins/transformers/latex.ts` (before all the other
imports):
```ts title="src/index.ts"
```ts title="quartz/plugins/transformers/latex.ts"
import "katex/contrib/mhchem"
```
+4 -14
View File
@@ -4,22 +4,12 @@ tags:
- feature/transformer
---
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.
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.
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.
By default, Quartz will render Mermaid diagrams to match the site theme.
> [!note]
> In the default config [[ObsidianFlavoredMarkdown]] (`order: 40`) runs after [[SyntaxHighlighting]] (`order: 20`). If Mermaid diagrams don't show up and you changed either `order`, restore that sequence.
```yaml title="quartz.config.yaml"
plugins:
- source: "@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.
> [!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]].
## Syntax
+3 -217
View File
@@ -8,224 +8,10 @@ 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]].
Since ObsidianFlavoredMarkdown 2.0, Markdown renders as it does in Obsidian: by default (`preset: "legacy"`) it parses with Obsidian's own parser. This replaces the Markdown parser, so other plugins' syntax extensions are not used and only YAML frontmatter is recognized. Use `preset: "strict"` (CommonMark/GFM as specified plus Obsidian's syntax) for TOML (`+++`) frontmatter or plugins that add their own Markdown syntax. [[GitHubFlavoredMarkdown]] runs before it (order 30, then 40); if you set `order` for either plugin, keep GitHubFlavoredMarkdown first.
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, [[built-in processing|built into Quartz]] ([[Frontmatter]], configured under `configuration.frontmatter`).
Finally, Quartz's built-in [[CrawlLinks|link processing]] (`configuration.links`) lets you customize link resolution to match Obsidian.
## Supported Features
### Wikilinks
Internal links using the `[[page]]` syntax are converted to regular links. See [[wikilinks]] for more details. All variations are supported:
```markdown
[[Page]] Link to a page
[[Page|Custom text]] Link with alias
[[Page#Heading]] Link to a heading
[[Page#Heading|Custom text]] Link to a heading with alias
[[Page#^block-id]] Link to a block reference
![[Page]] Embed (transclude) a page
![[image.png]] Embed an image
![[image.png|alt 100x200]] Embed with alt text and dimensions
```
Inside tables, pipes in wikilinks can be escaped with a backslash:
```markdown
| Column |
| --------------- |
| [[page\|alias]] |
```
### Line breaks
A single line break inside a paragraph renders as a line break (`<br>`), as in Obsidian's default reading view. Set `strictLineBreaks: true` in the ObsidianFlavoredMarkdown options to join the lines with a space instead, like Obsidian's "Strict line breaks" setting. It defaults to `true` under `preset: "strict"`.
### Highlights
Wrap text in `==` to highlight it:
```markdown
This is ==highlighted text== in a sentence.
```
This renders as: This is ==highlighted text== in a sentence.
### Comments
Obsidian-style comments are stripped from the output:
```markdown
This is visible. %%This is a comment and won't appear.%%
```
This renders as: This is visible. %%This is a comment and won't appear.%%
Multi-line comments are also supported:
```markdown
%%
This entire block
is a comment.
%%
```
### Tags
Tags starting with `#` are parsed and linked to tag pages:
```markdown
#tag #nested/tag #tag-with-dashes
```
For example: #feature/transformer
> [!note]
> Pure numeric tags like `#123` are ignored, matching Obsidian behaviour.
### Callouts
[[callouts|Obsidian callouts]] are fully supported, including collapsible variants:
```markdown
> [!note]
> This is a note callout.
> [!warning]- Collapsed by default
> This content is hidden initially.
> [!tip]+ Expanded by default
> This content is visible initially.
```
> [!example] Live example
> This is a live callout rendered from Obsidian-flavored Markdown.
All built-in callout types are supported: `note`, `abstract`, `info`, `todo`, `tip`, `success`, `question`, `warning`, `failure`, `danger`, `bug`, `example`, and `quote`, along with their aliases.
### Task Lists and Custom Task Characters
Standard checkboxes work out of the box. With `enableCheckbox: true`, you also get support for custom task characters that are popular in the Obsidian community:
```markdown
- [ ] Unchecked
- [x] Checked
- [?] Question
- [!] Important
- [>] Forwarded
- [/] In progress
- [-] Cancelled
- [s] Special
```
Each custom character is preserved as a `data-task` attribute on the rendered element, allowing CSS-based styling per character.
- [ ] Unchecked
- [x] Checked
- [?] Question
- [!] Important
### Mermaid Diagrams
[[Mermaid diagrams|Mermaid]] code blocks render as diagrams. Default is Mermaid.js; set `diagramRenderer: pele` for [Pele](https://pele.run):
````markdown
```mermaid
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[OK]
B -->|No| D[Cancel]
```
````
```mermaid
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[OK]
B -->|No| D[Cancel]
```
### YouTube Embeds
YouTube videos can be embedded using standard image syntax with a YouTube URL:
```markdown
![](https://youtu.be/v5LGaczJaf0)
![](https://www.youtube.com/watch?v=v5LGaczJaf0)
```
For example, the following embed is rendered from `![](https://youtu.be/v5LGaczJaf0)`:
![](https://youtu.be/v5LGaczJaf0)
### Tweet Embeds
Tweets from Twitter/X are embedded as static blockquotes with a link to the original:
```markdown
![](https://x.com/kepano/status/1882142872826442145)
![](https://twitter.com/kepano/status/1882142872826442145)
```
For example, the following embed is rendered from `![](https://x.com/kepano/status/1882142872826442145)`:
![](https://x.com/kepano/status/1882142872826442145)
### Block References
Block references allow linking to specific blocks within a page:
```markdown
Content paragraph. ^my-block
[[Page#^my-block]]
```
### Obsidian URI Links
Links using the `obsidian://` protocol are marked with a CSS class (`obsidian-uri`) and a `data-obsidian-uri` attribute, so you can style them differently from regular links.
### Video Embeds
Video files can be embedded using standard image syntax:
```markdown
![](video.mp4)
![](video.webm)
```
### Embed in HTML
By default, Obsidian does not render its Markdown syntax inside HTML blocks. Quartz extends this with the `enableInHtmlEmbed` option, which parses wikilinks, highlights, and tags inside raw HTML nodes.
### Footnotes
Footnotes using the `[^1]` syntax and inline footnotes (`^[…]`) are supported by the [[ObsidianFlavoredMarkdown]] plugin. Both are numbered in order; an undefined footnote reference shows its bare label, as in Obsidian:
```markdown
Here is a sentence with a footnote.[^1]
Here is one with an inline footnote.^[This is the inline footnote content.]
[^1]: This is the footnote content.
```
## Obsidian Community Plugin Support
Quartz focuses on supporting Obsidian's core features. Functionality from Obsidian community plugins is handled by Quartz community plugins:
| Obsidian Plugin | Quartz Support |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| Dataview | Supported via [Quartz Syncer](https://community.obsidian.md/plugins/quartz-syncer) — exports Dataview queries as static content during sync |
| Excalidraw | Supported via the [[ObsidianPluginExcalidraw\|obsidian-plugin-excalidraw]] community plugin |
| Leaflet Maps | Supported via the `obsidian-plugin-leaflet` community plugin |
| TTRPG Tools: Maps | Supported via the [[ObsidianPluginTtrpgToolsMaps\|obsidian-plugin-ttrpg-tools-maps]] community plugin |
| Style Settings | Supported via the [[ThemesCore\|@quartz-themes/core]] plugin |
> [!tip]
> As a general rule: Obsidian core features are supported by Quartz directly, while Obsidian community plugin features are supported by corresponding Quartz community plugins. Not all Obsidian community plugins will have Quartz equivalents, but popular ones are likely to be supported by the community.
Finally, Quartz also provides [[CrawlLinks]] plugin, which allows you to customize Quartz's link resolution behaviour to match Obsidian.
## Configuration
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.
This functionality is provided by the [[ObsidianFlavoredMarkdown]], [[Frontmatter]] and [[CrawlLinks]] plugins. See the plugin pages for customization options.
+10 -29
View File
@@ -8,35 +8,16 @@ tags:
Because the Markdown generated by ox-hugo is not pure Markdown but Hugo specific, we need to transform it to fit into Quartz. This is done by the [[OxHugoFlavoredMarkdown]] plugin. Even though this plugin was written with `ox-hugo` in mind, it should work for any Hugo specific Markdown.
The plugin is in the default `quartz.config.yaml` but disabled; set `enabled: true` on its entry. ox-hugo usually writes TOML frontmatter (`+++`), which Quartz's [[Frontmatter|built-in frontmatter parsing]] reads when configured under `configuration.frontmatter`. [[ObsidianFlavoredMarkdown]]'s default `legacy` preset only recognizes YAML frontmatter, so switch it to `preset: strict` too:
```yaml title="quartz.config.yaml"
configuration:
frontmatter:
delimiters: "+++"
language: toml # if using toml frontmatter
plugins:
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 30
- source: "@quartz-community/obsidian-flavored-markdown"
enabled: true
options:
preset: strict # needed for TOML (+++) frontmatter
order: 40
- source: "@quartz-community/ox-hugo"
enabled: true
order: 91
```
OxHugoFlavoredMarkdown rewrites the Markdown source before it is parsed, so its `order` relative to the other Markdown plugins doesn't matter.
For options that need code, place overrides before `loadQuartzConfig()` in `quartz.ts`:
```ts title="quartz.ts (override)"
import * as ExternalPlugin from "./.quartz/plugins"
ExternalPlugin.OxHugoFlavouredMarkdown({ replaceOrgLatex: false })
```typescript title="quartz.config.ts"
plugins: {
transformers: [
Plugin.FrontMatter({ delims: "+++", language: "toml" }), // if toml frontmatter
// ...
Plugin.OxHugoFlavouredMarkdown(),
Plugin.GitHubFlavoredMarkdown(),
// ...
],
},
```
## Usage
+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 with `configuration.contentIndex.rssSlug` (see [[ContentIndex]]).
> The `index.xml` path can be customized by passing the `rssSlug` option to the [[ContentIndex]] plugin.
## Configuration
This functionality is [[built-in processing|built into Quartz]]. See [[ContentIndex]] for customization options.
This functionality is provided by the [[ContentIndex]] plugin. See the plugin page for customization options.
+10 -19
View File
@@ -9,28 +9,19 @@ tags:
Quartz supports transforming the special Markdown syntax from Roam Research (like `{{[[components]]}}` and other formatting) into
regular Markdown via the [[RoamFlavoredMarkdown]] plugin.
The plugin is in the default `quartz.config.yaml` but disabled; set `enabled: true` on its entry:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/obsidian-flavored-markdown"
enabled: true
order: 40
- source: "@quartz-community/roam"
enabled: true
order: 92
```
For the TS override approach, place overrides before `loadQuartzConfig()` in `quartz.ts`:
```ts title="quartz.ts (override)"
import * as ExternalPlugin from "./.quartz/plugins"
ExternalPlugin.RoamFlavoredMarkdown()
```typescript title="quartz.config.ts"
plugins: {
transformers: [
// ...
Plugin.RoamFlavoredMarkdown(),
Plugin.ObsidianFlavoredMarkdown(),
// ...
],
},
```
> [!warning]
> With [[ObsidianFlavoredMarkdown]]'s wikilinks on (the default), syntax built on `[[…]]` — `{{[[TODO]]}}`, `{{[[DONE]]}}`, `[[>]]` — is parsed as a wikilink before this plugin runs, whatever the `order`, so it renders as a link. `^^highlight^^` and the other syntax not built on `[[…]]` work.
> As seen above placement of `Plugin.RoamFlavoredMarkdown()` within `quartz.config.ts` is very important. It must come before `Plugin.ObsidianFlavoredMarkdown()`.
## Customization
+1 -12
View File
@@ -1,18 +1,7 @@
---
title: "SPA Routing"
tags:
- feature
---
Single-page-app style rendering. This prevents flashes of unstyled content and improves the smoothness of Quartz.
Under the hood, this is done by hijacking page navigations and instead fetching the HTML via a `GET` request and then diffing and selectively replacing parts of the page using [micromorph](https://github.com/natemoo-re/micromorph). This allows us to change the content of the page without fully refreshing the page, reducing the amount of content that the browser needs to load.
## Configuration
- Disable SPA Routing: set the `enableSPA` field of the [[configuration]] in `quartz.config.yaml` to be `false`.
- Exclude a single link: add `data-router-ignore` to it in HTML; it is followed with a normal page load. Links with `target="_blank"` and links to other sites are never handled by the router. `data-router-noscroll` keeps the scroll position when the link is followed.
Pages are fetched ahead of a click by [[prefetching]], which the router uses to show them at once; the fetched pages are also reused by [[popover previews]].
Redirects are followed: when a link is redirected (for example `folder` → `folder/` on static hosts, or an alias page to its canonical page), the address bar shows the final URL and relative links on the new page resolve against it.
- Disable SPA Routing: set the `enableSPA` field of the [[configuration]] in `quartz.config.ts` to be `false`.
+5 -7
View File
@@ -6,12 +6,10 @@ tags:
A backlink for a note is a link from another note to that note. Links in the backlink pane also feature rich [[popover previews]] if you have that feature enabled.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
## Customization
- Removing backlinks: remove the `backlinks` entry from `quartz.config.yaml` or set `enabled: false`.
- Hide when empty: hide `Backlinks` if given page doesn't contain any backlinks (default to `true`). To disable this, set `hideWhenEmpty: false` in the plugin options in `quartz.config.yaml`.
- Install: `npx quartz plugin add @quartz-community/backlinks`
- Source: [`quartz-community/backlinks`](https://github.com/quartz-community/backlinks)
- Removing backlinks: delete all usages of `Component.Backlinks()` from `quartz.layout.ts`.
- Hide when empty: hide `Backlinks` if given page doesn't contain any backlinks (default to `true`). To disable this, use `Component.Backlinks({ hideWhenEmpty: false })`.
- Component: `quartz/components/Backlinks.tsx`
- Style: `quartz/components/styles/backlinks.scss`
- Script: `quartz/components/scripts/search.inline.ts`
+12 -34
View File
@@ -8,50 +8,28 @@ Breadcrumbs provide a way to navigate a hierarchy of pages within your site usin
By default, the element at the very top of your page is the breadcrumb navigation bar (can also be seen at the top on this page!).
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
## Customization
Most configuration can be done via the `options` section of the breadcrumbs plugin entry in `quartz.config.yaml`.
Most configuration can be done by passing in options to `Component.Breadcrumbs()`.
For example, here's what the default configuration looks like:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/breadcrumbs"
enabled: true
options:
spacerSymbol: "❯"
rootName: Home
resolveFrontmatterTitle: true
showCurrentPage: true
layout:
position: beforeBody
priority: 5
condition: not-index # no breadcrumbs on the home page
```
For the TS override approach:
```ts title="quartz.ts (override)"
import * as ExternalPlugin from "./.quartz/plugins"
// Must be placed before loadQuartzConfig()
ExternalPlugin.Breadcrumbs({
spacerSymbol: "❯",
rootName: "Home",
resolveFrontmatterTitle: true,
showCurrentPage: true,
```typescript title="quartz.layout.ts"
Component.Breadcrumbs({
spacerSymbol: "❯", // symbol between crumbs
rootName: "Home", // name of first/root element
resolveFrontmatterTitle: true, // whether to resolve folder names through frontmatter titles
showCurrentPage: true, // whether to display the current page in the breadcrumbs
})
```
When passing in your own options, you can omit any or all of these fields if you'd like to keep the default value for that field.
You can also adjust where the breadcrumbs will be displayed by changing the `layout.position` field in the plugin entry in `quartz.config.yaml` (see [[layout]]).
You can also adjust where the breadcrumbs will be displayed by adjusting the [[layout]] (moving `Component.Breadcrumbs()` up or down)
Want to customize it even more?
- Removing breadcrumbs: remove the `breadcrumbs` entry from `quartz.config.yaml` or set `enabled: false`.
- Install: `npx quartz plugin add @quartz-community/breadcrumbs`
- Source: [`quartz-community/breadcrumbs`](https://github.com/quartz-community/breadcrumbs)
- Removing breadcrumbs: delete all usages of `Component.Breadcrumbs()` from `quartz.layout.ts`.
- Component: `quartz/components/Breadcrumbs.tsx`
- Style: `quartz/components/styles/breadcrumbs.scss`
- Script: inline at `quartz/components/Breadcrumbs.tsx`
-90
View File
@@ -1,90 +0,0 @@
---
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.
Drafts can't be replaced: a filter plugin runs in addition to the built-in.
## 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. Built-in links also provides the classes it puts on links: `.internal`, `.external` and `.broken` (`dom` capabilities). In `from`, name the built-ins `quartz:frontmatter`, `quartz:links`, `quartz:drafts` and `quartz:contentIndex`.
- Don't list `@quartz-community/crawl-links`, `remove-draft` or `content-index` in your manifest's [[plugin manifest#dependencies|`dependencies`]]: Quartz 5.1 treats them as satisfied by the built-ins, but Quartz 5.0 fails the build when the plugin isn't in the config. To run after built-in links, set a `defaultOrder` above 60 (a transformer with a lower order that depends on `crawl-links` fails the build).
- Plugins can add their own fields to `contentIndex.json` — see [[making plugins#Extending the content index]].
+3 -3
View File
@@ -8,7 +8,7 @@ Quartz supports the same Admonition-callout syntax as Obsidian.
This includes
- 13 distinct callout types (most with several aliases)
- 12 Distinct callout types (each with several aliases)
- Collapsable callouts
```
@@ -18,8 +18,8 @@ This includes
See [documentation on supported types and syntax here](https://help.obsidian.md/Editing+and+formatting/Callouts).
> [!note]
> In the default config [[ObsidianFlavoredMarkdown]] (`order: 40`) runs after [[SyntaxHighlighting]] (`order: 20`). If callouts don't show up and you changed either `order`, restore that sequence.
> [!warning]
> Wondering why callouts may not be showing up even if you have them enabled? You may need to reorder your plugins so that [[ObsidianFlavoredMarkdown]] is _after_ [[SyntaxHighlighting]].
## Customization
+34 -85
View File
@@ -4,10 +4,7 @@ tags:
- component
---
Quartz can add a comment section to your pages with the [[plugins/Comments|Comments]] plugin, so readers can leave comments on your site.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
Quartz also has the ability to hook into various providers to enable readers to leave comments on your site.
![[giscus-example.png]]
@@ -33,55 +30,28 @@ After entering both your repository and selecting the discussion category, Giscu
![[giscus-results.png]]
Finally, in `quartz.config.yaml`, enable the comments plugin (it is in the default configuration but disabled) and fill in the values you got from above:
Finally, in `quartz.layout.ts`, edit the `afterBody` field of `sharedPageComponents` to include the following options but with the values you got from above:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/comments"
enabled: true
options:
provider: giscus
options:
repo: jackyzha0/quartz
repoId: MDEwOlJlcG9zaXRvcnkzODcyMTMyMDg
category: Announcements
categoryId: DIC_kwDOFxRnmM4B-Xg6
lang: en
layout:
position: afterBody
priority: 10
```ts title="quartz.layout.ts"
afterBody: [
Component.Comments({
provider: 'giscus',
options: {
// from data-repo
repo: 'jackyzha0/quartz',
// from data-repo-id
repoId: 'MDEwOlJlcG9zaXRvcnkzODcyMTMyMDg',
// from data-category
category: 'Announcements',
// from data-category-id
categoryId: 'DIC_kwDOFxRnmM4B-Xg6',
// from data-lang
lang: 'en'
}
}),
],
```
For the TS override approach:
```ts title="quartz.ts (override)"
// If using quartz.ts overrides instead of YAML:
import * as ExternalPlugin from "./.quartz/plugins"
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
const config = await loadQuartzConfig()
export default config
export const layout = await loadQuartzLayout({
defaults: {
afterBody: [
ExternalPlugin.Comments({
provider: "giscus",
options: {
repo: "jackyzha0/quartz",
repoId: "MDEwOlJlcG9zaXRvcnkzODcyMTMyMDg",
category: "Announcements",
categoryId: "DIC_kwDOFxRnmM4B-Xg6",
lang: "en",
},
}),
],
},
})
```
> [!note]
> If the plugin is not in your configuration, install it first: `npx quartz plugin add @quartz-community/comments`
### Customization
Quartz also exposes a few of the other Giscus options as well and you can provide them the same way `repo`, `repoId`, `category`, and `categoryId` are provided.
@@ -96,7 +66,7 @@ type Options = {
categoryId: string
// Url to folder with custom themes
// defaults to 'https://${baseUrl}/static/giscus'
// defaults to 'https://${cfg.baseUrl}/static/giscus'
themeUrl?: string
// filename for light theme .css file
@@ -132,44 +102,23 @@ type Options = {
#### Custom CSS theme
Quartz supports custom themes for Giscus. By default Giscus loads `light.css` and `dark.css` from `https://<baseUrl>/static/giscus`, which Quartz ships in `quartz/static/giscus/` (this needs `baseUrl` to be set to your real domain). To use a custom CSS theme, place the `.css` file inside the `quartz/static/giscus` folder and set the configuration values.
Quartz supports custom theme for Giscus. To use a custom CSS theme, place the `.css` file inside the `quartz/static` folder and set the configuration values.
For example, if you have a light theme `light-theme.css`, a dark theme `dark-theme.css`, and your Quartz site is hosted at `https://example.com/`:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/comments"
enabled: true
options:
provider: giscus
options:
# Other options...
themeUrl: "https://example.com/static/giscus" # corresponds to quartz/static/giscus/
lightTheme: light-theme # corresponds to light-theme.css in quartz/static/giscus/
darkTheme: dark-theme # corresponds to dark-theme.css in quartz/static/giscus/
```
```ts
afterBody: [
Component.Comments({
provider: 'giscus',
options: {
// Other options
```ts title="quartz.ts (override)"
import * as ExternalPlugin from "./.quartz/plugins"
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
const config = await loadQuartzConfig()
export default config
export const layout = await loadQuartzLayout({
defaults: {
afterBody: [
ExternalPlugin.Comments({
provider: "giscus",
options: {
// Other options...
themeUrl: "https://example.com/static/giscus",
lightTheme: "light-theme",
darkTheme: "dark-theme",
},
}),
],
},
})
themeUrl: "https://example.com/static/giscus", // corresponds to quartz/static/giscus/
lightTheme: "light-theme", // corresponds to light-theme.css in quartz/static/giscus/
darkTheme: "dark-theme", // corresponds to dark-theme.css quartz/static/giscus/
}
}),
],
```
#### Conditionally display comments
+4 -6
View File
@@ -6,14 +6,12 @@ tags:
Quartz supports darkmode out of the box that respects the user's theme preference. Any future manual toggles of the darkmode switch will be saved in the browser's local storage so it can be persisted across future page loads.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
## Customization
- Removing darkmode: remove the `darkmode` entry from `quartz.config.yaml` or set `enabled: false`.
- Install: `npx quartz plugin add @quartz-community/darkmode`
- Source: [`quartz-community/darkmode`](https://github.com/quartz-community/darkmode)
- Removing darkmode: delete all usages of `Component.Darkmode()` from `quartz.layout.ts`.
- Component: `quartz/components/Darkmode.tsx`
- Style: `quartz/components/styles/darkmode.scss`
- Script: `quartz/components/scripts/darkmode.inline.ts`
You can also listen to the `themechange` event to perform any custom logic when the theme changes.
+41 -112
View File
@@ -6,30 +6,6 @@ tags:
Quartz features an explorer that allows you to navigate all files and folders on your site. It supports nested folders and is highly customizable.
> [!info]
> The Explorer is now a community plugin. This demonstrates how external plugins can extend Quartz functionality while serving as a reference implementation for plugin developers.
## Installation
The Explorer is part of the default `quartz.config.yaml`. If your config doesn't have it, add it with:
```bash
npx quartz plugin add @quartz-community/explorer
```
This adds an entry like this to your `quartz.config.yaml`:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
layout:
position: left
priority: 50
```
## Features
By default, it shows all folders and files on your page. To display the explorer in a different spot, you can edit the [[layout]].
Display names for folders get determined by the `title` frontmatter field in `folder/index.md` (more detail in [[authoring content | Authoring Content]]). If this file does not exist or does not contain frontmatter, the local folder name will be used instead.
@@ -37,77 +13,46 @@ 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://developer.chrome.com/docs/devtools/storage/localstorage)). 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://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.
## Customization
Most configuration can be done through the plugin's `options`.
Most configuration can be done by passing in options to `Component.Explorer()`.
For example, here's what the default configuration looks like:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
options:
title: Explorer # defaults to the translated "Explorer"
folderClickBehavior: link # "link" to navigate or "collapse" to toggle
folderDefaultState: collapsed # "collapsed" or "open"
useSavedState: true
layout:
position: left
priority: 50
```
For advanced options like custom sort, filter, and map functions, use the TS override in `quartz.ts`:
```ts title="quartz.ts"
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
import * as ExternalPlugin from "./.quartz/plugins"
// Advanced: pass callback functions that can't be expressed in YAML
ExternalPlugin.Explorer({
sortFn: (a, b) => {
/* ... */
},
filterFn: (node) => {
/* ... */
},
mapFn: (node) => {
/* ... */
},
```typescript title="quartz.layout.ts"
Component.Explorer({
title: "Explorer", // title of the explorer component
folderClickBehavior: "collapse", // what happens when you click a folder ("link" to navigate to folder page on click or "collapse" to collapse folder on click)
folderDefaultState: "collapsed", // default state of folders ("collapsed" or "open")
useSavedState: true, // whether to use local storage to save "state" (which folders are opened) of explorer
// omitted but shown later
sortFn: ...,
filterFn: ...,
mapFn: ...,
// what order to apply functions in
order: ["filter", "map", "sort"],
})
const config = await loadQuartzConfig()
export default config
export const layout = await loadQuartzLayout()
```
> [!info] How overrides work
> When you call `ExternalPlugin.Explorer({...})` in `quartz.ts`, the options are recorded and merged with the YAML configuration when the component is instantiated during the build. Options set in `quartz.ts` take precedence over those in `quartz.config.yaml`, following this order: `plugin defaults < YAML options < quartz.ts overrides`.
>
> If you have two plugins that export the same name (e.g. two different Explorer plugins installed via `--name`), use the `plugins` map to disambiguate:
>
> ```ts title="quartz.ts"
> import * as ExternalPlugin from "./.quartz/plugins"
> ExternalPlugin.plugins["my-explorer"].Explorer({ mapFn: ... })
> ```
When passing in your own options, you can omit any or all of these fields if you'd like to keep the default value for that field.
Want to customize it even more?
- Removing explorer: remove the `explorer` entry from `quartz.config.yaml` or set `enabled: false`
- Removing explorer: remove `Component.Explorer()` from `quartz.layout.ts`
- (optional): After removing the explorer component, you can move the [[table of contents | Table of Contents]] component back to the `left` part of the layout
- Changing `sort`, `filter` and `map` behavior: explained in [[#Advanced customization]]
- Component: `quartz/components/Explorer.tsx`
- Style: `quartz/components/styles/explorer.scss`
- Script: `quartz/components/scripts/explorer.inline.ts`
## Advanced customization
This component allows you to fully customize all of its behavior. You can pass a custom `sort`, `filter` and `map` function.
All functions you can pass work with the `FileTrieNode` class, which has the following properties:
```ts title="@quartz-community/explorer"
```ts title="quartz/components/Explorer.tsx"
class FileTrieNode {
isFolder: boolean
children: Array<FileTrieNode>
@@ -115,7 +60,7 @@ class FileTrieNode {
}
```
```ts
```ts title="quartz/plugins/emitters/contentIndex.tsx"
export type ContentDetails = {
slug: FullSlug
title: string
@@ -129,7 +74,7 @@ Every function you can pass is optional. By default, only a `sort` function will
```ts title="Default sort function"
// Sort order: folders first, then files. Sort folders and files alphabetically
ExternalPlugin.Explorer({
Component.Explorer({
sortFn: (a, b) => {
if ((!a.isFolder && !b.isFolder) || (a.isFolder && b.isFolder)) {
return a.displayName.localeCompare(b.displayName, undefined, {
@@ -169,20 +114,8 @@ These examples show the basic usage of `sort`, `map` and `filter`.
Using this example, the explorer will alphabetically sort everything.
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
options:
# Simple options go in YAML
title: Explorer
folderDefaultState: collapsed
```
Custom sort functions require the TS override:
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
```ts title="quartz.layout.ts"
Component.Explorer({
sortFn: (a, b) => {
return a.displayName.localeCompare(b.displayName)
},
@@ -193,8 +126,8 @@ ExternalPlugin.Explorer({
Using this example, the display names of all `FileNodes` (folders + files) will be converted to full upper case.
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
```ts title="quartz.layout.ts"
Component.Explorer({
mapFn: (node) => {
node.displayName = node.displayName.toUpperCase()
return node
@@ -202,16 +135,13 @@ ExternalPlugin.Explorer({
})
```
> [!note]
> The `mapFn`, `filterFn`, and `sortFn` options require JavaScript callback functions and cannot be expressed in YAML. Use the TS override for these.
### Remove list of elements (`filter`)
Using this example, you can remove elements from your explorer by providing an array of folders/files to exclude.
Note that this example filters on the title but you can also do it via slug or any other field available on `FileTrieNode`.
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
```ts title="quartz.layout.ts"
Component.Explorer({
filterFn: (node) => {
// set containing names of everything you want to filter out
const omit = new Set(["authoring content", "tags", "advanced"])
@@ -228,11 +158,11 @@ ExternalPlugin.Explorer({
You can access the tags of a file by `node.data.tags`.
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
```ts title="quartz.layout.ts"
Component.Explorer({
filterFn: (node) => {
// exclude files with the tag "explorerexclude"
return node.data?.tags?.includes("explorerexclude") !== true
return node.data.tags?.includes("explorerexclude") !== true
},
})
```
@@ -242,8 +172,8 @@ ExternalPlugin.Explorer({
By default, the explorer will filter out the `tags` folder.
To override the default filter function, you can set the filter function to `undefined`.
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
```ts title="quartz.layout.ts"
Component.Explorer({
filterFn: undefined, // apply no filter function, every file and folder will visible
})
```
@@ -251,25 +181,24 @@ ExternalPlugin.Explorer({
## Advanced examples
> [!tip]
> When writing more complicated functions, the `quartz.ts` file can start to look very cramped.
> When writing more complicated functions, the `layout` file can start to look very cramped.
> You can fix this by defining your sort functions outside of the component
> and passing it in.
>
> ```ts title="quartz.ts"
> import * as ExternalPlugin from "./.quartz/plugins"
> import type { ExplorerOptions } from "./.quartz/plugins"
> ```ts title="quartz.layout.ts"
> import { Options } from "./quartz/components/Explorer"
>
> const mapFn: ExplorerOptions["mapFn"] = (node) => {
> export const mapFn: Options["mapFn"] = (node) => {
> // implement your function here
> }
> const filterFn: ExplorerOptions["filterFn"] = (node) => {
> export const filterFn: Options["filterFn"] = (node) => {
> // implement your function here
> }
> const sortFn: ExplorerOptions["sortFn"] = (a, b) => {
> export const sortFn: Options["sortFn"] = (a, b) => {
> // implement your function here
> }
>
> ExternalPlugin.Explorer({
> Component.Explorer({
> // ... your other options
> mapFn,
> filterFn,
@@ -279,10 +208,10 @@ ExternalPlugin.Explorer({
### Add emoji prefix
To add emoji prefixes (📁 for folders, 📄 for files), you could use a map function in `quartz.ts`:
To add emoji prefixes (📁 for folders, 📄 for files), you could use a map function like this:
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
```ts title="quartz.layout.ts"
Component.Explorer({
mapFn: (node) => {
if (node.isFolder) {
node.displayName = "📁 " + node.displayName
+3 -3
View File
@@ -8,13 +8,13 @@ Quartz emits listing pages for any folders and tags you have.
## Folder Listings
Quartz will generate an index page for all the pages under that folder. This includes any content that is multiple levels deep, and pages rendered from other files such as [[Bases|`.base`]] and [[Canvas|`.canvas`]] files: a folder that holds only such pages gets a folder page too.
Quartz will generate an index page for all the pages under that folder. This includes any content that is multiple levels deep.
Additionally, Quartz will also generate pages for subfolders. Say you have a note in a nested folder `content/abc/def/note.md`. Then Quartz would generate a page for all the notes under `abc` _and_ a page for all the notes under `abc/def`.
You can link to the folder listing by referencing its name, plus a trailing slash, like this: `[[advanced/]]` (results in [[advanced/]]).
By default, Quartz will title the page with the folder name (set the [[FolderPage]] option `prefixFolders: true` for `Folder: <folder name>`) and no description. You can override this by creating an `index.md` file in the folder with the `title` [[authoring content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the folder description.
By default, Quartz will title the page `Folder: <folder name>` and no description. You can override this by creating an `index.md` file in the folder with the `title` [[authoring content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the folder description.
For example, for the folder `content/posts`, you can add another file `content/posts/index.md` to add a specific description for it.
@@ -26,7 +26,7 @@ Quartz also supports tag hierarchies as well (e.g. `plugin/emitter`) and will al
You can link to the tag listing by referencing its name with a `tag/` prefix, like this: `[[tags/plugin]]` (results in [[tags/plugin]]).
Tag pages are titled with the tag name (set the [[TagPage]] option `prefixTags: true` for `Tag: <tag>`). As with folder listings, you can also provide a description and title for a tag page by creating a file for each tag. For example, if you wanted to create a custom description for the #component tag, you would create a file at `content/tags/component.md` with a title and description.
As with folder listings, you can also provide a description and title for a tag page by creating a file for each tag. For example, if you wanted to create a custom description for the #component tag, you would create a file at `content/tags/component.md` with a title and description.
## Customization
+8 -9
View File
@@ -6,26 +6,25 @@ tags:
Full-text search in Quartz is powered by [Flexsearch](https://github.com/nextapps-de/flexsearch). It's fast enough to return search results in under 10ms for Quartzs as large as half a million words.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
It can be opened by either clicking on the search bar or pressing `⌘`/`ctrl` + `K`. The top 8 search results are shown on each query, each with up to 5 of its tags. Matching subterms are highlighted and the most relevant 30 words are excerpted. Clicking on a search result will navigate to that page.
It can be opened by either clicking on the search bar or pressing `⌘`/`ctrl` + `K`. The top 5 search results are shown on each query. Matching subterms are highlighted and the most relevant 30 words are excerpted. Clicking on a search result will navigate to that page.
To search content by tags, you can either press `⌘`/`ctrl` + `shift` + `K` or start your query with `#` (e.g. `#components`).
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 reads `contentIndex.json`, which Quartz emits by default (see [[ContentIndex]]). It has no data if `configuration.contentIndex` is disabled.
> Search requires the `ContentIndex` emitter plugin to be present in the [[configuration]].
### Indexing Behaviour
By default, it indexes every page on the site with **Markdown syntax removed**. This means link URLs for instance are not indexed.
It properly tokenizes Chinese, Korean, and Japanese characters and constructs separate indexes for the title, content and tags, weighing title matches above content matches.
It properly tokenizes Chinese, Korean, and Japenese characters and constructs separate indexes for the title, content and tags, weighing title matches above content matches.
## Customization
- Removing search: remove the `search` entry from `quartz.config.yaml` or set `enabled: false`.
- Install: `npx quartz plugin add @quartz-community/search`
- Source: [`quartz-community/search`](https://github.com/quartz-community/search)
- Removing search: delete all usages of `Component.Search()` from `quartz.layout.ts`.
- Component: `quartz/components/Search.tsx`
- Style: `quartz/components/styles/search.scss`
- Script: `quartz/components/scripts/search.inline.ts`
- You can edit `contextWindowWords`, `numSearchResults` or `numTagResults` to suit your needs
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff. Show more