Initial import

This commit is contained in:
Admin
2026-07-11 17:08:37 +00:00
commit 03e5f3452b
303 changed files with 43365 additions and 0 deletions
@@ -0,0 +1,149 @@
---
title: Architecture
---
Quartz is a static site generator. How does it work?
This question is best answered by tracing what happens when a user (you!) runs `npx quartz build` in the command line:
## On the server
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.
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).
2. An HTTP file-server on a user defined port (normally 8080) to serve the actual website files.
4. If the `--serve` flag is set, it also starts a file watcher to detect source-code changes (e.g. anything that is `.ts`, `.tsx`, `.scss`, or packager files). On a change, we rebuild the module (step 2 above) using esbuild's [rebuild API](https://esbuild.github.io/api/#rebuild) which drastically reduces the build times.
5. After transpiling the main Quartz build module (`quartz/build.ts`), we write it to a cache file `.quartz-cache/transpiled-build.mjs` and then dynamically import this using `await import(cacheFile)`. However, we need to be pretty smart about how to bust Node's [import cache](https://github.com/nodejs/modules/issues/307) so we add a random query string to fake Node into thinking it's a new module. This does, however, cause memory leaks so we just hope that the user doesn't hot-reload their configuration too many times in a single session :)) (it leaks about ~350kB memory on each reload). After importing the module, we then invoke it, passing in the command line arguments we parsed earlier along with a callback function to signal the client to refresh.
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. 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 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 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 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 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.config.yaml`, 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.
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.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
Page types define how a category of pages is rendered. They are configured in the `pageTypes` array in `quartz.config.yaml`.
Quartz v5 introduces a community plugin system. Plugins are standalone Git repositories that are cloned into `.quartz/plugins/` and re-exported through an auto-generated index file at `.quartz/plugins/index.ts`.
### Plugin Types
There are now four plugin categories:
- **Transformers**: Map over content (parse frontmatter, generate descriptions, syntax highlighting)
- **Filters**: Filter content (remove drafts, explicit publish)
- **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). 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.
Note that plugin types are **not mutually exclusive** — a single plugin can be a transformer AND provide components (e.g., `obsidian-flavored-markdown`), or be a page type AND provide custom frames (e.g., `canvas-page`).
### Plugin Resolution
When `npx quartz plugin add github:quartz-community/explorer` is run:
1. The repository is cloned into `.quartz/plugins/explorer/`
2. The plugin is built using `tsup` (defined in each 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`
### 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 --clean` — Restore plugins from locked commits in `quartz.lock.json` (used in CI/CD)
- `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`
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.
@@ -0,0 +1,266 @@
---
title: Creating Component Plugins
---
> [!warning]
> This guide assumes you have experience writing JavaScript and are familiar with TypeScript.
Normally on the web, we write layout code using HTML which looks something like the following:
```html
<article>
<h1>An article header</h1>
<p>Some content</p>
</article>
```
This piece of HTML represents an article with a leading header that says "An article header" and a paragraph that contains the text "Some content". This is combined with CSS to style the page and JavaScript to add interactivity.
However, HTML doesn't let you create reusable templates. If you wanted to create a new page, you would need to copy and paste the above snippet and edit the header and content yourself. This isn't great if we have a lot of content on our site that shares a lot of similar layout. The smart people who created React also had similar complaints and invented the concept of Components -- JavaScript functions that return JSX -- to solve the code duplication problem.
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
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.
### Getting Started
To create a new component plugin, you can use the official plugin template:
```shell
git clone https://github.com/quartz-community/plugin-template.git my-component
cd my-component
npm install
```
### Plugin Structure
A component plugin's `src/index.ts` typically exports a function (a constructor) that returns a `QuartzComponent`. This allows users to pass configuration options to your component.
```tsx title="src/index.ts"
import {
QuartzComponent,
QuartzComponentConstructor,
QuartzComponentProps,
} from "@quartz-community/types"
interface Options {
favouriteNumber: number
}
const defaultOptions: Options = {
favouriteNumber: 42,
}
const MyComponent: QuartzComponentConstructor<Options> = (userOpts?: Options) => {
const opts = { ...defaultOptions, ...userOpts }
const Component: QuartzComponent = (props: QuartzComponentProps) => {
if (opts.favouriteNumber < 0) return null
return <p>My favourite number is {opts.favouriteNumber}</p>
}
return Component
}
export default MyComponent
```
### Props
All Quartz components accept the same set of props:
```tsx
export type QuartzComponentProps = {
fileData: QuartzPluginData
cfg: GlobalConfiguration
tree: Node<QuartzPluginData>
allFiles: QuartzPluginData[]
displayClass?: "mobile-only" | "desktop-only"
}
```
- `fileData`: Any metadata 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`.
- `tree`: the resulting [HTML AST](https://github.com/syntax-tree/hast) after processing and transforming the file.
- `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.
### Styling
In community plugins, styles are bundled with the plugin. You can define styles using the `.css` property on the component:
```tsx
Component.css = `
.my-component { color: red; }
`
```
For SCSS, you can import it and assign it to the `.css` property. The build system will handle the transformation:
```tsx
import styles from "./styles.scss"
Component.css = styles
```
> [!warning]
> Quartz does not use CSS modules so any styles you declare here apply _globally_. If you only want it to apply to your component, make sure you use specific class names and selectors.
### 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.
- `.beforeDOMLoaded`: Executed _before_ the page is done loading. Used for prefetching or early initialization.
- `.afterDOMLoaded`: Executed once the page has been completely loaded.
If you need to create an `afterDOMLoaded` script that depends on page-specific elements that may change when navigating, listen for the `"nav"` event:
```ts
document.addEventListener("nav", () => {
// do page specific logic here
const toggleSwitch = document.querySelector("#switch") as HTMLInputElement
if (toggleSwitch) {
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:
```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.
#### 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:
```tsx title="src/index.ts"
import script from "./script.inline.ts"
const Component: QuartzComponent = (props) => {
return <button id="btn">Click me</button>
}
Component.afterDOMLoaded = script
```
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 Plugin from "./.quartz/plugins"
const config = await loadQuartzConfig()
export default config
export const layout = await loadQuartzLayout({
byPageType: {
content: {
left: [Plugin.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
}
}
}
```
If your plugin does not export `init`, it continues to work as a pure side-effect import — this is fully backward compatible.
## Internal Components
Quartz also has internal components that provide layout utilities. These live in `quartz/components/` and are primarily used for structural purposes:
- `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
See [[layout-components]] for more details on these utilities.
> [!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.
@@ -0,0 +1,10 @@
---
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, or component plugin
- **[[creating components]]** — Create custom layout components with JSX
- **[[paths]]** — How Quartz resolves and transforms file paths
@@ -0,0 +1,748 @@
---
title: Making your own plugins
---
> [!warning]
> This part of the documentation will assume you have working knowledge in TypeScript and will include code snippets that describe the interface of what Quartz plugins should look like.
Quartz's plugins are a series of transformations over content. This is illustrated in the diagram of the processing pipeline below:
![[quartz transform pipeline.png]]
All plugins are defined as a function that takes in a single parameter for options `type OptionType = object | undefined` and return an object that corresponds to the type of plugin it is.
```ts
type OptionType = object | undefined
type QuartzPlugin<Options extends OptionType = undefined> = (opts?: Options) => QuartzPluginInstance
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
- `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)
- `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.
- `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.
## 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.
## 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
```
The plugin's `package.json` should declare dependencies on `@quartz-community/types` (for type definitions) and optionally `@quartz-community/utils` (for shared utilities).
## Plugin Types
## Choosing a Plugin Type
Quartz supports six plugin capabilities. A single plugin can combine multiple types.
| 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:
- `obsidian-flavored-markdown` is both a **transformer** (processes OFM syntax) and provides **components** (mermaid rendering)
- `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 **map** over content, taking a Markdown file and outputting modified content or adding metadata to the file itself.
```ts
export type QuartzTransformerPluginInstance = {
name: string
textTransform?: (ctx: BuildCtx, src: string) => string
markdownPlugins?: (ctx: BuildCtx) => PluggableList
htmlPlugins?: (ctx: BuildCtx) => PluggableList
externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
}
```
All transformer plugins must define at least a `name` field to register the plugin and a few optional functions that allow you to hook into various parts of transforming a single Markdown file.
- `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.
- `externalResources` defines any external resources the plugin may need to load on the client-side for it to work properly.
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:
```ts
import remarkMath from "remark-math"
import rehypeKatex from "rehype-katex"
import rehypeMathjax from "rehype-mathjax/svg"
import { QuartzTransformerPlugin } from "@quartz-community/types"
interface Options {
renderEngine: "katex" | "mathjax"
}
export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
const engine = opts?.renderEngine ?? "katex"
return {
name: "Latex",
markdownPlugins() {
return [remarkMath]
},
htmlPlugins() {
if (engine === "katex") {
// if you need to pass options into a plugin, you
// can use a tuple of [plugin, options]
return [[rehypeKatex, { output: "html" }]]
} else {
return [rehypeMathjax]
}
},
externalResources() {
if (engine === "katex") {
return {
css: [
{
// base 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://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/contrib/copy-tex.min.js",
loadTime: "afterDOMReady",
contentType: "external",
},
],
}
}
},
}
}
```
Another common thing that transformer plugins will do is parse a file and add extra data for that file:
```ts
import { 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`
const text = file.value
const words = text.split(" ").length
file.data.wordcount = words
}
},
]
},
}
}
// tell typescript about our custom data fields we are adding
// other plugins will then also be aware of this data field
declare module "vfile" {
interface DataMap {
wordcount: number
}
}
```
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 { visit } from "unist-util-visit"
import { findAndReplace } from "mdast-util-find-and-replace"
import { QuartzTransformerPlugin } from "@quartz-community/types"
import { Link } from "mdast"
export const TextTransforms: QuartzTransformerPlugin = () => {
return {
name: "TextTransforms",
markdownPlugins() {
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 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 }],
}
})
}
},
]
},
}
}
```
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 **filter** content, taking the output of all the transformers and determining what files to actually keep and what to discard.
```ts
export type QuartzFilterPlugin<Options extends OptionType = undefined> = (
opts?: Options,
) => QuartzFilterPluginInstance
export type QuartzFilterPluginInstance = {
name: string
shouldPublish(ctx: BuildCtx, content: ProcessedContent): boolean
}
```
A filter plugin must define a `name` field and a `shouldPublish` function that takes in a piece of content that has been processed by all the transformers and returns a `true` or `false` depending on whether it should be passed to the emitter plugins or not.
For example, here is the built-in plugin for removing drafts:
```ts
import { QuartzFilterPlugin } from "@quartz-community/types"
export const RemoveDrafts: QuartzFilterPlugin<{}> = () => ({
name: "RemoveDrafts",
shouldPublish(_ctx, [_tree, vfile]) {
// uses frontmatter parsed from transformers
const draftFlag: boolean = vfile.data?.frontmatter?.draft ?? false
return !draftFlag
},
})
```
### Emitters
Emitters **reduce** over content, taking in a list of all the transformed and filtered content and creating output files.
```ts
export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
opts?: Options,
) => QuartzEmitterPluginInstance
export type QuartzEmitterPluginInstance = {
name: string
emit(
ctx: BuildCtx,
content: ProcessedContent[],
resources: StaticResources,
): Promise<FilePath[]> | AsyncGenerator<FilePath>
partialEmit?(
ctx: BuildCtx,
content: ProcessedContent[],
resources: StaticResources,
changeEvents: ChangeEvent[],
): Promise<FilePath[]> | AsyncGenerator<FilePath> | null
getQuartzComponents(ctx: BuildCtx): QuartzComponent[]
}
```
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.
- `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.
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-community/utils` if you are creating files that contain text. `write` has the following signature:
```ts
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>
```
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.
If you are creating an emitter plugin that needs to render components, there are three more things to be aware of:
- 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-community/utils` to render Quartz components into HTML.
- If you need to render an HTML AST to JSX, you can use the `htmlToJsx` function from `@quartz-community/utils`.
For example, the following is a simplified version of the content page plugin that renders every single page.
```tsx
import { QuartzEmitterPlugin, FullPageLayout, QuartzComponentProps } from "@quartz-community/types"
import { renderPage, canonicalizeServer, pageResources, write } from "@quartz-community/utils"
export const ContentPage: QuartzEmitterPlugin = () => {
return {
name: "ContentPage",
getQuartzComponents(ctx) {
const { head, header, beforeBody, pageBody, afterBody, left, right, footer } = ctx.cfg.layout
return [head, ...header, ...beforeBody, pageBody, ...afterBody, ...left, ...right, footer]
},
async emit(ctx, content, resources): 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, {}, externalResources)
const fp = await write({
ctx,
content,
slug: file.data.slug!,
ext: ".html",
})
fps.push(fp)
}
return fps
},
}
}
```
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
}
```
- `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.
- `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).
- `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.
### 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: Footer }: PageFrameProps): unknown {
const renderSlot = (C: (props: typeof componentData) => unknown): ComponentChildren =>
C(componentData) as ComponentChildren
return (
<div class="center">
{(Content as any)(componentData)}
{(Footer as any)(componentData)}
</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.
- `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"
},
"./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`.
**4. Add the frame entry point to your build config:**
```ts title="tsup.config.ts"
export default defineConfig({
entry: ["src/index.ts", "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`:
```ts
import { viewRegistry } from "@quartz-community/bases-page";
import type { ViewTypeRegistration } from "@quartz-community/bases-page";
viewRegistry.register({
id: "timeline",
name: "Timeline",
icon: "git-branch",
render: ({ entries, view, slug, allSlugs }) => (
<div class="bases-timeline">
{entries.map(entry => <div>{entry.properties.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.
## 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({
// ...
noExternal: [/.*/], // Bundle everything
external: SINGLETON_EXTERNALS, // Except singletons
})
```
This means your plugin's `dist/index.js` is self-contained — no `npm install` needed at install time.
### 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
3. The CI workflow verifies `dist/` is up to date on every push
If `dist/` is missing or gitignored, Quartz falls back to the full install/build cycle (useful during local development with symlinked plugins).
### 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 will install it into the host project at build time
```shell
# Build the plugin
npm run build
# or
npx tsup
```
## What to Import from Where
| You need... | Import from |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Type definitions (`QuartzTransformerPlugin`, `QuartzComponent`, etc.) | `@quartz-community/types` |
| Path utilities (`simplifySlug`, `resolveRelative`, `pathToRoot`) | `@quartz-community/utils/path` |
| DOM utilities (`removeAllChildren`, `registerEscapeHandler`) | `@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` |
Do **not** import from `@jackyzha0/quartz` or from `vfile` directly. Use the community packages instead.
## 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 `resolve` 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#prune|prune]] and [[cli/plugin#resolve|resolve]] for full details.
## Component Plugins
For plugins that provide visual components (like Explorer, Graph, Search), see the [[creating components|creating component plugins]] guide.
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.
@@ -0,0 +1,51 @@
---
title: Paths in Quartz
---
Paths are pretty complex to reason about because, especially for a static site generator, they can come from so many places.
A full file path to a piece of content? Also a path. What about a slug for a piece of content? Yet another path.
It would be silly to type these all as `string` and call it a day as it's pretty common to accidentally mistake one type of path for another. Unfortunately, TypeScript does not have [nominal types](https://en.wikipedia.org/wiki/Nominal_type_system) for type aliases meaning even if you made custom types of a server-side slug or a client-slug slug, you can still accidentally assign one to another and TypeScript wouldn't catch it.
Luckily, we can mimic nominal typing using [brands](https://www.typescriptlang.org/play#example/nominal-typing).
```typescript
// instead of
type FullSlug = string
// we do
type FullSlug = string & { __brand: "full" }
// that way, the following will fail typechecking
const slug: FullSlug = "some random string"
```
While this prevents most typing mistakes _within_ our nominal typing system (e.g. mistaking a server slug for a client slug), it doesn't prevent us from _accidentally_ mistaking a string for a client slug when we forcibly cast it.
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 in `quartz/path.ts` convert between them.
```mermaid
graph LR
Browser{{Browser}} --> Window{{Body}} & LinkElement{{Link Element}}
Window --"getFullSlug()"--> FullSlug[Full Slug]
LinkElement --".href"--> Relative[Relative URL]
FullSlug --"simplifySlug()" --> SimpleSlug[Simple Slug]
SimpleSlug --"pathToRoot()"--> Relative
SimpleSlug --"resolveRelative()" --> Relative
MD{{Markdown File}} --> FilePath{{File Path}} & Links[Markdown links]
Links --"transformLink()"--> Relative
FilePath --"slugifyFilePath()"--> FullSlug[Full Slug]
style FullSlug stroke-width:4px
```
Here are the main types of slugs with a rough description of each type of path:
- `FilePath`: a real file path to a file on disk. Cannot be relative and must have a file extension.
- `FullSlug`: cannot be relative and may not have leading or trailing slashes. It can have `index` as it's last segment. Use this wherever possible is it's the most 'general' interpretation of a slug.
- `SimpleSlug`: cannot be relative and shouldn't have `/index` as an ending or a file extension. It _can_ however have a trailing slash to indicate a folder 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`.