Compare commits

..
Author SHA1 Message Date
saberzero1 2635c6080a fix(links): don't decode link targets twice under slugs.stripDiacritics
slugOptionsOnLinkPath decoded and stripped the target's path before transformLink, which
decodes it again and (utils 1.3) strips diacritics itself. It changed nothing for any link
except one with a percent-encoded % (`%2520`), which it turned into a space, so the link
pointed at the wrong slug and was marked broken. Removed; the stripDiacritics link tests
still pass without it.
2026-11-27 04:45:48 +01:00
saberzero1 149c82f1da test: cover 5.3 changes the mutation audit found untested
- SlugRedirects emitter (emit/partialEmit, gating, live set, relative targets)
- loadQuartzConfig with extends: default (merged configuration, plugins,
  layout; before/after against built-ins; JSON configs)
- fetchRemoteConfig: offline cache, http redirect, 1 MB limit (bytes),
  memoisation counted, retry after a failure; non-object base; cycle chain
- resolveTarget refuses http URLs that contain https://
- orderPlugins with several before/after targets
- plugin entry keys before/after accepted by the CLI validator
- Head on the 404 page and tag pages
- isolateComponentCss warning; componentStylesheet extracted from
  ComponentResources so the test uses the emitter's own wrapping
- dateIsFromFrontmatter, pluginMatchKey without name/subdir
- todo: stripDiacritics link paths decode a percent-encoded % twice
2026-11-27 04:44:46 +01:00
Emile Bangma 29be20f41c Merge pull request #2712 from jackyzha0/dev-mode/block-id-caret
fix: block anchors are #^id, separate from headings (as in Obsidian)
2026-11-27 00:44:05 +01:00
saberzero1 f7b41e7bbf chore(deps): block anchors #^id (utils 1.3.2, rehype-obsidian 1.6.0 via OFM 2.5.3, GFM 2.2.2, canvas-page 1.1.4, note-properties 1.2.3, bases-page 1.5.5) 2026-11-27 00:42:31 +01:00
saberzero1 7c24cc66e1 Merge remote-tracking branch 'origin/v5' into dev-mode/block-id-caret 2026-11-27 00:41:24 +01:00
saberzero1 3df0062b6f fix(transclude): find blocks by their lowercased name; docs for #^id block anchors 2026-11-27 00:22:34 +01:00
Emile Bangma beca3bc26d Merge pull request #2711 from jackyzha0/dev-mode/investigate-c
fix: broken marks for missing folder/tag pages, watch-mode re-emit, per-component CSS isolation, SPA scroll, stripDiacritics redirects, popover selector
2026-11-27 00:21:42 +01:00
saberzero1 0e16919455 docs(slugs): old addresses redirect when stripDiacritics is on; fold the redirect changeset into the option's 2026-11-27 00:20:07 +01:00
saberzero1 81b358224b fix(popover): escape the target id in the popover's scroll-to selector (ids like ^block-id are not CSS identifiers) 2026-11-26 23:30:54 +01:00
saberzero1 0346dc6149 feat(slugs): redirect from addresses that slugs.stripDiacritics changed 2026-11-26 23:25:25 +01:00
saberzero1 e0f1e03913 fix(spa): keep a scroll position still pending when Back/Forward leaves the entry 2026-11-26 23:23:03 +01:00
saberzero1 c79adab53b fix(css): parse each component's CSS on its own before joining the component stylesheet 2026-11-26 23:20:33 +01:00
saberzero1 af36801547 fix(links): mark links to folder/tag pages that aren't generated; re-emit pages whose link marks change in watch mode 2026-11-26 23:18:49 +01:00
Emile Bangma b1fc7acd8e Merge pull request #2707 from jackyzha0/docs/5-3-release-notes
docs: 5.2 and 5.3 release notes, upgrade steps and new plugin options
2026-11-26 23:13:24 +01:00
saberzero1 011c101cd3 docs: final stripDiacritics rule and stacking extends in what's new; canvas text-node embeds and tags; changeset no longer promises redirects from old addresses 2026-11-26 23:12:03 +01:00
saberzero1 690f7a0325 Merge remote-tracking branch 'origin/v5' into docs/5-3-release-notes 2026-11-26 23:11:21 +01:00
Emile Bangma abfda7b85e Merge pull request #2710 from jackyzha0/deps/5-3-audit-plugins
chore(deps): plugin releases from the pre-5.3 audit
2026-11-26 23:11:01 +01:00
saberzero1 57cd6631d3 docs: 5.2 and 5.3 release notes and upgrade steps; explorer sort/rootFolder, GFM singleTilde/replacements, OFM math/markdownEmbeds, canvas options, Pele default 2026-11-26 20:55:56 +01:00
40 changed files with 1383 additions and 133 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Block anchors are `#^id`, as in Obsidian: `@quartz-community/utils` 1.3.2 and `@quartz-community/rehype-obsidian` 1.6.0, bundled by obsidian-flavored-markdown 2.5.3, github-flavored-markdown 2.2.2, canvas-page 1.1.4, note-properties 1.2.3 and bases-page 1.5.5, give blocks `id="^id"` and link to them as `#^id`. A block and a heading with the same name (`^para-1`, `## Para 1`) no longer share an id, so `[[#^para-1]]` and `[[#Para 1]]` each reach their own target. canvas-page also scopes the ids of text nodes rendered with `textNodeMarkdown: basic`.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Block anchors are `#^id`: with @quartz-community/utils 1.3.2 and rehype-obsidian 1.6.0, blocks get the id `^id` and links to them `#^id` (was `#id`), as in Obsidian, so block `^para-1` and heading `## Para 1` no longer share an id. A block transclusion finds its block whatever the case of its `^id` (`![[note#^Para-1]]`), and the popover scrolls to a block it links to.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Each component's CSS is parsed on its own before the component stylesheet is put together, so a missing `}` or an unclosed comment in one plugin's CSS no longer swallows the rules of every component after it, and a stray `}` no longer fails the build; a syntax error is reported with the component's name.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
A scroll made just before Back (less than 150 ms) is no longer lost: Forward returns to where the reader scrolled.
+1 -1
View File
@@ -2,4 +2,4 @@
"@jackyzha0/quartz": minor
---
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses, and the old addresses redirect to them; heading anchors keep their diacritics. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses; heading anchors keep their diacritics. Turning it on changes the URLs of existing pages; their old addresses redirect to the new ones. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Links to a folder or tag page that isn't generated (a folder whose notes are all drafts or that holds only images, a tag no published page uses) are marked broken, and in watch mode a page whose links to a page that was published or filtered out change is re-emitted, so its marks don't go stale.
+2 -1
View File
@@ -65,5 +65,6 @@ Heading ids follow the GitHub rule (`github-slugger`, as `rehype-slug` and the t
- `slugHeading(text)`: the id of a heading with this text;
- `HeadingSlugger`: slugs all headings of one page in order and numbers repeats (`foo`, `foo-1`, …) — create one per page;
- `obsidianHeadingAnchor(text)`: the anchor Obsidian writes for a heading (it replaces `:`, `|`, `^`, `#` and `\` with spaces); slug it with `slugHeading` and add it as an extra id when it differs;
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, a block reference `#^name`, or a heading's text);
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, or a heading's text); a block reference `#^name` always points at the block (`#^name`), never at a heading;
- `blockAnchor(name)`: the anchor of the block `^name`, `#^name` (lowercased). Blocks have the id `^name`, so they never share an id with a heading;
- `slugTag(tag)`: the slug of a tag, as used for tag pages.
+1 -1
View File
@@ -91,7 +91,7 @@ This part of the configuration concerns anything that can affect the whole site.
- `stripDiacritics`: `true` strips accents and other diacritics from page, folder and file URLs, e.g. `české/čeština.md` is published at `/ceske/cestina` instead of `/české/čeština` (which browsers show as `%C4%8Desk%C3%A9/...` when copied). Off by default.
- Links keep working as written in your notes: `[[čeština]]`, `[[české/čeština#Nadpis]]` and embeds like `![[obrázek.png]]` resolve to the stripped addresses. Aliases and `permalink`s are stripped the same way. Heading anchors (`#Nadpis`) keep their diacritics. Tag pages and the pages plugins generate from files (canvas, bases, …) are stripped too with `@quartz-community/utils` 1.3 or newer; with older versions they keep their diacritics.
- Only Latin letters change: they lose their accents (`á č é ů …`), and Latin letters without a decomposition fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`). Other scripts (Chinese, Japanese, Korean, Greek, Cyrillic, Arabic, Hebrew, Devanagari, …) are left as written, marks included.
- Turning it on changes the URLs of existing pages; links shared elsewhere to the old addresses will 404 unless you add the old addresses as `aliases`.
- Turning it on changes the URLs of existing pages. Quartz writes a redirect from each page's, folder's and alias's old address (the slug with its diacritics) to the new one, so links shared elsewhere keep working. Old `permalink` addresses are not redirected; add them as `aliases` if they need to keep working.
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
- `theme`: configure how the site looks.
- `fontOrigin`: where to load fonts from.
+2 -2
View File
@@ -6,7 +6,7 @@ tags:
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.
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.
Diagrams are drawn with [Pele](https://pele.run), as in Obsidian 1.15 (since [[ObsidianFlavoredMarkdown]] 2.4 / Quartz 5.3), inside a `<div class="mermaid">`. Set `diagramRenderer: mermaid` on ObsidianFlavoredMarkdown to use the deprecated Mermaid.js instead.
> [!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.
@@ -16,7 +16,7 @@ plugins:
- source: "@quartz-community/obsidian-flavored-markdown"
options:
mermaid: true
diagramRenderer: pele # default: mermaid
diagramRenderer: pele # or mermaid (deprecated)
```
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.
+78 -9
View File
@@ -59,7 +59,70 @@ plugins:
priority: 50
```
For advanced options like custom sort, filter, and map functions, use the TS override in `quartz.ts`:
### Sorting
`sort` is a list of rules. Each folder's entries are sorted by the first rule; entries it considers equal are sorted by the next one, and so on. A rule is `{ by: <key>, direction: asc | desc }` (`direction` defaults to `asc`), or just the key. As in [[Bases]] views, `direction` may also be written `ASC` / `DESC`, and `by` as `property`.
| `by` | Sorts by |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `folder` | Folders before files (`desc`: files before folders) |
| `title` | The displayed name (the page title), in natural order: `Note 2` before `Note 10`, case-insensitive |
| `name` | The file or folder name, whatever the title or `mapFn` (e.g. numbered names: `10 Research`) |
| `date` | The page's date, as `defaultDateType` picks it (created, modified or published). A folder's date is its index page's date when that page sets one in its frontmatter, else the date of its newest page |
| `tag` | The page's tags in the order they are written: first tags compared, then second tags when those are equal, and so on. With `firstTagOnly: true`, only the first tags |
Entries without a date or tags come after the others, in either direction. The default is `[folder, title]`. Newest first, folders still on top:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
options:
sort:
- folder
- { by: date, direction: desc }
- title
```
Grouped by first tag, newest first within a tag:
```yaml
sort:
- by: tag
firstTagOnly: true
- by: date
direction: desc
```
A `sortFn` set in `quartz.ts` replaces `sort`. Sorting runs at the `sort` step of `order`, so with the default order it sees the names `mapFn` set. `order: [filter, sort, map]` sorts by the original names, for example to strip [Johnny.Decimal](https://johnnydecimal.com/) prefixes in `mapFn` while keeping the numbered order.
### Several explorers
List the plugin once per explorer, each entry with its own options and layout. `rootFolder` shows only one folder's contents (a folder path as in your vault, or its slug):
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
layout:
position: left
priority: 50
- source: "@quartz-community/explorer"
enabled: true
options:
title: Notes
rootFolder: Notes/Daily Notes
layout:
position: left
priority: 55
display: desktop-only # one menu button on phones
```
Opened folders are remembered per folder, so a folder shown in both explorers is open or closed in both; scroll positions are kept per explorer. Options set in a TypeScript override apply to every entry.
### Custom functions
For 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"
@@ -100,7 +163,8 @@ Want to customize it even more?
- Removing explorer: remove the `explorer` entry from `quartz.config.yaml` or set `enabled: false`
- (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]]
- Changing the sort order: [[#Sorting]]
- Custom `sort`, `filter` and `map` functions: explained in [[#Advanced customization]]
## Advanced customization
@@ -122,9 +186,13 @@ export type ContentDetails = {
links: SimpleSlug[]
tags: string[]
content: string
date?: string // ISO 8601, the date `defaultDateType` picks (Quartz 5.3+)
dateFromFrontmatter?: true // the date is set in the page's frontmatter (Quartz 5.3+)
}
```
To sort by date, use `sort: [{ by: date, direction: desc }]` (see [[#Sorting]]), or compare `a.data?.date` in a `sortFn`.
Every function you can pass is optional. By default, only a `sort` function will be used:
```ts title="Default sort function"
@@ -167,24 +235,25 @@ These examples show the basic usage of `sort`, `map` and `filter`.
### Use `sort` to put files first
Using this example, the explorer will alphabetically sort everything.
Files before folders, everything by title:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
options:
# Simple options go in YAML
title: Explorer
folderDefaultState: collapsed
sort:
- { by: folder, direction: desc }
- title
```
Custom sort functions require the TS override:
The same with a sort function in the TS override:
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
sortFn: (a, b) => {
return a.displayName.localeCompare(b.displayName)
if (a.isFolder === b.isFolder) return a.displayName.localeCompare(b.displayName)
return a.isFolder ? 1 : -1
},
})
```
@@ -203,7 +272,7 @@ 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.
> The `mapFn`, `filterFn`, and `sortFn` options require JavaScript callback functions and cannot be expressed in YAML. Use the TS override for these. Sorting by folder, title, name, date or tag needs no code: see [[#Sorting]].
### Remove list of elements (`filter`)
+63
View File
@@ -28,6 +28,69 @@ npx quartz plugin install --latest
See the [[upgrade|CLI reference for upgrade]] for more details on available flags.
## Upgrading from 5.2 to 5.3
Quartz 5.3 needs **Node.js 22.22 or later**. Then upgrade as usual:
```bash
npx quartz upgrade
npx quartz plugin install --latest
```
### Changes you may notice
- **Block anchors**: a block's id is now `^id` and links to it are `#^id` (`[[note#^para-1]]` → `note#^para-1`, was `note#para-1`), as in Obsidian, where blocks and headings are separate namespaces: block `^para-1` and heading `## Para 1` no longer share an id, so `[[#^para-1]]` and `[[#Para 1]]` each land on their own target. Links inside the site are regenerated; old `#id` URLs of blocks from outside the site now go to the top of the page (or to a heading of that name). CSS or scripts that select a block by id need `#\^para-1` (or `getElementById`).
- **Unresolved links**: `configuration.links.disableBrokenWikilinks` is now on by default. Links to pages that don't exist get the `broken` class and are styled as unresolved, as in Obsidian. Links to pages a filter removes (drafts, unpublished notes) are marked the same way, with `data-filtered="<filter>"`. Set `links.disableBrokenWikilinks: false` to style them as before.
- **Mermaid diagrams** render with [Pele](https://pele.run) by default, as in Obsidian, inside a `<div class="mermaid">` rather than a code block. Set `diagramRenderer: mermaid` on [[ObsidianFlavoredMarkdown]] to keep Mermaid.js. See [[Mermaid diagrams]].
- **Block wrappers**: each top-level block of a note is wrapped in the `div` Obsidian puts it in (`div.el-p > p`, `div.el-h2 > h2`). Custom CSS that selects a page's blocks as direct children (`article > p`) no longer matches. Select them without `>`, or set `blockWrappers: false` on ObsidianFlavoredMarkdown.
- **Transclusions** use Obsidian's embed markup: the title of a whole-note embed is a `div.markdown-embed-title` (it was an `h1`), and the content is in `div.markdown-embed-content`. It looks the same without a theme. Custom CSS for transclusions may need new selectors.
- **Page structure**: the centre column is a `<main>` (it was a `div`; the `center` class is unchanged) and the default frame's sidebars are `<aside>` elements. Page listings use `h2` titles (they were `h3`) at the same size. Footnote links keep the `internal` class but no longer have `internal-link`.
- **Colours**: the templates' `gray` and `tertiary` colours meet WCAG AA contrast. Your site keeps the colours in its own `quartz.config.yaml`. To adopt the new ones, set them under `configuration.theme.colors`:
```yaml title="quartz.config.yaml"
configuration:
theme:
colors:
lightMode:
gray: "#727272" # was #b8b8b8
tertiary: "#587971" # was #84a59d
darkMode:
gray: "#7f7f7f" # was #646464
```
- **Folding**: the `obsidian` template folds headings and lists. Other sites can turn it on with `foldHeadings` and `foldLists` on ObsidianFlavoredMarkdown.
- **Stylesheets**: component styles are one `component-<hash>.css` file instead of one per component. The styles are unchanged.
- **Frontmatter** is read as YAML 1.2. Frontmatter with only comments has no properties, as in Obsidian, instead of being reported as invalid.
- **Custom TypeScript**: type checking (`npm run check`) uses TypeScript 7 with `moduleResolution: bundler`. Code that imports a package's internal files may need to import from the package itself.
### New options
- `extends` (experimental) and `before`/`after` on plugin entries. See [[configuration#Extending the default configuration]].
- `configuration.slugs.stripDiacritics`. See [[configuration#General Configuration]].
- The layout conditions `is-index`, `is-folder-index` and `not-<condition>`. See [[layout#Conditional Rendering]].
- [[plugins/Explorer|Explorer]]: `sort`, `rootFolder`, and `order` in YAML. [[GitHubFlavoredMarkdown]]: `singleTilde`, `replacements`. [[ObsidianFlavoredMarkdown]]: `math`, `markdownEmbeds`, `blockWrappers`, `foldHeadings`, `foldLists`. [[CanvasPage]]: `wheelBehavior`, `textNodeMarkdown`.
See [[whats-new#New in 5.3|What's new in 5.3]] for everything else.
## Upgrading from 5.1 to 5.2
```bash
npx quartz upgrade
npx quartz plugin doctor --fix
```
`--fix` moves the Fonts plugin's entry (`@quartz-community/quartz-fonts`) into `configuration.fonts`, now that font loading is built in. Until you run it, the entry keeps working and is applied automatically.
### Changes you may notice
- **Themes**: [[ThemesCore]] 3 converts Obsidian themes at build time, so the `@quartz-themes/<theme>` packages are no longer needed. Theme ids from 2.x (`tokyo-night`) keep working. The `aspects`, `include`, `calloutStyle` and `fonts` options were removed.
- **Callouts and transclusions** render as `<div>` elements, as in Obsidian (callouts were `<blockquote>`). Callout titles are in `.callout-title-inner` without a `<p>`. Custom CSS for either may need new selectors.
- **Bases** columns are labelled with the property's name (`priority`, `file name`) instead of title case (`Priority`, `Name`). Set `propertyLabels: title` on [[BasesPage]] for the old labels.
- **Permalinks** with `.` or `..` segments are ignored with a warning.
- **Fonts**: configured `body`, `code` and `interface` fonts now apply under an Obsidian theme, and the interface and heading fonts are loaded from Google Fonts like the others.
See [[whats-new#New in 5.2|What's new in 5.2]] for everything else.
## Upgrading from 5.0 to 5.1
Run the upgrade, then let `plugin doctor` update your config:
+30
View File
@@ -7,6 +7,36 @@ aliases:
Quartz 5 is a ground-up rearchitecture of Quartz focused on extensibility, performance, and Obsidian compatibility. If you're coming from v4, see [[migrating|Migrating to Quartz 5]] for the upgrade path.
## New in 5.3
Upgrading from 5.2? See [[upgrading#Upgrading from 5.2 to 5.3|Upgrading from 5.2 to 5.3]] for the changes you may notice.
- **Accessibility** — the templates' colours meet WCAG AA contrast, and so does text in the table of contents, footer, folder and tag listings, search button and Bases group headings. The centre column is a `<main>` and the sidebars are `<aside>` elements, page listings no longer skip heading levels, and ARIA attributes and ids are valid in the table of contents, explorer, backlinks, heading anchors and Bases views.
- **Faster pages** — component styles are one stylesheet (about 20 fewer render-blocking requests per page), the [[graph view]] loads d3 and PixiJS only when it is shown and opens five times faster on large sites, and KaTeX's stylesheet no longer blocks pages without math.
- **Back and Forward** — with [[SPA Routing]], Back and Forward return to where you were on each page, and moving between headings of the same page only scrolls.
- **Markup as in Obsidian** — [[ObsidianFlavoredMarkdown]] wraps each top-level block in Obsidian's `div.el-*` wrappers, renders [[Mermaid diagrams]] with Pele by default, and can fold headings and lists (`foldHeadings`, `foldLists`; on in the `obsidian` template). Transclusions use Obsidian's embed markup, a missing attachment reads "could not be found", and notes embedded with a Markdown link (`![](note.md#Section)`) are transcluded. Obsidian themes ([[ThemesCore]] 3.2) style all of these.
- **Unresolved links** — links to pages that don't exist, or that a filter removed (drafts, [[ExplicitPublish]]), get the `broken` class, as Obsidian marks unresolved links (`links.disableBrokenWikilinks` is on by default). See [[CrawlLinks]].
- **Extending a configuration** (experimental) — `extends: default` in `quartz.config.yaml` keeps only your changes to the default configuration; it also takes a path or an `https://` URL. Several presets can be listed and stack. Plugin entries can declare `before:` / `after:` other plugins. See [[configuration#Extending the default configuration]].
- **Slugs without accents** — `configuration.slugs.stripDiacritics` publishes `české/čeština.md` at `/ceske/cestina` and `Łódź.md` at `/lodz`, so URLs in Latin-script languages need no percent-encoding; other scripts are left as written. See [[configuration#General Configuration]].
- **Layout conditions** — `is-index` (home page), `is-folder-index`, and `not-<condition>` for any condition (`not-has-tags`). See [[layout#Conditional Rendering]].
- **Explorer** 1.2 — sort from YAML with rules applied in sequence (`sort: [folder, { by: date, direction: desc }]`), several explorers on a page (`rootFolder`), and `order` in YAML. See [[plugins/Explorer|Explorer]].
- **Plugin options** — [[GitHubFlavoredMarkdown]]: `singleTilde` and `replacements` (for example Quartz 4's arrows); [[ObsidianFlavoredMarkdown]]: `math`; [[CanvasPage]]: the wheel and trackpad pan the canvas as in Obsidian, and text nodes render with the site's Markdown plugins (Mermaid, callouts, math).
- **Link previews and search engines** — each page has a canonical link, and `og:url`, `og:type` and the article times are set as Open Graph readers expect.
- **Content index** — `contentIndex.json` entries carry the page's `date`, for client-side components such as the explorer.
- **Releases** — release tags are verified on GitHub, and each release publishes a versioned Docker image.
## New in 5.2
Upgrading from 5.1? See [[upgrading#Upgrading from 5.1 to 5.2|Upgrading from 5.1 to 5.2]].
- **Obsidian themes** — [[ThemesCore]] 3.1 converts any Obsidian community theme at build time: name it as Obsidian lists it (`Minimal`, `AnuPpuccin`), or give a GitHub repository, a URL or a local `theme.css`. Style Settings exports and CSS snippets apply as in Obsidian.
- **Fonts built in** — font loading is part of Quartz as `configuration.fonts` (formerly the Fonts plugin), including the interface font and per-heading fonts. See [[configuration#Fonts]].
- **`quartz build --config <path>`** — read the configuration from another file, so it can live with your content and one Quartz install can build several sites.
- **Bases** closer to Obsidian ([[BasesPage]] 1.5) — custom summaries, `html()`, `image()`, `icon()`, regular expressions and `file.backlinks` in formulas, `kanban` views, `groupOrder`, grouped lists and cards, and columns labelled with the property's name. Bases inside a transcluded note render, and links in bases follow `configuration.links`.
- **Transclusions** — headings and footnotes inside a transclusion get ids unique on the page, and a heading transclusion holds only the footnotes it references.
- **Permalinks on large sites** — notes with a `permalink` are published at it on sites of any size.
- **Plugins** can be async and declare `renderTransforms`, so encrypted notes show their bases and transclusions once unlocked ([[EncryptedPages]]).
## New in 5.1
Upgrading from 5.0? See [[upgrading#Upgrading from 5.0 to 5.1|Upgrading from 5.0 to 5.1]] for the steps and the changes you may notice.
+3 -1
View File
@@ -21,6 +21,8 @@ This plugin accepts the following configuration options:
- `initialZoom`: The initial zoom level when the canvas is first displayed. Default: `1{:ts}`.
- `minZoom`: The minimum zoom level allowed when zooming out. Default: `0.1{:ts}`.
- `maxZoom`: The maximum zoom level allowed when zooming in. Default: `5{:ts}`.
- `wheelBehavior`: What the mouse wheel and two-finger trackpad scroll do. `"pan"` (default) moves the canvas, as in Obsidian (Shift + wheel: sideways); Ctrl/Cmd + wheel and pinching zoom. `"zoom"`: the wheel always zooms.
- `textNodeMarkdown`: How text nodes are rendered. `"site"` (default): with the site's own Markdown plugins, like a note. `"basic"`: plain CommonMark + GFM, with wikilinks and links to notes still resolved.
### Canvas Frame
@@ -43,7 +45,7 @@ layout:
### Features
- **Text nodes**: Render Markdown content including headings, bold, italic, strikethrough, lists, links, and code blocks via [GFM](https://github.github.com/gfm/) support.
- **Text nodes**: Rendered with the site's own Markdown plugins, like a note, as in Obsidian: wikilinks, callouts, [[Mermaid diagrams]], math, syntax highlighting and embedded notes (`![[Note#Section]]`). Tags in text nodes count as the canvas's tags, so they get tag pages.
- **File nodes**: Link to other pages in your vault. Supports popover previews on hover.
- **Link nodes**: Reference external URLs.
- **Group nodes**: Visual grouping containers with optional labels and background colors.
+5 -3
View File
@@ -26,15 +26,17 @@ This plugin accepts the following configuration options:
- `folderClickBehavior`: The behavior when a folder is clicked. Can be `"link"` to navigate or `"collapse"` to toggle. Defaults to `link`.
- `folderDefaultState`: The default state of folders. Can be `"collapsed"` or `"open"`. Defaults to `collapsed`.
- `useSavedState`: Whether to use local storage to save the state of the explorer. Defaults to `true`.
- `sort`: Sort rules, applied in sequence: entries the first rule considers equal are sorted by the next one. Defaults to `[folder, title]` (folders first, then by title). See [[features/explorer#Sorting]].
- `rootFolder`: Show only this folder's contents, e.g. `Notes` or `Notes/Daily Notes`. Defaults to everything. See [[features/explorer#Several explorers]].
- `order`: The order in which `filterFn`, `mapFn` and `sortFn` run. Defaults to `[filter, map, sort]`.
**TS override options** (in `quartz.ts`, for callback functions that can't be expressed in YAML):
- `sortFn`: Custom sort function for ordering files and folders.
- `sortFn`: Custom sort function for ordering files and folders. Replaces `sort`.
- `filterFn`: Custom filter function to exclude specific nodes.
- `mapFn`: Custom map function to transform node properties (e.g. display names).
- `order`: Array controlling the order of operations. Defaults to `["filter", "map", "sort"]`.
By default the explorer hides the `tags` folder (`filterFn`) and sorts folders before files, then alphabetically with numeric ordering (`sortFn`).
By default the explorer hides the `tags` folder (`filterFn`) and sorts folders before files, then by title in natural order (`Note 2` before `Note 10`).
### Default options
+25
View File
@@ -20,6 +20,8 @@ This plugin accepts the following configuration options:
- `enableSmartyPants`: When true, enables typographic enhancements. Default is true.
- `linkHeadings`: When true, gives headings their `id`s and adds a link to each heading. Default is true. Setting it to `false` also turns off heading ids, so links to headings (`[[page#Heading]]`) and section embeds no longer reach them (on pages with a [[table of contents]], TableOfContents still gives headings ids).
- `singleTilde`: When true (default), text between single tildes (`~text~`) is struck through, as on GitHub. `false` strikes only `~~text~~`, as Obsidian does, so a `~` meaning "about" (`~20 W and (~€120)`) stays as written. Under [[ObsidianFlavoredMarkdown]]'s default `legacy` preset, which parses as Obsidian, single tildes never strike.
- `replacements`: Text to replace as written, outside code and math, before SmartyPants; the longest match wins. Empty by default: neither GitHub nor Obsidian replaces anything. See [[#Arrows]].
### Default options
@@ -29,11 +31,34 @@ This plugin accepts the following configuration options:
options:
enableSmartyPants: true
linkHeadings: true
singleTilde: true
replacements: {}
order: 30
```
This plugin must run before [[ObsidianFlavoredMarkdown]] (order `30` and `40` in the default config). If you set `order` on either plugin, keep this one first.
## Arrows
Quartz 4 turned typed arrows into arrow characters (`parseArrows`). Obsidian doesn't, so Quartz 5 leaves them as typed. To render them as Quartz 4 did:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/github-flavored-markdown"
options:
replacements:
"->": "→"
"-->": "⇒"
"=>": "⇒"
"==>": "⇒"
"<-": "←"
"<--": "⇐"
"<=": "⇐"
"<==": "⇐"
```
Text in code, inline code and math is left alone. Note that `<=` then also replaces a "less than or equal" written in prose.
## Heading ids
Heading ids are made from the heading as written, with the same slug function that links and the [[table of contents]] use, and match GitHub's:
+3 -1
View File
@@ -22,10 +22,11 @@ This plugin accepts the following configuration options:
- `strictLineBreaks`: Obsidian's "Strict line breaks" setting. `false` (the default under `preset: "legacy"`) renders a single line break inside a paragraph as a `<br>`, as in Obsidian's default reading view. `true` (the default under `preset: "strict"`) renders it as a space, as CommonMark does. This replaces the deprecated [[HardLineBreaks]] plugin.
- `comments`: If `true` (default), enables parsing of `%%` style Obsidian comment blocks.
- `highlight`: If `true` (default), enables parsing of `==` style highlights within content. A highlight that starts with a colour emoji (🔴 🟠 🟡 🟢 🔵 🟣, or the matching squares) is coloured as in Obsidian 1.14, e.g. `==🔴 urgent==`.
- `math`: If `true` (default), parses `$inline$` and `$$display$$` math. With `false`, dollar signs stay text (`cost of $2-$3`), for sites without math.
- `wikilinks`: If `true` (default), turns [[wikilinks]] into regular links.
- `callouts`: If `true` (default), adds support for [[callouts|callout]] blocks for emphasizing content.
- `mermaid`: If `true` (default), enables [[Mermaid diagrams|Mermaid diagram]] parsing within Markdown files.
- `diagramRenderer`: `"mermaid"` (default) or `"pele"`. Which engine draws Mermaid fences. [Pele](https://pele.run) is opt-in; Mermaid.js is deprecated.
- `diagramRenderer`: `"pele"` (default) or `"mermaid"`. Which engine draws Mermaid fences: [Pele](https://pele.run), as in Obsidian, or the deprecated Mermaid.js.
- `parseTags`: If `true` (default), parses and links tags within the content.
- `parseBlockReferences`: If `true` (default), handles block references, linking to specific content blocks.
- `enableInHtmlEmbed`: If `true`, allows embedding of content directly within HTML. Defaults to `false`.
@@ -34,6 +35,7 @@ This plugin accepts the following configuration options:
- `enableVideoEmbed`: If `true` (default), enables the embedding of video files.
- `enableCheckbox`: If `true`, adds support for interactive checkboxes in content, including custom task characters (e.g. `- [?]`, `- [!]`, `- [/]`). Defaults to `false`; the default `quartz.config.yaml` turns it on.
- `enableObsidianUri`: If `true` (default), marks `obsidian://` protocol links with a CSS class and data attribute for custom styling.
- `markdownEmbeds`: If `true` (default), a note, canvas or base embedded with a Markdown link (`![](note.md#Section)`, `![](note)`, `![alt](board.canvas)`, `![](projects.base)`) is transcluded like `![[note#Section]]`, as in Obsidian (which writes embeds this way when its `Use [[Wikilinks]]` setting is off), instead of shown as a broken image. The link resolves like any Markdown link, by `configuration.links.markdownLinkResolution`.
- `blockWrappers`: If `true` (default), wraps each top-level block in the `div` Obsidian puts it in (`div.el-p > p`), which Obsidian themes space blocks with. No visible change without a theme.
- `foldHeadings`: If `true`, headings fold as in Obsidian's reading view ("Fold heading"): an arrow before each heading, shown on hover, hides everything up to the next heading of the same or a higher level. Defaults to `false`.
- `foldLists`: If `true`, list items with a sublist fold as in Obsidian's reading view ("Fold indent"): an arrow before the item, shown on hover, hides its sublist. Defaults to `false`.
+33 -33
View File
@@ -16,9 +16,9 @@
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.4",
"@quartz-community/bases-page": "^1.5.5",
"@quartz-community/breadcrumbs": "^1.0.5",
"@quartz-community/canvas-page": "^1.1.2",
"@quartz-community/canvas-page": "^1.1.4",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
@@ -33,12 +33,12 @@
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.3",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.1",
"@quartz-community/github-flavored-markdown": "^2.2.2",
"@quartz-community/graph": "^1.0.8",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.2",
"@quartz-community/note-properties": "^1.2.2",
"@quartz-community/obsidian-flavored-markdown": "^2.5.2",
"@quartz-community/note-properties": "^1.2.3",
"@quartz-community/obsidian-flavored-markdown": "^2.5.3",
"@quartz-community/og-image": "^1.1.3",
"@quartz-community/ox-hugo": "^1.0.3",
"@quartz-community/page-title": "^1.0.2",
@@ -97,7 +97,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.2",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
@@ -2330,14 +2330,14 @@
}
},
"node_modules/@quartz-community/bases-page": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.4.tgz",
"integrity": "sha512-WDUQ/FGMz3ynQbHCt/SCn6nAbEfkvK/isfxqKHbfQTl1e1eSBc4AImux9wtJSLpnCriwV9w7ChZpLidDRigk6Q==",
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.5.tgz",
"integrity": "sha512-aUJgKt3KjP2UOT4sfeHugkwMyptqXpkRBrHiOthyEND2NI43kZUTNQ2FicTZQLDMLOSnuUu4PXgHv0NF4Ntyrw==",
"license": "MIT",
"dependencies": {
"@lucide/icons": "^1.70.0",
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2383,13 +2383,13 @@
}
},
"node_modules/@quartz-community/canvas-page": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.2.tgz",
"integrity": "sha512-dAsTC/cGVdMQqxF+hJxppln3nNDjLOY9FxGszTBOWSFoyylciaoCKiqpdfJcgeVtI4JNUvFZ/kofaWcpW7FDkA==",
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.4.tgz",
"integrity": "sha512-HNvwpnIbv887epOKTKcr1fMV9cSN6JjQw7mxNSiBJSSe9dtYUu4F7FPIFE33JFSWOpilDgV6f+ApnYVQ1c9yaA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2712,13 +2712,13 @@
}
},
"node_modules/@quartz-community/github-flavored-markdown": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/github-flavored-markdown/-/github-flavored-markdown-2.2.1.tgz",
"integrity": "sha512-i1FwY8AY7d78TOs665XGgeGRZT2EefUZ8hZu35E0sNFiX09VrnSzGz0NmnamFYBMkmEc55R3N6gNtoqLVMr2Kw==",
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/@quartz-community/github-flavored-markdown/-/github-flavored-markdown-2.2.2.tgz",
"integrity": "sha512-JsSeydLs05VZj2jc2KT/5vse+zNGCDH92Ih8/yp5s6EUY+wwOmzSTPxT65Ey0LK/X/nclfkMu4S4Domd2RkwmA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.1.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2802,13 +2802,13 @@
}
},
"node_modules/@quartz-community/note-properties": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.2.tgz",
"integrity": "sha512-qyrNdL+Yveb1/mdN23B0yACvuDMDKPsPhTvATisaN4h0dNS/4i/Nu6J6W1wbcN3t1tKhE7cdNWMYpabay+l42g==",
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.3.tgz",
"integrity": "sha512-udQ8hWrkX9V1tcrxyxRniE8QkFXHAp1AFYjhZ9ZcRFNdSxgyu7Q18vHRl65jrW7MKoApN6VB3dOjUwiM1hn88A==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2828,15 +2828,15 @@
}
},
"node_modules/@quartz-community/obsidian-flavored-markdown": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.2.tgz",
"integrity": "sha512-t30nSwmEVLvIw4LnOp+iAe3ZcJNy2Bew+luAL425Ek/XM6udXkIzaafEhjXQXTN34k8/6rjvat1w2HGepdv/nw==",
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.3.tgz",
"integrity": "sha512-nevXFettUGuQemzqcXkDiUjKLeUKQ36RkITQx36G56gAB1TkrHv03gP4iX9EVXHi/9ZCSlgDdyHIkDRgP0lL4Q==",
"license": "MIT",
"dependencies": {
"@quartz-community/rehype-obsidian": "^1.5.1",
"@quartz-community/rehype-obsidian": "^1.6.0",
"@quartz-community/remark-obsidian": "^2.2.4",
"@quartz-community/types": "^1.1.0",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.2",
"pele": "^1.13.0"
},
"engines": {
@@ -2970,9 +2970,9 @@
}
},
"node_modules/@quartz-community/rehype-obsidian": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.5.1.tgz",
"integrity": "sha512-PvU1JCyAndgbkjPeFaPs1r/FnijtTFTDetn9F8mUBRGB9zEDEGIHqpo+/LZvQQUP46eCbRUXkz2RVc72g0V/UQ==",
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.6.0.tgz",
"integrity": "sha512-7NyJNKr515xtCBBhzLr4UdoENutGPgAJhh3GA0S3j6Qj2r7v+hFNSq4yd3gtFP0GK7b4PPfOtTTyAWCC8BYiig==",
"license": "MIT",
"engines": {
"node": ">=22"
@@ -3230,9 +3230,9 @@
}
},
"node_modules/@quartz-community/utils": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.1.tgz",
"integrity": "sha512-HGlcmwzt+nzu77sVfERtGFgw9CqO0/sApDX4RBM4pJZOxBDFKOL+5aKOw3TlHUW+57GJeDO1QM464foXbp+VWQ==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.2.tgz",
"integrity": "sha512-50SiiB1HY2zdpjO7SUJklITcFqH/sJNq6PE1a8dtc8HIvQfPW4kXALoiPUqvaYzcBVscnkZ9rfmlSgn/vaA4eA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
+6 -6
View File
@@ -46,9 +46,9 @@
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.4",
"@quartz-community/bases-page": "^1.5.5",
"@quartz-community/breadcrumbs": "^1.0.5",
"@quartz-community/canvas-page": "^1.1.2",
"@quartz-community/canvas-page": "^1.1.4",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
@@ -63,12 +63,12 @@
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.3",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.1",
"@quartz-community/github-flavored-markdown": "^2.2.2",
"@quartz-community/graph": "^1.0.8",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.2",
"@quartz-community/note-properties": "^1.2.2",
"@quartz-community/obsidian-flavored-markdown": "^2.5.2",
"@quartz-community/note-properties": "^1.2.3",
"@quartz-community/obsidian-flavored-markdown": "^2.5.3",
"@quartz-community/og-image": "^1.1.3",
"@quartz-community/ox-hugo": "^1.0.3",
"@quartz-community/page-title": "^1.0.2",
@@ -124,7 +124,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.2",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
+6 -3
View File
@@ -27,7 +27,7 @@ import { formatLayoutReport, getLayoutReport } from "./plugins/loader/layoutRepo
import { getBuiltinPlan } from "./plugins/loader/config-loader"
import { prepareContentIndex } from "./plugins/builtins/contentIndex"
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
import { LinksInstance, markLinksToRemovedPages } from "./plugins/builtins/links"
import { LinksInstance, removedPages } from "./plugins/builtins/links"
import { collectPermalinks } from "./util/permalinks"
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
@@ -67,7 +67,10 @@ function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
}
/** Mark links to pages the filters removed as broken (built-in links, crawl-links#7). */
/**
* Record the pages the filters removed, so PageTypeDispatcher marks links to them as broken
* (built-in links, crawl-links#7) once it knows which folder and tag pages are generated.
*/
function markRemovedLinks(
ctx: BuildCtx,
all: ProcessedContent[],
@@ -76,7 +79,7 @@ function markRemovedLinks(
const links = ctx.cfg.plugins.transformers.find((t) => t.name === "Links") as
LinksInstance | undefined
// also when nothing was removed: in watch mode, marks from the last build may need undoing
if (links?.marksBrokenLinks) markLinksToRemovedPages(all, published, filteredBy)
ctx.removedPages = links?.marksBrokenLinks ? removedPages(all, published, filteredBy) : undefined
}
function reportSlugCollisions(content: ProcessedContent[]): void {
+30
View File
@@ -198,6 +198,36 @@ describe("validatePluginEntry", () => {
)
})
test("accepts before, after and every layout key", () => {
assert.deepStrictEqual(
validatePluginEntry({
source: "@quartz-community/description",
enabled: true,
order: 60,
before: "Links",
after: ["obsidian-flavored-markdown"],
layout: {
position: "right",
priority: 5,
display: "desktop-only",
condition: "not-index",
group: "toolbar",
groupOptions: { grow: true },
},
}),
[],
)
})
test("an unknown key without a close match lists the allowed keys", () => {
assert.deepStrictEqual(
validatePluginEntry({ source: "x/y", enabled: true, zzzzzz: 1 }).map((i) => i.message),
[
'unknown key "zzzzzz" is ignored (allowed: source, enabled, options, order, before, after, layout)',
],
)
})
test("catches typoed keys and a missing enabled flag", () => {
const issues = validatePluginEntry({ source: "x/y", enable: true, option: {} })
const messages = issues.map((i) => i.message).join("\n")
+33
View File
@@ -64,4 +64,37 @@ describe("Head", () => {
})
assert.strictEqual(meta(html, "article:modified_time"), undefined)
})
test("the 404 page: no canonical, no article meta, og:url is the site's address", () => {
const real = new Date("2024-05-06T00:00:00Z")
// as the 404 page type generates it (a virtual page gets `404.md` as its relativePath)
const html = head({
slug: "404",
relativePath: "404.md",
frontmatter: { title: "Not Found", tags: [] },
dates: { created: real, modified: real, published: real },
})
assert.strictEqual(meta(html, "og:type"), "website")
assert.strictEqual(meta(html, "og:url"), "https://example.org/")
assert.strictEqual(meta(html, "twitter:url"), "https://example.org/")
assert.doesNotMatch(html, /rel="canonical"/)
assert.doesNotMatch(html, /article:/)
// a note has all three
const note = head({
slug: "notes/a b",
dates: { created: real, modified: real, published: real },
})
assert.strictEqual(meta(note, "og:url"), "https://example.org/notes/a%20b")
assert.match(note, /<link rel="canonical" href="https:\/\/example.org\/notes\/a%20b"\/>/)
assert.strictEqual(meta(note, "article:modified_time"), real.toISOString())
})
test("tag pages and pages without a file are not articles", () => {
assert.strictEqual(meta(head({ slug: "tags/recipes" }), "og:type"), "website")
assert.strictEqual(meta(head({ slug: "tags/food/recipes" }), "og:type"), "website")
// a note in a folder named like the tag folder is still an article
assert.strictEqual(meta(head({ slug: "notes/tags/recipes" }), "og:type"), "article")
assert.strictEqual(meta(head({ slug: "my-tags/x" }), "og:type"), "article")
assert.strictEqual(meta(head({ slug: "a", relativePath: undefined }), "og:type"), "website")
})
})
+42
View File
@@ -120,6 +120,48 @@ describe("renderTranscludes", () => {
assert.ok(texts.includes("Target content"), "transcluded content should be inlined")
})
test("a block transclusion finds the block by its name and scopes its ^id", () => {
const block: Element = {
type: "element",
tagName: "p",
properties: { id: "^para-1" },
children: [
{ type: "text", value: "Block text " },
{
type: "element",
tagName: "a",
properties: { href: "#^para-1" },
children: [{ type: "text", value: "self" }],
},
],
}
const heading: Element = {
type: "element",
tagName: "h2",
properties: { id: "para-1" },
children: [{ type: "text", value: "Para 1" }],
}
const targetHtml: Root = { type: "root", children: [heading, block] }
const allFiles = [makePageData("target", targetHtml, { blocks: { "para-1": block } })]
const root: Root = {
type: "root",
children: [makeTranscludeBlockquote("target", "#^Para-1")],
}
renderTranscludes(
root,
cfg,
"current" as FullSlug,
makeComponentData(allFiles) as QuartzComponentProps,
new Set<FullSlug>(["current" as FullSlug]),
)
const html = toHtml(root)
assert.ok(html.includes("Block text"), html)
assert.ok(!html.includes("Para 1"), "the heading of the same name isn't transcluded")
const id = /<p id="([^"]+)"/.exec(html)?.[1]
assert.ok(id?.endsWith("^para-1") && id !== "^para-1", `scoped block id, got ${id}`)
assert.ok(html.includes(`href="#${id}"`), "the link inside points at the scoped id")
})
test("allows the same page to be embedded twice as siblings", () => {
const root: Root = {
type: "root",
+3 -2
View File
@@ -308,8 +308,9 @@ export function renderTranscludes(
let blockRef = el.properties.dataBlock as string | undefined
if (blockRef?.startsWith("#^")) {
// block transclude
blockRef = blockRef.slice("#^".length)
// block transclude: `data.blocks` is keyed by the block's name, lowercased (`para-1`); the
// block element's id is `^para-1` (rehype-obsidian), its anchor `#^para-1`
blockRef = blockRef.slice("#^".length).toLowerCase()
let blockNode = page.blocks?.[blockRef]
if (blockNode) {
if (blockNode.tagName === "li") {
+2 -1
View File
@@ -32,7 +32,8 @@ async function mouseEnterHandler(
if (hash !== "") {
const inner = popoverElement.querySelector(".popover-inner") as HTMLElement | null
if (inner) {
const targetAnchor = `#popover-internal-${hash.slice(1)}`
// ids are not CSS identifiers: block ids start with `^`, headings may start with a digit
const targetAnchor = `#${CSS.escape(`popover-internal-${hash.slice(1)}`)}`
const heading = inner.querySelector(targetAnchor) as HTMLElement | null
if (heading) {
// leave ~12px of buffer when scrolling to a heading
+40 -4
View File
@@ -70,13 +70,43 @@ history.scrollRestoration = "manual"
let renderedPath = window.location.pathname
let saveTimer: ReturnType<typeof setTimeout> | undefined
// Each entry the router creates gets a key, so a position that was still waiting to be saved
// when Back or Forward left its entry (history.state is the new entry's by then) is kept here
// and written to the entry when it is shown again.
type EntryState = { key?: string; scrollY?: unknown } | null
const newKey = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
const unsavedScroll = new Map<string, number>()
let shownKey: string | undefined
function entryKey(): string {
let key = (history.state as EntryState)?.key
if (typeof key !== "string") {
key = newKey()
history.replaceState({ ...(history.state ?? {}), key }, "")
}
return key
}
function pushEntry(url: URL) {
history.pushState({ key: newKey() }, "", url)
shownKey = entryKey()
}
function saveScroll() {
clearTimeout(saveTimer)
saveTimer = undefined
history.replaceState({ ...(history.state ?? {}), scrollY: window.scrollY }, "")
}
function savedScroll(): number | undefined {
const y = (history.state as { scrollY?: unknown } | null)?.scrollY
const key = entryKey()
const unsaved = unsavedScroll.get(key)
if (unsaved !== undefined) {
unsavedScroll.delete(key)
history.replaceState({ ...(history.state ?? {}), scrollY: unsaved }, "")
return unsaved
}
const y = (history.state as EntryState)?.scrollY
return typeof y === "number" ? y : undefined
}
@@ -185,7 +215,7 @@ async function _navigate(url: URL, isBack: boolean = false) {
// delay setting the url until now
// at this point everything is loaded so changing the url should resolve to the correct addresses
if (!isBack) {
history.pushState({}, "", finalUrl)
pushEntry(finalUrl)
}
renderedPath = window.location.pathname
@@ -220,7 +250,7 @@ function createRouter() {
if (isSamePage(url) && url.hash) {
// Save where the reader was, then add the entry, then jump: Back returns here.
saveScroll()
history.pushState({}, "", url)
pushEntry(url)
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
el?.scrollIntoView()
return
@@ -230,8 +260,13 @@ function createRouter() {
})
window.addEventListener("popstate", () => {
// Whatever is pending belongs to the entry just left.
// Whatever is pending belongs to the entry just left: keep it for when it's shown again.
if (saveTimer !== undefined && shownKey !== undefined) {
unsavedScroll.set(shownKey, window.scrollY)
}
clearTimeout(saveTimer)
saveTimer = undefined
shownKey = entryKey()
// Back or Forward between headings of the page on screen: only scroll.
if (window.location.pathname === renderedPath) {
restoreScroll()
@@ -257,6 +292,7 @@ function createRouter() {
window.addEventListener("pagehide", () => {
if (!isNavigating) saveScroll()
})
shownKey = entryKey()
if (savedScroll() !== undefined) restoreScroll()
}
+65 -3
View File
@@ -14,7 +14,13 @@ import {
extractLinksFromValue,
readFrontmatterData,
} from "./frontmatter"
import { Links, LinksInstance, markLinksToRemovedPages } from "./links"
import {
Links,
LinksInstance,
markLinksToRemovedPages,
markUnpublishedLinks,
removedPages,
} from "./links"
import {
buildLayeredCSS,
buildUnlayeredCSS,
@@ -35,8 +41,8 @@ import {
import type { PluginJsonEntry } from "../loader/types"
import type { BuildCtx } from "../../util/ctx"
import type { ContentDetails } from "../types"
import type { FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions } from "../../util/path"
import type { FilePath, FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions, slugifyFilePath } from "../../util/path"
import type { ProcessedContent } from "../vfile"
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
@@ -458,6 +464,25 @@ describe("links built-in", () => {
}
})
test("slugs.stripDiacritics: a percent-encoded % in a link target is decoded once", () => {
setSlugOptions({ stripDiacritics: true })
try {
// `Kódování/Mezera je %20.md`, linked as Obsidian writes a Markdown link to it
const target = slugifyFilePath("Kódování/Mezera je %20.md" as FilePath)
assert.strictEqual(target, "kodovani/mezera-je--percent20")
const { els } = run(
[a("K%C3%B3dov%C3%A1n%C3%AD/Mezera%20je%20%2520.md")],
"index",
{ markdownLinkResolution: "shortest" },
["index", target],
)
assert.strictEqual(els[0].properties.href, "./kodovani/mezera-je--percent20")
assert.ok(!(els[0].properties.className as string[]).includes("broken"))
} finally {
setSlugOptions(undefined)
}
})
test("without slugs.stripDiacritics link targets keep their diacritics", () => {
const { els } = run([a("Příliš")], "page", { markdownLinkResolution: "shortest" }, [
"page",
@@ -1054,6 +1079,43 @@ describe("links to pages removed by filters (crawl-links#7)", () => {
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
})
test("marks links to folder and tag pages no page type generated", () => {
const home = page("index", [
link("drafts/index"),
link("notes/index"),
link("tags/unused"),
link("tags/used"),
link("tags/parent"),
link("index"),
])
const generated = new Set(["notes/index", "tags/used", "tags/parent/index", "tags/index"])
const changed = new Set<FullSlug>()
const marked = markUnpublishedLinks([home], new Map(), generated, changed)
const broken = anchors(home).map((a) => (a.properties.className as string[]).includes("broken"))
assert.deepStrictEqual(broken, [true, false, true, false, false, false])
assert.strictEqual(marked, 2)
assert.strictEqual(anchors(home)[0].properties["data-missing"], "")
assert.deepStrictEqual([...changed], ["index"])
})
test("reports the pages whose marks changed, so watch mode re-emits them", () => {
const home = page("index", [link("draft")])
const other = page("other", [link("published")])
const draft = page("draft", [])
const all = [home, other, draft]
const changed = new Set<FullSlug>()
markUnpublishedLinks([home, other], removedPages(all, [home, other]), new Set(), changed)
assert.deepStrictEqual([...changed], ["index"])
changed.clear()
// nothing changed: nothing to re-emit
markUnpublishedLinks([home, other], removedPages(all, [home, other]), new Set(), changed)
assert.deepStrictEqual([...changed], [])
// the draft is published: its link is unmarked, the page re-emitted
markUnpublishedLinks([home, other, draft], removedPages(all, all), new Set(), changed)
assert.deepStrictEqual([...changed], ["index"])
assert.deepStrictEqual(anchors(home)[0].properties.className, ["internal", "internal-link"])
})
test("the Links instance says whether it marks broken links", () => {
assert.strictEqual((Links() as LinksInstance).marksBrokenLinks, true)
assert.strictEqual(
+78 -46
View File
@@ -15,8 +15,6 @@ import {
resolveRelative,
simplifySlug,
slugifyFilePath,
applySlugOptions,
getSlugOptions,
splitAnchor,
stripSlashes,
transformLink,
@@ -116,21 +114,19 @@ export function linkTargetMissing(allSlugs: readonly string[], full: string): bo
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
const FILTERED_ATTR = "data-filtered"
/** The `broken` mark for links to folder and tag pages that no page type generated. */
const MISSING_ATTR = "data-missing"
/**
* Links are classified while the transformers run, before the filters decide what is
* published, so a link to a page a filter removes (a draft, a page without `publish: true`)
* still points at an address in `allSlugs` and is not marked `broken` — yet it 404s
* (crawl-links#7). This runs after the filters: links in published pages whose target was
* removed get the `broken` class and `data-filtered="<filter>"`. Links that were marked this
* way and whose target is published again (watch mode) lose both. Returns the number of links
* marked.
* The pages the filters removed (drafts, pages without `publish: true`, …) and their aliases,
* each with the filter that removed it. A folder's `index` note is left out: the folder may still
* get a generated folder page, which only the generated pages tell (markUnpublishedLinks).
*/
export function markLinksToRemovedPages(
export function removedPages(
all: ProcessedContent[],
published: ProcessedContent[],
filteredBy: (slug: string) => string | undefined = () => "filter",
): number {
): Map<string, string> {
const publishedSet = new Set(published)
const live = new Set<string>()
for (const item of published) {
@@ -146,61 +142,97 @@ export function markLinksToRemovedPages(
const reason = filteredBy(data.slug) ?? "filter"
// its aliases (and the file path of a page with a permalink) are gone with it
for (const slug of [data.slug, ...(data.aliases ?? [])]) {
// a folder whose index note is removed still gets a generated folder page
if (slug.endsWith("/index")) continue
if (!live.has(slug) && !removed.has(slug)) removed.set(slug, reason)
}
}
return removed
}
/** Link targets that page types generate (folder pages, tag pages), unknown while transforming. */
function isGeneratedTarget(slug: string): boolean {
return (
slug === "tags" || slug.startsWith("tags/") || (slug !== "index" && slug.endsWith("/index"))
)
}
/**
* Links are classified while the transformers run, before the filters decide what is
* published and before page types generate folder and tag pages, so two kinds of links that
* 404 are not marked `broken` then:
*
* - a link to a page a filter removes (a draft, a page without `publish: true`) still points at
* an address in `allSlugs` (crawl-links#7): it gets `data-filtered="<filter>"`;
* - a link to a folder or tag page (see pageExists) that no page type generated — a folder whose
* notes are all drafts or that holds only images, a tag no published page uses, any folder or
* tag when folder-page / tag-page isn't installed: it gets `data-missing`.
*
* With `generated` (the slugs of the virtual pages, once page types ran) both are checked;
* without it only removed pages, and folder pages are assumed to exist. Links marked this way
* whose target is published again (watch mode) lose the mark; pages whose tree changed are added
* to `changed`, so watch mode re-emits them. Returns the number of links marked.
*/
export function markUnpublishedLinks(
published: ProcessedContent[],
removed: ReadonlyMap<string, string>,
generated?: ReadonlySet<string>,
changed?: Set<FullSlug>,
): number {
const live = new Set<string>(generated ?? [])
for (const [, file] of published) {
if (file.data.slug) live.add(file.data.slug)
for (const alias of file.data.aliases ?? []) live.add(alias)
}
let marked = 0
for (const [tree] of published) {
for (const [tree, file] of published) {
let touched = false
visit(tree as Root, "element", (node: Element) => {
if (node.tagName !== "a" || !node.properties) return
const target = node.properties["data-slug"]
if (typeof target !== "string") return
const classes = Array.isArray(node.properties.className)
? (node.properties.className as string[])
: []
const reason = removed.get(target)
if (reason !== undefined) {
const props = node.properties
const classes = Array.isArray(props.className) ? (props.className as string[]) : []
let attr: string | undefined
let value = ""
// a parent tag's page is `tags/a/index`, served at `tags/a` too
if (!live.has(target) && !live.has(`${target}/index`)) {
const reason = removed.get(target)
if (reason !== undefined) [attr, value] = [FILTERED_ATTR, reason]
else if (generated && isGeneratedTarget(target)) attr = MISSING_ATTR
}
let cleared = false
for (const other of [FILTERED_ATTR, MISSING_ATTR]) {
if (other === attr || props[other] === undefined) continue
delete props[other]
cleared = touched = true
}
if (attr !== undefined) {
if (props[attr] !== value || !classes.includes("broken")) touched = true
if (!classes.includes("broken")) classes.push("broken")
node.properties.className = classes
node.properties[FILTERED_ATTR] = reason
props.className = classes
props[attr] = value
marked++
} else if (node.properties[FILTERED_ATTR] !== undefined) {
node.properties.className = classes.filter((c) => c !== "broken")
delete node.properties[FILTERED_ATTR]
} else if (cleared) {
props.className = classes.filter((c) => c !== "broken")
}
})
if (touched && changed && file.data.slug) changed.add(file.data.slug)
}
return marked
}
/** {@link removedPages} + {@link markUnpublishedLinks}, before page types ran. */
export function markLinksToRemovedPages(
all: ProcessedContent[],
published: ProcessedContent[],
filteredBy: (slug: string) => string | undefined = () => "filter",
): number {
return markUnpublishedLinks(published, removedPages(all, published, filteredBy))
}
/** The Links instance marks links to removed pages after filtering (see build.ts). */
export type LinksInstance = QuartzTransformerPluginInstance & { marksBrokenLinks: boolean }
/**
* Link targets are written as in the vault (`[[Čeština]]`, `../české/x.png`). With
* `configuration.slugs.stripDiacritics` the pages and files they point at have stripped slugs,
* so the path part of the target is stripped the same way before it is resolved (wikilinks
* from obsidian-flavored-markdown are slugged with the plain rules first). The `#anchor` is
* left alone: heading ids keep their diacritics.
*/
function slugOptionsOnLinkPath(raw: string): string {
if (!getSlugOptions().stripDiacritics) return raw
const hash = raw.indexOf("#")
const linkPath = hash === -1 ? raw : raw.slice(0, hash)
const anchor = hash === -1 ? "" : raw.slice(hash)
let decoded = linkPath
try {
decoded = decodeURI(linkPath)
} catch {
// not percent-encoded (or malformed): strip as written
}
const stripped = applySlugOptions(decoded)
return stripped === decoded ? raw : stripped + anchor
}
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const opts = { ...linksDefaults, ...userOpts }
const instance: LinksInstance = {
@@ -227,7 +259,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, slugOptionsOnLinkPath(raw), transformOptions)
const rel = transformLink(pathSlug, raw, transformOptions)
if (!rebase) return rel
const hash = rel.indexOf("#")
const anchor = hash === -1 ? "" : rel.slice(hash)
+14 -9
View File
@@ -25,6 +25,7 @@ import {
import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild"
import { write } from "./helpers"
import { componentStylesheet } from "../../util/componentCss"
/**
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
@@ -39,6 +40,8 @@ type ComponentResources = {
beforeDOMLoaded: string[]
afterDOMLoaded: string[]
componentCssStrings: Set<string>
/** Component CSS → the component that brought it, to name it in warnings. */
cssOwners: Map<string, string>
}
function getComponentResources(ctx: BuildCtx): ComponentResources {
@@ -61,9 +64,13 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
afterDOMLoaded: new Set<string>(),
}
const cssOwners = new Map<string, string>()
for (const component of allComponents) {
const { css, beforeDOMLoaded, afterDOMLoaded } = component
for (const c of normalizeResource(css)) componentResources.css.add(c)
for (const c of normalizeResource(css)) {
componentResources.css.add(c)
if (!cssOwners.has(c)) cssOwners.set(c, component.displayName ?? component.name ?? "")
}
for (const b of normalizeResource(beforeDOMLoaded)) componentResources.beforeDOMLoaded.add(b)
for (const a of normalizeResource(afterDOMLoaded)) componentResources.afterDOMLoaded.add(a)
}
@@ -73,6 +80,7 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
beforeDOMLoaded: [...componentResources.beforeDOMLoaded],
afterDOMLoaded: [...componentResources.afterDOMLoaded],
componentCssStrings: new Set(componentResources.css),
cssOwners,
}
}
@@ -436,14 +444,11 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
const cssStringToFilename = new Map<string, string>()
const componentCss = [...componentResources.componentCssStrings]
if (componentCss.length > 0) {
const wrapped = `@layer quartz-base {\n${componentCss.join("\n")}\n}`
const minified = transform({
filename: "component.css",
code: Buffer.from(wrapped),
minify: true,
targets: lightningTargets,
include: Features.MediaQueries,
}).code.toString()
const minified = componentStylesheet(
componentCss,
(c) => componentResources.cssOwners.get(c),
lightningTargets,
)
const hash = hashContent(minified)
const slug = `component-${hash}`
+1
View File
@@ -1,3 +1,4 @@
export { Assets } from "./assets"
export { Static } from "./static"
export { ComponentResources } from "./componentResources"
export { SlugRedirects } from "./slugRedirects"
@@ -0,0 +1,148 @@
import assert from "node:assert/strict"
import test, { afterEach, describe } from "node:test"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { VFile } from "vfile"
import { Root } from "hast"
import { ProcessedContent } from "../vfile"
import { FilePath, FullSlug, setSlugOptions, slugifyFilePath } from "../../util/path"
import { BuildCtx } from "../../util/ctx"
import type { StaticResources } from "../../util/resources"
import { SlugRedirects, strippedAddressMoves } from "./slugRedirects"
const page = (
relativePath: string,
frontmatter: Record<string, unknown> = {},
): ProcessedContent => {
const file = new VFile("")
file.data = {
relativePath: relativePath as FilePath,
slug: slugifyFilePath(relativePath as FilePath),
frontmatter: { title: relativePath, ...frontmatter },
} as VFile["data"]
return [{ type: "root", children: [] } as Root, file]
}
describe("redirects from addresses slugs.stripDiacritics changed", () => {
test("pages, their folders and aliases redirect from the unstripped address", () => {
setSlugOptions({ stripDiacritics: true })
try {
const content = [
page("české/Žluťoučký kůň/poznámka.md", { aliases: ["stará"] }),
page("plain/note.md"),
]
const live = new Set(content.map(([, f]) => f.data.slug!))
assert.deepEqual(Object.fromEntries(strippedAddressMoves(content, live)), {
"české/žluťoučký-kůň/poznámka": "ceske/zlutoucky-kun/poznamka",
"české/index": "ceske/index",
"české/žluťoučký-kůň/index": "ceske/zlutoucky-kun/index",
stará: "ceske/zlutoucky-kun/poznamka",
})
} finally {
setSlugOptions(undefined)
}
})
test("an old address that is a page of the site is left alone", () => {
setSlugOptions({ stripDiacritics: true })
try {
const content = [page("café.md")]
const live = new Set(["café" as FullSlug, "cafe" as FullSlug])
assert.equal(strippedAddressMoves(content, live).size, 0)
} finally {
setSlugOptions(undefined)
}
})
})
describe("SlugRedirects emitter", () => {
const tempDirs: string[] = []
afterEach(async () => {
setSlugOptions(undefined)
await Promise.all(tempDirs.splice(0).map((dir) => fs.promises.rm(dir, { recursive: true })))
})
/** Runs `emit` (or `partialEmit`) into a temp output dir → output path → file contents. */
const emitAll = async (content: ProcessedContent[], partial = false) => {
const output = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-slug-redirects-"))
tempDirs.push(output)
const ctx = { argv: { output } } as unknown as BuildCtx
const plugin = SlugRedirects()
assert.equal(plugin.name, "SlugRedirects")
const emitted = partial
? plugin.partialEmit!(ctx, content, {} as StaticResources, [])
: plugin.emit(ctx, content, {} as StaticResources)
const written: Record<string, string> = {}
for await (const fp of emitted as AsyncIterable<string>) {
written[path.relative(output, fp).split(path.sep).join("/")] = await fs.promises.readFile(
fp,
"utf8",
)
}
return written
}
const redirect = (to: string, url: string) => `<!DOCTYPE html>
<html lang="en-us">
<head>
<title>${to}</title>
<link rel="canonical" href="${url}">
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=${url}">
</head>
</html>
`
const withAliases = (content: ProcessedContent, aliases: string[]): ProcessedContent => {
content[1].data.aliases = aliases as FullSlug[]
return content
}
test("writes a redirect at each unstripped address to the stripped one", async () => {
setSlugOptions({ stripDiacritics: true })
const content = [withAliases(page("české/Čeština.md", { aliases: ["stará"] }), ["stara"])]
assert.equal(content[0][1].data.slug, "ceske/cestina")
const expected = {
"české/čeština.html": redirect("ceske/cestina", "../ceske/cestina"),
"české/index.html": redirect("ceske/", "../ceske/"),
"stará.html": redirect("ceske/cestina", "./ceske/cestina"),
}
assert.deepEqual(await emitAll(content), expected)
assert.deepEqual(await emitAll(content, true), expected)
})
test("the redirect target is relative to the nested old address", async () => {
setSlugOptions({ stripDiacritics: true })
const written = await emitAll([page("Ä/b/Über.md")])
assert.deepEqual(written, {
"ä/b/über.html": redirect("a/b/uber", "../../a/b/uber"),
"ä/b/index.html": redirect("a/b/", "../../a/b/"),
"ä/index.html": redirect("a/", "../a/"),
})
})
test("an old address that is another page's alias is not overwritten", async () => {
setSlugOptions({ stripDiacritics: true })
// a page (e.g. from a plugin that registers addresses) already answers at `české/index`
const content = [page("české/Čeština.md"), withAliases(page("other.md"), ["české/index"])]
assert.deepEqual(Object.keys(await emitAll(content)).sort(), ["české/čeština.html"])
})
test("an old address that is a page without a file (a plugin's page) is not overwritten", async () => {
setSlugOptions({ stripDiacritics: true })
const virtual = new VFile("")
virtual.data = { slug: "české/index" as FullSlug, frontmatter: { title: "České" } }
const content: ProcessedContent[] = [
page("české/Čeština.md"),
[{ type: "root", children: [] } as Root, virtual],
]
assert.deepEqual(Object.keys(await emitAll(content)), ["české/čeština.html"])
})
test("nothing is emitted without slugs.stripDiacritics", async () => {
setSlugOptions({ stripDiacritics: false })
assert.deepEqual(await emitAll([page("české/Čeština.md", { aliases: ["stará"] })]), {})
})
})
+105
View File
@@ -0,0 +1,105 @@
import { QuartzEmitterPlugin } from "../types"
import { ProcessedContent } from "../vfile"
import {
FilePath,
FullSlug,
getSlugOptions,
resolveRelative,
setSlugOptions,
simplifySlug,
slugifyFilePath,
} from "../../util/path"
import { write } from "./helpers"
import { BuildCtx } from "../../util/ctx"
/** The slug `fp` had without `slugs.stripDiacritics` (lowercased, diacritics kept). */
function unstrippedSlug(fp: string): FullSlug {
const options = getSlugOptions()
setSlugOptions({ ...options, stripDiacritics: false })
try {
return slugifyFilePath(fp as FilePath)
} finally {
setSlugOptions(options)
}
}
/**
* The addresses `slugs.stripDiacritics` changed → where they moved: every published page's
* address as it was without the option (`české/žluťoučký-kůň/poznámka` →
* `ceske/zlutoucky-kun/poznamka`), its folders' (`české/` → `ceske/`) and its aliases'. An old
* address that is a page of the site, or another old address's, is left alone.
*/
export function strippedAddressMoves(
content: ProcessedContent[],
live: ReadonlySet<string>,
): Map<FullSlug, FullSlug> {
const moves = new Map<FullSlug, FullSlug>()
const add = (from: FullSlug, to: FullSlug) => {
if (from === to || live.has(from) || moves.has(from)) return
moves.set(from, to)
}
for (const [, file] of content) {
const { slug, relativePath } = file.data
if (!slug || !relativePath) continue
const old = unstrippedSlug(relativePath)
const now = slugifyFilePath(relativePath as FilePath)
// a page at its file path (not a permalink) moved with it
if (now === slug) add(old, slug)
// its folders: `české/žluťoučký-kůň/x` → `české/index`, `české/žluťoučký-kůň/index`
const oldParts = old.split("/")
const nowParts = now.split("/")
if (oldParts.length === nowParts.length) {
for (let i = 1; i < oldParts.length; i++) {
add(
[...oldParts.slice(0, i), "index"].join("/") as FullSlug,
[...nowParts.slice(0, i), "index"].join("/") as FullSlug,
)
}
}
for (const alias of (file.data.frontmatter?.aliases as unknown[] | undefined) ?? []) {
if (typeof alias !== "string") continue
const fp = alias.endsWith(".md") ? alias : `${alias}.md`
add(unstrippedSlug(fp), slug)
}
}
return moves
}
function redirectHtml(to: string, url: string): string {
return `<!DOCTYPE html>
<html lang="en-us">
<head>
<title>${to}</title>
<link rel="canonical" href="${url}">
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=${url}">
</head>
</html>
`
}
async function* emitMoves(ctx: BuildCtx, content: ProcessedContent[]) {
if (!getSlugOptions().stripDiacritics) return
const live = new Set<string>()
for (const [, file] of content) {
if (file.data.slug) live.add(file.data.slug)
for (const alias of file.data.aliases ?? []) live.add(alias)
}
for (const [from, to] of strippedAddressMoves(content, live)) {
const url = resolveRelative(from, simplifySlug(to) as unknown as FullSlug)
yield write({ ctx, slug: from, ext: ".html", content: redirectHtml(simplifySlug(to), url) })
}
}
/**
* With `configuration.slugs.stripDiacritics`, pages, folders and aliases whose names have
* diacritics get new addresses. This writes a redirect at each old address (as Quartz 5 slugged
* it: lowercased, diacritics kept) to the new one, so links and bookmarks to the old site keep
* working. alias-redirects' case redirects only cover the address as spelled in the vault.
*/
export const SlugRedirects: QuartzEmitterPlugin = () => ({
name: "SlugRedirects",
emit: (ctx, content) => emitMoves(ctx, content),
partialEmit: (ctx, content) => emitMoves(ctx, content),
})
+176 -6
View File
@@ -87,6 +87,7 @@ describe("pluginMatchKey for monorepo subdirectories", () => {
)
}
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer", subdir: "." }), "explorer")
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer" }), "explorer")
})
test("an overlay entry for one monorepo plugin leaves the other alone", () => {
const merged = mergeQuartzConfigs(
@@ -355,7 +356,10 @@ describe("resolveExtends", () => {
quartzRoot: root,
readFile,
}),
/cycle/,
{
name: "ConfigExtendsError",
message: '"extends" cycle: quartz.config.yaml → a.yaml → b.yaml → a.yaml',
},
)
await assert.rejects(
() =>
@@ -375,6 +379,21 @@ describe("resolveExtends", () => {
)
})
test("a base that is not a configuration object is an error", async () => {
files[path.join(root, "list.yaml")] = "- source: explorer\n- source: graph\n"
const file = path.join(root, "list.yaml")
await assert.rejects(
resolveExtends({ extends: "./list.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
{
name: "ConfigExtendsError",
message: `"extends: ./list.yaml": ${file} is not a valid config (${file} does not contain a configuration object)`,
},
)
})
test("extends: default reproduces the shipped default config exactly", async () => {
const defaultFile = path.resolve("quartz.config.default.yaml")
const shipped = YAML.parse(fs.readFileSync(defaultFile, "utf-8"))
@@ -448,11 +467,6 @@ describe("fetchRemoteConfig", () => {
await fetchRemoteConfig(url, { cacheDir, fetchImpl: ok("a: 1\n"), offline: false }),
"a: 1\n",
)
// memoised per process: a second call does not fetch again
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
"a: 1\n",
)
const warnings: string[] = []
const other = tmp()
fs.cpSync(cacheDir, other, { recursive: true })
@@ -503,3 +517,159 @@ describe("fetchRemoteConfig", () => {
)
})
})
describe("fetchRemoteConfig limits and memoisation", () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
/** A fetch that answers `body` (from `finalUrl` after redirects) and counts its calls. */
const counting = (body: string, finalUrl?: string) => {
const calls: string[] = []
const impl = (async (url: string) => {
calls.push(url)
return {
ok: true,
status: 200,
url: finalUrl ?? url,
text: async () => body,
}
}) as unknown as typeof fetch
return { calls, impl }
}
const failing = (async () => {
throw new Error("getaddrinfo ENOTFOUND")
}) as unknown as typeof fetch
test("two calls for one URL fetch once", async () => {
const cacheDir = tmp()
const { calls, impl } = counting("a: 1\n")
const url = "https://cfg.example/memo.yaml"
const warnings: string[] = []
const opts = {
cacheDir,
fetchImpl: impl,
offline: false,
warn: (m: string) => warnings.push(m),
}
const [first, second] = await Promise.all([
fetchRemoteConfig(url, opts),
fetchRemoteConfig(url, opts),
])
assert.strictEqual(await fetchRemoteConfig(url, opts), "a: 1\n")
assert.deepStrictEqual([first, second], ["a: 1\n", "a: 1\n"])
assert.deepStrictEqual(calls, [url])
assert.deepStrictEqual(warnings, [])
})
test("a failed fetch is tried again by the next call", async () => {
const cacheDir = tmp()
const url = "https://cfg.example/retry.yaml"
await assert.rejects(
fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
/could not be fetched: getaddrinfo ENOTFOUND/,
)
const { calls, impl } = counting("b: 2\n")
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir, fetchImpl: impl, offline: false }),
"b: 2\n",
)
assert.deepStrictEqual(calls, [url])
})
test("offline, the cached copy is returned without fetching", async () => {
const online = tmp()
const url = "https://cfg.example/offline.yaml"
await fetchRemoteConfig(url, { cacheDir: online, fetchImpl: counting("c: 3\n").impl })
const offlineDir = tmp()
fs.cpSync(online, offlineDir, { recursive: true })
const { calls, impl } = counting("c: changed\n")
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir: offlineDir, fetchImpl: impl, offline: true }),
"c: 3\n",
)
assert.deepStrictEqual(calls, [])
})
test("a redirect to http:// is an error, even with a cached copy", async () => {
const url = "https://cfg.example/redirected.yaml"
const cacheDir = tmp()
await fetchRemoteConfig(url, { cacheDir, fetchImpl: counting("d: 4\n").impl })
const other = tmp()
fs.cpSync(cacheDir, other, { recursive: true })
const warnings: string[] = []
await assert.rejects(
fetchRemoteConfig(url, {
cacheDir: other,
fetchImpl: counting("d: evil\n", "http://evil.example/x.yaml").impl,
offline: false,
warn: (m) => warnings.push(m),
}),
{
name: "ConfigExtendsError",
message: `"extends: ${url}" redirected to http://evil.example/x.yaml, which is not https`,
},
)
assert.deepStrictEqual(warnings, [])
// a redirect that stays on https is fine
assert.strictEqual(
await fetchRemoteConfig(url, {
cacheDir: tmp(),
fetchImpl: counting("d: 5\n", "https://mirror.example/x.yaml").impl,
offline: false,
}),
"d: 5\n",
)
})
test("a body over 1 MB is an error and is not cached", async () => {
const limit = 1024 * 1024
const exactly = tmp()
const atLimit = "#".repeat(limit)
assert.strictEqual(
await fetchRemoteConfig("https://cfg.example/1mb.yaml", {
cacheDir: exactly,
fetchImpl: counting(atLimit).impl,
offline: false,
}),
atLimit,
)
for (const [name, body] of [
["over.yaml", "#".repeat(limit + 1)],
// 524 289 characters, 1 048 578 bytes: the limit is in bytes
["utf8.yaml", "é".repeat(limit / 2 + 1)],
]) {
const url = `https://cfg.example/${name}`
const cacheDir = tmp()
await assert.rejects(
fetchRemoteConfig(url, { cacheDir, fetchImpl: counting(body).impl, offline: false }),
{ name: "ConfigExtendsError", message: `"extends: ${url}" is larger than 1 MB` },
)
assert.deepStrictEqual(fs.readdirSync(cacheDir), [])
}
})
})
describe("resolveTarget accepts only https URLs", () => {
const from = path.resolve("/site/quartz.config.yaml")
test("an http URL with https:// in its query is refused", () => {
for (const target of [
"http://evil.example/?https://cfg.example/x.yaml",
"http://evil.example/https://cfg.example/x.yaml",
"file:///etc/https://x.yaml",
]) {
assert.throws(() => resolveTarget(target, from, "/site"), {
name: "ConfigExtendsError",
message: `${from}: "extends: ${target}" — only https:// URLs can be extended`,
})
}
assert.throws(
() => resolveTarget("?https://x", "http://evil.example/base.yaml", "/site"),
/only https:\/\/ URLs can be extended/,
)
})
test("a local path that contains :// is a path, not a URL", () => {
assert.strictEqual(
resolveTarget("mirror/https://cfg.example/x.yaml", from, "/site"),
path.resolve("/site/mirror/https:/cfg.example/x.yaml"),
)
})
})
@@ -0,0 +1,159 @@
import test, { after, afterEach, before, describe } from "node:test"
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { registerHooks } from "node:module"
import { getSlugOptions, setSlugOptions } from "../../util/path"
import type { QuartzComponent } from "../../components/types"
// loadQuartzConfig imports the built-in emitters, whose SCSS and inline browser scripts esbuild
// bundles in a real build; under tsx they are stubbed out.
registerHooks({
load(url, context, next) {
if (url.endsWith(".scss") || /\.inline\.ts$/.test(url)) {
return { format: "module", source: "export default ''", shortCircuit: true }
}
return next(url, context)
},
})
const { loadQuartzConfig, loadQuartzLayout } = await import("./config-loader")
const names = (list: { name: string }[]) => list.map((p) => p.name)
const componentNames = (list: QuartzComponent[] | undefined) =>
(list ?? []).map((c) => c.displayName ?? c.name)
describe("loadQuartzConfig with extends: default", () => {
let dir: string
before(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
process.env.QUARTZ_CONFIG_QUIET = "1"
})
afterEach(() => {
delete process.env.QUARTZ_CONFIG_PATH
setSlugOptions(undefined)
})
after(() => {
delete process.env.QUARTZ_CONFIG_QUIET
fs.rmSync(dir, { recursive: true })
})
const useConfig = (name: string, content: string) => {
const file = path.join(dir, name)
fs.writeFileSync(file, content)
process.env.QUARTZ_CONFIG_PATH = file
}
test("merges configuration, plugins, layout and applies before/after", async () => {
useConfig(
"quartz.config.yaml",
`extends: default
configuration:
pageTitle: Extended garden
slugs:
stripDiacritics: true
plugins:
- source: "@quartz-community/description"
order: 60
before: Links
- source: "@quartz-community/favicon"
after: [CustomOgImages, Links]
# names that don't run among the transformers: a disabled plugin, an absorbed one, a built-in
# emitter. They are accepted and change nothing
- source: "@quartz-community/latex"
after: [citations, remove-draft, Fonts]
- source: "@quartz-community/explorer"
layout:
position: right
priority: 5
layout:
byPageType:
folder:
positions:
right: null
`,
)
const cfg = await loadQuartzConfig()
// the extending file's value, and the base's for what it leaves out
assert.equal(cfg.configuration.pageTitle, "Extended garden")
assert.equal(cfg.configuration.baseUrl, "quartz.jzhao.xyz")
assert.equal(getSlugOptions().stripDiacritics, true)
// plugins enabled only in the base are loaded; Description (order 60 here, 70 in the base)
// runs before the built-in Links at the same order
assert.deepEqual(names(cfg.plugins.transformers), [
"Frontmatter",
"NoteProperties",
"CreatedModifiedDate",
"SyntaxHighlighting",
"GitHubFlavoredMarkdown",
"ObsidianFlavoredMarkdown",
"UnlistedPages",
"TableOfContents",
"BasesTransformer",
"Description",
"Links",
"Latex",
"EncryptedPages",
])
// `after:` names og-image by its instance name; favicon comes first in the base list
assert.deepEqual(names(cfg.plugins.emitters), [
"ComponentResources",
"Assets",
"Static",
"SlugRedirects",
"ContentIndex",
"AliasRedirects",
"CustomOgImages",
"Favicon",
"CNAME",
"Fonts",
"EncryptedContentIndex",
"PageTypeDispatcher",
])
const layout = await loadQuartzLayout()
assert.deepEqual(componentNames(layout.defaults.right), [
"ExplorerComponent",
"Graph",
"TableOfContents",
"Backlinks",
])
assert.ok(!componentNames(layout.defaults.left).includes("ExplorerComponent"))
// `right: null` removed the base's `right: []` for folder pages
assert.deepEqual(Object.keys(layout.byPageType?.folder ?? {}), ["left"])
assert.deepEqual(Object.keys(layout.byPageType?.tag ?? {}).sort(), ["left", "right"])
})
test("after: on a built-in is checked against the order kept from the base", async () => {
useConfig(
"after-links.yaml",
`extends: default
plugins:
- source: "@quartz-community/table-of-contents"
after: Links
`,
)
await assert.rejects(loadQuartzConfig(), {
name: "PluginOrderError",
message:
'plugin "@quartz-community/table-of-contents" (order 50) must run after "Links", but "Links" has order 60, so it runs later. ' +
'Give "@quartz-community/table-of-contents" an order above 60, or "Links" one below 50.',
})
})
test("a JSON config extends too", async () => {
useConfig(
"quartz.plugins.json",
JSON.stringify({
extends: "default",
configuration: { pageTitle: "From JSON" },
plugins: [{ source: "@quartz-community/latex", enabled: false }],
}),
)
const cfg = await loadQuartzConfig()
assert.equal(cfg.configuration.pageTitle, "From JSON")
assert.equal(cfg.configuration.locale, "en-US")
const transformers = names(cfg.plugins.transformers)
assert.ok(!transformers.includes("Latex"))
assert.ok(transformers.includes("Description"))
})
})
+1
View File
@@ -749,6 +749,7 @@ export async function loadQuartzConfig(
builtinPlugins.ComponentResources(),
builtinPlugins.Assets(),
builtinPlugins.Static(),
builtinPlugins.SlugRedirects(),
]
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
@@ -26,6 +26,30 @@ describe("orderPlugins", () => {
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["z", "y", "x"])
})
test("one plugin before several others", () => {
const items = [item("b", 50), item("c", 50), item("a", 50, { before: ["b", "c"] })]
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "b", "c"])
})
test("one plugin after several others, and several targets in both directions", () => {
const items = [item("x", 50, { after: ["z", "y"] }), item("y", 50), item("z", 50)]
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["y", "z", "x"])
const mixed = [
item("p", 50),
item("q", 50, { after: ["r", "s"], before: ["p", "t"] }),
item("r", 50),
item("s", 50),
item("t", 50),
]
assert.deepStrictEqual(orderPlugins(mixed, known("p", "q", "r", "s", "t")), [
"r",
"s",
"q",
"p",
"t",
])
})
test("constraints that agree with order are fine and change nothing", () => {
const items = [item("late", 70, { after: ["early"] }), item("early", 40, { before: ["late"] })]
assert.deepStrictEqual(orderPlugins(items, known("late", "early")), ["early", "late"])
+26
View File
@@ -30,6 +30,7 @@ import { htmlToJsx } from "../../util/jsx"
import { trace } from "../../util/trace"
import { attributeError, originOf } from "../../util/pluginErrors"
import { rejectingFilter } from "../../processors/filter"
import { markUnpublishedLinks } from "../builtins/links"
import fs from "fs"
import path from "path"
@@ -382,6 +383,24 @@ function populateVirtualPageHtmlAst(
return virtualEntries.filter((ve) => !failed.has(ve))
}
/**
* Mark links to pages that are not emitted: removed by a filter, or a folder / tag page no page
* type generated (markUnpublishedLinks). Returns the pages whose links changed, which watch mode
* re-emits although their source didn't change.
*/
function markLinksToUnpublishedPages(
ctx: BuildCtx,
content: ProcessedContent[],
virtualEntries: VirtualEntry[],
): Set<FullSlug> {
const changed = new Set<FullSlug>()
if (ctx.removedPages) {
const generated = new Set<string>(virtualEntries.map((ve) => ve.vpSlug))
markUnpublishedLinks(content, ctx.removedPages, generated, changed)
}
return changed
}
export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>> = (userOpts) => {
const defaults = userOpts?.defaults ?? {}
const byPageType = userOpts?.byPageType ?? {}
@@ -413,6 +432,8 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
byPageType,
)
markLinksToUnpublishedPages(ctx, content, virtualEntries)
if (virtualEntries.some((ve) => ve.fileBacked)) {
ctx.trie = folderTrie(allFiles, virtualEntries)
}
@@ -507,6 +528,11 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
ctx.trie = folderTrie(allFiles, virtualEntries)
// a page whose links to a published / removed page changed is re-emitted too
for (const slug of markLinksToUnpublishedPages(ctx, content, virtualEntries)) {
changedSlugs.add(slug)
}
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
// Render Body components to populate htmlAst for transclusion
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict"
import test, { beforeEach, describe } from "node:test"
import { Features, transform } from "lightningcss"
import { componentStylesheet, isolateComponentCss } from "./componentCss"
import { getDiagnostics, resetDiagnostics } from "./diagnostics"
/** The component stylesheet as ComponentResources builds it. */
const sheet = (chunks: string[]) => componentStylesheet(chunks, () => "Bad")
describe("isolateComponentCss", () => {
beforeEach(() => resetDiagnostics())
const later = ".later{color:red}"
for (const [what, bad] of [
["a missing }", ".bad{color:blue"],
["an unclosed comment", ".bad{color:blue} /* note"],
["an unclosed @media", ".bad{color:blue} @media (min-width: 1px) { .x { color: red }"],
["an unclosed string", '.bad{content:"x'],
]) {
test(`${what} in one component doesn't swallow the next one's rules`, () => {
assert.match(sheet([bad, later]), /@layer quartz-base\{.*\.later\{color:red\}\}$/)
// the end of the chunk closes what it left open: not an error
assert.deepEqual(getDiagnostics(), [])
})
}
test("a stray } doesn't fail the stylesheet", () => {
assert.match(sheet([".bad{color:blue}}", later]), /\.bad\{color:#00f\}.*\.later\{color:red\}/)
assert.deepEqual(
getDiagnostics().map((d) => d.message.split(" has ")[0]),
["The CSS of component Bad"],
)
})
test("CSS that doesn't parse keeps the rules that do, with a warning naming the component", () => {
assert.equal(
isolateComponentCss(".bad{color:blue}}", "Explorer"),
".bad {\n color: #00f;\n}\n",
)
assert.deepEqual(getDiagnostics(), [
{
severity: "warning",
area: "css",
message:
"The CSS of component Explorer has a syntax error (Unexpected end of input at line 1, column 18); the rules that parse are kept.",
},
])
resetDiagnostics()
isolateComponentCss(".bad{color:blue}}")
assert.match(getDiagnostics()[0].message, /^The CSS of a component has a syntax error/)
})
test("balanced CSS comes out as it did before", () => {
const css = ".a{color:red;& .b{margin:0}}@media (max-width:800px){.a{display:none}}"
const raw = transform({
filename: "component.css",
code: Buffer.from(`@layer quartz-base {\n${css}\n${later}\n}`),
minify: true,
include: Features.MediaQueries,
}).code.toString()
assert.equal(sheet([css, later]), raw)
assert.deepEqual(getDiagnostics(), [])
})
})
+53
View File
@@ -0,0 +1,53 @@
import { Features, Targets, transform } from "lightningcss"
import { recordDiagnostic } from "./diagnostics"
/**
* One component's CSS, parsed on its own and printed back balanced. All components' CSS goes
* into one stylesheet: an unclosed `{`, `/*` or string in one would swallow every later
* component's rules, and a stray `}` close the shared layer (and fail the build). Parsed alone,
* the end of the chunk closes what it left open, as a stylesheet of its own would in a browser;
* a chunk that doesn't parse is printed with the rules that do, with a warning naming the
* component.
*/
export function isolateComponentCss(css: string, owner = ""): string {
const name = owner ? `component ${owner}` : "a component"
const parse = (errorRecovery: boolean) =>
transform({ filename: "component.css", code: Buffer.from(css), errorRecovery })
try {
return parse(false).code.toString()
} catch (err) {
const loc = (err as { loc?: { line: number; column: number } }).loc
recordDiagnostic({
severity: "warning",
area: "css",
message:
`The CSS of ${name} has a syntax error (${(err as Error).message}` +
`${loc ? ` at line ${loc.line}, column ${loc.column}` : ""}); the rules that parse are kept.`,
})
try {
return parse(true).code.toString()
} catch {
return ""
}
}
}
/**
* All components' CSS as ComponentResources emits it: each chunk isolated, in order, in one
* `quartz-base` layer, minified.
*/
export function componentStylesheet(
chunks: string[],
ownerOf: (css: string) => string | undefined = () => undefined,
targets?: Targets,
): string {
const isolated = chunks.map((c) => isolateComponentCss(c, ownerOf(c)))
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
return transform({
filename: "component.css",
code: Buffer.from(wrapped),
minify: true,
targets,
include: Features.MediaQueries,
}).code.toString()
}
+6
View File
@@ -49,6 +49,12 @@ export interface BuildCtx {
* `.base` / `.canvas` pages).
*/
virtualPages: ProcessedContent[]
/**
* Pages the filters removed (and their aliases) → the filter, set after filtering when the
* Links transformer marks broken links. PageTypeDispatcher marks links to them, and to folder
* and tag pages no page type generated, once the virtual pages exist (markUnpublishedLinks).
*/
removedPages?: ReadonlyMap<string, string>
/** Content-hashed asset filenames, populated by ComponentResources emitter */
hashedResourceNames?: HashedResourceNames
/** Maps CSS content strings to their emitted hashed filenames. Populated by ComponentResources. */
+31 -1
View File
@@ -1,6 +1,6 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import { realDate } from "./dates"
import { dateIsFromFrontmatter, realDate } from "./dates"
import type { QuartzPluginData } from "../plugins/vfile"
const data = (d: Record<string, unknown>) => d as unknown as QuartzPluginData
@@ -43,3 +43,33 @@ describe("realDate", () => {
assert.strictEqual(realDate(data({ dates: { modified: now } }), undefined), undefined)
})
})
describe("dateIsFromFrontmatter", () => {
test("a date-time value is compared as written, a date-only one as local midnight", () => {
const d = data({ frontmatter: { published: "2024-01-02T10:00:00" } })
assert.strictEqual(dateIsFromFrontmatter(d, new Date("2024-01-02T10:00:00"), "published"), true)
assert.strictEqual(
dateIsFromFrontmatter(d, new Date("2024-01-02T00:00:00"), "published"),
false,
)
const dateOnly = data({ frontmatter: { published: "2024-01-02" } })
assert.strictEqual(
dateIsFromFrontmatter(dateOnly, new Date("2024-01-02T00:00:00"), "published"),
true,
)
})
test("YAML dates and timestamps compare by value; other values and missing ones never match", () => {
const when = new Date("2024-01-02T10:00:00Z")
const of = (published: unknown) => data({ frontmatter: { published } })
assert.strictEqual(dateIsFromFrontmatter(of(new Date(when)), when, "published"), true)
assert.strictEqual(dateIsFromFrontmatter(of(when.getTime()), when, "published"), true)
assert.strictEqual(dateIsFromFrontmatter(of([when.toISOString()]), when, "published"), false)
assert.strictEqual(dateIsFromFrontmatter(of(""), new Date(0), "published"), false)
assert.strictEqual(dateIsFromFrontmatter(of(null), new Date(0), "published"), false)
assert.strictEqual(dateIsFromFrontmatter(of(when), new Date(NaN), "published"), false)
// the page's default date type
const d = data({ frontmatter: { modified: when.toISOString() }, defaultDateType: "modified" })
assert.strictEqual(dateIsFromFrontmatter(d, when), true)
})
})