mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce1b5d4d89 | ||
|
|
e02d690957 | ||
|
|
5d94a93a03 | ||
|
|
9a4beb1747 | ||
|
|
c03c643a7c | ||
|
|
74d06afca0 | ||
|
|
f285e12ff9 | ||
|
|
6729a1e7bb | ||
|
|
37a61cfc08 | ||
|
|
45ed91c90c | ||
|
|
9909b508e7 | ||
|
|
bd3ac11469 | ||
|
|
92fa358ef1 | ||
|
|
ae8049d0fa | ||
|
|
e42cdf469d | ||
|
|
747d10ce3a | ||
|
|
2635c6080a | ||
|
|
149c82f1da | ||
|
|
f47668e024 | ||
|
|
29be20f41c | ||
|
|
f7b41e7bbf | ||
|
|
7c24cc66e1 | ||
|
|
3df0062b6f | ||
|
|
beca3bc26d | ||
|
|
0e16919455 | ||
|
|
81b358224b | ||
|
|
0346dc6149 | ||
|
|
e0f1e03913 | ||
|
|
c79adab53b | ||
|
|
af36801547 | ||
|
|
b1fc7acd8e | ||
|
|
011c101cd3 | ||
|
|
690f7a0325 | ||
|
|
abfda7b85e | ||
|
|
f646ffe97d | ||
|
|
61b06fa295 | ||
|
|
39520c2aca | ||
|
|
842712113b | ||
|
|
8be4d8eadc | ||
|
|
7b4da1cbcc | ||
|
|
b2241c313e | ||
|
|
bc0e3937c3 | ||
|
|
9de19e3027 | ||
|
|
a51b7df1ce | ||
|
|
2b061ab9de | ||
|
|
0d05ef72d8 | ||
|
|
e07aad698d | ||
|
|
dd667ee315 | ||
|
|
673a596cf8 | ||
|
|
57cd6631d3 | ||
|
|
623e710fe8 | ||
|
|
8c612458cd | ||
|
|
1c48865b9f | ||
|
|
c608817610 | ||
|
|
2bea104934 | ||
|
|
5071ecd403 | ||
|
|
51c13bcca4 | ||
|
|
01f8f963ea | ||
|
|
11334aa029 | ||
|
|
c2293500d7 | ||
|
|
4172d3f56c | ||
|
|
09a6b0336a | ||
|
|
415af8a52d | ||
|
|
6ce31a4814 | ||
|
|
df11e31ef3 | ||
|
|
734e1b8531 | ||
|
|
b25eba0dca | ||
|
|
465d0e03eb | ||
|
|
3a1dc46aab | ||
|
|
d5dad620d8 | ||
|
|
661b56afc3 | ||
|
|
2209ee6d7d | ||
|
|
caec7d24ee | ||
|
|
773e2c7fe1 | ||
|
|
96fc9c1bfb | ||
|
|
7ef986a16b | ||
|
|
a5b07e3c48 | ||
|
|
c97a377b84 | ||
|
|
52af9f1a29 | ||
|
|
093d233d2c | ||
|
|
a55f25f185 | ||
|
|
050586dc14 | ||
|
|
0cfcfc868b | ||
|
|
2f2c35d64c | ||
|
|
fb6464ef68 | ||
|
|
dc10654108 | ||
|
|
c33b6cfc48 | ||
|
|
3ab4503fe0 | ||
|
|
799b8e370f | ||
|
|
9d6cdba8e4 | ||
|
|
71454c77b6 | ||
|
|
8417bdc03f | ||
|
|
db7484e05e | ||
|
|
52f7895ea6 | ||
|
|
0bab8ea1bb | ||
|
|
282ef789b6 | ||
|
|
c97c545f0c | ||
|
|
e85dceaf23 | ||
|
|
7ce0665400 | ||
|
|
cc22cfe413 | ||
|
|
ed5912a53b | ||
|
|
43e2eb9e11 | ||
|
|
cfa0413736 | ||
|
|
a96d993bf5 | ||
|
|
09c0e5203d | ||
|
|
d70ab4e164 | ||
|
|
fd744c0a9e | ||
|
|
d9566ec223 | ||
|
|
72097c86e4 | ||
|
|
9c172ca3a4 | ||
|
|
39ecd2a76d | ||
|
|
a9b4be1046 | ||
|
|
b7316ae8fa | ||
|
|
d77bc173d3 | ||
|
|
488da675e7 | ||
|
|
16bc33e9fb | ||
|
|
33acb1c716 | ||
|
|
6f689dcdb9 | ||
|
|
4679f825fd | ||
|
|
05b5082388 | ||
|
|
c4d02241d5 | ||
|
|
8ce7599280 | ||
|
|
edd97cc665 | ||
|
|
fd8256e4a0 | ||
|
|
fd1e5eb8bf | ||
|
|
7c3df898ed | ||
|
|
5bec47ee54 | ||
|
|
ea2b3485bf | ||
|
|
857de3b2bc | ||
|
|
df13ac29e5 | ||
|
|
3b78d1658d | ||
|
|
c568c93fa0 | ||
|
|
dfd1d6bd67 | ||
|
|
b4d73585f7 | ||
|
|
723759f931 | ||
|
|
f5773b611f | ||
|
|
7714325740 | ||
|
|
4036e25a77 | ||
|
|
c770681ba8 | ||
|
|
55311cb0bc | ||
|
|
cc253bea53 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
A plugin that depends on a plugin of another pipeline stage (an emitter or component on a transformer) no longer fails the build because of their `order`: order is checked only between plugins of the same stage.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Plugin updates with the fixes from a test audit:
|
||||
|
||||
- note-properties: an empty `tags:` or `aliases:` no longer fails the build.
|
||||
- bases-page: sorting, filters, formulas and group headings work as in Obsidian.
|
||||
- encrypted-pages: a numeric `password` encrypts the page, and a custom `outputPath` works.
|
||||
- darkmode, reader-mode, syntax-highlighting and comments: no double handlers after a page is unlocked.
|
||||
- stacked-pages: links work under a base path.
|
||||
- breadcrumbs: `resolveFrontmatterTitle` is honoured.
|
||||
- canvas-page: a `#View` link selects that view.
|
||||
- search: fields left out of `fieldPriority` are searched, and excerpts keep their last word.
|
||||
- explorer: a note next to a folder of the same name stays listed, and folder options apply.
|
||||
- folder-page, og-image, description, table-of-contents, graph, obsidian-flavored-markdown and utils: smaller fixes.
|
||||
- latex: `customMacros` work with MathJax. ox-hugo: figure parameters in backticks.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Relative links and embeds keep their query string after SPA navigation and in popovers (`./viewer.html?file=a.pdf` no longer loses `?file=a.pdf`).
|
||||
@@ -11,17 +11,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Preview
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- name: Cache Quartz plugins
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: .quartz/plugins
|
||||
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
|
||||
|
||||
@@ -19,17 +19,17 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- name: Cache Quartz plugins
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: .quartz/plugins
|
||||
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
|
||||
@@ -71,11 +71,11 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
- name: Get package version
|
||||
|
||||
@@ -16,17 +16,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy v5 to Cloudflare Pages
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- name: Cache Quartz plugins
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: .quartz/plugins
|
||||
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
|
||||
|
||||
@@ -21,11 +21,11 @@ jobs:
|
||||
echo "OWNER_LOWERCASE=${OWNER,,}" >> ${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- name: Inject slug/short variables
|
||||
uses: rlespinasse/github-slug-action@v5.6.0
|
||||
uses: rlespinasse/github-slug-action@v5.7.1
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
- name: Set up Docker Buildx
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
network=host
|
||||
- name: Install cosign
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: sigstore/cosign-installer@v4.1.2
|
||||
uses: sigstore/cosign-installer@v4.1.3
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
if: github.event_name != 'pull_request'
|
||||
|
||||
@@ -21,12 +21,13 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
actions: write # start the Docker build for the new tag
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
@@ -34,24 +35,43 @@ jobs:
|
||||
|
||||
- name: Create or update the release PR
|
||||
id: changesets
|
||||
uses: changesets/action@v1
|
||||
uses: changesets/action@v2
|
||||
with:
|
||||
version: npm run version-packages
|
||||
title: "chore: release Quartz"
|
||||
commit: "chore: release Quartz"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
version-script: npm run version-packages
|
||||
pr-title: "chore: release Quartz"
|
||||
commit-message: "chore: release Quartz"
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Tag and publish the GitHub release
|
||||
if: steps.changesets.outputs.hasChangesets == 'false'
|
||||
if: steps.changesets.outputs.has-changesets == 'false'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Each step can be re-run: an existing tag on this commit, or an existing release, is
|
||||
# kept, and the Docker build is started again (a failed run used to stop at "already
|
||||
# exists" on the next attempt).
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
TAG="v$VERSION"
|
||||
if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
|
||||
echo "$TAG already exists — nothing to release."
|
||||
exit 0
|
||||
# The commit the tag points at on GitHub (empty when there is no tag yet); an annotated
|
||||
# tag is followed to its commit.
|
||||
tag_commit() {
|
||||
local ref type sha
|
||||
ref=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" --jq '.object.type + " " + .object.sha' 2>/dev/null) || return 0
|
||||
read -r type sha <<<"$ref"
|
||||
if [ "$type" = "tag" ]; then
|
||||
sha=$(gh api "repos/$GITHUB_REPOSITORY/git/tags/$sha" --jq '.object.sha')
|
||||
fi
|
||||
echo "$sha"
|
||||
}
|
||||
EXISTING=$(tag_commit)
|
||||
if [ -n "$EXISTING" ] && [ "$EXISTING" != "$GITHUB_SHA" ]; then
|
||||
if git merge-base --is-ancestor "$EXISTING" "$GITHUB_SHA" 2>/dev/null; then
|
||||
echo "$TAG was released at $EXISTING — nothing to release."
|
||||
exit 0
|
||||
fi
|
||||
echo "::error::$TAG already exists but points at $EXISTING, which is not this commit ($GITHUB_SHA) or one of its ancestors. Check the tag (delete it if it is wrong), then re-run this workflow."
|
||||
exit 1
|
||||
fi
|
||||
# Only versions produced by `changeset version` are released (guards against tagging
|
||||
# an arbitrary commit with a version that was never released through this workflow).
|
||||
@@ -60,8 +80,23 @@ jobs:
|
||||
echo "CHANGELOG.md has no section for $VERSION — not tagging."
|
||||
exit 0
|
||||
fi
|
||||
# GitHub creates the tag, on the commit this push brought (the merged release PR). A tag
|
||||
# made here with `git tag -a` is an unsigned tag object, which GitHub marks "Unverified"
|
||||
# (jackyzha0/quartz#2455). This one points straight at the commit, which shows as verified
|
||||
# because GitHub signs the commits it merges. `git describe --tags` sees it all the same.
|
||||
gh release create "$TAG" --target "$GITHUB_SHA" --title "Quartz $VERSION" --notes-file release-notes.md
|
||||
# The tag is a lightweight ref straight to the merged release commit, created here
|
||||
# before the release. GitHub signs the commits it merges, so the tag shows as verified.
|
||||
# Letting `gh release create` make the tag instead gives an unsigned annotated tag
|
||||
# object (tagger: whoever merged the release PR), which GitHub marks "Unverified"
|
||||
# (jackyzha0/quartz#2455). `git describe --tags` reads lightweight tags as well.
|
||||
if [ -z "$EXISTING" ]; then
|
||||
gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" >/dev/null
|
||||
else
|
||||
echo "$TAG already points at this commit — keeping it."
|
||||
fi
|
||||
if gh release view "$TAG" >/dev/null 2>&1; then
|
||||
echo "The $TAG release already exists — keeping it."
|
||||
else
|
||||
gh release create "$TAG" --verify-tag --title "Quartz $VERSION" --notes-file release-notes.md
|
||||
fi
|
||||
# A tag created with GITHUB_TOKEN doesn't trigger `on: push: tags`, so the Docker workflow
|
||||
# never built the versioned images; start it for the tag explicitly. Started with
|
||||
# `--ref vX.Y.Z`, the run's GITHUB_REF is refs/tags/vX.Y.Z, which is all
|
||||
# docker/metadata-action's `type=semver` tags need (it checks the ref, not the event).
|
||||
gh workflow run docker-build-push.yaml --ref "$TAG"
|
||||
+1
-1
@@ -1 +1 @@
|
||||
v22.16.0
|
||||
v22.22.0
|
||||
@@ -1,5 +1,104 @@
|
||||
# @jackyzha0/quartz
|
||||
|
||||
## 5.3.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 55311cb: Links: `disableBrokenWikilinks` is on by default. Internal links to pages that don't exist get the `broken` class, as Obsidian marks unresolved links (`is-unresolved`), so Quartz's and Obsidian themes' unresolved-link styles apply. Tag and folder pages, which are generated later, count as existing. Set `links.disableBrokenWikilinks: false` for the old behaviour.
|
||||
- 857de3b: Quartz now requires Node.js 22.22 or later (was 22), for chokidar 6, which watches content in `--serve` mode. chokidar 6 confirms each change against the file system before rebuilding and fixes missed and duplicate change events.
|
||||
- df11e31: Experimental `extends` in `quartz.config.yaml`: `extends: default` (or a path) starts from `quartz.config.default.yaml` and applies only the changes in your file. `configuration` and `layout` merge key by key, plugin entries merge with the default entry of the same plugin. Configs without `extends` behave exactly as before.
|
||||
- 09a6b03: `contentIndex.json` entries have `dateFromFrontmatter: true` when their `date` is the one set in the page's frontmatter for the configured date type (not from git or the file system), so client-side components can tell explicit dates apart, e.g. for folder dates in the explorer.
|
||||
- d5dad62: `contentIndex.json` entries now include the page's `date` (the one `defaultDateType` selects) as an ISO 8601 string, so client-side components such as the explorer can sort by date. Pages without a date have no `date` field.
|
||||
- 2209ee6: Layout conditions: add `is-index` (only on the home page) and `is-folder-index` (only on folder index pages), and let `not-<condition>` negate any condition, built-in or registered (`not-has-tags`, `not-has-backlinks`, …).
|
||||
- c770681: Transclusions use Obsidian's embed markup: a `div.markdown-embed-title` (the note's title, for a whole-note embed; it was an `h1`), then the content in `div.markdown-embed-content > div.markdown-preview-view.markdown-rendered`, then the link to the original. Obsidian themes' embed styles apply (embed titles, padding, maximum height). The title looks as before without a theme. Obsidian's icon link to the note (`a.markdown-embed-link`, Lucide's maximize-2) follows; Quartz hides it, and Obsidian themes, through @quartz-themes/core, show it in the embed's corner.
|
||||
- c229350: Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
|
||||
- b25eba0: 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).
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- f7b41e7: 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`.
|
||||
- 3df0062: 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.
|
||||
- 2b061ab: Links: links to files Quartz emits, such as `[feed](/index.xml)`, `/sitemap.xml`, `/static/icon.png` or `/404.html`, are no longer marked `broken`. A link is only marked when its target is known to be missing: a page that doesn't exist, or a vault file (image, audio, video, PDF, canvas, base) the content doesn't have. Other files may come from an emitter, so they are left unmarked.
|
||||
- 734e1b8: Links to pages removed by a filter (drafts, ExplicitPublish) are now marked `broken` (with `data-filtered="<filter>"`), like links to pages that don't exist — they 404 on the site.
|
||||
- 9de19e3: `extends` (experimental): `npx quartz plugin list`, `status`, `doctor`, `install`, `prune` and `npx quartz info` read the merged configuration, as the build does. Before, they saw only the entries in your own file, so `list` showed a handful of plugins and `doctor` warned that overlay entries without `enabled` are disabled. `enable`, `disable` and `config` now work on plugins from a base by adding or changing your own entry for them (only that change is written; the merged configuration never is), `config --unset` resets an option a base sets with `null`, and `remove` refuses a plugin that comes from a base. `npx quartz build --serve` also rebuilds when a local base file changes.
|
||||
- a51b7df: `extends` (experimental): presets in a list now stack. With `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, everything `a.yaml` changed was lost, because `b.yaml` was merged on top with all of `default` again. Each file of the `extends` chain is now applied once, after the bases it extends, so the order is `default` → `a.yaml` → `b.yaml` → your file, and later entries win only where they change the same thing.
|
||||
|
||||
Also: a plugin source with a `subdir` and no `name` is matched by repository and folder, so an entry for one plugin of a monorepo no longer changes another; `extends: []` extends nothing; an empty base file is an empty config; `HTTPS://` URLs are accepted; and `plugins:` that isn't a list gets a clear error.
|
||||
|
||||
- b2241c3: Layout conditions: `is-folder-index` is false on tag pages. The all-tags page (`tags/index`) matched it, so components meant for folder pages showed there; nothing under `tags/` counts as a folder index now.
|
||||
- cc253be: Footnote references and back-links keep the `internal` class but no longer get `internal-link`: Obsidian doesn't treat them as note links, and Obsidian themes' link styles (underline, colour) overrode their footnote styles.
|
||||
- 71454c7: Markdown links in frontmatter with an angle-bracket destination, which Obsidian writes for paths with spaces (`[Exec Briefing](<./Exec Briefing.md>)`), resolve to the note instead of a missing `….md` page, so the note gets the backlink and graph edge.
|
||||
- 8be4d8e: Markdown links in frontmatter are read as CommonMark reads them: angle-bracket destinations with parentheses (`[b](<Note (2024).md>)`), balanced parentheses in plain destinations (`[d](Note_(2024).md)`), titles in `"…"`, `'…'` or `(…)` (`[c](<My Note.md> "t")`), and backslash escapes. They pointed at `note-(2024` and `my-note.md-t`, so the linked note got no backlink or graph edge.
|
||||
- c33b6cf: @quartz-community/graph 1.0.5: the graph scales to large sites. On 3,000 notes and 33,000 links, the global graph opens in 0.5 s instead of 2.5 s, and it stops using the CPU once its layout settles. It also loads d3 and PixiJS as pinned, integrity-checked versions, with PixiJS's minified build (200 KB instead of 2.5 MB on every page).
|
||||
- 6ce31a4: - `@quartz-community/graph` 1.0.7: the local graph on folder index pages shows the folder's connections instead of a single node.
|
||||
- `@quartz-community/utils` 1.2.1: `unescapeHTML` decodes each entity once, so a page description that mentions `<br>` keeps it in the page's meta tags instead of turning it into `<br>`.
|
||||
- 9d6cdba: Pages get a canonical link (`<link rel="canonical">`, the page's URL as the sitemap lists it), and `og:url` uses the same URL: `folder/` instead of `folder/index`, and the site root for the home page. `og:site_name` is a `property` (it was a `name`, which Open Graph readers ignore). Notes are `og:type: article`, with `article:modified_time` and, when the frontmatter has a date, `article:published_time`. The home page and folder and tag pages stay `website`.
|
||||
|
||||
The `fonts.gstatic.com` preconnect is a CORS connection, which the font files can reuse, and the unused `cdnjs.cloudflare.com` preconnect is gone.
|
||||
|
||||
- c79adab: 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.
|
||||
- 3b78d16: Frontmatter is read with js-yaml 5, using YAML 1.2's core schema (the values Quartz read before are unchanged). Frontmatter with only comments now has no properties, as in Obsidian, instead of being reported as invalid frontmatter.
|
||||
- a55f25f: The page frames mark their regions for assistive technology: the centre column is a `<main>` (it was a `div.center`; the classes are unchanged) and the default frame's sidebars are `<aside>` elements. Screen readers can jump to the page's content, and the page looks the same.
|
||||
- 7714325: Heading transclusions and their footnotes look through Obsidian's per-block wrappers (`div.el-h2 > h2`), which `@quartz-community/rehype-obsidian` now renders around each of a note's top-level blocks. `blockOf()` (in `components/transcludeScope.ts`) returns the block inside a wrapper, for other code that walks a page's top-level blocks.
|
||||
- b4d7358: Obsidian's fold arrows in headings and list items (`.heading-collapse-indicator`, `.list-collapse-indicator`, rendered by rehype-obsidian for Obsidian themes) are hidden unless obsidian-flavored-markdown's `foldHeadings` / `foldLists` turn folding on.
|
||||
- 0bab8ea: @quartz-community/obsidian-flavored-markdown 2.4.0 (Obsidian's block wrappers, heading and list folding, missing-attachment embeds, Pele diagrams) and @quartz-community/og-image 1.1.2 (no build failure on emoji variants such as the footnote back-link `↩︎`).
|
||||
- db7484e: @quartz-themes/core 3.2.0 (Obsidian's block wrappers styled natively, property inputs, fold arrows) and the plugin releases that carry Obsidian's markup:
|
||||
|
||||
- latex 1.1.0: maths in Obsidian's math elements;
|
||||
- note-properties 1.2.0: Obsidian's properties markup;
|
||||
- search 1.1.0: the quick switcher's classes, excerpts as written;
|
||||
- explorer 1.1.2: Obsidian's folder rows;
|
||||
- table-of-contents 1.0.4: the collapsed table of contents no longer clips its header;
|
||||
- graph 1.0.4: colours follow Obsidian themes;
|
||||
- syntax-highlighting 1.0.4: the copy button's stylesheet in the base layer;
|
||||
- canvas-page 1.0.4: heading embeds look through the block wrappers.
|
||||
|
||||
- fd744c0: The `obsidian` template folds headings and lists (obsidian-flavored-markdown's `foldHeadings` and `foldLists`), as Obsidian does by default.
|
||||
- 7b4da1c: A note whose name ends in "index" (`reindex.md`) is an `og:type: article` again. The home page and folder index pages were told apart by the slug ending in `index`, not by its last segment, so such notes were `website` and had no article dates.
|
||||
- bc0e393: Plugin order: `before:` / `after:` naming a plugin that is built into Quartz now (`crawl-links`, `remove-draft`, `content-index`) passed validation but was ignored. They now mean the built-in that replaced them (`links`, `drafts`, `contentIndex`), so `before: crawl-links` orders the plugin before link processing, and is checked against its `order` like `before: links`.
|
||||
- 52af9f1: `PageList` entries are `h2` headings under the page's `h1` (they were `h3`, which skipped a level for screen readers), at the `h3`'s size, as in `@quartz-community/folder-page` and `@quartz-community/tag-page`.
|
||||
- f646ffe: Plugin fixes from the pre-release audit:
|
||||
|
||||
- `@quartz-community/latex` 1.1.2: KaTeX's stylesheet applies on pages whose maths comes from a transclusion or a popover, and after SPA navigation (it stayed print-only).
|
||||
- `@quartz-community/obsidian-flavored-markdown` 2.5.2: bundles rehype-obsidian 1.5.1 and remark-obsidian 2.2.4, so same-page block links (`[[#^id]]`) work, only real YouTube hosts become embeds, large notes use less memory, and under `preset: strict` other plugins' text rewrites survive in notes with callouts; `math: false` works under `strict` with the LaTeX plugin; Markdown-link embeds with a query or in reference style are transcluded.
|
||||
- `@quartz-community/github-flavored-markdown` 2.2.1: `replacements` leaves autolink text alone, applies to wikilink aliases, and honours backslash escapes; `data-heading` keeps the heading as written.
|
||||
- `@quartz-community/canvas-page` 1.1.2 and `@quartz-community/tag-page` 1.0.7: file nodes find headings as Obsidian writes them (`#Sub Section`), embeds in text nodes are filled in, text-node tags get tag pages, and ids are unique per node; the tag index lists pages as `h3` under each tag.
|
||||
- `@quartz-community/search` 1.1.2: Enter on a result navigates without a full reload, `#tags` match with `slugs.stripDiacritics`, and searches ignore accents (`creme` finds "Crème").
|
||||
- `@quartz-community/explorer` 1.2.2: keeps the current page open after a `render` event without details (encrypted pages), and each explorer's phone button is named after its title.
|
||||
- `@quartz-community/bases-page` 1.5.4: view tabs follow the WAI-ARIA tabs pattern (arrow keys, unique ids).
|
||||
- `@quartz-community/graph` 1.0.8: no animation loop while the graph is idle, closed or removed.
|
||||
- `@quartz-community/created-modified-date` 1.0.5: stand-in dates are marked, so they stay out of `contentIndex.json`, and git dates work for a symlinked vault in a content folder outside git.
|
||||
- `@quartz-community/og-image` 1.1.3, `@quartz-community/ox-hugo` 1.0.3, `@quartz-community/breadcrumbs` 1.0.5, `@quartz-community/folder-page` 1.1.3, `@quartz-community/note-properties` 1.2.2: descriptions decoded once and keycap/flag emoji in social images; captioned figures and indented code in ox-hugo; utils 1.3.1 (Latin-only `stripDiacritics`).
|
||||
|
||||
- 8c61245: Plugin updates:
|
||||
|
||||
- `@quartz-community/explorer` 1.2.0: `sort` option (rules applied in sequence, e.g. folders first, then newest) and `rootFolder` option, so several explorers on one page work side by side; the `order` option is applied; scroll fixes (the bottom fade, the scroll position across SPA navigation with `layout.sidebars.left: scroll`, and opening a page no longer scrolls the page itself).
|
||||
- `@quartz-community/obsidian-flavored-markdown` 2.5.0: notes, canvases and bases embedded with a Markdown link (``) are transcluded, as in Obsidian; `math` option (`false` leaves dollar signs as text). With `@quartz-community/rehype-obsidian` 1.5.1: same-page block links (`[[#^id]]`) reach their block, and only images on YouTube become YouTube embeds.
|
||||
- `@quartz-community/github-flavored-markdown` 2.2.0: `singleTilde` option (`false` strikes only `~~text~~`, as Obsidian does) and `replacements` option (for example Quartz 4's arrows), empty by default.
|
||||
- `@quartz-community/canvas-page` 1.1.0: the mouse wheel and trackpad pan the canvas, as in Obsidian (`wheelBehavior`); text nodes are rendered with the site's Markdown plugins, so Mermaid diagrams, callouts and math work in them (`textNodeMarkdown`).
|
||||
- `@quartz-community/utils` 1.3.0: the `stripDiacritics` slug option reaches plugins too; links in embedded folder notes point at the right directory.
|
||||
- `@quartz-community/created-modified-date` 1.0.4: git dates resolve when `content/` is a symlink to a vault in another git repository.
|
||||
- `@quartz-community/ox-hugo` 1.0.2: the Markdown rewrites leave code alone and no longer match across unrelated text.
|
||||
|
||||
- 96fc9c1: Plugin updates for accessibility and page speed:
|
||||
|
||||
- Text in the table of contents, footer, folder and tag listings, search button and Bases group headings meets WCAG AA contrast in light and dark mode. Under an Obsidian theme from quartz-themes (`@quartz-themes/core` 3.2.1), the search button and Bases group headings keep the theme's faint text colour.
|
||||
- Page listings in folder and tag pages use `<h2>` titles (at the previous size), so headings no longer skip a level.
|
||||
- Valid ARIA and unique ids in the table of contents, explorer, backlinks, heading anchors and Bases views.
|
||||
- The graph loads d3 and PixiJS only when it scrolls into view (or when the global graph opens), instead of on every page.
|
||||
- KaTeX's stylesheet no longer blocks rendering on pages without math.
|
||||
- `@quartz-community/remark-obsidian` 2.2.3: the `legacy` parser no longer uses memory that grows with the square of the note's length on notes with many tables, lists or other blocks.
|
||||
|
||||
- 661b56a: Release tags are verified on GitHub: the release workflow creates each `vX.Y.Z` tag as a lightweight tag on the merged release commit (which GitHub signs) instead of letting the release create an unsigned annotated tag. It also starts the Docker build for the tag, so versioned images (`5.3.0`, `5.3`) are published for each release (none were built for 5.1.0–5.2.2).
|
||||
- 799b8e3: Component styles are one stylesheet (`component-<hash>.css`, in the `quartz-base` layer as before) instead of one per component. Pages load about 20 fewer render-blocking stylesheets (29 to 11 on the docs site), and the styles they compute are unchanged.
|
||||
- e0f1e03: A scroll made just before Back (less than 150 ms) is no longer lost: Forward returns to where the reader scrolled.
|
||||
- 3ab4503: With SPA navigation, Back and Forward return to where the reader was on each page. The router keeps each history entry's scroll position and restores it after swapping the page in. The browser restored the position while the previous page was still on screen, so it came out wrong: Back after a table-of-contents link stayed at the heading, and Back to a page landed at its top or bottom. Back and Forward between headings of the same page now only scroll, instead of reloading the page, and a reload keeps the position.
|
||||
- 0d05ef7: Build-time stand-in dates are no longer written as real dates. A page whose date no source gives (for example `defaultDateType: published` and no `published:`, or an invalid one) gets the build time from the date plugin; `contentIndex.json` now leaves its `date` out, and `article:published_time` / `article:modified_time` are only set for real dates (an invalid `published:` gave the build time). RSS and the sitemap keep the build time. created-modified-date 1.0.5 lists its stand-ins in `file.data.fallbackDates`; with older versions a `published` date only counts when the frontmatter sets it.
|
||||
- dd667ee: `slugs.stripDiacritics` reaches plugins and the browser: bases-page 1.5.3, breadcrumbs 1.0.4, canvas-page 1.1.1, explorer 1.2.1, folder-page 1.1.2, note-properties 1.2.1 and obsidian-flavored-markdown 2.5.1 bundle `@quartz-community/utils` 1.3, so their links, tag pages from inline tags, canvas file nodes and base views use the stripped addresses. Quartz also passes the option to scripts in the browser, so the explorer places folders and pages with accents where the build put them.
|
||||
- 093d233: The templates' colours meet WCAG AA contrast (4.5:1) on their backgrounds. Light `gray` goes from #b8b8b8 to #727272 (was 1.9:1), dark `gray` from #646464 to #7f7f7f (was 3.1:1), and light `tertiary`, the link hover colour, from #84a59d to #587971 (was 2.5:1). Text selection mixes 40% of `tertiary` instead of 60%, so text stays readable on it in both modes. Existing sites keep the colours in their own `quartz.config.yaml`.
|
||||
- 7c3df89: Type checking (`npm run check`) uses TypeScript 7. `tsconfig.json` switches `moduleResolution` from `node` (removed in TypeScript 7) to `bundler`, which reads packages' `exports`: custom code that imports a package's internal files may need to import from the package itself.
|
||||
- af36801: 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.
|
||||
|
||||
## 5.2.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -556,10 +556,10 @@ export const MyFrame: PageFrame = {
|
||||
`,
|
||||
render({ componentData, pageBody: Content, footer: Footers }: PageFrameProps): unknown {
|
||||
return (
|
||||
<div class="center">
|
||||
<main class="center">
|
||||
{Content(componentData) as ComponentChildren}
|
||||
{Footers.map((Footer) => Footer(componentData) as ComponentChildren)}
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
},
|
||||
}
|
||||
@@ -569,6 +569,7 @@ Key requirements:
|
||||
|
||||
- `name`: A unique string identifier. This is what page types and YAML config reference.
|
||||
- `render()`: Receives all layout slots (header, sidebars, content, footer) and returns JSX for the inner page structure. Note that `footer` is a `QuartzComponent[]` (an array) — frames should iterate over it with `.map()` to render all footer components.
|
||||
- Put the page's content in a `<main>` element (and sidebars in `<aside>`), as the built-in frames do, so screen readers can jump to it.
|
||||
- `css` (optional): Frame-specific CSS. Scope it with `.page[data-frame="my-frame"]` selectors to avoid conflicts.
|
||||
|
||||
**2. Re-export the frame:**
|
||||
|
||||
@@ -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.
|
||||
@@ -23,6 +23,39 @@ layout:
|
||||
|
||||
`configuration` and `plugins` are described below; the `layout` section (component groups, `byPageType` overrides, sidebar modes) is described in [[layout]].
|
||||
|
||||
## Extending the default configuration
|
||||
|
||||
Without a `quartz.config.yaml`, Quartz uses `quartz.config.default.yaml`. A `quartz.config.yaml` normally replaces it completely. With `extends`, your file can hold just the changes you make to another configuration instead:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
extends: default # quartz.config.default.yaml
|
||||
configuration:
|
||||
pageTitle: "My Site"
|
||||
baseUrl: example.com
|
||||
plugins:
|
||||
- source: "@quartz-community/graph"
|
||||
enabled: false # turn off a default plugin
|
||||
- source: "@quartz-community/explorer"
|
||||
options:
|
||||
folderDefaultState: open # only this option changes
|
||||
- source: github:me/my-plugin # a plugin the defaults don't have
|
||||
enabled: true
|
||||
```
|
||||
|
||||
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. An empty file (or one with only comments) is an empty config, and `extends: []` extends nothing.
|
||||
- A list stacks presets: each file in it adds its own changes. Quartz puts every file of the `extends` chain in one line and applies each once, its bases before it: the list's entries in order, each after the bases it extends, and your file last. A base that several entries share (usually `default`) is applied once, at its first appearance. So with `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, the order is `default` → `a.yaml` → `b.yaml` → your file: what `a.yaml` changes stays unless `b.yaml` changes the same thing (later entries win), and your file wins over both. An entry that doesn't extend the shared base is applied before it if it comes first, so the base's settings win over it; make such a preset extend `default` too, or list it after the others.
|
||||
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
|
||||
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
|
||||
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). A source with a `name` matches by that name; a source with a `subdir` and no `name` matches by repository and folder, so two plugins of one repository stay separate. `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
|
||||
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
|
||||
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
|
||||
|
||||
- `npx quartz build --serve` also rebuilds when a local file your config extends changes.
|
||||
- `npx quartz plugin` commands and `npx quartz info` read the merged configuration, as the build does: `plugin list`, `status`, `doctor`, `install` and `prune` see the plugins your bases configure. Commands that change plugins only ever write your own file, never the merged result: `enable`, `disable` and `config --set` add or change your entry for the plugin (`- source: …` with just that change), `config --unset` removes your value and, when a base sets the option, sets it to `null` so the plugin's default applies, and `add` appends a full entry. `remove` refuses a plugin that a base configures (it can't be removed from your file); disable it instead.
|
||||
|
||||
> [!warning] Experimental
|
||||
> `extends` is experimental: the merge rules may still change.
|
||||
|
||||
## General Configuration
|
||||
|
||||
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
|
||||
@@ -54,6 +87,11 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `"all"` (default): every file that isn't ignored.
|
||||
- `"referenced"`: only files a published page links to or embeds. Use this with [[ExplicitPublish]] or [[private pages|drafts]], so that files only unpublished notes use stay private.
|
||||
- Files that Quartz renders as pages themselves (e.g. `.base` and `.canvas` files) are never copied as raw assets.
|
||||
- `slugs`: how file paths become URLs.
|
||||
- `stripDiacritics`: `true` strips accents and other diacritics from page, folder and file URLs, e.g. `české/čeština.md` is published at `/ceske/cestina` instead of `/české/čeština` (which browsers show as `%C4%8Desk%C3%A9/...` when copied). Off by default.
|
||||
- Links keep working as written in your notes: `[[čeština]]`, `[[české/čeština#Nadpis]]` and embeds like `![[obrázek.png]]` resolve to the stripped addresses. Aliases and `permalink`s are stripped the same way. Heading anchors (`#Nadpis`) keep their diacritics. Tag pages and the pages plugins generate from files (canvas, bases, …) are stripped too with `@quartz-community/utils` 1.3 or newer; with older versions they keep their diacritics.
|
||||
- Only 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. 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.
|
||||
@@ -133,6 +171,20 @@ plugins:
|
||||
|
||||
Plugins are categorized by their type (transformer, filter, emitter, pageType) based on their manifest. The `order` field controls execution order within each category.
|
||||
|
||||
`before` and `after` name plugins that this one must run before or after (one name or a list; `obsidian-flavored-markdown`, `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` all work, as do the built-ins `frontmatter`, `links`, `drafts` and `contentIndex`; the names of the plugins they replaced, `crawl-links`, `remove-draft` and `content-index`, mean those built-ins). They never override `order`; they are checked against it:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
plugins:
|
||||
- source: github:me/my-transformer
|
||||
enabled: true
|
||||
order: 45
|
||||
after: obsidian-flavored-markdown # needs the links OFM creates
|
||||
```
|
||||
|
||||
- Between plugins with the same `order`, `before`/`after` decide the order (otherwise the list order does).
|
||||
- If `order` contradicts a constraint (here: OFM moved to order 50), the build stops with an error that names both orders, instead of silently running the plugins the wrong way round.
|
||||
- A name that isn't in your config is an error. A plugin that is disabled, or runs in another category (a filter named by a transformer), is skipped: the constraint applies only where both plugins run.
|
||||
|
||||
> [!note]
|
||||
> For advanced TS override of plugin configuration, you can modify `quartz.ts`:
|
||||
>
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -15,4 +15,6 @@ Under the hood, this is done by hijacking page navigations and instead fetching
|
||||
|
||||
Pages are fetched ahead of a click by [[prefetching]], which the router uses to show them at once; the fetched pages are also reused by [[popover previews]].
|
||||
|
||||
Back and Forward return to where you were on each page: the router keeps each history entry's scroll position and restores it after the page is swapped in, and a reload keeps it too. Links to a heading on the same page add a history entry and only scroll, so Back returns to where you clicked.
|
||||
|
||||
Redirects are followed: when a link is redirected (for example `folder` → `folder/` on static hosts, or an alias page to its canonical page), the address bar shows the final URL and relative links on the new page resolve against it.
|
||||
@@ -33,7 +33,7 @@ configuration:
|
||||
openLinksInNewTab: false
|
||||
lazyLoad: false
|
||||
externalLinkIcon: true
|
||||
disableBrokenWikilinks: false
|
||||
disableBrokenWikilinks: true
|
||||
drafts:
|
||||
publish: false # true = publish drafts anyway (e.g. preview deployments)
|
||||
contentIndex:
|
||||
|
||||
@@ -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`)
|
||||
|
||||
|
||||
@@ -8,13 +8,13 @@ This guide walks you through setting up Quartz from scratch. If you already ran
|
||||
|
||||
You need these tools installed before continuing:
|
||||
|
||||
- **[Node.js](https://nodejs.org/) v22 or later** (run `node -v` to check)
|
||||
- **[Node.js](https://nodejs.org/) v22.22 or later** (run `node -v` to check)
|
||||
- **npm v10.9.2 or later** (bundled with Node — run `npm -v` to check)
|
||||
- **[Git](https://git-scm.com/)** (run `git -v` to check)
|
||||
|
||||
> [!warning] Common issues
|
||||
>
|
||||
> - **Linux**: System packages (`apt install nodejs`) often ship much older versions. Use [nvm](https://github.com/nvm-sh/nvm) or the [NodeSource](https://github.com/nodesource/distributions) repository to get Node.js v22.
|
||||
> - **Linux**: System packages (`apt install nodejs`) often ship much older versions. Use [nvm](https://github.com/nvm-sh/nvm) or the [NodeSource](https://github.com/nodesource/distributions) repository to get Node.js v22.22 or later.
|
||||
> - **Windows**: When installing Git, make sure **"Git from the command line and also from 3rd-party software"** is selected so that `git` is available in your terminal. If `node -v` or `git -v` shows "command not found", restart your terminal or check your PATH.
|
||||
> - **macOS**: The Xcode command-line tools include Git (`xcode-select --install`). For Node.js, [nvm](https://github.com/nvm-sh/nvm) or the [official installer](https://nodejs.org/) both work.
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ cd quartz
|
||||
## 2. Install Dependencies
|
||||
|
||||
> [!important]
|
||||
> Quartz requires **Node.js 22** or later. Check your version with `node -v` and upgrade at [nodejs.org](https://nodejs.org/) if needed.
|
||||
> Quartz requires **Node.js 22.22** or later. Check your version with `node -v` and upgrade at [nodejs.org](https://nodejs.org/) if needed.
|
||||
|
||||
```bash
|
||||
npm i
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 (``) 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.
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Quartz is a fast, batteries-included static-site generator that transforms Markd
|
||||
|
||||
## 🪴 Get Started
|
||||
|
||||
Quartz requires **at least [Node](https://nodejs.org/) v22** and `npm` v10.9.2 to function correctly. Ensure you have these installed on your machine before continuing. See the [[getting-started/index#Prerequisites|prerequisites]] for help installing them.
|
||||
Quartz requires **at least [Node](https://nodejs.org/) v22.22** and `npm` v10.9.2 to function correctly. Ensure you have these installed on your machine before continuing. See the [[getting-started/index#Prerequisites|prerequisites]] for help installing them.
|
||||
|
||||
> [!tip] GitHub users
|
||||
> You can also use the **[GitHub template](https://github.com/jackyzha0/quartz/generate)** to create your repository in one click, then clone that instead. See [[installation#Option A Use the GitHub Template Recommended|Option A]] in the installation guide.
|
||||
|
||||
@@ -170,12 +170,17 @@ plugins:
|
||||
|
||||
Available built-in conditions:
|
||||
|
||||
| Condition | Description |
|
||||
| --------------- | ----------------------------------------------------- |
|
||||
| `not-index` | Only render when the page is not the root `index.md` |
|
||||
| `has-tags` | Only render when the page has tags in its frontmatter |
|
||||
| `has-backlinks` | Only render when the page has backlinks |
|
||||
| `has-toc` | Only render when the page has a table of contents |
|
||||
| Condition | Description |
|
||||
| ----------------- | --------------------------------------------------------------------------- |
|
||||
| `is-index` | Only render on the root `index.md` (the home page) |
|
||||
| `not-index` | Only render when the page is not the root `index.md` |
|
||||
| `is-folder-index` | Only render on a folder's index page (`folder/index.md` or a generated one) |
|
||||
| `has-tags` | Only render when the page has tags in its frontmatter |
|
||||
| `has-backlinks` | Only render when the page has backlinks |
|
||||
| `has-toc` | Only render when the page has a table of contents |
|
||||
| `not-<condition>` | Negates any other condition, e.g. `not-has-tags`, `not-has-backlinks` |
|
||||
|
||||
The `not-` prefix also works for conditions registered by plugins or in `quartz.ts`. To change the layout of a whole page type (folder pages, tag pages, …) rather than single pages, use `layout.byPageType` (see [[layout#Per-page-type overrides]]).
|
||||
|
||||
### TS Override
|
||||
|
||||
|
||||
+9
-6
@@ -132,12 +132,15 @@ plugins:
|
||||
|
||||
Available conditions:
|
||||
|
||||
| Condition | Effect |
|
||||
| --------------- | ------------------------------------------------------------------------ |
|
||||
| `not-index` | Hidden on the root index page, shown everywhere else |
|
||||
| `has-tags` | Only shown on pages that have tags in frontmatter |
|
||||
| `has-backlinks` | Only shown on pages that another (listed) page links to |
|
||||
| `has-toc` | Only shown on pages with a table of contents (needs `table-of-contents`) |
|
||||
| Condition | Effect |
|
||||
| ----------------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| `is-index` | Only shown on the root index page (the home page) |
|
||||
| `not-index` | Hidden on the root index page, shown everywhere else |
|
||||
| `is-folder-index` | Only shown on folder index pages (`folder/index.md` or a generated one), not on tag pages (`tags/` and `tags/<tag>`) |
|
||||
| `has-tags` | Only shown on pages that have tags in frontmatter |
|
||||
| `has-backlinks` | Only shown on pages that another (listed) page links to |
|
||||
| `has-toc` | Only shown on pages with a table of contents (needs `table-of-contents`) |
|
||||
| `not-<condition>` | Negates any condition, built-in or registered: `not-has-tags`, `not-has-toc` |
|
||||
|
||||
Plugins can register additional conditions. An unknown condition name prints a warning at build time and the component is always shown.
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ With Quartz 5.1, `.base` pages follow the site's publish filters (e.g. [[Explici
|
||||
|
||||
This plugin accepts the following configuration options:
|
||||
|
||||
- `propertyLabels`: How column and property labels are shown. `"name"` (default) shows a property's name as Obsidian does (`priority`, `file name`); `"title"` title-cases it (`Priority`, `Name`). A property's `displayName` is always used.
|
||||
- `defaultViewType`: Open a base on its first view of this type. Unset by default: a base opens on its first view, as in Obsidian.
|
||||
- `linkResolution`: How to resolve internal links in view renderers. Should match `configuration.links.markdownLinkResolution` (built-in [[CrawlLinks|link processing]]). Can be `"absolute"`, `"relative"`, or `"shortest"`. Defaults to `"shortest"`.
|
||||
- `customViews`: A map of custom view renderers. Keys are view type names. These override built-in renderers for the same type, or add new view types. Requires a TS override.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -36,6 +36,10 @@ Options:
|
||||
> [!note]
|
||||
> An existing `@quartz-community/content-index` entry is applied to `configuration.contentIndex` automatically. Run `npx quartz plugin doctor --fix` to move it.
|
||||
|
||||
## `contentIndex.json`
|
||||
|
||||
Each entry of `static/contentIndex.json` is keyed by slug and holds `slug`, `filePath`, `title`, `links`, `tags` and `content` (the page's text), plus `date` when the page has one: the date selected by `defaultDateType` of [[CreatedModifiedDate]] (the same date [[ContentMeta]] shows and the RSS feed uses), as an ISO 8601 string such as `"2024-01-02T03:04:05.000Z"`. Client-side components can use it to sort by date, e.g. `new Date(entry.date)`. When that date is the one the page's frontmatter sets for the configured date type (e.g. `modified:` / `lastmod:` with `defaultDateType: modified`), rather than one from git or the file system, the entry also has `dateFromFrontmatter: true`; otherwise the field is absent.
|
||||
|
||||
## Adding fields
|
||||
|
||||
Plugins can add their own fields to each entry of `contentIndex.json` with `extendContentIndex` — see [[making plugins#Extending the content index]].
|
||||
|
||||
@@ -32,7 +32,7 @@ Options:
|
||||
- `openLinksInNewTab`: If `true`, configures external links to open in a new tab. Defaults to `false`.
|
||||
- `lazyLoad`: If `true`, adds lazy loading to resource elements (`img`, `video`, etc.) to improve page load performance. Defaults to `false`.
|
||||
- `externalLinkIcon`: Adds an icon next to external links when `true` (default) to visually distinguishing them from internal links.
|
||||
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `false`. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed.
|
||||
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `true`, as Obsidian marks unresolved links. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed. Only targets Quartz can check are marked: pages, and files of the types a vault holds (images, audio, video, PDFs, canvases, bases) that the content doesn't have. Links to other files, which Quartz or a plugin may emit (`index.xml`, `sitemap.xml`, `robots.txt`, anything under `static/`), are never marked. Links to pages that a filter removes (e.g. [[RemoveDrafts|drafts]] or pages without `publish: true` under [[ExplicitPublish]]) are marked `broken` too, since they 404; they also get `data-filtered="<filter name>"`. A folder link stays unbroken when only the folder's `index.md` is removed, because the folder still gets a generated folder page.
|
||||
- `enabled`: set to `false` to turn link processing off (not recommended — links break on nested pages and backlinks/graph are empty).
|
||||
- `order`: position among transformers. Defaults to `60`, after the Markdown flavour plugins (e.g. [[ObsidianFlavoredMarkdown]] at `40`) that turn wikilinks into links.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -22,7 +22,7 @@ This plugin accepts the following configuration options:
|
||||
- `mathJaxOptions`: Additional options passed to the MathJax renderer. See the [MathJax docs](https://docs.mathjax.org/en/latest/options/) for available options.
|
||||
- `typstOptions`: Additional options passed to the Typst renderer.
|
||||
|
||||
With KaTeX, the KaTeX stylesheet and its copy-tex script are loaded from jsDelivr.
|
||||
With KaTeX, the KaTeX stylesheet and its copy-tex script are loaded from jsDelivr. The stylesheet blocks rendering only on pages with math; elsewhere it loads in the background, ready for pages opened with SPA navigation.
|
||||
|
||||
### Default options
|
||||
|
||||
|
||||
@@ -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,10 @@ 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 (``, ``, ``, ``) 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`.
|
||||
|
||||
Also supported:
|
||||
|
||||
|
||||
Vendored
+6
@@ -3,6 +3,12 @@ declare module "*.scss" {
|
||||
export = content
|
||||
}
|
||||
|
||||
// micromorph ships these types, but its package.json "exports" don't list them, so TypeScript's
|
||||
// "bundler" resolution doesn't find them
|
||||
declare module "micromorph" {
|
||||
export default function micromorph(from: Node, to: Node): Promise<void>
|
||||
}
|
||||
|
||||
// dom custom event
|
||||
interface CustomEventMap {
|
||||
prenav: CustomEvent<{}>
|
||||
|
||||
Generated
+894
-985
File diff suppressed because it is too large.
Load diff
+36
-37
@@ -2,7 +2,7 @@
|
||||
"name": "@jackyzha0/quartz",
|
||||
"description": "🌱 publish your digital garden and notes as a website",
|
||||
"private": true,
|
||||
"version": "5.2.2",
|
||||
"version": "5.3.0",
|
||||
"type": "module",
|
||||
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
|
||||
"license": "MIT",
|
||||
@@ -25,7 +25,7 @@
|
||||
},
|
||||
"engines": {
|
||||
"npm": ">=10.9.2",
|
||||
"node": ">=22"
|
||||
"node": ">=22.22"
|
||||
},
|
||||
"keywords": [
|
||||
"site generator",
|
||||
@@ -45,57 +45,57 @@
|
||||
"@napi-rs/simple-git": "1.2.0",
|
||||
"@quartz-community/alias-redirects": "^1.0.3",
|
||||
"@quartz-community/article-title": "^1.0.2",
|
||||
"@quartz-community/backlinks": "^1.0.3",
|
||||
"@quartz-community/bases-page": "^1.3.0",
|
||||
"@quartz-community/breadcrumbs": "^1.0.3",
|
||||
"@quartz-community/canvas-page": "^1.0.3",
|
||||
"@quartz-community/backlinks": "^1.0.4",
|
||||
"@quartz-community/bases-page": "^1.5.6",
|
||||
"@quartz-community/breadcrumbs": "^1.0.6",
|
||||
"@quartz-community/canvas-page": "^1.1.6",
|
||||
"@quartz-community/citations": "^1.0.1",
|
||||
"@quartz-community/cname": "^1.0.1",
|
||||
"@quartz-community/comments": "^1.0.2",
|
||||
"@quartz-community/comments": "^1.0.3",
|
||||
"@quartz-community/content-meta": "^1.0.2",
|
||||
"@quartz-community/content-page": "^1.0.3",
|
||||
"@quartz-community/created-modified-date": "^1.0.3",
|
||||
"@quartz-community/darkmode": "^1.0.2",
|
||||
"@quartz-community/description": "^1.0.2",
|
||||
"@quartz-community/encrypted-pages": "^1.2.0",
|
||||
"@quartz-community/created-modified-date": "^1.0.5",
|
||||
"@quartz-community/darkmode": "^1.0.3",
|
||||
"@quartz-community/description": "^1.0.3",
|
||||
"@quartz-community/encrypted-pages": "^1.3.1",
|
||||
"@quartz-community/explicit-publish": "^1.2.0",
|
||||
"@quartz-community/explorer": "^1.0.3",
|
||||
"@quartz-community/explorer": "^1.2.5",
|
||||
"@quartz-community/favicon": "^1.0.1",
|
||||
"@quartz-community/folder-page": "^1.1.0",
|
||||
"@quartz-community/footer": "^1.1.1",
|
||||
"@quartz-community/github-flavored-markdown": "^2.1.1",
|
||||
"@quartz-community/graph": "^1.0.3",
|
||||
"@quartz-community/folder-page": "^1.1.4",
|
||||
"@quartz-community/footer": "^1.1.2",
|
||||
"@quartz-community/github-flavored-markdown": "^2.2.2",
|
||||
"@quartz-community/graph": "^1.0.9",
|
||||
"@quartz-community/hard-line-breaks": "^1.1.0",
|
||||
"@quartz-community/latex": "^1.0.2",
|
||||
"@quartz-community/note-properties": "^1.1.4",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.2.0",
|
||||
"@quartz-community/og-image": "^1.1.1",
|
||||
"@quartz-community/ox-hugo": "^1.0.1",
|
||||
"@quartz-community/latex": "^1.1.3",
|
||||
"@quartz-community/note-properties": "^1.2.4",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
|
||||
"@quartz-community/og-image": "^1.1.4",
|
||||
"@quartz-community/ox-hugo": "^1.0.4",
|
||||
"@quartz-community/page-title": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.3",
|
||||
"@quartz-community/recent-notes": "^1.0.3",
|
||||
"@quartz-community/roam": "^1.1.0",
|
||||
"@quartz-community/search": "^1.0.3",
|
||||
"@quartz-community/search": "^1.1.4",
|
||||
"@quartz-community/spacer": "^1.0.2",
|
||||
"@quartz-community/stacked-pages": "^1.0.3",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.3",
|
||||
"@quartz-community/table-of-contents": "^1.0.3",
|
||||
"@quartz-community/stacked-pages": "^1.0.4",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.5",
|
||||
"@quartz-community/table-of-contents": "^1.0.6",
|
||||
"@quartz-community/tag-list": "^1.0.3",
|
||||
"@quartz-community/tag-page": "^1.0.5",
|
||||
"@quartz-community/tag-page": "^1.0.7",
|
||||
"@quartz-community/unlisted-pages": "^1.2.0",
|
||||
"@quartz-themes/core": "^3.1.0",
|
||||
"@quartz-themes/core": "^3.2.1",
|
||||
"ansi-truncate": "^1.4.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"chokidar": "^5.0.0",
|
||||
"chokidar": "^6.0.0",
|
||||
"esbuild-sass-plugin": "^3.6.0",
|
||||
"globby": "^16.1.0",
|
||||
"gray-matter": "^4.0.3",
|
||||
"hast-util-from-html": "^2.0.0",
|
||||
"hast-util-to-html": "^9.0.5",
|
||||
"hast-util-to-html": "^9.0.7",
|
||||
"hast-util-to-jsx-runtime": "^2.3.6",
|
||||
"is-absolute-url": "^4.0.1",
|
||||
"is-absolute-url": "^5.0.0",
|
||||
"isomorphic-git": "^1.36.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"js-yaml": "^5.5.0",
|
||||
"lightningcss": "^1.31.1",
|
||||
"micromorph": "^0.4.5",
|
||||
"minimatch": "^11.0.5",
|
||||
@@ -117,16 +117,15 @@
|
||||
"unist-util-visit": "^5.1.0",
|
||||
"vfile": "^6.0.3",
|
||||
"workerpool": "^10.0.1",
|
||||
"ws": "^8.19.0",
|
||||
"ws": "^8.23.0",
|
||||
"yaml": "^2.8.2",
|
||||
"yargs": "^18.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.29.2",
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.2.0",
|
||||
"@quartz-community/utils": "^1.3.3",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
"@types/semver": "^7.7.1",
|
||||
@@ -136,6 +135,6 @@
|
||||
"esbuild": "^0.28.2",
|
||||
"prettier": "^3.8.1",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3"
|
||||
"typescript": "^7.0.2"
|
||||
}
|
||||
}
|
||||
@@ -24,17 +24,17 @@ configuration:
|
||||
lightMode:
|
||||
light: "#faf8f8"
|
||||
lightgray: "#e5e5e5"
|
||||
gray: "#b8b8b8"
|
||||
gray: "#727272"
|
||||
darkgray: "#4e4e4e"
|
||||
dark: "#2b2b2b"
|
||||
secondary: "#284b63"
|
||||
tertiary: "#84a59d"
|
||||
tertiary: "#587971"
|
||||
highlight: rgba(143, 159, 169, 0.15)
|
||||
textHighlight: "#fff23688"
|
||||
darkMode:
|
||||
light: "#161618"
|
||||
lightgray: "#393639"
|
||||
gray: "#646464"
|
||||
gray: "#7f7f7f"
|
||||
darkgray: "#d4d4d4"
|
||||
dark: "#ebebec"
|
||||
secondary: "#7b97aa"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env -S node --no-deprecation
|
||||
const [major] = process.versions.node.split(".").map(Number)
|
||||
if (major < 22) {
|
||||
const [major, minor] = process.versions.node.split(".").map(Number)
|
||||
if (major < 22 || (major === 22 && minor < 22)) {
|
||||
console.error(
|
||||
`\nQuartz requires Node.js >= 22, but you are running Node.js ${process.version}.\n` +
|
||||
`\nQuartz requires Node.js >= 22.22, but you are running Node.js ${process.version}.\n` +
|
||||
`Please upgrade: https://nodejs.org/\n`,
|
||||
)
|
||||
process.exit(1)
|
||||
|
||||
+19
-1
@@ -26,7 +26,8 @@ import { minimatch } from "minimatch"
|
||||
import { formatLayoutReport, getLayoutReport } from "./plugins/loader/layoutReport"
|
||||
import { getBuiltinPlan } from "./plugins/loader/config-loader"
|
||||
import { prepareContentIndex } from "./plugins/builtins/contentIndex"
|
||||
import { printDiagnosticsSummary, warn } from "./util/diagnostics"
|
||||
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
|
||||
import { LinksInstance, removedPages } from "./plugins/builtins/links"
|
||||
import { collectPermalinks } from "./util/permalinks"
|
||||
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
|
||||
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
|
||||
@@ -66,6 +67,21 @@ function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
|
||||
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[],
|
||||
published: ProcessedContent[],
|
||||
): void {
|
||||
const links = ctx.cfg.plugins.transformers.find((t) => t.name === "Links") as
|
||||
LinksInstance | undefined
|
||||
// also when nothing was removed: in watch mode, marks from the last build may need undoing
|
||||
ctx.removedPages = links?.marksBrokenLinks ? removedPages(all, published, filteredBy) : undefined
|
||||
}
|
||||
|
||||
function reportSlugCollisions(content: ProcessedContent[]): void {
|
||||
const collisions = detectSlugCollisions(content)
|
||||
if (collisions.length === 0) return
|
||||
@@ -161,6 +177,7 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
|
||||
const parsedFiles = await parseMarkdown(ctx, filePaths)
|
||||
reportSlugCollisions(parsedFiles)
|
||||
const filteredContent = filterContent(ctx, parsedFiles)
|
||||
markRemovedLinks(ctx, parsedFiles, filteredContent)
|
||||
|
||||
await emitContent(ctx, filteredContent)
|
||||
console.log(
|
||||
@@ -418,6 +435,7 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
|
||||
.map((file) => file.content)
|
||||
reportSlugCollisions(markdownContent)
|
||||
let processedFiles = filterContent(ctx, markdownContent)
|
||||
markRemovedLinks(ctx, markdownContent, processedFiles)
|
||||
|
||||
let emittedFiles = 0
|
||||
|
||||
|
||||
+11
-1
@@ -109,6 +109,16 @@ export interface GlobalConfiguration {
|
||||
* - "referenced": Only copy assets referenced by published pages
|
||||
*/
|
||||
publishAssets?: "all" | "referenced"
|
||||
/** How file paths become URLs. */
|
||||
slugs?: SlugsConfig
|
||||
}
|
||||
|
||||
export interface SlugsConfig {
|
||||
/**
|
||||
* Strip accents and other diacritics from generated slugs (`české/čeština.md` →
|
||||
* `ceske/cestina`), aliases and permalinks; links are resolved the same way. Off by default.
|
||||
*/
|
||||
stripDiacritics?: boolean
|
||||
}
|
||||
|
||||
/** Shared by every built-in: `enabled: false` turns it off (e.g. to replace it with a plugin). */
|
||||
@@ -136,7 +146,7 @@ export interface LinksConfig extends BuiltinToggle {
|
||||
lazyLoad?: boolean
|
||||
/** Add an icon after external links. Default `true`. */
|
||||
externalLinkIcon?: boolean
|
||||
/** Add a `broken` class to internal links whose target does not exist. Default `false`. */
|
||||
/** Add a `broken` class to internal links whose target does not exist, as Obsidian marks unresolved links. Default `true`. */
|
||||
disableBrokenWikilinks?: boolean
|
||||
}
|
||||
|
||||
|
||||
+12
-5
@@ -39,6 +39,7 @@ import {
|
||||
readPluginsJson,
|
||||
writePluginsJson,
|
||||
updateGlobalConfig,
|
||||
extendedConfigFiles,
|
||||
LOCKFILE_PATH,
|
||||
} from "./plugin-data.js"
|
||||
import {
|
||||
@@ -619,11 +620,17 @@ export async function handleBuild(argv) {
|
||||
"quartz.config.default.yaml",
|
||||
])
|
||||
const extraWatch = process.env.QUARTZ_CONFIG_PATH ? [process.env.QUARTZ_CONFIG_PATH] : []
|
||||
chokidar
|
||||
.watch([...paths, ...extraWatch], { ignoreInitial: true })
|
||||
.on("add", () => build(clientRefresh))
|
||||
.on("change", () => build(clientRefresh))
|
||||
.on("unlink", () => build(clientRefresh))
|
||||
// local files the config extends (and the files they extend); looked up again after each
|
||||
// change, so a newly added base is watched too
|
||||
const watcher = chokidar.watch([...paths, ...extraWatch, ...(await extendedConfigFiles())], {
|
||||
ignoreInitial: true,
|
||||
})
|
||||
const rebuild = async () => {
|
||||
await build(clientRefresh)
|
||||
const bases = await extendedConfigFiles()
|
||||
if (bases.length > 0) watcher.add(bases)
|
||||
}
|
||||
watcher.on("add", rebuild).on("change", rebuild).on("unlink", rebuild)
|
||||
|
||||
console.log(styleText("gray", "hint: exit with ctrl+c"))
|
||||
}
|
||||
|
||||
+11
-2
@@ -23,6 +23,7 @@ import { builtinKeyFor, describeBuiltins } from "./builtin-migration.js"
|
||||
import { shortPluginName } from "./plugin-validation.js"
|
||||
import {
|
||||
readConfigWithDiagnostics,
|
||||
resolveEffectiveConfig,
|
||||
readLockfile,
|
||||
extractPluginName,
|
||||
formatSource,
|
||||
@@ -56,10 +57,18 @@ function readPackage(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
export function collectInfo(root = process.cwd()) {
|
||||
export async function collectInfo(root = process.cwd()) {
|
||||
const version = readQuartzVersion(root)
|
||||
const checkout = describeQuartzCheckout(root)
|
||||
const config = readConfigWithDiagnostics()
|
||||
// with `extends`, the merged configuration the build uses
|
||||
if (config.data && !config.error) {
|
||||
try {
|
||||
config.data = await resolveEffectiveConfig(config.data, config.path)
|
||||
} catch (err) {
|
||||
config.error = `extends: ${String(err?.message ?? err)}`
|
||||
}
|
||||
}
|
||||
const lockfile = readLockfile()
|
||||
const entries = Array.isArray(config.data?.plugins) ? config.data.plugins : []
|
||||
|
||||
@@ -176,7 +185,7 @@ export function formatInfoMarkdown(info) {
|
||||
}
|
||||
|
||||
export async function handleInfo({ json = false } = {}) {
|
||||
const info = collectInfo()
|
||||
const info = await collectInfo()
|
||||
if (json) {
|
||||
console.log(JSON.stringify(info, null, 2))
|
||||
return
|
||||
|
||||
@@ -158,6 +158,65 @@ export function readPluginsJson() {
|
||||
return data
|
||||
}
|
||||
|
||||
/** Whether a config (as read from its file) extends another (`extends:` with at least one base). */
|
||||
export function configExtends(data) {
|
||||
if (!isPlainObject(data)) return false
|
||||
const value = data.extends
|
||||
if (value === undefined || value === null) return false
|
||||
return !Array.isArray(value) || value.length > 0
|
||||
}
|
||||
|
||||
let configExtendsModule
|
||||
/**
|
||||
* The build's `extends` implementation (quartz/plugins/loader/config-extends.ts), loaded through
|
||||
* tsx only when a config uses `extends`, so the CLI merges exactly as the build does.
|
||||
*/
|
||||
export function loadConfigExtendsModule() {
|
||||
configExtendsModule ??= import("tsx/esm/api").then(({ tsImport }) =>
|
||||
tsImport("../plugins/loader/config-extends.ts", import.meta.url),
|
||||
)
|
||||
return configExtendsModule
|
||||
}
|
||||
|
||||
/**
|
||||
* The configuration the build uses: the config file with its `extends` applied. A config
|
||||
* without `extends` is returned as read. Read-only commands (list, status, doctor, info,
|
||||
* install, prune) use this; commands that edit the file keep using readPluginsJson(), which
|
||||
* returns only what the user's file contains. Throws a clear error when a base can't be loaded.
|
||||
*/
|
||||
export async function resolveEffectiveConfig(data, configPath = resolveConfigPath()) {
|
||||
if (!configExtends(data)) return data
|
||||
const { resolveExtends } = await loadConfigExtendsModule()
|
||||
return resolveExtends(data, configPath)
|
||||
}
|
||||
|
||||
/** readPluginsJson() with `extends` applied; reports a base that can't be loaded and returns null. */
|
||||
export async function readEffectivePluginsJson() {
|
||||
const data = readPluginsJson()
|
||||
try {
|
||||
return await resolveEffectiveConfig(data)
|
||||
} catch (err) {
|
||||
console.error(`✗ ${path.basename(resolveConfigPath())}: ${String(err?.message ?? err)}`)
|
||||
process.exitCode = 1
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Local files the config extends (directly or through other bases), for `--serve` to watch.
|
||||
* Empty when it extends nothing or a base can't be loaded (the build reports that).
|
||||
*/
|
||||
export async function extendedConfigFiles() {
|
||||
const data = readPluginsJson()
|
||||
if (!configExtends(data)) return []
|
||||
try {
|
||||
const { localExtendsFiles } = await loadConfigExtendsModule()
|
||||
return await localExtendsFiles(data, resolveConfigPath())
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Path of the config file the CLI reads from (may be a default/legacy file). */
|
||||
export function getConfigReadPath() {
|
||||
return resolveConfigPath()
|
||||
|
||||
@@ -4,6 +4,11 @@ import os from "os"
|
||||
import { styleText } from "util"
|
||||
import {
|
||||
readPluginsJson,
|
||||
readEffectivePluginsJson,
|
||||
resolveEffectiveConfig,
|
||||
configExtends,
|
||||
loadConfigExtendsModule,
|
||||
getConfigReadPath,
|
||||
writePluginsJson,
|
||||
readLockfile,
|
||||
writeLockfile,
|
||||
@@ -128,6 +133,67 @@ function resolveConfigEntryOrReport(json, name) {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* For commands that edit quartz.config.yaml: `json` is the user's own file (what gets written
|
||||
* back) and `effective` the configuration the build uses (with `extends` applied; the same
|
||||
* object without it). Plugins are looked up in `effective`; changes go to the user's entry for
|
||||
* the plugin (see overlayEntryFor), never the merged configuration. Returns null after
|
||||
* reporting when a base can't be loaded.
|
||||
*/
|
||||
async function readConfigForEdit() {
|
||||
const json = readPluginsJson()
|
||||
if (!configExtends(json)) return { json, effective: json, extending: false }
|
||||
try {
|
||||
const effective = await resolveEffectiveConfig(json, getConfigReadPath())
|
||||
const { pluginMatchKey } = await loadConfigExtendsModule()
|
||||
return { json, effective, extending: true, matchKey: pluginMatchKey }
|
||||
} catch (err) {
|
||||
console.log(
|
||||
styleText(
|
||||
"red",
|
||||
`✗ ${path.basename(getConfigReadPath())}: ${String(err?.message ?? err)} — nothing changed`,
|
||||
),
|
||||
)
|
||||
markFailed()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's entry for a plugin of the merged configuration (matched as `extends` merges
|
||||
* entries; the last one wins when there are several). With `create`, an entry
|
||||
* `{ source }` is added when the user's file has none, which then changes only what is set in it.
|
||||
*/
|
||||
function overlayEntryFor(edit, mergedEntry, create = false) {
|
||||
if (!edit.extending) return mergedEntry
|
||||
if (edit.json.plugins == null) edit.json.plugins = []
|
||||
if (!Array.isArray(edit.json.plugins)) {
|
||||
throw new Error(`"plugins" in ${path.basename(getConfigReadPath())} must be a list`)
|
||||
}
|
||||
const key = edit.matchKey(mergedEntry.source)
|
||||
let entry = edit.json.plugins.findLast((e) => {
|
||||
try {
|
||||
return e?.source !== undefined && edit.matchKey(e.source) === key
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
if (!entry && create) {
|
||||
entry = { source: mergedEntry.source }
|
||||
edit.json.plugins.push(entry)
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
function hasOptionPath(obj, segments) {
|
||||
let node = obj
|
||||
for (const segment of segments) {
|
||||
if (node === null || typeof node !== "object" || !(segment in node)) return false
|
||||
node = node[segment]
|
||||
}
|
||||
return node !== undefined && node !== null
|
||||
}
|
||||
|
||||
/** Read the manifest (`quartz` field of package.json) of a configured plugin, if installed. */
|
||||
function readEntryManifest(source) {
|
||||
const dir = resolvePluginDir(source)
|
||||
@@ -427,7 +493,7 @@ async function regeneratePluginIndex() {
|
||||
// npm plugins in the config are part of the index too (they used to be dropped here until the
|
||||
// next build regenerated it); the generator is shared with the build, see plugin-index.js
|
||||
const npmPackages = []
|
||||
for (const entry of readPluginsJson()?.plugins ?? []) {
|
||||
for (const entry of (await readEffectivePluginsJson())?.plugins ?? []) {
|
||||
if (builtinMessage(entry.source)) continue
|
||||
try {
|
||||
const parsed = parseGitSource(entry.source)
|
||||
@@ -455,7 +521,9 @@ export async function handlePluginInstallUnified({
|
||||
|
||||
// Plugins that are built into core now (crawl-links, remove-draft, content-index) are never
|
||||
// cloned or built, even if the config or the lockfile still lists them.
|
||||
const rawPluginsJson = readPluginsJson()
|
||||
// with `extends`, the plugins of the merged configuration (as the build loads them)
|
||||
const rawPluginsJson = await readEffectivePluginsJson()
|
||||
if (!rawPluginsJson && configExtends(readPluginsJson())) return
|
||||
const pluginsJson = rawPluginsJson && {
|
||||
...rawPluginsJson,
|
||||
plugins: (rawPluginsJson.plugins ?? []).filter((entry) => !builtinMessage(entry.source)),
|
||||
@@ -1476,8 +1544,12 @@ export async function handlePluginAdd(
|
||||
fs.mkdirSync(PLUGINS_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const pluginsJson = readPluginsJson()
|
||||
const configured = pluginsJson?.plugins ?? []
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
// added entries go to the user's file; "already configured" also covers plugins that come
|
||||
// from an `extends` base
|
||||
const pluginsJson = edit.json
|
||||
const configured = Array.isArray(edit.effective?.plugins) ? edit.effective.plugins : []
|
||||
|
||||
const addedPlugins = []
|
||||
let hadFailure = false
|
||||
@@ -1696,7 +1768,11 @@ export async function handlePluginAdd(
|
||||
writeLockfile(lockfile)
|
||||
}
|
||||
|
||||
if (pluginsJson?.plugins && addedPlugins.length > 0) {
|
||||
// an extending config may have no `plugins:` yet
|
||||
if (pluginsJson && pluginsJson.plugins == null && addedPlugins.length > 0) {
|
||||
pluginsJson.plugins = []
|
||||
}
|
||||
if (Array.isArray(pluginsJson?.plugins) && addedPlugins.length > 0) {
|
||||
for (const { pluginDir, source, configSource } of addedPlugins) {
|
||||
const manifest = readManifestFromPackageJson(pluginDir)
|
||||
const newEntry = {
|
||||
@@ -1774,13 +1850,36 @@ export async function handlePluginAdd(
|
||||
|
||||
export async function handlePluginRemove(names) {
|
||||
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
|
||||
const pluginsJson = readPluginsJson()
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
const pluginsJson = edit.json
|
||||
// With `extends`: the plugins the bases configure (without the user's entries). Those can't
|
||||
// be removed from the user's file, only disabled.
|
||||
const basePlugins = edit.extending
|
||||
? ((await resolveEffectiveConfig({ ...pluginsJson, plugins: [] }, getConfigReadPath()))
|
||||
.plugins ?? [])
|
||||
: []
|
||||
let lockfileChanged = false
|
||||
let configChanged = false
|
||||
let removedFiles = false
|
||||
const removedSources = []
|
||||
|
||||
for (const name of names) {
|
||||
const fromBase = findConfigEntries(basePlugins, name, nameHelpers).indices
|
||||
if (fromBase.length > 0) {
|
||||
const label = extractPluginName(basePlugins[fromBase[0]].source)
|
||||
console.log(
|
||||
styleText(
|
||||
"red",
|
||||
`✗ ${label} comes from the configuration ${path.basename(getConfigReadPath())} extends, so it can't be removed from your file.`,
|
||||
),
|
||||
)
|
||||
console.log(
|
||||
styleText("gray", ` Turn it off with 'npx quartz plugin disable ${label}' instead.`),
|
||||
)
|
||||
markFailed()
|
||||
continue
|
||||
}
|
||||
// Prefer the config entry (accepts short names such as "explorer").
|
||||
const { indices } = findConfigEntries(pluginsJson?.plugins ?? [], name, nameHelpers)
|
||||
const configIndex = indices.length === 1 ? indices[0] : -1
|
||||
@@ -1892,7 +1991,9 @@ export async function handlePluginRemove(names) {
|
||||
}
|
||||
|
||||
async function setEnabled(names, enabled) {
|
||||
const json = readPluginsJson()
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
const json = edit.json
|
||||
const verb = enabled ? "enable" : "disable"
|
||||
if (!json) {
|
||||
console.log(styleText("red", `✗ No quartz.config.yaml found. Cannot ${verb} plugins.`))
|
||||
@@ -1903,12 +2004,13 @@ async function setEnabled(names, enabled) {
|
||||
let changed = false
|
||||
for (const name of names) {
|
||||
const builtin = builtinMessage(name)
|
||||
if (builtin && !(json.plugins ?? []).some((e) => officialPluginName(e.source) === name)) {
|
||||
const plugins = Array.isArray(edit.effective.plugins) ? edit.effective.plugins : []
|
||||
if (builtin && !plugins.some((e) => officialPluginName(e.source) === name)) {
|
||||
console.log(styleText("yellow", `⚠ ${builtin}`))
|
||||
markFailed()
|
||||
continue
|
||||
}
|
||||
const resolved = resolveConfigEntryOrReport(json, name)
|
||||
const resolved = resolveConfigEntryOrReport(edit.effective, name)
|
||||
if (!resolved) continue
|
||||
const { entry } = resolved
|
||||
const label = extractPluginName(entry.source)
|
||||
@@ -1917,7 +2019,8 @@ async function setEnabled(names, enabled) {
|
||||
console.log(styleText("gray", `✓ ${label} is already ${verb}d`))
|
||||
continue
|
||||
}
|
||||
entry.enabled = enabled
|
||||
// with `extends`: set in the user's entry for the plugin (added if needed)
|
||||
overlayEntryFor(edit, entry, true).enabled = enabled
|
||||
changed = true
|
||||
console.log(styleText("green", `✓ ${enabled ? "Enabled" : "Disabled"} ${label}`))
|
||||
if (
|
||||
@@ -1962,14 +2065,18 @@ function printOptionIssues(issues, label) {
|
||||
}
|
||||
|
||||
export async function handlePluginConfig(name, options = {}) {
|
||||
const json = readPluginsJson()
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
const json = edit.json
|
||||
if (!json) {
|
||||
console.log(styleText("red", "✗ No quartz.config.yaml found."))
|
||||
markFailed()
|
||||
return
|
||||
}
|
||||
|
||||
const resolved = resolveConfigEntryOrReport(json, name)
|
||||
// `entry` is the plugin as the build sees it (merged with `extends` bases); changes go to
|
||||
// `target`, the user's own entry for it
|
||||
const resolved = resolveConfigEntryOrReport(edit.effective, name)
|
||||
if (!resolved) return
|
||||
const { entry } = resolved
|
||||
const label = extractPluginName(entry.source)
|
||||
@@ -1979,7 +2086,8 @@ export async function handlePluginConfig(name, options = {}) {
|
||||
const unsets = [options.unset ?? []].flat().filter((v) => v !== undefined)
|
||||
|
||||
if (sets.length > 0 || unsets.length > 0) {
|
||||
if (!entry.options || typeof entry.options !== "object") entry.options = {}
|
||||
const target = overlayEntryFor(edit, entry, true)
|
||||
if (!target.options || typeof target.options !== "object") target.options = {}
|
||||
let changed = false
|
||||
for (const assignment of sets) {
|
||||
const eqIndex = String(assignment).indexOf("=")
|
||||
@@ -1996,7 +2104,7 @@ export async function handlePluginConfig(name, options = {}) {
|
||||
continue
|
||||
}
|
||||
const value = parseCliValue(assignment.slice(eqIndex + 1))
|
||||
setOptionPath(entry.options, segments, value)
|
||||
setOptionPath(target.options, segments, value)
|
||||
changed = true
|
||||
console.log(
|
||||
styleText("green", `✓ Set ${label}.${segments.join(".")} = ${JSON.stringify(value)}`),
|
||||
@@ -2010,7 +2118,29 @@ export async function handlePluginConfig(name, options = {}) {
|
||||
}
|
||||
for (const keyPath of unsets) {
|
||||
const segments = parseOptionPath(String(keyPath))
|
||||
if (unsetOptionPath(entry.options, segments)) {
|
||||
if (edit.extending) {
|
||||
// drop the user's value, then reset a value a base still sets with `null` (merging
|
||||
// removes the key, so the plugin's default applies)
|
||||
const hadOwn = unsetOptionPath(target.options, segments)
|
||||
const merged = await resolveEffectiveConfig(json, getConfigReadPath())
|
||||
const key = edit.matchKey(entry.source)
|
||||
const now = (merged.plugins ?? []).findLast((e) => edit.matchKey(e.source) === key)
|
||||
const fromBase = hasOptionPath(now?.options, segments)
|
||||
if (fromBase) setOptionPath(target.options, segments, null)
|
||||
if (hadOwn || fromBase) {
|
||||
changed = true
|
||||
console.log(
|
||||
styleText(
|
||||
"green",
|
||||
`✓ Unset ${label}.${segments.join(".")} (plugin default applies${fromBase ? "; null overrides the extended config" : ""})`,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
console.log(styleText("yellow", `⚠ ${label} has no option "${keyPath}" set`))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (unsetOptionPath(target.options, segments)) {
|
||||
changed = true
|
||||
console.log(
|
||||
styleText("green", `✓ Unset ${label}.${segments.join(".")} (plugin default applies)`),
|
||||
@@ -2102,7 +2232,8 @@ function collectUntrackedEntries(pluginsJson, lockfile) {
|
||||
|
||||
export async function handlePluginList() {
|
||||
const lockfile = readLockfile()
|
||||
const pluginsJson = readPluginsJson()
|
||||
const pluginsJson = await readEffectivePluginsJson()
|
||||
if (!pluginsJson && configExtends(readPluginsJson())) return
|
||||
const { npm, missing } = collectUntrackedEntries(pluginsJson, lockfile)
|
||||
const lockEntries = Object.entries(lockfile?.plugins ?? {})
|
||||
|
||||
@@ -2222,7 +2353,8 @@ export async function handlePluginList() {
|
||||
|
||||
export async function handlePluginStatus() {
|
||||
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
|
||||
const pluginsJson = readPluginsJson()
|
||||
const pluginsJson = await readEffectivePluginsJson()
|
||||
if (!pluginsJson && configExtends(readPluginsJson())) return
|
||||
const { npm } = collectUntrackedEntries(pluginsJson, lockfile)
|
||||
if (Object.keys(lockfile.plugins).length === 0 && npm.length === 0) {
|
||||
console.log(styleText("gray", "No plugins installed"))
|
||||
@@ -2459,7 +2591,23 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
report("info", null, `using ${configLabel} (no quartz.config.yaml yet)`)
|
||||
}
|
||||
|
||||
if (!Array.isArray(config.data?.plugins)) {
|
||||
// With `extends`, check the merged configuration (what the build loads); --fix still edits
|
||||
// only this file.
|
||||
const extending = configExtends(config.data)
|
||||
const effectiveOf = async (data) => (extending ? resolveEffectiveConfig(data, config.path) : data)
|
||||
let effective
|
||||
try {
|
||||
effective = await effectiveOf(config.data)
|
||||
} catch (err) {
|
||||
report("error", configLabel, `extends: ${String(err?.message ?? err)}`)
|
||||
markFailed()
|
||||
return
|
||||
}
|
||||
if (extending) {
|
||||
report("info", null, `${configLabel} uses extends; checking the merged configuration`)
|
||||
}
|
||||
|
||||
if (!Array.isArray(effective?.plugins)) {
|
||||
report("error", configLabel, "`plugins` must be a list")
|
||||
markFailed()
|
||||
return
|
||||
@@ -2474,6 +2622,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
for (const change of changes) console.log(styleText("green", `✓ ${change}`))
|
||||
console.log()
|
||||
config.data = migrated
|
||||
effective = await effectiveOf(migrated)
|
||||
} else {
|
||||
for (const { name, key } of migrations) {
|
||||
report(
|
||||
@@ -2487,9 +2636,11 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
}
|
||||
}
|
||||
const absorbed = new Set(
|
||||
migrations.filter((m) => m.name !== "note-properties").map((m) => m.entry),
|
||||
findBuiltinMigrations(effective)
|
||||
.filter((m) => m.name !== "note-properties")
|
||||
.map((m) => m.entry),
|
||||
)
|
||||
const plugins = config.data.plugins.filter((entry) => !absorbed.has(entry))
|
||||
const plugins = effective.plugins.filter((entry) => !absorbed.has(entry))
|
||||
|
||||
const lockfile = readLockfile()
|
||||
if (fs.existsSync(LOCKFILE_PATH) && !lockfile) {
|
||||
@@ -2669,7 +2820,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
// satisfied by the built-in: its entries were absorbed above.
|
||||
const builtinKey = builtinKeyFor(dep)
|
||||
if (builtinKey) {
|
||||
const builtin = describeBuiltins(config.data.configuration).find(
|
||||
const builtin = describeBuiltins(effective.configuration).find(
|
||||
(b) => b.key === builtinKey,
|
||||
)
|
||||
if (builtin && !builtin.enabled) {
|
||||
@@ -2771,7 +2922,13 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
|
||||
return
|
||||
}
|
||||
|
||||
const pluginsJson = readPluginsJson()
|
||||
// plugins of the merged configuration: a plugin from an `extends` base is not an orphan
|
||||
const pluginsJson = await readEffectivePluginsJson()
|
||||
if (!pluginsJson && configExtends(readPluginsJson())) {
|
||||
console.log(styleText("red", "✗ Not pruning: the configuration could not be resolved."))
|
||||
markFailed()
|
||||
return
|
||||
}
|
||||
const configuredNames = new Set(
|
||||
(pluginsJson?.plugins ?? []).map((entry) => extractPluginName(entry.source)),
|
||||
)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import test, { describe, beforeEach, afterEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { execSync } from "child_process"
|
||||
import { execSync, spawnSync } from "child_process"
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import YAML from "yaml"
|
||||
import {
|
||||
buildPluginAsync,
|
||||
checkoutPinnedCommitAsync,
|
||||
@@ -212,3 +213,84 @@ describe("checkoutPinnedCommitAsync", () => {
|
||||
assert.strictEqual(fs.readFileSync(path.join(dir, "package-lock.json"), "utf-8"), `{ "v": 1 }`)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin commands with an extending config", () => {
|
||||
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
|
||||
// stdout and stderr, whatever the exit code (doctor fails on npm plugins that aren't installed)
|
||||
const run = (dir, args) => {
|
||||
const result = spawnSync(process.execPath, [cli, ...args.split(" ")], {
|
||||
cwd: dir,
|
||||
encoding: "utf-8",
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
|
||||
})
|
||||
return { output: result.stdout + result.stderr, status: result.status }
|
||||
}
|
||||
const site = () => {
|
||||
const dir = path.join(root, "site")
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.0" }`)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.default.yaml"),
|
||||
[
|
||||
"configuration:",
|
||||
" pageTitle: Default",
|
||||
"plugins:",
|
||||
' - source: "@quartz-community/graph"',
|
||||
" enabled: true",
|
||||
" options: { depth: 1, scale: 2 }",
|
||||
' - source: "@quartz-community/comments"',
|
||||
" enabled: false",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.yaml"),
|
||||
[
|
||||
"extends: default",
|
||||
"plugins:",
|
||||
' - source: "@quartz-community/graph"',
|
||||
" options: { depth: 3 }",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
return dir
|
||||
}
|
||||
const read = (dir) => fs.readFileSync(path.join(dir, "quartz.config.yaml"), "utf-8")
|
||||
|
||||
test("list and doctor read the merged configuration", () => {
|
||||
const dir = site()
|
||||
const list = run(dir, "plugin list").output
|
||||
assert.match(list, /@quartz-community\/comments .*disabled/)
|
||||
assert.match(list, /@quartz-community\/graph .*enabled/)
|
||||
const doctor = run(dir, "plugin doctor").output
|
||||
assert.match(doctor, /Checking plugins/)
|
||||
assert.doesNotMatch(doctor, /no `enabled` field/)
|
||||
})
|
||||
|
||||
test("enable, disable and config change only the user's entries", () => {
|
||||
const dir = site()
|
||||
run(dir, "plugin enable comments")
|
||||
run(dir, "plugin disable graph")
|
||||
run(dir, "plugin config graph --unset scale")
|
||||
run(dir, "plugin config graph --unset depth")
|
||||
const out = read(dir)
|
||||
assert.match(out, /^extends: default$/m)
|
||||
assert.doesNotMatch(out, /pageTitle/) // the merged configuration is not written back
|
||||
const data = YAML.parse(out)
|
||||
assert.deepStrictEqual(data.plugins, [
|
||||
// the base sets both: null drops them from the merged options, so the plugin's defaults
|
||||
// apply (the user's own depth: 3 is gone too)
|
||||
{ source: "@quartz-community/graph", options: { depth: null, scale: null }, enabled: false },
|
||||
{ source: "@quartz-community/comments", enabled: true },
|
||||
])
|
||||
})
|
||||
|
||||
test("remove refuses a plugin that comes from a base", () => {
|
||||
const dir = site()
|
||||
const { output, status } = run(dir, "plugin remove comments")
|
||||
assert.match(output, /comes from the configuration/)
|
||||
assert.strictEqual(status, 1)
|
||||
assert.doesNotMatch(read(dir), /comments/)
|
||||
})
|
||||
})
|
||||
@@ -5,7 +5,15 @@
|
||||
// see plugin-validation.d.ts).
|
||||
|
||||
/** Top-level keys allowed on a plugin entry (mirrors quartz-plugins.schema.json). */
|
||||
export const PLUGIN_ENTRY_KEYS = ["source", "enabled", "options", "order", "layout"]
|
||||
export const PLUGIN_ENTRY_KEYS = [
|
||||
"source",
|
||||
"enabled",
|
||||
"options",
|
||||
"order",
|
||||
"before",
|
||||
"after",
|
||||
"layout",
|
||||
]
|
||||
|
||||
/** Keys allowed on an object-form `source`. */
|
||||
export const SOURCE_OBJECT_KEYS = ["repo", "subdir", "ref", "name"]
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -25,17 +25,17 @@ configuration:
|
||||
lightMode:
|
||||
light: "#faf8f8"
|
||||
lightgray: "#e5e5e5"
|
||||
gray: "#b8b8b8"
|
||||
gray: "#727272"
|
||||
darkgray: "#4e4e4e"
|
||||
dark: "#2b2b2b"
|
||||
secondary: "#284b63"
|
||||
tertiary: "#84a59d"
|
||||
tertiary: "#587971"
|
||||
highlight: rgba(143, 159, 169, 0.15)
|
||||
textHighlight: "#fff23688"
|
||||
darkMode:
|
||||
light: "#161618"
|
||||
lightgray: "#393639"
|
||||
gray: "#646464"
|
||||
gray: "#7f7f7f"
|
||||
darkgray: "#d4d4d4"
|
||||
dark: "#ebebec"
|
||||
secondary: "#7b97aa"
|
||||
|
||||
@@ -25,17 +25,17 @@ configuration:
|
||||
lightMode:
|
||||
light: "#faf8f8"
|
||||
lightgray: "#e5e5e5"
|
||||
gray: "#b8b8b8"
|
||||
gray: "#727272"
|
||||
darkgray: "#4e4e4e"
|
||||
dark: "#2b2b2b"
|
||||
secondary: "#284b63"
|
||||
tertiary: "#84a59d"
|
||||
tertiary: "#587971"
|
||||
highlight: rgba(143, 159, 169, 0.15)
|
||||
textHighlight: "#fff23688"
|
||||
darkMode:
|
||||
light: "#161618"
|
||||
lightgray: "#393639"
|
||||
gray: "#646464"
|
||||
gray: "#7f7f7f"
|
||||
darkgray: "#d4d4d4"
|
||||
dark: "#ebebec"
|
||||
secondary: "#7b97aa"
|
||||
|
||||
@@ -26,17 +26,17 @@ configuration:
|
||||
lightMode:
|
||||
light: "#faf8f8"
|
||||
lightgray: "#e5e5e5"
|
||||
gray: "#b8b8b8"
|
||||
gray: "#727272"
|
||||
darkgray: "#4e4e4e"
|
||||
dark: "#2b2b2b"
|
||||
secondary: "#284b63"
|
||||
tertiary: "#84a59d"
|
||||
tertiary: "#587971"
|
||||
highlight: rgba(143, 159, 169, 0.15)
|
||||
textHighlight: "#fff23688"
|
||||
darkMode:
|
||||
light: "#161618"
|
||||
lightgray: "#393639"
|
||||
gray: "#646464"
|
||||
gray: "#7f7f7f"
|
||||
darkgray: "#d4d4d4"
|
||||
dark: "#ebebec"
|
||||
secondary: "#7b97aa"
|
||||
|
||||
@@ -25,17 +25,17 @@ configuration:
|
||||
lightMode:
|
||||
light: "#faf8f8"
|
||||
lightgray: "#e5e5e5"
|
||||
gray: "#b8b8b8"
|
||||
gray: "#727272"
|
||||
darkgray: "#4e4e4e"
|
||||
dark: "#2b2b2b"
|
||||
secondary: "#284b63"
|
||||
tertiary: "#84a59d"
|
||||
tertiary: "#587971"
|
||||
highlight: rgba(143, 159, 169, 0.15)
|
||||
textHighlight: "#fff23688"
|
||||
darkMode:
|
||||
light: "#161618"
|
||||
lightgray: "#393639"
|
||||
gray: "#646464"
|
||||
gray: "#7f7f7f"
|
||||
darkgray: "#d4d4d4"
|
||||
dark: "#ebebec"
|
||||
secondary: "#7b97aa"
|
||||
@@ -44,7 +44,7 @@ configuration:
|
||||
textHighlight: "#b3aa0288"
|
||||
links:
|
||||
markdownLinkResolution: shortest
|
||||
# disableBrokenWikilinks: false # Set true to add a "broken" CSS class to internal links whose target does not exist.
|
||||
# disableBrokenWikilinks: true # Set false to stop adding a "broken" CSS class to internal links whose target does not exist.
|
||||
contentIndex:
|
||||
enableSiteMap: true
|
||||
enableRSS: true
|
||||
@@ -80,6 +80,8 @@ plugins:
|
||||
enableYouTubeEmbed: true
|
||||
enableVideoEmbed: true
|
||||
enableCheckbox: true
|
||||
foldHeadings: true
|
||||
foldLists: true
|
||||
order: 40
|
||||
- source: "@quartz-community/github-flavored-markdown"
|
||||
enabled: true
|
||||
|
||||
@@ -25,17 +25,17 @@ configuration:
|
||||
lightMode:
|
||||
light: "#faf8f8"
|
||||
lightgray: "#e5e5e5"
|
||||
gray: "#b8b8b8"
|
||||
gray: "#727272"
|
||||
darkgray: "#4e4e4e"
|
||||
dark: "#2b2b2b"
|
||||
secondary: "#284b63"
|
||||
tertiary: "#84a59d"
|
||||
tertiary: "#587971"
|
||||
highlight: rgba(143, 159, 169, 0.15)
|
||||
textHighlight: "#fff23688"
|
||||
darkMode:
|
||||
light: "#161618"
|
||||
lightgray: "#393639"
|
||||
gray: "#646464"
|
||||
gray: "#7f7f7f"
|
||||
darkgray: "#d4d4d4"
|
||||
dark: "#ebebec"
|
||||
secondary: "#7b97aa"
|
||||
@@ -44,7 +44,7 @@ configuration:
|
||||
textHighlight: "#b3aa0288"
|
||||
links:
|
||||
markdownLinkResolution: shortest
|
||||
# disableBrokenWikilinks: false # Set true to add a "broken" CSS class to internal links whose target does not exist.
|
||||
# disableBrokenWikilinks: true # Set false to stop adding a "broken" CSS class to internal links whose target does not exist.
|
||||
contentIndex:
|
||||
enableSiteMap: true
|
||||
enableRSS: true
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { h } from "preact"
|
||||
import { render } from "preact-render-to-string"
|
||||
import HeadConstructor from "./Head"
|
||||
import type { QuartzComponentProps } from "./types"
|
||||
|
||||
const Head = HeadConstructor()
|
||||
|
||||
function head(fileData: Record<string, unknown>): string {
|
||||
const props = {
|
||||
cfg: {
|
||||
pageTitle: "Site",
|
||||
baseUrl: "example.org",
|
||||
locale: "en-US",
|
||||
theme: { cdnCaching: false, typography: {} },
|
||||
},
|
||||
fileData: { relativePath: `${fileData.slug}.md`, frontmatter: { title: "T" }, ...fileData },
|
||||
externalResources: { css: [], js: [], additionalHead: [] },
|
||||
ctx: { cfg: { plugins: { emitters: [] } } },
|
||||
} as unknown as QuartzComponentProps
|
||||
return render(h(Head, props))
|
||||
}
|
||||
const meta = (html: string, property: string) =>
|
||||
new RegExp(`<meta property="${property}" content="([^"]*)"`).exec(html)?.[1]
|
||||
|
||||
describe("Head", () => {
|
||||
test("a note whose name ends in 'index' is an article; index pages are not", () => {
|
||||
assert.strictEqual(meta(head({ slug: "reindex" }), "og:type"), "article")
|
||||
assert.strictEqual(meta(head({ slug: "notes/reindex" }), "og:type"), "article")
|
||||
assert.strictEqual(meta(head({ slug: "index" }), "og:type"), "website")
|
||||
assert.strictEqual(meta(head({ slug: "notes/index" }), "og:type"), "website")
|
||||
})
|
||||
|
||||
test("article dates: only real ones (no build-time stand-ins, no invalid published:)", () => {
|
||||
const now = new Date()
|
||||
const real = new Date("2024-05-06T00:00:00")
|
||||
const modified = new Date("2025-01-02T03:04:05.000Z")
|
||||
// created-modified-date >= 1.0.5 marks the stand-ins
|
||||
let html = head({
|
||||
slug: "a",
|
||||
dates: { created: now, modified, published: now },
|
||||
fallbackDates: ["published"],
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:published_time"), undefined)
|
||||
assert.strictEqual(meta(html, "article:modified_time"), modified.toISOString())
|
||||
// older versions: an invalid `published:` gave the build time
|
||||
html = head({
|
||||
slug: "a",
|
||||
frontmatter: { title: "T", published: "not a date" },
|
||||
dates: { created: now, modified, published: now },
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:published_time"), undefined)
|
||||
html = head({
|
||||
slug: "a",
|
||||
frontmatter: { title: "T", published: "2024-05-06" },
|
||||
dates: { created: now, modified, published: real },
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:published_time"), real.toISOString())
|
||||
html = head({
|
||||
slug: "a",
|
||||
dates: { created: now, modified: now, published: now },
|
||||
fallbackDates: ["modified", "published"],
|
||||
})
|
||||
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")
|
||||
})
|
||||
})
|
||||
+28
-10
@@ -1,9 +1,10 @@
|
||||
import { i18n } from "../i18n"
|
||||
import { FullSlug, getFileExtension, joinSegments, pathToRoot } from "../util/path"
|
||||
import { FullSlug, getFileExtension, joinSegments, pathToRoot, simplifySlug } from "../util/path"
|
||||
import { CSSResourceToStyleElement, JSResourceToScriptElement } from "../util/resources"
|
||||
import { googleFontHref, googleFontSubsetHref } from "../util/theme"
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import { unescapeHTML } from "../util/escape"
|
||||
import { realDate } from "../util/dates"
|
||||
|
||||
export default (() => {
|
||||
const Head: QuartzComponent = ({
|
||||
@@ -27,9 +28,23 @@ export default (() => {
|
||||
const baseDir = fileData.slug === "404" ? path : pathToRoot(fileData.slug!)
|
||||
const iconPath = joinSegments(baseDir, "static/icon.png")
|
||||
|
||||
// Url of current page
|
||||
const socialUrl =
|
||||
fileData.slug === "404" ? url.toString() : joinSegments(url.toString(), fileData.slug!)
|
||||
// The page's public URL, as the sitemap lists it: `folder/` for `folder/index`,
|
||||
// no `index` for the home page, encoded.
|
||||
const isNotFound = fileData.slug === "404"
|
||||
const pageUrl = isNotFound
|
||||
? url.toString()
|
||||
: joinSegments(url.toString(), encodeURI(simplifySlug(fileData.slug!)))
|
||||
// Notes (not the home page, folder or tag pages) are articles.
|
||||
const isArticle =
|
||||
!isNotFound &&
|
||||
fileData.relativePath !== undefined &&
|
||||
fileData.slug !== "index" &&
|
||||
!fileData.slug!.endsWith("/index") &&
|
||||
!fileData.slug!.startsWith("tags/")
|
||||
// Real dates only: a date no source gave is the build time (see util/dates), and an
|
||||
// invalid `published:` gives none.
|
||||
const published = isArticle ? realDate(fileData, "published")?.toISOString() : undefined
|
||||
const modified = isArticle ? realDate(fileData, "modified")?.toISOString() : undefined
|
||||
|
||||
const usesCustomOgImage = ctx.cfg.plugins.emitters.some((e) => e.name === "CustomOgImages")
|
||||
const ogImageDefaultPath = `https://${cfg.baseUrl}/static/og-image.png`
|
||||
@@ -50,19 +65,21 @@ export default (() => {
|
||||
{cfg.theme.cdnCaching && cfg.theme.fontOrigin === "googleFonts" && (
|
||||
<>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" />
|
||||
{/* Font files are fetched with CORS, so only a CORS connection is reused. */}
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
|
||||
<link rel="stylesheet" href={googleFontHref(cfg.theme)} />
|
||||
{cfg.theme.typography.title && (
|
||||
<link rel="stylesheet" href={googleFontSubsetHref(cfg.theme, cfg.pageTitle)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossOrigin="anonymous" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
<meta name="og:site_name" content={cfg.pageTitle}></meta>
|
||||
<meta property="og:site_name" content={cfg.pageTitle} />
|
||||
<meta property="og:title" content={title} />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:type" content={isArticle ? "article" : "website"} />
|
||||
{published && <meta property="article:published_time" content={published} />}
|
||||
{modified && <meta property="article:modified_time" content={modified} />}
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content={title} />
|
||||
<meta name="twitter:description" content={description} />
|
||||
@@ -84,8 +101,9 @@ export default (() => {
|
||||
{cfg.baseUrl && (
|
||||
<>
|
||||
<meta property="twitter:domain" content={cfg.baseUrl}></meta>
|
||||
<meta property="og:url" content={socialUrl}></meta>
|
||||
<meta property="twitter:url" content={socialUrl}></meta>
|
||||
<meta property="og:url" content={pageUrl}></meta>
|
||||
<meta property="twitter:url" content={pageUrl}></meta>
|
||||
{!isNotFound && <link rel="canonical" href={pageUrl} />}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -74,14 +74,14 @@ export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit, sort
|
||||
<div class="section">
|
||||
<p class="meta">{page.dates && <Date date={getDate(page)!} locale={cfg.locale} />}</p>
|
||||
<div class="desc">
|
||||
<h3>
|
||||
<h2>
|
||||
<a
|
||||
href={resolveRelative(fileData.slug!, page.slug!)}
|
||||
class="internal internal-link"
|
||||
>
|
||||
{title}
|
||||
</a>
|
||||
</h3>
|
||||
</h2>
|
||||
</div>
|
||||
<ul class="tags">
|
||||
{tags.map((tag) => (
|
||||
@@ -104,8 +104,10 @@ export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit, sort
|
||||
}
|
||||
|
||||
PageList.css = `
|
||||
.section h3 {
|
||||
/* An h2 under the page's h1 (it was an h3, which skipped a level), at the h3's size. */
|
||||
.section h2 {
|
||||
margin: 0;
|
||||
font-size: 1.12rem;
|
||||
}
|
||||
|
||||
.section > .tags {
|
||||
|
||||
@@ -24,12 +24,12 @@ export const DefaultFrame: PageFrame = {
|
||||
}: PageFrameProps) {
|
||||
return (
|
||||
<>
|
||||
<div class="left sidebar" data-sidebar-mode={sidebars?.left ?? "fit"}>
|
||||
<aside class="left sidebar" data-sidebar-mode={sidebars?.left ?? "fit"}>
|
||||
{left.map((BodyComponent) => (
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
<div class="center">
|
||||
</aside>
|
||||
<main class="center">
|
||||
<div class="page-header">
|
||||
<Header {...componentData}>
|
||||
{header.map((HeaderComponent) => (
|
||||
@@ -49,12 +49,12 @@ export const DefaultFrame: PageFrame = {
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div class="right sidebar" data-sidebar-mode={sidebars?.right ?? "fit"}>
|
||||
</main>
|
||||
<aside class="right sidebar" data-sidebar-mode={sidebars?.right ?? "fit"}>
|
||||
{right.map((BodyComponent) => (
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
{footer.map((FooterComponent) => (
|
||||
<FooterComponent {...componentData} />
|
||||
))}
|
||||
|
||||
@@ -23,7 +23,7 @@ export const FullWidthFrame: PageFrame = {
|
||||
}: PageFrameProps) {
|
||||
return (
|
||||
<>
|
||||
<div class="center full-width">
|
||||
<main class="center full-width">
|
||||
<div class="page-header">
|
||||
<Header {...componentData}>
|
||||
{header.map((HeaderComponent) => (
|
||||
@@ -43,7 +43,7 @@ export const FullWidthFrame: PageFrame = {
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
{footer.map((FooterComponent) => (
|
||||
<FooterComponent {...componentData} />
|
||||
))}
|
||||
|
||||
@@ -13,9 +13,9 @@ export const MinimalFrame: PageFrame = {
|
||||
render({ componentData, pageBody: Content, footer }: PageFrameProps) {
|
||||
return (
|
||||
<>
|
||||
<div class="center minimal">
|
||||
<main class="center minimal">
|
||||
<Content {...componentData} />
|
||||
</div>
|
||||
</main>
|
||||
{footer.map((FooterComponent) => (
|
||||
<FooterComponent {...componentData} />
|
||||
))}
|
||||
|
||||
@@ -3,7 +3,9 @@ import { toHtml } from "hast-util-to-html"
|
||||
import assert from "node:assert"
|
||||
import { renderTranscludes, pageResources, transformPageContent } from "./renderPage"
|
||||
import { Root, Element } from "hast"
|
||||
import { FullSlug } from "../util/path"
|
||||
import { FullSlug, setSlugOptions } from "../util/path"
|
||||
import { slugifyFilePath } from "@quartz-community/utils"
|
||||
import vm from "node:vm"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
import { QuartzComponentProps } from "./types"
|
||||
import { StaticResources } from "../util/resources"
|
||||
@@ -49,6 +51,42 @@ function makeComponentData(
|
||||
}
|
||||
|
||||
describe("renderTranscludes", () => {
|
||||
test("wraps transcluded content in Obsidian's embed markup", () => {
|
||||
const root: Root = { type: "root", children: [makeTranscludeBlockquote("target")] }
|
||||
const targetHtml: Root = {
|
||||
type: "root",
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "p",
|
||||
properties: {},
|
||||
children: [{ type: "text", value: "Target content" }],
|
||||
},
|
||||
],
|
||||
}
|
||||
renderTranscludes(
|
||||
root,
|
||||
cfg,
|
||||
"current" as FullSlug,
|
||||
makeComponentData([makePageData("target", targetHtml)]) as QuartzComponentProps,
|
||||
new Set<FullSlug>(["current" as FullSlug]),
|
||||
)
|
||||
const [title, content, link, embedLink] = (root.children[0] as Element).children as Element[]
|
||||
assert.deepStrictEqual(title.properties.className, ["embed-title", "markdown-embed-title"])
|
||||
assert.deepStrictEqual(content.properties.className, ["markdown-embed-content"])
|
||||
const view = content.children[0] as Element
|
||||
assert.deepStrictEqual(view.properties.className, [
|
||||
"markdown-preview-view",
|
||||
"markdown-rendered",
|
||||
])
|
||||
assert.strictEqual((view.children[0] as Element).tagName, "p")
|
||||
assert.deepStrictEqual(link.properties.class, ["internal", "internal-link", "transclude-src"])
|
||||
// Obsidian's icon link to the note, after Quartz's (hidden unless a theme shows it).
|
||||
assert.deepStrictEqual(embedLink.properties.className, ["markdown-embed-link"])
|
||||
assert.strictEqual(embedLink.properties.href, link.properties.href)
|
||||
assert.strictEqual((embedLink.children[0] as Element).tagName, "svg")
|
||||
})
|
||||
|
||||
test("resolves a single page transclusion", () => {
|
||||
const root: Root = {
|
||||
type: "root",
|
||||
@@ -82,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",
|
||||
@@ -184,6 +264,43 @@ describe("renderTranscludes", () => {
|
||||
assert.ok(!secondText.includes("Circular transclusion"), "should not show circular warning")
|
||||
})
|
||||
|
||||
test("a header transclusion finds headings inside Obsidian's block wrappers", () => {
|
||||
const root: Root = {
|
||||
type: "root",
|
||||
children: [makeTranscludeBlockquote("target", "#details")],
|
||||
}
|
||||
const wrap = (tagName: string, properties: Element["properties"], value: string): Element => ({
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { className: [`el-${tagName}`] },
|
||||
children: [{ type: "element", tagName, properties, children: [{ type: "text", value }] }],
|
||||
})
|
||||
const targetHtml: Root = {
|
||||
type: "root",
|
||||
children: [
|
||||
wrap("h2", { id: "intro" }, "Intro"),
|
||||
wrap("p", {}, "Intro text"),
|
||||
wrap("h2", { id: "details" }, "Details"),
|
||||
wrap("p", {}, "Details text"),
|
||||
wrap("h2", { id: "after" }, "After"),
|
||||
wrap("p", {}, "After text"),
|
||||
],
|
||||
}
|
||||
|
||||
renderTranscludes(
|
||||
root,
|
||||
cfg,
|
||||
"current" as FullSlug,
|
||||
makeComponentData([makePageData("target", targetHtml)]) as QuartzComponentProps,
|
||||
new Set<FullSlug>(["current" as FullSlug]),
|
||||
)
|
||||
|
||||
const html = toHtml(root.children[0] as Element)
|
||||
assert.ok(html.includes('<div class="el-p"><p>Details text</p></div>'), html)
|
||||
assert.ok(!html.includes("Intro text"), "the slice starts at its heading")
|
||||
assert.ok(!html.includes("After text"), "the slice ends at the next heading")
|
||||
})
|
||||
|
||||
test("a header transclusion matches a heading's Obsidian-anchor alias", () => {
|
||||
const root: Root = {
|
||||
type: "root",
|
||||
@@ -386,6 +503,40 @@ describe("pageResources", () => {
|
||||
)
|
||||
})
|
||||
|
||||
const inlineScript = (result: ReturnType<typeof pageResources>) =>
|
||||
result.js
|
||||
.filter((j) => j.contentType === "inline")
|
||||
.map((j) => ("script" in j ? j.script : ""))
|
||||
.join("\n")
|
||||
|
||||
test("slugs.stripDiacritics reaches scripts in the browser (#2410)", () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
const script = inlineScript(pageResources("." as FullSlug, emptyResources))
|
||||
// run it as the page does; the global it sets is the one utils reads
|
||||
const page = vm.createContext({
|
||||
fetch: () => new Promise(() => {}),
|
||||
location: { href: "https://x/" },
|
||||
URL,
|
||||
})
|
||||
vm.runInContext(script.replace("window.", "globalThis."), page)
|
||||
const set = vm.runInContext(
|
||||
`JSON.stringify(globalThis[Symbol.for("@quartz-community/utils/slugOptions")])`,
|
||||
page,
|
||||
)
|
||||
assert.strictEqual(set, JSON.stringify({ stripDiacritics: true }))
|
||||
// same global as utils in this thread: a script with utils 1.3 slugs as the build does
|
||||
assert.strictEqual(slugifyFilePath("české/čeština.md" as never), "ceske/cestina")
|
||||
} finally {
|
||||
setSlugOptions(undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test("the default slug options write nothing to the page", () => {
|
||||
const script = inlineScript(pageResources("." as FullSlug, emptyResources))
|
||||
assert.ok(!script.includes("slugOptions"), script)
|
||||
})
|
||||
|
||||
test("omits subpath prefix when baseDir is empty (serve mode)", () => {
|
||||
const result = pageResources("." as FullSlug, emptyResources)
|
||||
for (const css of result.css) {
|
||||
|
||||
@@ -7,7 +7,13 @@ import {
|
||||
JSResourceToScriptElement,
|
||||
StaticResources,
|
||||
} from "../util/resources"
|
||||
import { FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path"
|
||||
import {
|
||||
FullSlug,
|
||||
RelativeURL,
|
||||
getSlugOptions,
|
||||
joinSegments,
|
||||
normalizeHastElement,
|
||||
} from "../util/path"
|
||||
import { clone } from "../util/clone"
|
||||
import { Root, Element, ElementContent } from "hast"
|
||||
import { GlobalConfiguration, SidebarModes } from "../cfg"
|
||||
@@ -15,7 +21,7 @@ import { i18n } from "../i18n"
|
||||
import { styleText } from "util"
|
||||
import { resolveFrame } from "./frames"
|
||||
import type { PageTreeTransforms, TreeTransform } from "../plugins/types"
|
||||
import { createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
import { blockOf, createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
import type { BuildCtx } from "../util/ctx"
|
||||
|
||||
interface RenderComponents {
|
||||
@@ -51,6 +57,17 @@ function headingHasId(heading: Element, id: string): boolean {
|
||||
)
|
||||
return hasAlias(heading)
|
||||
}
|
||||
/**
|
||||
* `configuration.slugs` for scripts in the browser. @quartz-community/utils (1.3+) keeps its slug
|
||||
* options on this global, so every plugin script that slugs (the explorer places pages by their
|
||||
* file path) slugs as the build did. Nothing is written with the default options.
|
||||
*/
|
||||
export function slugOptionsScript(): string {
|
||||
const options = getSlugOptions()
|
||||
if (!options.stripDiacritics) return ""
|
||||
return `;globalThis[Symbol.for("@quartz-community/utils/slugOptions")] = ${JSON.stringify(options)}`
|
||||
}
|
||||
|
||||
export function pageResources(
|
||||
baseDir: FullSlug | RelativeURL,
|
||||
staticResources: StaticResources,
|
||||
@@ -102,7 +119,8 @@ export function pageResources(
|
||||
`.catch(e => { console.warn("[Quartz] Could not load ${contentIndexPath} (" + e.message + "); is configuration.contentIndex disabled?"); return {} });` +
|
||||
// Absolute URL of static/ (plugin assets live in static/plugins/<to>). Resolved once on the
|
||||
// first page, so it stays valid across SPA navigations.
|
||||
`window.quartzStaticUrl = new URL(${JSON.stringify(joinSegments(baseDir, "static") + "/")}, location.href).href`
|
||||
`window.quartzStaticUrl = new URL(${JSON.stringify(joinSegments(baseDir, "static") + "/")}, location.href).href` +
|
||||
slugOptionsScript()
|
||||
|
||||
const resources: StaticResources = {
|
||||
css: [
|
||||
@@ -139,6 +157,73 @@ export function pageResources(
|
||||
return resources
|
||||
}
|
||||
|
||||
/** Lucide's maximize-2, Obsidian's icon for opening an embedded note. */
|
||||
const MAXIMIZE_ICON: Element = {
|
||||
type: "element",
|
||||
tagName: "svg",
|
||||
properties: {
|
||||
xmlns: "http://www.w3.org/2000/svg",
|
||||
width: "24",
|
||||
height: "24",
|
||||
viewBox: "0 0 24 24",
|
||||
fill: "none",
|
||||
stroke: "currentColor",
|
||||
strokeWidth: "2",
|
||||
strokeLinecap: "round",
|
||||
strokeLinejoin: "round",
|
||||
className: ["svg-icon", "lucide-maximize-2"],
|
||||
},
|
||||
children: ["M15 3h6v6", "m21 3-7 7", "m3 21 7-7", "M9 21H3v-6"].map((d) => ({
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: { d },
|
||||
children: [],
|
||||
})),
|
||||
}
|
||||
|
||||
/**
|
||||
* Obsidian's embed markup around transcluded content, so Obsidian themes' embed
|
||||
* styles apply: the title (the note's, for a whole-note embed), then the content in a
|
||||
* rendered view, then Quartz's link to the original, then Obsidian's icon link to it
|
||||
* (`.markdown-embed-link`), which Quartz hides and Obsidian's styles show.
|
||||
*/
|
||||
function obsidianEmbed(title: string, content: ElementContent[], link: Element): ElementContent[] {
|
||||
const embedLink: Element = {
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: {
|
||||
href: link.properties.href,
|
||||
className: ["markdown-embed-link"],
|
||||
ariaLabel: (link.children[0] as { value?: string } | undefined)?.value,
|
||||
dataNoPopover: true,
|
||||
},
|
||||
children: [structuredClone(MAXIMIZE_ICON)],
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { className: ["embed-title", "markdown-embed-title"] },
|
||||
children: title ? [{ type: "text", value: title }] : [],
|
||||
},
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { className: ["markdown-embed-content"] },
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { className: ["markdown-preview-view", "markdown-rendered"] },
|
||||
children: content,
|
||||
},
|
||||
],
|
||||
},
|
||||
link,
|
||||
embedLink,
|
||||
]
|
||||
}
|
||||
|
||||
/** @internal Exported for testing only. */
|
||||
export function renderTranscludes(
|
||||
root: Root,
|
||||
@@ -172,6 +257,15 @@ export function renderTranscludes(
|
||||
}
|
||||
|
||||
const inner = el.children[0] as Element
|
||||
const linkToOriginal = (): Element => ({
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: {
|
||||
href: inner.properties?.href,
|
||||
class: ["internal", "internal-link", "transclude-src"],
|
||||
},
|
||||
children: [{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal }],
|
||||
})
|
||||
const transcludeTarget = (inner.properties["data-slug"] ?? slug) as FullSlug
|
||||
if (visited.has(transcludeTarget)) {
|
||||
console.warn(
|
||||
@@ -214,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") {
|
||||
@@ -227,20 +322,11 @@ export function renderTranscludes(
|
||||
}
|
||||
}
|
||||
|
||||
el.children = [
|
||||
normalizeHastElement(blockNode, slug, transcludeTarget),
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: {
|
||||
href: inner.properties?.href,
|
||||
class: ["internal", "internal-link", "transclude-src"],
|
||||
},
|
||||
children: [
|
||||
{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal },
|
||||
],
|
||||
},
|
||||
]
|
||||
el.children = obsidianEmbed(
|
||||
"",
|
||||
[normalizeHastElement(blockNode, slug, transcludeTarget)],
|
||||
linkToOriginal(),
|
||||
)
|
||||
}
|
||||
} else if (blockRef?.startsWith("#") && page.htmlAst) {
|
||||
// header transclude
|
||||
@@ -248,7 +334,9 @@ export function renderTranscludes(
|
||||
let startIdx = undefined
|
||||
let startDepth = undefined
|
||||
let endIdx = undefined
|
||||
for (const [i, htmlEl] of page.htmlAst.children.entries()) {
|
||||
for (const [i, child] of page.htmlAst.children.entries()) {
|
||||
// The heading, inside its block wrapper if it has one (`div.el-h2 > h2`).
|
||||
const htmlEl = blockOf(child as ElementContent)
|
||||
if (!(htmlEl.type === "element" && htmlEl.tagName.match(headerRegex))) continue
|
||||
const depth = Number(htmlEl.tagName.substring(1))
|
||||
|
||||
@@ -268,55 +356,25 @@ export function renderTranscludes(
|
||||
continue
|
||||
}
|
||||
|
||||
el.children = [
|
||||
...sliceWithFootnotes(page.htmlAst.children as ElementContent[], startIdx, endIdx).map(
|
||||
(c) => normalizeHastElement(c as Element, slug, transcludeTarget),
|
||||
),
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: {
|
||||
href: inner.properties?.href,
|
||||
class: ["internal", "internal-link", "transclude-src"],
|
||||
},
|
||||
children: [
|
||||
{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal },
|
||||
],
|
||||
},
|
||||
]
|
||||
} else if (page.htmlAst) {
|
||||
// page transclude
|
||||
el.children = [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "h1",
|
||||
properties: {},
|
||||
children: [
|
||||
{
|
||||
type: "text",
|
||||
value:
|
||||
page.frontmatter?.title ??
|
||||
i18n(cfg.locale).components.transcludes.transcludeOf({
|
||||
targetSlug: page.slug!,
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
...(page.htmlAst.children as ElementContent[]).map((c) =>
|
||||
el.children = obsidianEmbed(
|
||||
"",
|
||||
sliceWithFootnotes(page.htmlAst.children as ElementContent[], startIdx, endIdx).map((c) =>
|
||||
normalizeHastElement(c as Element, slug, transcludeTarget),
|
||||
),
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: {
|
||||
href: inner.properties?.href,
|
||||
class: ["internal", "internal-link", "transclude-src"],
|
||||
},
|
||||
children: [
|
||||
{ type: "text", value: i18n(cfg.locale).components.transcludes.linkToOriginal },
|
||||
],
|
||||
},
|
||||
]
|
||||
linkToOriginal(),
|
||||
)
|
||||
} else if (page.htmlAst) {
|
||||
// page transclude
|
||||
el.children = obsidianEmbed(
|
||||
page.frontmatter?.title ??
|
||||
i18n(cfg.locale).components.transcludes.transcludeOf({
|
||||
targetSlug: page.slug!,
|
||||
}),
|
||||
(page.htmlAst.children as ElementContent[]).map((c) =>
|
||||
normalizeHastElement(c as Element, slug, transcludeTarget),
|
||||
),
|
||||
linkToOriginal(),
|
||||
)
|
||||
}
|
||||
|
||||
// Recurse into the replaced children to resolve nested transclusions,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -62,6 +62,67 @@ function stopLoading() {
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll positions are restored by the router, not the browser (#2674). The browser
|
||||
// saves an entry's position when `pushState` runs and restores it on Back while the
|
||||
// *other* page's content is still shown, before the router swaps the page in, so
|
||||
// positions came out wrong. Each entry keeps its own `scrollY` in `history.state`.
|
||||
history.scrollRestoration = "manual"
|
||||
let renderedPath = window.location.pathname
|
||||
let saveTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
// 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 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
|
||||
}
|
||||
|
||||
/** Scrolls to where the current entry was left, else to its `#heading`, else to the top. */
|
||||
function restoreScroll() {
|
||||
const y = savedScroll()
|
||||
if (y !== undefined) {
|
||||
window.scrollTo({ top: y, behavior: "instant" })
|
||||
return
|
||||
}
|
||||
const hash = window.location.hash
|
||||
const el = hash ? document.getElementById(decodeURIComponent(hash.substring(1))) : null
|
||||
if (el) el.scrollIntoView({ behavior: "instant" })
|
||||
else window.scrollTo({ top: 0, behavior: "instant" })
|
||||
}
|
||||
|
||||
let isNavigating = false
|
||||
let p: DOMParser
|
||||
async function _navigate(url: URL, isBack: boolean = false) {
|
||||
@@ -104,6 +165,10 @@ async function _navigate(url: URL, isBack: boolean = false) {
|
||||
|
||||
if (!contents) return
|
||||
|
||||
// Keep the position of the page being left, for Back. (On Back, the entry has
|
||||
// already changed: what's on screen belongs to another entry.)
|
||||
if (!isBack) saveScroll()
|
||||
|
||||
// notify about to nav
|
||||
const event: CustomEventMap["prenav"] = new CustomEvent("prenav", { detail: {} })
|
||||
document.dispatchEvent(event)
|
||||
@@ -132,13 +197,13 @@ async function _navigate(url: URL, isBack: boolean = false) {
|
||||
micromorph(document.body, html.body)
|
||||
|
||||
// scroll into place and add history
|
||||
if (!isBack) {
|
||||
if (url.hash) {
|
||||
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
|
||||
el?.scrollIntoView()
|
||||
} else {
|
||||
window.scrollTo({ top: 0 })
|
||||
}
|
||||
if (isBack) {
|
||||
restoreScroll()
|
||||
} else if (url.hash) {
|
||||
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
|
||||
el?.scrollIntoView()
|
||||
} else {
|
||||
window.scrollTo({ top: 0 })
|
||||
}
|
||||
|
||||
// now, patch head, re-executing scripts
|
||||
@@ -150,8 +215,9 @@ 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
|
||||
|
||||
notifyNav(getFullSlug(window))
|
||||
delete announcer.dataset.persist
|
||||
@@ -182,21 +248,52 @@ function createRouter() {
|
||||
event.preventDefault()
|
||||
|
||||
if (isSamePage(url) && url.hash) {
|
||||
// Save where the reader was, then add the entry, then jump: Back returns here.
|
||||
saveScroll()
|
||||
pushEntry(url)
|
||||
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
|
||||
el?.scrollIntoView()
|
||||
history.pushState({}, "", url)
|
||||
return
|
||||
}
|
||||
|
||||
navigate(url, false)
|
||||
})
|
||||
|
||||
window.addEventListener("popstate", (event) => {
|
||||
const { url } = getOpts(event) ?? {}
|
||||
if (window.location.hash && window.location.pathname === url?.pathname) return
|
||||
window.addEventListener("popstate", () => {
|
||||
// Whatever is pending belongs to the entry just left: 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()
|
||||
return
|
||||
}
|
||||
navigate(new URL(window.location.toString()), true)
|
||||
return
|
||||
})
|
||||
|
||||
// Record the position as the reader scrolls, so that Forward (and Back to an
|
||||
// entry left without a link) also lands where the reader was.
|
||||
window.addEventListener(
|
||||
"scroll",
|
||||
() => {
|
||||
if (isNavigating) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => {
|
||||
if (!isNavigating) saveScroll()
|
||||
}, 150)
|
||||
},
|
||||
{ passive: true },
|
||||
)
|
||||
// A reload or a return from another site: the browser no longer restores it.
|
||||
window.addEventListener("pagehide", () => {
|
||||
if (!isNavigating) saveScroll()
|
||||
})
|
||||
shownKey = entryKey()
|
||||
if (savedScroll() !== undefined) restoreScroll()
|
||||
}
|
||||
|
||||
return new (class Router {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import type { Element, ElementContent } from "hast"
|
||||
import { createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
import { blockOf, createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
|
||||
const h = (
|
||||
tagName: string,
|
||||
@@ -113,3 +113,40 @@ describe("sliceWithFootnotes", () => {
|
||||
assert.deepStrictEqual(footnoteIds(sliceWithFootnotes(plain, 0, undefined)), [])
|
||||
})
|
||||
})
|
||||
|
||||
describe("block wrappers", () => {
|
||||
const wrap = (block: Element) => h("div", { className: [`el-${block.tagName}`] }, [block])
|
||||
const page: ElementContent[] = [
|
||||
wrap(h("h2", { id: "a" }, [text("A")])),
|
||||
text("\n"),
|
||||
wrap(h("p", {}, [h("a", { href: "#user-content-fn-1", dataFootnoteRef: "" }, [text("1")])])),
|
||||
text("\n"),
|
||||
wrap(
|
||||
h("section", { dataFootnotes: "", className: ["footnotes"] }, [
|
||||
h("ol", {}, [h("li", { id: "user-content-fn-1" }), h("li", { id: "user-content-fn-2" })]),
|
||||
]),
|
||||
),
|
||||
]
|
||||
|
||||
test("blockOf looks through Obsidian's per-block wrapper", () => {
|
||||
assert.strictEqual((blockOf(page[0]!) as Element).tagName, "h2")
|
||||
const plain = h("p")
|
||||
assert.strictEqual(blockOf(plain), plain)
|
||||
const callout = h("div", { className: ["callout"] }, [h("p")])
|
||||
assert.strictEqual(blockOf(callout), callout)
|
||||
})
|
||||
|
||||
test("a heading slice gets its footnotes in the section's wrapper", () => {
|
||||
const slice = sliceWithFootnotes(page, 0, undefined)
|
||||
const wrappers = slice.filter((n): n is Element => n.type === "element")
|
||||
assert.deepStrictEqual(
|
||||
wrappers.map((w) => w.properties.className),
|
||||
[["el-h2"], ["el-p"], ["el-section"]],
|
||||
)
|
||||
const section = wrappers[2]!.children[0] as Element
|
||||
const ids = ((section.children[0] as Element).children as Element[]).map(
|
||||
(li) => li.properties.id,
|
||||
)
|
||||
assert.deepStrictEqual(ids, ["user-content-fn-1"])
|
||||
})
|
||||
})
|
||||
@@ -91,7 +91,21 @@ export function scopeTranscludedIds(el: Element, prefix: string, sourceHref?: st
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The block inside Obsidian's per-block wrapper (`div.el-p > p`, `div.el-h2 > h2`), which
|
||||
* `@quartz-community/rehype-obsidian` renders around each of a note's top-level blocks; any other
|
||||
* node is its own block. Code walking a page's top-level blocks looks through the wrappers.
|
||||
*/
|
||||
export function blockOf(node: ElementContent): ElementContent {
|
||||
if (node.type !== "element" || node.tagName !== "div") return node
|
||||
const classes = ([] as unknown[]).concat(node.properties?.className ?? [])
|
||||
if (!classes.some((c) => /^el-[a-z0-9]+$/.test(String(c)))) return node
|
||||
const inner = node.children.filter((c) => c.type === "element")
|
||||
return inner.length === 1 ? inner[0]! : node
|
||||
}
|
||||
|
||||
function isFootnotesSection(node: ElementContent): node is Element {
|
||||
node = blockOf(node)
|
||||
if (node.type !== "element" || node.tagName !== "section") return false
|
||||
const props = node.properties ?? {}
|
||||
const classes = (props.className ?? []) as string[]
|
||||
@@ -101,7 +115,8 @@ function isFootnotesSection(node: ElementContent): node is Element {
|
||||
/**
|
||||
* A heading transclusion: the slice of the page from the heading to the next one of the same or
|
||||
* a higher level. The page's footnotes section is not part of the section; the footnotes the
|
||||
* slice references are added after it (in a copy of the section holding only those).
|
||||
* slice references are added after it (in a copy of the section holding only those, in its block
|
||||
* wrapper if it has one).
|
||||
*/
|
||||
export function sliceWithFootnotes(
|
||||
pageChildren: ElementContent[],
|
||||
|
||||
@@ -7,13 +7,20 @@ import { VFile } from "vfile"
|
||||
import { Element, Root, Text } from "hast"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { BUILTINS, instantiateBuiltins, officialPluginName, planBuiltins, PlanInput } from "."
|
||||
import { normalizePluginName, orderPlugins } from "../loader/plugin-order"
|
||||
import {
|
||||
Frontmatter,
|
||||
normalizeFrontmatter,
|
||||
extractLinksFromValue,
|
||||
readFrontmatterData,
|
||||
} from "./frontmatter"
|
||||
import { Links } from "./links"
|
||||
import {
|
||||
Links,
|
||||
LinksInstance,
|
||||
markLinksToRemovedPages,
|
||||
markUnpublishedLinks,
|
||||
removedPages,
|
||||
} from "./links"
|
||||
import {
|
||||
buildLayeredCSS,
|
||||
buildUnlayeredCSS,
|
||||
@@ -34,7 +41,8 @@ import {
|
||||
import type { PluginJsonEntry } from "../loader/types"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { ContentDetails } from "../types"
|
||||
import type { FullSlug } from "../../util/path"
|
||||
import type { 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 => ({
|
||||
@@ -180,6 +188,39 @@ describe("planBuiltins", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin order constraints naming a replaced plugin", () => {
|
||||
test("after: crawl-links / before: remove-draft order against the built-in", () => {
|
||||
const transformers = instantiateBuiltins(plan([]), "transformer")
|
||||
const links = transformers.find((b) => b.instance.name === "Links")!
|
||||
assert.ok(links.names.includes("crawl-links"))
|
||||
const known = new Set(
|
||||
[...transformers.flatMap((b) => b.names), "my-plugin"].map(normalizePluginName),
|
||||
)
|
||||
// same order as Links (60): without the mapping the constraint was ignored and the list
|
||||
// order (built-ins first) put Links first anyway, so run it before
|
||||
const mine = {
|
||||
order: 60,
|
||||
instance: { name: "Mine" },
|
||||
label: "my-plugin",
|
||||
names: ["my-plugin"],
|
||||
before: ["crawl-links"],
|
||||
}
|
||||
const ordered = orderPlugins(
|
||||
[
|
||||
...transformers.map((b) => ({
|
||||
order: b.order,
|
||||
instance: b.instance as { name: string },
|
||||
label: b.instance.name,
|
||||
names: b.names,
|
||||
})),
|
||||
mine,
|
||||
],
|
||||
known,
|
||||
).map((i) => i.name)
|
||||
assert.ok(ordered.indexOf("Mine") < ordered.indexOf("Links"), ordered.join(", "))
|
||||
})
|
||||
})
|
||||
|
||||
describe("frontmatter built-in", () => {
|
||||
const ctx = () => ({ allSlugs: [] as FullSlug[] }) as unknown as BuildCtx
|
||||
|
||||
@@ -223,6 +264,63 @@ describe("frontmatter built-in", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("frontmatter Markdown links with an angle-bracket destination drop the brackets", () => {
|
||||
assert.deepStrictEqual(
|
||||
extractLinksFromValue([
|
||||
"[Exec Briefing](<./Exec Briefing.md>)",
|
||||
"[x](<./Exec Briefing.md#Next steps>)",
|
||||
"[y](./Exec Briefing.md)",
|
||||
]),
|
||||
["./Exec Briefing.md", "./Exec Briefing.md#Next steps", "./Exec Briefing.md"],
|
||||
)
|
||||
})
|
||||
|
||||
test("frontmatter Markdown links: parentheses, titles and escapes as CommonMark reads them (#2672)", () => {
|
||||
assert.deepStrictEqual(
|
||||
extractLinksFromValue([
|
||||
"[b](<Note (2024).md>)",
|
||||
'[c](<My Note.md> "t")',
|
||||
"[d](notes/Note_(2024).md)",
|
||||
"[e](other.md 'single')",
|
||||
"[f](other.md (paren title))",
|
||||
'[g](<a b.md> "t" )',
|
||||
"[h](a\\(1\\).md)",
|
||||
"[i](./My Note.md)",
|
||||
"[j](unclosed.md",
|
||||
"two: [k](k.md) and [l](<l l.md>)",
|
||||
]),
|
||||
[
|
||||
"Note (2024).md",
|
||||
"My Note.md",
|
||||
"notes/Note_(2024).md",
|
||||
"other.md",
|
||||
"other.md",
|
||||
"a b.md",
|
||||
"a(1).md",
|
||||
"./My Note.md",
|
||||
"k.md",
|
||||
"l l.md",
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("reads YAML frontmatter with YAML 1.2's core schema, as Obsidian does", () => {
|
||||
const data = readFrontmatterData(
|
||||
"---\ntitle: Hello world\ndate: 2024-01-02\ndraft: True\nn: 012\nnone: ~\nratio: .5\nalias: yes\n---\n",
|
||||
)
|
||||
assert.deepStrictEqual(data, {
|
||||
title: "Hello world",
|
||||
date: "2024-01-02",
|
||||
draft: true,
|
||||
n: 12,
|
||||
none: null,
|
||||
ratio: 0.5,
|
||||
alias: "yes",
|
||||
})
|
||||
// a block without a document holds no properties
|
||||
assert.deepStrictEqual(readFrontmatterData("---\n# only a comment\n---\nbody\n"), {})
|
||||
})
|
||||
|
||||
test("refuses JavaScript frontmatter instead of executing it", async () => {
|
||||
const g = globalThis as { __quartzFrontmatterRan?: boolean }
|
||||
delete g.__quartzFrontmatterRan
|
||||
@@ -337,11 +435,83 @@ describe("links built-in", () => {
|
||||
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
|
||||
})
|
||||
|
||||
test("slugs.stripDiacritics: link targets are stripped like the slugs they point at (#2410)", () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
const img: Element = {
|
||||
type: "element",
|
||||
tagName: "img",
|
||||
properties: { src: "obr%C3%A1zek.png" },
|
||||
children: [],
|
||||
}
|
||||
const { els, file } = run(
|
||||
[a("./%C4%8Ce%C5%A1tina#%C4%8Cesk%C3%BD-nadpis", "Čeština"), a("Příliš"), img],
|
||||
"ceske/page",
|
||||
{ markdownLinkResolution: "shortest" },
|
||||
["ceske/page", "ceske/cestina", "jine/prilis", "ceske/obrazek.png"],
|
||||
)
|
||||
const [cestina, prilis] = els.filter((e) => e.tagName === "a")
|
||||
assert.strictEqual(cestina.properties.href, "../ceske/cestina#český-nadpis")
|
||||
assert.ok(!(cestina.properties.className as string[]).includes("broken"))
|
||||
assert.strictEqual(prilis.properties.href, "../jine/prilis")
|
||||
assert.strictEqual(
|
||||
els.find((e) => e.tagName === "img")!.properties.src,
|
||||
"../ceske/obrazek.png",
|
||||
)
|
||||
assert.ok(file.data.links?.includes("ceske/cestina" as SimpleSlug))
|
||||
} finally {
|
||||
setSlugOptions(undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test("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",
|
||||
"jine/příliš",
|
||||
])
|
||||
assert.strictEqual(els[0].properties.href, "./jine/příliš")
|
||||
})
|
||||
|
||||
test("footnote anchors stay internal without Obsidian's note-link class", () => {
|
||||
const fn = (props: Record<string, unknown>): Element => ({
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: "#user-content-fn-1", ...props },
|
||||
children: [{ type: "text", value: "1" }],
|
||||
})
|
||||
const { els } = run([fn({ dataFootnoteRef: "" }), fn({ dataFootnoteBackref: "" })])
|
||||
for (const el of els.filter((e) => e.tagName === "a")) {
|
||||
const classes = el.properties.className as string[]
|
||||
assert.ok(classes.includes("internal"))
|
||||
assert.ok(!classes.includes("internal-link"))
|
||||
}
|
||||
})
|
||||
|
||||
test("makes internal links relative, records outgoing links, marks external ones", () => {
|
||||
const { els, file } = run(
|
||||
[a("other/note", "Note"), a("https://example.com"), a("#heading")],
|
||||
"folder/page",
|
||||
{ markdownLinkResolution: "absolute" },
|
||||
["folder/page", "other/note"],
|
||||
)
|
||||
const [internal, external] = els.filter((e) => e.tagName === "a")
|
||||
assert.strictEqual(internal.properties.href, "../other/note")
|
||||
@@ -435,6 +605,62 @@ describe("links built-in", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("missing targets get the broken class by default, as Obsidian marks them", () => {
|
||||
const { els } = run([a("missing"), a("page")], "page", {}, ["page"])
|
||||
assert.ok((els[0].properties.className as string[]).includes("broken"))
|
||||
assert.ok(!(els[1].properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("tag and folder pages, generated later, are not broken", () => {
|
||||
const { els } = run([a("tags/specimen"), a("folder/"), a("empty/")], "page", {}, [
|
||||
"page",
|
||||
"folder/note",
|
||||
])
|
||||
const broken = els.map((e) => (e.properties.className as string[]).includes("broken"))
|
||||
assert.deepStrictEqual(broken, [false, false, true])
|
||||
})
|
||||
|
||||
test("links to files Quartz emits are not broken; missing vault files are", () => {
|
||||
const targets = [
|
||||
"/index.xml",
|
||||
"/sitemap.xml",
|
||||
"/static/icon.png",
|
||||
"/robots.txt",
|
||||
"/404.html",
|
||||
"/page.html",
|
||||
"/pic.png",
|
||||
"/missing.png",
|
||||
"/missing.pdf",
|
||||
"/missing.html",
|
||||
"/v1.2",
|
||||
]
|
||||
const { els } = run(
|
||||
targets.map((t) => a(t)),
|
||||
"page",
|
||||
{},
|
||||
["page", "pic.png"],
|
||||
)
|
||||
const broken = els.map((e) => (e.properties.className as string[]).includes("broken"))
|
||||
assert.deepStrictEqual(broken, [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
])
|
||||
})
|
||||
|
||||
test("disableBrokenWikilinks: false leaves missing targets unmarked", () => {
|
||||
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: false }, ["page"])
|
||||
assert.ok(!(els[0].properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("disableBrokenWikilinks adds a broken class to missing targets", () => {
|
||||
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: true }, ["page"])
|
||||
assert.ok((els[0].properties.className as string[]).includes("broken"))
|
||||
@@ -490,6 +716,99 @@ describe("content index built-in", () => {
|
||||
])
|
||||
})
|
||||
|
||||
test("writes the page date to contentIndex.json as an ISO string (explorer#5)", () => {
|
||||
const created = new Date("2024-01-02T03:04:05.000Z")
|
||||
const modified = new Date("2025-06-07T08:09:10.000Z")
|
||||
const dated = page("dated", { defaultDateType: "created", dates: { created, modified } })
|
||||
const idx = buildContentIndex(ctxWith([]), [dated, page("undated")])
|
||||
const json = JSON.parse(serializeContentIndex(idx))
|
||||
assert.strictEqual(json.dated.date, "2024-01-02T03:04:05.000Z")
|
||||
assert.ok(!("description" in json.dated))
|
||||
// pages without a date keep the build-time stand-in for RSS, but not in the JSON
|
||||
assert.ok(idx.get("undated" as FullSlug)!.date instanceof Date)
|
||||
assert.ok(!("date" in json.undated))
|
||||
})
|
||||
|
||||
test("dateFromFrontmatter marks dates set in frontmatter for the configured type", () => {
|
||||
const fmModified = new Date("2024-03-04T00:00:00") // local midnight, like the date plugin
|
||||
const gitModified = new Date("2025-01-01T10:00:00.000Z")
|
||||
const created = new Date("2020-01-01T00:00:00.000Z")
|
||||
const fromFm = page("fm", {
|
||||
defaultDateType: "modified",
|
||||
frontmatter: { title: "FM", modified: "2024-03-04" },
|
||||
dates: { created, modified: fmModified },
|
||||
})
|
||||
const fromGit = page("git", {
|
||||
defaultDateType: "modified",
|
||||
frontmatter: { title: "GIT", created: "2020-01-01T00:00:00.000Z" },
|
||||
dates: { created, modified: gitModified },
|
||||
})
|
||||
// frontmatter has a date, but for another type than the configured one
|
||||
const otherType = page("other", {
|
||||
defaultDateType: "created",
|
||||
frontmatter: { title: "O", modified: "2024-03-04" },
|
||||
dates: { created: gitModified, modified: fmModified },
|
||||
})
|
||||
// frontmatter value lost to a higher-priority source (date differs)
|
||||
const overridden = page("over", {
|
||||
defaultDateType: "modified",
|
||||
frontmatter: { title: "OV", modified: "2023-01-01" },
|
||||
dates: { created, modified: gitModified },
|
||||
})
|
||||
const json = JSON.parse(
|
||||
serializeContentIndex(
|
||||
buildContentIndex(ctxWith([]), [fromFm, fromGit, otherType, overridden, page("undated")]),
|
||||
),
|
||||
)
|
||||
assert.strictEqual(json.fm.dateFromFrontmatter, true)
|
||||
assert.strictEqual(json.fm.date, fmModified.toISOString())
|
||||
for (const slug of ["git", "other", "over", "undated"]) {
|
||||
assert.ok(!("dateFromFrontmatter" in json[slug]), slug)
|
||||
}
|
||||
})
|
||||
|
||||
test("stand-in dates of the date plugin are not written to contentIndex.json", () => {
|
||||
const now = new Date()
|
||||
const published = new Date("2024-05-06T00:00:00")
|
||||
const json = JSON.parse(
|
||||
serializeContentIndex(
|
||||
buildContentIndex(ctxWith([]), [
|
||||
// created-modified-date >= 1.0.5 lists the dates it filled with the build time
|
||||
page("marked", {
|
||||
defaultDateType: "published",
|
||||
dates: { created: now, modified: now, published: now },
|
||||
fallbackDates: ["published"],
|
||||
}),
|
||||
// older versions don't: a published date only counts when frontmatter sets it
|
||||
page("old", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "OLD" },
|
||||
dates: { created: now, modified: now, published: now },
|
||||
}),
|
||||
page("invalid", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "INV", published: "not a date" },
|
||||
dates: { created: now, modified: now, published: now },
|
||||
}),
|
||||
page("real", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "REAL", published: "2024-05-06" },
|
||||
dates: { created: now, modified: now, published },
|
||||
fallbackDates: [],
|
||||
}),
|
||||
page("oldReal", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "OR", published: "2024-05-06" },
|
||||
dates: { created: now, modified: now, published },
|
||||
}),
|
||||
]),
|
||||
),
|
||||
)
|
||||
for (const slug of ["marked", "old", "invalid"]) assert.ok(!("date" in json[slug]), slug)
|
||||
assert.strictEqual(json.real.date, published.toISOString())
|
||||
assert.strictEqual(json.oldReal.date, published.toISOString())
|
||||
})
|
||||
|
||||
test("plugins add fields through extendContentIndex", () => {
|
||||
const ctx = ctxWith([
|
||||
{
|
||||
@@ -696,3 +1015,407 @@ describe("fonts built-in", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("links to pages removed by filters (crawl-links#7)", () => {
|
||||
const link = (slug: string, className: string[] = ["internal", "internal-link"]): Element => ({
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${slug}`, "data-slug": slug, className: [...className] },
|
||||
children: [{ type: "text", value: slug }],
|
||||
})
|
||||
const page = (slug: string, links: Element[], data: Record<string, unknown> = {}) => {
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
|
||||
return [{ type: "root", children: links } as Root, file] as ProcessedContent
|
||||
}
|
||||
const anchors = (item: ProcessedContent) => (item[0] as Root).children as Element[]
|
||||
|
||||
test("marks links to removed pages and their aliases broken, with the filter", () => {
|
||||
const home = page("index", [
|
||||
link("draft"),
|
||||
link("old-name"),
|
||||
link("published"),
|
||||
link("folder/index"),
|
||||
])
|
||||
const draft = page("draft", [], { aliases: ["old-name"] })
|
||||
const published = page("published", [])
|
||||
const folderIndex = page("folder/index", [])
|
||||
const all = [home, draft, published, folderIndex]
|
||||
const marked = markLinksToRemovedPages(all, [home, published], (s) =>
|
||||
s === "draft" || s === "folder/index" ? "RemoveDrafts" : undefined,
|
||||
)
|
||||
const [toDraft, toAlias, toPublished, toFolder] = anchors(home)
|
||||
assert.strictEqual(marked, 2)
|
||||
assert.ok((toDraft.properties.className as string[]).includes("broken"))
|
||||
assert.strictEqual(toDraft.properties["data-filtered"], "RemoveDrafts")
|
||||
assert.ok((toAlias.properties.className as string[]).includes("broken"))
|
||||
assert.ok(!(toPublished.properties.className as string[]).includes("broken"))
|
||||
// a folder whose index note is a draft still gets a generated folder page
|
||||
assert.ok(!(toFolder.properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("a removed page's alias that a published page owns is not broken", () => {
|
||||
const home = page("index", [link("shared")])
|
||||
const draft = page("draft", [], { aliases: ["shared"] })
|
||||
const owner = page("shared", [])
|
||||
markLinksToRemovedPages([home, draft, owner], [home, owner])
|
||||
assert.ok(!(anchors(home)[0].properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("unmarks links when the target is published again (watch mode)", () => {
|
||||
const home = page("index", [link("draft")])
|
||||
const draft = page("draft", [])
|
||||
markLinksToRemovedPages([home, draft], [home])
|
||||
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
|
||||
markLinksToRemovedPages([home, draft], [home, draft])
|
||||
const a = anchors(home)[0]
|
||||
assert.deepStrictEqual(a.properties.className, ["internal", "internal-link"])
|
||||
assert.strictEqual(a.properties["data-filtered"], undefined)
|
||||
})
|
||||
|
||||
test("leaves links marked broken by the links transformer alone", () => {
|
||||
const home = page("index", [link("missing", ["internal", "internal-link", "broken"])])
|
||||
markLinksToRemovedPages([home], [home])
|
||||
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("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("links to published folder notes and pages are not marked once page types ran", () => {
|
||||
// `notes/index` is a content page (notes/index.md or a folder note), so no page type
|
||||
// generates it: it is live because it is published, not because it was generated
|
||||
const home = page("index", [
|
||||
link("notes/index"),
|
||||
link("projects/index"),
|
||||
link("published"),
|
||||
link("aka"),
|
||||
link("tags/x"),
|
||||
])
|
||||
const notes = page("notes/index", [])
|
||||
const projects = page("projects/index", [], { aliases: ["aka"] })
|
||||
const published = page("published", [])
|
||||
const changed = new Set<FullSlug>()
|
||||
const marked = markUnpublishedLinks(
|
||||
[home, notes, projects, published],
|
||||
new Map(),
|
||||
new Set(["tags/x"]),
|
||||
changed,
|
||||
)
|
||||
assert.strictEqual(marked, 0)
|
||||
for (const a of anchors(home)) {
|
||||
assert.deepStrictEqual(a.properties.className, ["internal", "internal-link"])
|
||||
assert.strictEqual(a.properties["data-missing"], undefined)
|
||||
assert.strictEqual(a.properties["data-filtered"], undefined)
|
||||
}
|
||||
assert.deepStrictEqual([...changed], [])
|
||||
})
|
||||
|
||||
test("a folder note that is a draft: its folder page is generated, or the link is missing", () => {
|
||||
const home = page("index", [link("notes/index"), link("drafts/index")])
|
||||
const notesIndex = page("notes/index", [])
|
||||
const draftsIndex = page("drafts/index", [])
|
||||
const all = [home, notesIndex, draftsIndex]
|
||||
const removed = removedPages(all, [home], () => "RemoveDrafts")
|
||||
// folder index notes are left to the generated pages
|
||||
assert.deepStrictEqual([...removed], [])
|
||||
markUnpublishedLinks([home], removed, new Set(["notes/index"]))
|
||||
const [toNotes, toDrafts] = anchors(home)
|
||||
assert.ok(!(toNotes.properties.className as string[]).includes("broken"))
|
||||
assert.ok((toDrafts.properties.className as string[]).includes("broken"))
|
||||
assert.strictEqual(toDrafts.properties["data-missing"], "")
|
||||
assert.strictEqual(toDrafts.properties["data-filtered"], undefined)
|
||||
})
|
||||
|
||||
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(
|
||||
(Links({ disableBrokenWikilinks: false }) as LinksInstance).marksBrokenLinks,
|
||||
false,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("links built-in: options, other elements and edge cases", () => {
|
||||
const el = (tagName: string, properties: Element["properties"], text?: string): Element => ({
|
||||
type: "element",
|
||||
tagName,
|
||||
properties,
|
||||
children: text === undefined ? [] : [{ type: "text", value: text }],
|
||||
})
|
||||
const a = (href: string, text = href) => el("a", { href }, text)
|
||||
function run(
|
||||
nodes: Element[],
|
||||
{
|
||||
slug = "folder/page",
|
||||
opts = {},
|
||||
allSlugs = ["folder/page"],
|
||||
data = {},
|
||||
permalinks,
|
||||
}: {
|
||||
slug?: string
|
||||
opts?: Record<string, unknown>
|
||||
allSlugs?: string[]
|
||||
data?: Record<string, unknown>
|
||||
permalinks?: Record<string, string>
|
||||
} = {},
|
||||
) {
|
||||
const tree: Root = { type: "root", children: nodes }
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
|
||||
const ctx = { allSlugs, permalinks } as unknown as BuildCtx
|
||||
const [factory] = Links(opts).htmlPlugins!(ctx) as [() => (t: Root, f: VFile) => void]
|
||||
factory()(tree, file)
|
||||
return { nodes, file }
|
||||
}
|
||||
const classes = (e: Element) => e.properties.className as string[] | undefined
|
||||
const text = (e: Element) => (e.children[0] as Text).value
|
||||
|
||||
test("defaults: pretty links, external links open in place with an icon, no lazy loading", () => {
|
||||
const { nodes } = run([
|
||||
a("https://example.com/a/b"),
|
||||
a("other/note"),
|
||||
el("img", { src: "pic.png", alt: "x" }),
|
||||
])
|
||||
const [external, internal, img] = nodes
|
||||
assert.strictEqual(external.properties.target, undefined)
|
||||
assert.strictEqual(text(external), "https://example.com/a/b")
|
||||
assert.deepStrictEqual(external.children[1], {
|
||||
type: "element",
|
||||
tagName: "svg",
|
||||
properties: {
|
||||
"aria-hidden": "true",
|
||||
class: "external-icon",
|
||||
style: "max-width:0.8em;max-height:0.8em",
|
||||
viewBox: "0 0 512 512",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: {
|
||||
d: "M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
assert.strictEqual(text(internal), "note")
|
||||
assert.strictEqual(img.properties.loading, undefined)
|
||||
})
|
||||
|
||||
test("openLinksInNewTab and externalLinkIcon: false apply to external links only", () => {
|
||||
const { nodes } = run([a("https://example.com"), a("other")], {
|
||||
opts: { openLinksInNewTab: true, externalLinkIcon: false },
|
||||
})
|
||||
const [external, internal] = nodes
|
||||
assert.strictEqual(external.properties.target, "_blank")
|
||||
assert.strictEqual(external.children.length, 1)
|
||||
assert.strictEqual(internal.properties.target, undefined)
|
||||
})
|
||||
|
||||
test("prettyLinks: false keeps the link text; text that isn't a single text node is left alone", () => {
|
||||
const off = run([a("folder/note")], { opts: { prettyLinks: false } }).nodes
|
||||
assert.strictEqual(text(off[0]), "folder/note")
|
||||
const formatted: Element = {
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: "folder/note" },
|
||||
children: [el("em", {}, "folder/note"), { type: "text", value: " more" }],
|
||||
}
|
||||
run([formatted])
|
||||
assert.strictEqual(text(formatted.children[0] as Element), "folder/note")
|
||||
assert.strictEqual((formatted.children[1] as Text).value, " more")
|
||||
assert.ok(!classes(formatted)!.includes("alias"))
|
||||
})
|
||||
|
||||
test("lazyLoad and src resolution for img, video, audio and iframe; external sources are kept", () => {
|
||||
const { nodes } = run(
|
||||
[
|
||||
el("img", { src: "a.png", alt: "a" }),
|
||||
el("video", { src: "v.mp4" }),
|
||||
el("audio", { src: "s.mp3" }),
|
||||
el("iframe", { src: "doc.pdf" }),
|
||||
el("img", { src: "https://cdn.example.com/x.png", alt: "x" }),
|
||||
el("script", { src: "x.js" }),
|
||||
],
|
||||
{ opts: { lazyLoad: true, markdownLinkResolution: "absolute" } },
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => [n.properties.src, n.properties.loading]),
|
||||
[
|
||||
["../a.png", "lazy"],
|
||||
["../v.mp4", "lazy"],
|
||||
["../s.mp3", "lazy"],
|
||||
["../doc.pdf", "lazy"],
|
||||
["https://cdn.example.com/x.png", "lazy"],
|
||||
["x.js", undefined],
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("only an image of a missing file gets its path as alt text", () => {
|
||||
const { nodes } = run([el("video", { src: "missing.mp4" }), el("img", { src: "#x" })])
|
||||
assert.strictEqual(nodes[0].properties.alt, undefined)
|
||||
assert.strictEqual(nodes[1].properties.alt, undefined)
|
||||
})
|
||||
|
||||
test("object[data] / source[src] that are empty, fragments or external are not rewritten", () => {
|
||||
const values = ["", "#frag", "https://example.com/x.svg"]
|
||||
const { nodes } = run([
|
||||
...values.map((data) => el("object", { data })),
|
||||
...values.map((src) => el("source", { src })),
|
||||
])
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => n.properties.data ?? n.properties.src),
|
||||
[...values, ...values],
|
||||
)
|
||||
})
|
||||
|
||||
test("anchors without an href are not links", () => {
|
||||
const named = el("a", { id: "here" }, "folder/x")
|
||||
run([named])
|
||||
assert.deepStrictEqual(named.properties, { id: "here" })
|
||||
assert.strictEqual(text(named), "folder/x")
|
||||
})
|
||||
|
||||
test("the home page and folder pages: index always exists; a folder needs a page under it", () => {
|
||||
const { nodes } = run([a("/"), a("/fold/"), a("/folder/"), a("/a/")], {
|
||||
slug: "page",
|
||||
allSlugs: ["page", "folder/note", "a/b"],
|
||||
})
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => classes(n)!.includes("broken")),
|
||||
[false, true, false, false],
|
||||
)
|
||||
})
|
||||
|
||||
test("a missing vault file's type is its last extension", () => {
|
||||
const { nodes } = run([a("/missing.txt.png"), a("/missing.png.txt")], { slug: "page" })
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => classes(n)!.includes("broken")),
|
||||
[true, false],
|
||||
)
|
||||
})
|
||||
|
||||
test("permalinks: a link's heading anchor is kept when it is rebased onto the permalink", () => {
|
||||
const { nodes, file } = run([a("target#Some Heading", "Target"), a("#local")], {
|
||||
slug: "home",
|
||||
data: { relativePath: "folder/page.md" },
|
||||
allSlugs: ["home", "t", "folder/page", "folder/target"],
|
||||
permalinks: { "folder/page.md": "home", "folder/target.md": "t" },
|
||||
})
|
||||
assert.strictEqual(nodes[0].properties.href, "./t#some-heading")
|
||||
assert.strictEqual(nodes[1].properties.href, "#local")
|
||||
assert.deepStrictEqual(file.data.links, ["t"])
|
||||
})
|
||||
|
||||
test("frontmatter links: a bare #heading adds no outgoing link, note#heading links the note", () => {
|
||||
const { file } = run([], {
|
||||
data: { frontmatterLinks: ["#intro", "other#part", "https://example.com"] },
|
||||
opts: { markdownLinkResolution: "absolute" },
|
||||
})
|
||||
assert.deepStrictEqual(file.data.links, ["other"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("links to removed pages: marks that change", () => {
|
||||
const link = (slug: string): Element => ({
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${slug}`, "data-slug": slug, className: ["internal"] },
|
||||
children: [{ type: "text", value: slug }],
|
||||
})
|
||||
const page = (slug: string, children: Element[], data: Record<string, unknown> = {}) => {
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
|
||||
return [{ type: "root", children } as Root, file] as ProcessedContent
|
||||
}
|
||||
|
||||
test("a filter that changes re-marks the link once and re-emits the page", () => {
|
||||
const home = page("index", [link("draft")])
|
||||
const changed = new Set<FullSlug>()
|
||||
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), undefined, changed)
|
||||
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), undefined, changed)
|
||||
const a = (home[0] as Root).children[0] as Element
|
||||
assert.deepStrictEqual(a.properties.className, ["internal", "broken"])
|
||||
changed.clear()
|
||||
markUnpublishedLinks([home], new Map([["draft", "ExplicitPublish"]]), undefined, changed)
|
||||
assert.deepStrictEqual([...changed], ["index"])
|
||||
assert.strictEqual(a.properties["data-filtered"], "ExplicitPublish")
|
||||
assert.deepStrictEqual(a.properties.className, ["internal", "broken"])
|
||||
})
|
||||
|
||||
test("removedPages names the filter, 'filter' when unknown, and the first removed page wins", () => {
|
||||
const home = page("index", [])
|
||||
const a = page("a", [], { aliases: ["shared"] })
|
||||
const b = page("b", [], { aliases: ["shared"] })
|
||||
const noSlug = page("", [])
|
||||
noSlug[1].data.slug = undefined
|
||||
assert.deepStrictEqual(
|
||||
[...removedPages([home, a, b, noSlug], [home])],
|
||||
[
|
||||
["a", "filter"],
|
||||
["shared", "filter"],
|
||||
["b", "filter"],
|
||||
],
|
||||
)
|
||||
const reasons = removedPages([home, a, b], [home], (s) => (s === "a" ? "Drafts" : undefined))
|
||||
assert.deepStrictEqual(
|
||||
[...reasons],
|
||||
[
|
||||
["a", "Drafts"],
|
||||
["shared", "Drafts"],
|
||||
["b", "filter"],
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("only <a> elements are marked; the tags index is a generated target", () => {
|
||||
const div: Element = {
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { "data-slug": "draft" },
|
||||
children: [],
|
||||
}
|
||||
const home = page("index", [div, link("tags")])
|
||||
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), new Set())
|
||||
assert.deepStrictEqual(div.properties, { "data-slug": "draft" })
|
||||
const tags = (home[0] as Root).children[1] as Element
|
||||
assert.strictEqual(tags.properties["data-missing"], "")
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import fs from "node:fs/promises"
|
||||
import { Root } from "hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import { styleText } from "util"
|
||||
import { getDate } from "@quartz-community/utils"
|
||||
import { dateIsFromFrontmatter as dateIsFromFrontmatterOfType, realDate } from "../../util/dates"
|
||||
import { ContentIndexConfig, GlobalConfiguration } from "../../cfg"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { escapeHTML } from "../../util/escape"
|
||||
@@ -53,6 +53,7 @@ export const CORE_CONTENT_INDEX_FIELDS = new Set([
|
||||
"content",
|
||||
"richContent",
|
||||
"date",
|
||||
"dateFromFrontmatter",
|
||||
"description",
|
||||
])
|
||||
|
||||
@@ -150,6 +151,38 @@ export function prepareContentIndex(ctx: BuildCtx, content: ProcessedContent[]):
|
||||
return index
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages without a date, or with one the date plugin filled in with the build time (its
|
||||
* `fallbackDates`), get the build time, so RSS and the sitemap keep working as before.
|
||||
* Those stand-in dates are remembered here and not written to contentIndex.json, where a
|
||||
* build-time date would look like a real one to client-side sorting (explorer, recent notes).
|
||||
*/
|
||||
const buildTimeDates = new WeakSet<Date>()
|
||||
function buildTimeDate(): Date {
|
||||
const date = new Date()
|
||||
buildTimeDates.add(date)
|
||||
return date
|
||||
}
|
||||
|
||||
function entryDate(data: QuartzPluginData): Date {
|
||||
// a stand-in date of the date plugin (fallbackDates) is a build-time date as well
|
||||
const date = realDate(data, data.defaultDateType as string | undefined)
|
||||
if (!date) return buildTimeDate()
|
||||
if (dateIsFromFrontmatter(data, date)) frontmatterDates.add(date)
|
||||
return date
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page's `date` is the one its frontmatter sets for the configured date type
|
||||
* (`defaultDateType`). See util/dates.
|
||||
*/
|
||||
export function dateIsFromFrontmatter(data: QuartzPluginData, date: Date | undefined): boolean {
|
||||
return dateIsFromFrontmatterOfType(data, date)
|
||||
}
|
||||
|
||||
/** Pages whose date came from frontmatter (see dateIsFromFrontmatter). */
|
||||
const frontmatterDates = new WeakSet<Date>()
|
||||
|
||||
/** Build the index from processed content (also used by tests and potentially other emitters). */
|
||||
export function buildContentIndex(
|
||||
ctx: BuildCtx,
|
||||
@@ -176,7 +209,7 @@ export function buildContentIndex(
|
||||
options.rssFullHtml && data.encrypted !== true
|
||||
? escapeHTML(toHtml(tree as Root, { allowDangerousHtml: true }))
|
||||
: undefined,
|
||||
date: getDate(data as Parameters<typeof getDate>[0]) ?? new Date(),
|
||||
date: entryDate(data),
|
||||
description: (data.description as string | undefined) ?? "",
|
||||
}
|
||||
index.set(slug, applyContentIndexExtensions(ctx, extensions, entry, data))
|
||||
@@ -240,13 +273,25 @@ function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndexMap, limit?:
|
||||
</rss>`
|
||||
}
|
||||
|
||||
/** Entries as written to contentIndex.json (date and description are RSS/sitemap-only). */
|
||||
/**
|
||||
* Entries as written to contentIndex.json. `date` is the page's date (the one
|
||||
* `defaultDateType` selects, as shown by ContentMeta and used by RSS) as an ISO 8601 string,
|
||||
* left out for pages without a date. `dateFromFrontmatter: true` is added when that date is the
|
||||
* one the page's frontmatter sets for the date type (absent otherwise). `description` is
|
||||
* RSS-only.
|
||||
*/
|
||||
export function serializeContentIndex(idx: ContentIndexMap): string {
|
||||
const simplified = Object.fromEntries(
|
||||
Array.from(idx).map(([slug, { date: _date, description: _description, ...rest }]) => [
|
||||
slug,
|
||||
rest,
|
||||
]),
|
||||
Array.from(idx).map(([slug, { date, description: _description, ...rest }]) => {
|
||||
const hasDate = date instanceof Date && !isNaN(date.getTime()) && !buildTimeDates.has(date)
|
||||
if (!hasDate) return [slug, rest]
|
||||
return [
|
||||
slug,
|
||||
frontmatterDates.has(date)
|
||||
? { ...rest, date: date.toISOString(), dateFromFrontmatter: true }
|
||||
: { ...rest, date: date.toISOString() },
|
||||
]
|
||||
}),
|
||||
)
|
||||
return JSON.stringify(simplified)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import matter from "gray-matter"
|
||||
import remarkFrontmatter from "remark-frontmatter"
|
||||
import yaml from "js-yaml"
|
||||
import { CORE_SCHEMA, loadAll } from "js-yaml"
|
||||
import toml from "toml"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import { QuartzPluginData } from "../vfile"
|
||||
@@ -67,7 +67,76 @@ export function slugifyWikilinkTarget(target: string): string {
|
||||
}
|
||||
|
||||
const WIKILINK_PATTERN = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g
|
||||
const MDLINK_PATTERN = /\[(?:[^\]]*)\]\(([^)]+)\)/g
|
||||
/** The start of a Markdown link: `[text](`; the destination is parsed by markdownLinkTarget. */
|
||||
const MDLINK_START = /\[(?:[^\]]*)\]\(/g
|
||||
|
||||
const ASCII_PUNCTUATION = /[!-/:-@[-`{-~]/
|
||||
const isSpace = (c: string | undefined) => c === " " || c === "\t" || c === "\n" || c === "\r"
|
||||
/** CommonMark backslash escapes: `\(` → `(` (only before ASCII punctuation). */
|
||||
const unescapeLink = (s: string) => s.replace(/\\([!-/:-@[-`{-~])/g, "$1")
|
||||
|
||||
/**
|
||||
* The destination of the Markdown link whose `(` ends at `start` in `s`, as CommonMark reads
|
||||
* it: `<…>` (may hold spaces and parentheses) or a plain destination (ends at a space or an
|
||||
* unbalanced `)`), then an optional title in `"…"`, `'…'` or `(…)`. A plain destination
|
||||
* with spaces that isn't followed by a title (`[x](./My Note.md)`, which Obsidian accepts)
|
||||
* runs to the closing `)`. Returns undefined when there is no closing `)`.
|
||||
*/
|
||||
export function markdownLinkTarget(s: string, start: number): string | undefined {
|
||||
let i = start
|
||||
while (isSpace(s[i])) i++
|
||||
const destStart = i
|
||||
let dest: string
|
||||
if (s[i] === "<") {
|
||||
let j = i + 1
|
||||
while (j < s.length && s[j] !== ">" && s[j] !== "<" && s[j] !== "\n") {
|
||||
j += s[j] === "\\" && ASCII_PUNCTUATION.test(s[j + 1] ?? "") ? 2 : 1
|
||||
}
|
||||
if (s[j] !== ">") return undefined
|
||||
dest = unescapeLink(s.slice(i + 1, j))
|
||||
i = j + 1
|
||||
} else {
|
||||
let depth = 0
|
||||
while (i < s.length) {
|
||||
const c = s[i]
|
||||
if (c === "\\" && ASCII_PUNCTUATION.test(s[i + 1] ?? "")) {
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if (isSpace(c)) break
|
||||
if (c === "(") depth++
|
||||
else if (c === ")") {
|
||||
if (depth === 0) break
|
||||
depth--
|
||||
}
|
||||
i++
|
||||
}
|
||||
dest = unescapeLink(s.slice(destStart, i))
|
||||
}
|
||||
while (isSpace(s[i])) i++
|
||||
if (s[i] === ")") return dest
|
||||
const close = s[i] === '"' ? '"' : s[i] === "'" ? "'" : s[i] === "(" ? ")" : undefined
|
||||
if (close) {
|
||||
let j = i + 1
|
||||
while (j < s.length && s[j] !== close) {
|
||||
j += s[j] === "\\" && ASCII_PUNCTUATION.test(s[j + 1] ?? "") ? 2 : 1
|
||||
}
|
||||
let k = j + 1
|
||||
while (isSpace(s[k])) k++
|
||||
if (j < s.length && s[k] === ")") return dest
|
||||
}
|
||||
if (s[destStart] === "<") return undefined
|
||||
// lenient: a plain destination with spaces, up to the `)` that closes the link
|
||||
let depth = 0
|
||||
for (let j = destStart; j < s.length; j++) {
|
||||
if (s[j] === "(") depth++
|
||||
else if (s[j] === ")") {
|
||||
if (depth === 0) return unescapeLink(s.slice(destStart, j).trim())
|
||||
depth--
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** All link targets (wikilinks and Markdown links) inside a frontmatter value, recursively. */
|
||||
export function extractLinksFromValue(value: unknown): string[] {
|
||||
@@ -75,7 +144,12 @@ export function extractLinksFromValue(value: unknown): string[] {
|
||||
const links: string[] = []
|
||||
for (const match of value.matchAll(WIKILINK_PATTERN))
|
||||
links.push(slugifyWikilinkTarget(match[1]!))
|
||||
for (const match of value.matchAll(MDLINK_PATTERN)) links.push(match[1]!)
|
||||
for (const match of value.matchAll(MDLINK_START)) {
|
||||
// `[x](<./My Note.md> "title")`: angle-bracket destinations (which Obsidian writes for
|
||||
// paths with spaces), balanced parentheses and titles, as CommonMark reads them
|
||||
const dest = markdownLinkTarget(value, match.index! + match[0].length)
|
||||
if (dest) links.push(dest)
|
||||
}
|
||||
return links
|
||||
}
|
||||
if (Array.isArray(value)) return value.flatMap((item) => extractLinksFromValue(item))
|
||||
@@ -141,6 +215,17 @@ const refuseJavaScript = (): never => {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* YAML frontmatter as properties. YAML 1.2's core schema, as Obsidian reads properties: `true`,
|
||||
* `null`, `~` and numbers resolve, dates stay strings. A block without a document (empty, or only
|
||||
* comments) holds no properties.
|
||||
*/
|
||||
function loadYaml(source: string): object {
|
||||
const docs = loadAll(source, { schema: CORE_SCHEMA })
|
||||
if (docs.length > 1)
|
||||
throw new Error("expected a single document in the frontmatter, but found more")
|
||||
return (docs[0] ?? {}) as object
|
||||
}
|
||||
/** Parse a file's frontmatter with the configured delimiters and language (`{}` when it has none). */
|
||||
export function readFrontmatterData(
|
||||
source: Buffer | string,
|
||||
@@ -158,7 +243,7 @@ export function readFrontmatterData(
|
||||
delimiters: options.delimiters ?? frontmatterDefaults.delimiters,
|
||||
language,
|
||||
engines: {
|
||||
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
|
||||
yaml: loadYaml,
|
||||
toml: (s) => toml.parse(s) as object,
|
||||
javascript: refuseJavaScript,
|
||||
js: refuseJavaScript,
|
||||
|
||||
@@ -303,7 +303,7 @@ export function planBuiltins(input: PlanInput): BuiltinPlan {
|
||||
export function instantiateBuiltins<C extends BuiltinCategory>(
|
||||
plan: BuiltinPlan,
|
||||
category: C,
|
||||
): { order: number; instance: BuiltinInstance }[] {
|
||||
): { order: number; instance: BuiltinInstance; names: string[] }[] {
|
||||
return (
|
||||
plan.builtins
|
||||
.filter((b) => b.enabled && b.spec.category === category)
|
||||
@@ -318,7 +318,13 @@ export function instantiateBuiltins<C extends BuiltinCategory>(
|
||||
category: b.spec.category,
|
||||
builtin: true,
|
||||
})
|
||||
return { order: b.order, instance }
|
||||
// `before`/`after` may name the built-in by its config key or by the plugin it
|
||||
// replaced (`after: crawl-links` is `after: links`)
|
||||
return {
|
||||
order: b.order,
|
||||
instance,
|
||||
names: [instance.name, b.spec.configKey, ...b.spec.absorbs],
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,8 @@ import { visit } from "unist-util-visit"
|
||||
import isAbsoluteUrl from "is-absolute-url"
|
||||
import { Element, Root, Text } from "hast"
|
||||
import { VFile } from "vfile"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import { QuartzTransformerPlugin, QuartzTransformerPluginInstance } from "../types"
|
||||
import { ProcessedContent } from "../vfile"
|
||||
import { LinksConfig } from "../../cfg"
|
||||
import {
|
||||
FullSlug,
|
||||
@@ -38,7 +39,7 @@ export const linksDefaults: Required<Omit<LinksConfig, "enabled" | "order">> = {
|
||||
openLinksInNewTab: false,
|
||||
lazyLoad: false,
|
||||
externalLinkIcon: true,
|
||||
disableBrokenWikilinks: false,
|
||||
disableBrokenWikilinks: true,
|
||||
}
|
||||
|
||||
/** Defaults of the former crawl-links plugin, applied when its config entry is migrated. */
|
||||
@@ -46,10 +47,10 @@ export const legacyCrawlLinksDefaults: Partial<LinksConfig> = {
|
||||
markdownLinkResolution: "absolute",
|
||||
}
|
||||
|
||||
const isAbsolute = isAbsoluteUrl as (url: string, options?: { httpOnly?: boolean }) => boolean
|
||||
// As in Obsidian: a URL with a scheme (`x:y`, but not `../x:y`), or a link whose path is not valid
|
||||
// percent-encoding (`%zz`, `a%E2.md`), which names no file
|
||||
const isExternalUrl = (url: string) => isAbsolute(url, { httpOnly: false }) || !linkPathDecodes(url)
|
||||
const isExternalUrl = (url: string) =>
|
||||
isAbsoluteUrl(url, { httpOnly: false }) || !linkPathDecodes(url)
|
||||
// An href percent-decoded, to compare with link text; left as it is when it does not decode
|
||||
const decodedHref = (href: string) => {
|
||||
try {
|
||||
@@ -71,10 +72,172 @@ function canonicalSlug(dest: string, curSlug: SimpleSlug): FullSlug {
|
||||
return decodeURIComponent(stripSlashes(canonical, true)) as FullSlug
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a link's target is a page of the site. Tag and folder pages are generated after
|
||||
* the transformers run, so they aren't in `allSlugs` yet: a tag page (`tags/…`) exists for
|
||||
* every tag that is used, and a folder page (`folder/index`) for every folder with content.
|
||||
*/
|
||||
export function pageExists(allSlugs: readonly string[], full: string): boolean {
|
||||
if (allSlugs.includes(full)) return true
|
||||
if (full === "index" || full.startsWith("tags/")) return true
|
||||
if (full.endsWith("/index")) {
|
||||
const folder = full.slice(0, -"index".length)
|
||||
return allSlugs.some((s) => s.startsWith(folder))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** File types Obsidian opens from the vault (embeds and attachments): a link to one that the content doesn't have names a missing file. */
|
||||
const VAULT_FILE_TYPES = new Set(
|
||||
"avif bmp gif jpeg jpg png svg webp flac m4a mp3 ogg wav 3gp mkv mov mp4 ogv webm pdf canvas base".split(
|
||||
" ",
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether an internal link target is known to be missing, so it gets the `broken` class.
|
||||
* Only targets Quartz can check are: pages (see pageExists) and files of the types a vault
|
||||
* holds (images, audio, video, PDFs, canvases, bases), which the content copies as assets.
|
||||
* Anything else may be a file Quartz or a plugin emits and the transformers can't know about
|
||||
* (`index.xml`, `sitemap.xml`, `robots.txt`, `static/…`, og images), so it is not marked.
|
||||
*/
|
||||
export function linkTargetMissing(allSlugs: readonly string[], full: string): boolean {
|
||||
// the not-found page is always emitted (`.html` is dropped from links like `.md`)
|
||||
if (full === "404" || pageExists(allSlugs, full)) return false
|
||||
// quartz/static and plugin assets are served at static/
|
||||
if (full.startsWith("static/")) return false
|
||||
const name = full.slice(full.lastIndexOf("/") + 1)
|
||||
const ext = /\.([a-z][a-z0-9]{0,9})$/i.exec(name)?.[1]?.toLowerCase()
|
||||
if (ext === undefined) return true
|
||||
return VAULT_FILE_TYPES.has(ext)
|
||||
}
|
||||
|
||||
/** 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"
|
||||
|
||||
/**
|
||||
* 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 removedPages(
|
||||
all: ProcessedContent[],
|
||||
published: ProcessedContent[],
|
||||
filteredBy: (slug: string) => string | undefined = () => "filter",
|
||||
): Map<string, string> {
|
||||
const publishedSet = new Set(published)
|
||||
const live = new Set<string>()
|
||||
for (const item of published) {
|
||||
const data = item[1].data
|
||||
if (data.slug) live.add(data.slug)
|
||||
for (const alias of data.aliases ?? []) live.add(alias)
|
||||
}
|
||||
const removed = new Map<string, string>()
|
||||
for (const item of all) {
|
||||
if (publishedSet.has(item)) continue
|
||||
const data = item[1].data
|
||||
if (!data.slug) continue
|
||||
const reason = filteredBy(data.slug) ?? "filter"
|
||||
// its aliases (and the file path of a page with a permalink) are gone with it
|
||||
for (const slug of [data.slug, ...(data.aliases ?? [])]) {
|
||||
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, 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 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")
|
||||
props.className = classes
|
||||
props[attr] = value
|
||||
marked++
|
||||
} 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 }
|
||||
|
||||
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
const opts = { ...linksDefaults, ...userOpts }
|
||||
return {
|
||||
const instance: LinksInstance = {
|
||||
name: "Links",
|
||||
marksBrokenLinks: opts.disableBrokenWikilinks,
|
||||
htmlPlugins(ctx) {
|
||||
return [
|
||||
() => {
|
||||
@@ -114,8 +277,17 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
let dest = node.properties.href as RelativeURL
|
||||
const classes = (node.properties.className ?? []) as string[]
|
||||
const isExternal = isExternalUrl(dest)
|
||||
// Footnote anchors aren't note links: Obsidian gives them `footnote-link`,
|
||||
// never `internal-link`, whose link styles would override theirs.
|
||||
const isFootnote =
|
||||
node.properties.dataFootnoteRef !== undefined ||
|
||||
node.properties.dataFootnoteBackref !== undefined
|
||||
classes.push(
|
||||
...(isExternal ? ["external", "external-link"] : ["internal", "internal-link"]),
|
||||
...(isExternal
|
||||
? ["external", "external-link"]
|
||||
: isFootnote
|
||||
? ["internal"]
|
||||
: ["internal", "internal-link"]),
|
||||
)
|
||||
|
||||
if (isExternal && opts.externalLinkIcon) {
|
||||
@@ -163,7 +335,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
outgoing.add(simplifySlug(full))
|
||||
node.properties["data-slug"] = full
|
||||
|
||||
if (opts.disableBrokenWikilinks && !ctx.allSlugs.includes(full)) {
|
||||
if (opts.disableBrokenWikilinks && linkTargetMissing(ctx.allSlugs, full)) {
|
||||
classes.push("broken")
|
||||
node.properties.className = classes
|
||||
}
|
||||
@@ -238,4 +410,5 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
]
|
||||
},
|
||||
}
|
||||
return instance
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
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 test, { after, describe } from "node:test"
|
||||
import { createContext, runInContext } from "node:vm"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { QuartzComponent } from "../../components/types"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { GlobalConfiguration } from "../../cfg"
|
||||
|
||||
// The emitter imports SCSS and inline browser scripts that esbuild bundles in a real build. Under
|
||||
// tsx each one is replaced by a marker: `.stub-<name>{--stub:<name>}` for SCSS, `window.__stub_<name>`
|
||||
// for scripts, so the tests can tell where each one ends up.
|
||||
registerHooks({
|
||||
load(url, context, next) {
|
||||
const name = path.basename(new URL(url).pathname).replace(/\.(inline\.ts|scss)$/, "")
|
||||
if (url.endsWith(".scss")) {
|
||||
const css = `.stub-${name.replace(/\W/g, "_")}{--stub:${name.replace(/\W/g, "_")}}`
|
||||
return {
|
||||
format: "module",
|
||||
source: `export default ${JSON.stringify(css)}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
if (/\.inline\.ts$/.test(url)) {
|
||||
const js = `window.__stub_${name} = 1`
|
||||
return {
|
||||
format: "module",
|
||||
source: `export default ${JSON.stringify(js)}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
return next(url, context)
|
||||
},
|
||||
})
|
||||
const { ComponentResources } = await import("./componentResources")
|
||||
|
||||
const theme = {
|
||||
fontOrigin: "local",
|
||||
cdnCaching: true,
|
||||
typography: { header: "Header Font", body: "Body Font", code: "Code Font" },
|
||||
colors: {
|
||||
lightMode: {
|
||||
light: "#fff",
|
||||
lightgray: "#eee",
|
||||
gray: "#999",
|
||||
darkgray: "#444",
|
||||
dark: "#222",
|
||||
secondary: "#00f",
|
||||
tertiary: "#0f0",
|
||||
highlight: "#ff0",
|
||||
textHighlight: "#ff08",
|
||||
},
|
||||
darkMode: {
|
||||
light: "#000",
|
||||
lightgray: "#111",
|
||||
gray: "#666",
|
||||
darkgray: "#bbb",
|
||||
dark: "#ddd",
|
||||
secondary: "#88f",
|
||||
tertiary: "#8f8",
|
||||
highlight: "#880",
|
||||
textHighlight: "#8808",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const Widget: QuartzComponent = Object.assign(() => null, {
|
||||
css: ".widget{color:blue}",
|
||||
beforeDOMLoaded: "window.__widgetBefore = 1",
|
||||
afterDOMLoaded: "window.__widgetAfter = 1",
|
||||
})
|
||||
const Other: QuartzComponent = Object.assign(() => null, {
|
||||
css: [".other{color:green}"],
|
||||
afterDOMLoaded: ["window.__otherAfter = 1"],
|
||||
})
|
||||
|
||||
const dirs: string[] = []
|
||||
after(() => {
|
||||
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function emit(
|
||||
configuration: Partial<GlobalConfiguration>,
|
||||
{
|
||||
serve = false,
|
||||
resources = { css: [], js: [], additionalHead: [] } as StaticResources,
|
||||
// the same component from two emitters is collected once; an emitter may have none
|
||||
emitters = [
|
||||
{ getQuartzComponents: () => [Widget, Other] },
|
||||
{ getQuartzComponents: () => [Widget] },
|
||||
{},
|
||||
] as unknown[],
|
||||
} = {},
|
||||
) {
|
||||
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-component-resources-"))
|
||||
dirs.push(output)
|
||||
const ctx = {
|
||||
argv: { output, serve },
|
||||
cfg: {
|
||||
configuration: { enableSPA: true, enablePopovers: true, theme, ...configuration },
|
||||
plugins: { emitters },
|
||||
},
|
||||
} as unknown as BuildCtx
|
||||
const written: string[] = []
|
||||
for await (const fp of ComponentResources().emit(ctx, [], resources) as AsyncIterable<string>) {
|
||||
written.push(path.relative(output, fp).split(path.sep).join("/"))
|
||||
}
|
||||
const read = (name: string) => fs.readFileSync(path.join(output, name), "utf8")
|
||||
return { ctx, written, read }
|
||||
}
|
||||
|
||||
/** The script files postscript.js imports, in its order, with whether each is awaited alone. */
|
||||
function importedScripts(postscript: string) {
|
||||
return [...postscript.matchAll(/import\("\.\/([^"]+)"\)/g)].map((m) => m[1])
|
||||
}
|
||||
|
||||
describe("ComponentResources emitter", () => {
|
||||
test("production: content-hashed index.css / prescript / postscript, named in ctx.hashedResourceNames", async () => {
|
||||
const { ctx, written, read } = await emit({})
|
||||
const names = ctx.hashedResourceNames!
|
||||
assert.match(names["index.css"], /^index-[0-9a-f]{8}\.css$/)
|
||||
assert.match(names["prescript.js"], /^prescript-[0-9a-f]{8}\.js$/)
|
||||
assert.match(names["postscript.js"], /^postscript-[0-9a-f]{8}\.js$/)
|
||||
for (const file of Object.values(names)) assert.ok(written.includes(file), file)
|
||||
|
||||
// components' beforeDOMLoaded scripts go in the prescript (once, though listed twice)
|
||||
const prescript = read(names["prescript.js"])
|
||||
assert.equal(prescript.split("__widgetBefore").length, 2)
|
||||
})
|
||||
|
||||
test("production: postscript loads component scripts in parallel and the SPA router last", async () => {
|
||||
const { ctx, written, read } = await emit({ prefetch: "hover" })
|
||||
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
|
||||
const scripts = importedScripts(postscript)
|
||||
for (const s of scripts) {
|
||||
assert.match(s, /^static\/scripts\/script-\d+-[0-9a-f]{8}\.js$/)
|
||||
assert.ok(written.includes(s), s)
|
||||
}
|
||||
const contents = scripts.map(read)
|
||||
// component scripts, then the global ones: popover, prefetch (with its settings), router
|
||||
assert.deepEqual(
|
||||
contents.map((c) =>
|
||||
c.includes("__widgetAfter")
|
||||
? "widget"
|
||||
: c.includes("__otherAfter")
|
||||
? "other"
|
||||
: c.includes("__stub_popover")
|
||||
? "popover"
|
||||
: c.includes("__stub_prefetch")
|
||||
? "prefetch"
|
||||
: c.includes("__stub_spa")
|
||||
? "spa"
|
||||
: c,
|
||||
),
|
||||
["widget", "other", "popover", "prefetch", "spa"],
|
||||
)
|
||||
assert.match(
|
||||
contents[3],
|
||||
/window\.__quartzPrefetchMode = "hover";\nwindow\.__quartzSpa = true;/,
|
||||
)
|
||||
// all but the router are imported together; the router (which dispatches the first `nav`)
|
||||
// only after they all registered their listeners
|
||||
const last = scripts[scripts.length - 1]
|
||||
const [parallel, rest] = postscript.split(`await import("./${last}")`)
|
||||
assert.ok(parallel.startsWith("await Promise.all(["), postscript)
|
||||
assert.ok(!parallel.includes("__stub_spa") && !parallel.includes(last), postscript)
|
||||
for (const s of scripts.slice(0, -1)) assert.ok(parallel.includes(`import("./${s}")`), s)
|
||||
assert.equal(rest.trim(), ";")
|
||||
})
|
||||
|
||||
test("prefetching defaults to viewport mode", async () => {
|
||||
const { ctx, read } = await emit({ prefetch: undefined })
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
const prefetch = scripts.find((s) => s.includes("__stub_prefetch"))!
|
||||
assert.match(prefetch, /^window\.__quartzPrefetchMode = "viewport";/)
|
||||
})
|
||||
|
||||
test("without SPA routing the last script dispatches the first nav itself; prefetch: false loads no prefetcher", async () => {
|
||||
const { ctx, read } = await emit({
|
||||
enableSPA: false,
|
||||
enablePopovers: false,
|
||||
prefetch: false as never,
|
||||
})
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
assert.ok(!scripts.some((s) => s.includes("__stub_spa")))
|
||||
assert.ok(!scripts.some((s) => s.includes("__stub_prefetch") || s.includes("__stub_popover")))
|
||||
assert.match(scripts[scripts.length - 1], /new CustomEvent\("nav"/)
|
||||
assert.ok(!read(ctx.hashedResourceNames!["index.css"]).includes("stub-popover"))
|
||||
})
|
||||
|
||||
test("component CSS goes into one component stylesheet; index.css has theme, global and base styles", async () => {
|
||||
const { ctx, written, read } = await emit({})
|
||||
const componentFile = written.find((f) => /^component-[0-9a-f]{8}\.css$/.test(f))
|
||||
assert.ok(componentFile, written.join(", "))
|
||||
const componentCss = read(componentFile)
|
||||
assert.match(componentCss, /\.widget\{color:#00f\}/)
|
||||
assert.match(componentCss, /\.other\{color:green\}/)
|
||||
assert.equal(ctx.componentCssMap!.get(".widget{color:blue}"), componentFile)
|
||||
assert.equal(ctx.componentCssMap!.get(".other{color:green}"), componentFile)
|
||||
|
||||
const index = read(ctx.hashedResourceNames!["index.css"])
|
||||
assert.ok(!index.includes(".widget"), "component CSS is not duplicated into index.css")
|
||||
// the popover's CSS (added globally) and base styles in the quartz-base layer, then custom.scss
|
||||
assert.match(
|
||||
index,
|
||||
/^@layer quartz-base\{.*\.stub-popover\{.*\.stub-base\{.*\}\.stub-custom\{/s,
|
||||
)
|
||||
assert.match(index, /--secondary:#00f/)
|
||||
assert.match(index, /--titleFont:"Header Font"/)
|
||||
})
|
||||
|
||||
test("inline plugin CSS/JS resources are moved to files named in ctx.extractedInlineResources", async () => {
|
||||
const resources = {
|
||||
css: [
|
||||
{ content: ".plugin-inline { color: red; }", inline: true },
|
||||
{ content: "https://example.com/external.css" },
|
||||
],
|
||||
js: [
|
||||
{ script: "window.__early = 1", loadTime: "beforeDOMReady", contentType: "inline" },
|
||||
{ script: "window.__late = 1", loadTime: "afterDOMReady", contentType: "inline" },
|
||||
{ src: "https://example.com/x.js", loadTime: "afterDOMReady", contentType: "external" },
|
||||
],
|
||||
additionalHead: [],
|
||||
} as unknown as StaticResources
|
||||
const { ctx, written, read } = await emit({}, { resources })
|
||||
const map = ctx.extractedInlineResources!
|
||||
assert.equal(map.size, 3)
|
||||
const css = map.get(".plugin-inline { color: red; }")!
|
||||
assert.match(css, /^static\/resource-style-[0-9a-f]{8}\.css$/)
|
||||
assert.equal(read(css), ".plugin-inline{color:red}")
|
||||
const early = map.get("window.__early = 1")!
|
||||
const late = map.get("window.__late = 1")!
|
||||
assert.match(early, /^static\/resource-before-[0-9a-f]{8}\.js$/)
|
||||
assert.match(late, /^static\/resource-after-[0-9a-f]{8}\.js$/)
|
||||
assert.match(read(late), /window\.__late=1/)
|
||||
for (const f of [css, early, late]) assert.ok(written.includes(f), f)
|
||||
// the resources themselves are left as they are (partial rebuilds reuse them)
|
||||
assert.equal(resources.css.length, 2)
|
||||
})
|
||||
|
||||
test("CSS a plugin marks inline that lightningcss can't parse is written as it is", async () => {
|
||||
const broken = ".a { color: red"
|
||||
const resources = {
|
||||
css: [
|
||||
{ content: "@media (", inline: true },
|
||||
{ content: broken, inline: true },
|
||||
],
|
||||
js: [],
|
||||
additionalHead: [],
|
||||
} as unknown as StaticResources
|
||||
const { ctx, read } = await emit({}, { resources })
|
||||
assert.equal(read(ctx.extractedInlineResources!.get("@media (")!), "@media (")
|
||||
})
|
||||
|
||||
test("serve mode: unhashed names and one minified postscript bundle in order", async () => {
|
||||
const { ctx, written, read } = await emit({}, { serve: true })
|
||||
assert.deepEqual(ctx.hashedResourceNames, {
|
||||
"index.css": "index.css",
|
||||
"prescript.js": "prescript.js",
|
||||
"postscript.js": "postscript.js",
|
||||
})
|
||||
assert.ok(!written.some((f) => f.startsWith("static/scripts/")))
|
||||
const postscript = read("postscript.js")
|
||||
const order = [
|
||||
"__widgetAfter",
|
||||
"__otherAfter",
|
||||
"__stub_popover",
|
||||
"__stub_prefetch",
|
||||
"__stub_spa",
|
||||
].map((marker) => postscript.indexOf(marker))
|
||||
assert.ok(order.every((at) => at >= 0))
|
||||
assert.deepEqual(
|
||||
[...order].sort((a, b) => a - b),
|
||||
order,
|
||||
)
|
||||
// minified by esbuild
|
||||
assert.ok(!postscript.includes("window.__widgetAfter = 1"), postscript)
|
||||
})
|
||||
|
||||
test("postscript.js is a valid module: the parallel imports are comma-separated", async () => {
|
||||
const { ctx, read } = await emit({})
|
||||
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
|
||||
const AsyncFunction = (async () => {}).constructor as new (code: string) => unknown
|
||||
assert.doesNotThrow(() => new AsyncFunction(postscript), postscript)
|
||||
assert.equal(importedScripts(postscript).length, 5)
|
||||
})
|
||||
|
||||
test("without component CSS no component stylesheet is emitted", async () => {
|
||||
const { ctx, written } = await emit({}, { emitters: [] })
|
||||
assert.ok(!written.some((f) => f.startsWith("component-")), written.join(", "))
|
||||
assert.equal(ctx.componentCssMap!.size, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("analytics scripts", () => {
|
||||
/** Run the site's analytics script in a fake page; returns the URLs of the scripts it loads. */
|
||||
async function loadedScripts(analytics: Record<string, unknown>) {
|
||||
const { ctx, read } = await emit(
|
||||
{
|
||||
analytics: analytics as GlobalConfiguration["analytics"],
|
||||
enablePopovers: false,
|
||||
prefetch: false as never,
|
||||
},
|
||||
{ emitters: [] },
|
||||
)
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
// the analytics script(s), before the router
|
||||
const ours = scripts.slice(0, -1)
|
||||
const loaded: { src: string; attributes: Record<string, string> }[] = []
|
||||
const element = () => ({
|
||||
attributes: {} as Record<string, string>,
|
||||
setAttribute(name: string, value: string) {
|
||||
this.attributes[name] = value
|
||||
},
|
||||
})
|
||||
const firstScript = { parentNode: { insertBefore: (s: never) => loaded.push(s) } }
|
||||
const document = Object.assign(new EventTarget(), {
|
||||
title: "Page",
|
||||
createElement: element,
|
||||
head: { appendChild: (s: never) => loaded.push(s) },
|
||||
getElementsByTagName: () => [firstScript],
|
||||
})
|
||||
const context = createContext({
|
||||
document,
|
||||
location: { hostname: "garden.example", pathname: "/", href: "https://garden.example/" },
|
||||
})
|
||||
context.window = context
|
||||
for (const script of ours) runInContext(script, context)
|
||||
return { loaded: loaded.map((s) => ({ src: s.src, attributes: s.attributes })), context, ours }
|
||||
}
|
||||
|
||||
const cases: [Record<string, unknown>, string, Record<string, string>?][] = [
|
||||
[{ provider: "google", tagId: "G-1" }, "https://www.googletagmanager.com/gtag/js?id=G-1"],
|
||||
[
|
||||
{ provider: "plausible" },
|
||||
"https://plausible.io/js/script.manual.js",
|
||||
{ "data-domain": "garden.example" },
|
||||
],
|
||||
[{ provider: "plausible", host: "https://p.example" }, "https://p.example/js/script.manual.js"],
|
||||
[
|
||||
{ provider: "umami", websiteId: "w1" },
|
||||
"https://analytics.umami.is/script.js",
|
||||
{ "data-website-id": "w1" },
|
||||
],
|
||||
[
|
||||
{ provider: "umami", websiteId: "w1", host: "https://u.example", script: "u.js" },
|
||||
"https://u.example/u.js",
|
||||
],
|
||||
[{ provider: "goatcounter", websiteId: "g1" }, "https://gc.zgo.at/count.js"],
|
||||
[{ provider: "posthog", apiKey: "k" }, "https://app.posthog.com/static/array.js"],
|
||||
[
|
||||
{ provider: "posthog", apiKey: "k", host: "https://ph.example" },
|
||||
"https://ph.example/static/array.js",
|
||||
],
|
||||
[
|
||||
{ provider: "posthog", apiKey: "k", host: "https://h", apiHost: "https://api.h" },
|
||||
"https://api.h/static/array.js",
|
||||
],
|
||||
[{ provider: "tinylytics", siteId: "t 1" }, "https://tinylytics.app/embed/t%201.js?spa"],
|
||||
[{ provider: "cabin" }, "https://scripts.withcabin.com/hello.js"],
|
||||
[{ provider: "cabin", host: "https://c.example" }, "https://c.example/hello.js"],
|
||||
[{ provider: "clarity", projectId: "c1" }, "https://www.clarity.ms/tag/c1"],
|
||||
[{ provider: "matomo", host: "m.example", siteId: "3" }, "//m.example/matomo.js"],
|
||||
[{ provider: "vercel" }, "/_vercel/insights/script.js"],
|
||||
[
|
||||
{ provider: "rybbit", siteId: "r1" },
|
||||
"https://app.rybbit.io/api/script.js",
|
||||
{ "data-site-id": "r1" },
|
||||
],
|
||||
[
|
||||
{ provider: "rybbit", siteId: "r1", host: "https://r.example" },
|
||||
"https://r.example/api/script.js",
|
||||
],
|
||||
]
|
||||
for (const [analytics, src, attributes] of cases) {
|
||||
test(`${JSON.stringify(analytics)} loads ${src}`, async () => {
|
||||
const { loaded } = await loadedScripts(analytics)
|
||||
assert.deepEqual(
|
||||
loaded.map((s) => s.src),
|
||||
[src],
|
||||
)
|
||||
for (const [name, value] of Object.entries(attributes ?? {})) {
|
||||
assert.equal(loaded[0].attributes[name], value, name)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("goatcounter counts at the site's endpoint; posthog gets its options", async () => {
|
||||
const gc = await loadedScripts({ provider: "goatcounter", websiteId: "g1", host: "gc.example" })
|
||||
assert.ok(gc.ours.join("\n").includes('"https://" + "g1" + "." + "gc.example" + "/count"'))
|
||||
const ph = await loadedScripts({
|
||||
provider: "posthog",
|
||||
apiKey: "k",
|
||||
uiHost: "https://ui.example",
|
||||
personProfiles: "identified_only",
|
||||
})
|
||||
const init = (ph.context.posthog as { _i: [string, Record<string, unknown>][] })._i[0]
|
||||
assert.deepEqual(init[0], "k")
|
||||
assert.deepEqual(
|
||||
{ ...init[1] },
|
||||
{
|
||||
api_host: "https://app.posthog.com",
|
||||
ui_host: "https://ui.example",
|
||||
person_profiles: "identified_only",
|
||||
capture_pageview: false,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("vercel's queue stub is defined in the prescript, before any script runs", async () => {
|
||||
const { ctx, read } = await emit({ analytics: { provider: "vercel" } }, { emitters: [] })
|
||||
const context = createContext({})
|
||||
context.window = context
|
||||
runInContext(read(ctx.hashedResourceNames!["prescript.js"]), context)
|
||||
assert.equal(typeof context.va, "function")
|
||||
context.va("event", "x")
|
||||
assert.deepEqual(
|
||||
[...(context.vaq as unknown[][])].map((args) => [...args]),
|
||||
[["event", "x"]],
|
||||
)
|
||||
})
|
||||
|
||||
test("no analytics, no analytics script", async () => {
|
||||
const { ours } = await loadedScripts({})
|
||||
assert.deepEqual(ours, [])
|
||||
})
|
||||
})
|
||||
@@ -2,26 +2,19 @@ import assert from "node:assert/strict"
|
||||
import { readFileSync } from "node:fs"
|
||||
import test, { describe } from "node:test"
|
||||
import { createContext, runInContext, runInNewContext } from "node:vm"
|
||||
import ts from "typescript"
|
||||
|
||||
// Exercise the actual generated script without importing the emitter's SCSS
|
||||
// and inline-script assets into Node or copying its counting implementation.
|
||||
const source = ts.createSourceFile(
|
||||
"componentResources.ts",
|
||||
readFileSync(new URL("./componentResources.ts", import.meta.url), "utf8"),
|
||||
ts.ScriptTarget.Latest,
|
||||
true,
|
||||
)
|
||||
let template: ts.TemplateExpression | undefined
|
||||
function findTemplate(node: ts.Node) {
|
||||
if (ts.isTemplateExpression(node) && node.head.text.includes("window.goatcounter = {")) {
|
||||
assert.equal(template, undefined, "expected a single GoatCounter script")
|
||||
template = node
|
||||
}
|
||||
ts.forEachChild(node, findTemplate)
|
||||
}
|
||||
findTemplate(source)
|
||||
assert.ok(template, "GoatCounter script template must exist")
|
||||
// The script is a template literal without nested template literals: it runs from the
|
||||
// backtick before its first line to the next backtick.
|
||||
const emitterSource = readFileSync(new URL("./componentResources.ts", import.meta.url), "utf8")
|
||||
const marker = "window.goatcounter = {"
|
||||
assert.equal(emitterSource.split(marker).length, 2, "expected a single GoatCounter script")
|
||||
const markerAt = emitterSource.indexOf(marker)
|
||||
const templateStart = emitterSource.lastIndexOf("`", markerAt)
|
||||
const templateEnd = emitterSource.indexOf("`", markerAt)
|
||||
assert.ok(templateStart >= 0 && templateEnd > markerAt, "GoatCounter script template must exist")
|
||||
const template = emitterSource.slice(templateStart, templateEnd + 1)
|
||||
|
||||
type Pageview = { path: string; title?: string }
|
||||
type Script = {
|
||||
@@ -65,7 +58,7 @@ function setup(
|
||||
context.window = context
|
||||
// the emitter writes config values with this helper (JSON string literals)
|
||||
const js = (value: unknown) => JSON.stringify(String(value)).replace(/</g, "\\u003c")
|
||||
const script = runInNewContext(template!.getText(source), { analytics, js })
|
||||
const script = runInNewContext(template, { analytics, js })
|
||||
runInContext(script, context)
|
||||
|
||||
return {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,23 +438,22 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
|
||||
// All component styles go into one stylesheet, in their order, in one
|
||||
// `quartz-base` layer: a file per component meant ~20 render-blocking
|
||||
// requests per page, many for a few hundred bytes.
|
||||
const cssStringToFilename = new Map<string, string>()
|
||||
for (const cssString of componentResources.componentCssStrings) {
|
||||
if (cssStringToFilename.has(cssString)) continue
|
||||
|
||||
const wrapped = `@layer quartz-base {\n${cssString}\n}`
|
||||
const minified = transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(wrapped),
|
||||
minify: true,
|
||||
targets: lightningTargets,
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
const componentCss = [...componentResources.componentCssStrings]
|
||||
if (componentCss.length > 0) {
|
||||
const minified = componentStylesheet(
|
||||
componentCss,
|
||||
(c) => componentResources.cssOwners.get(c),
|
||||
lightningTargets,
|
||||
)
|
||||
|
||||
const hash = hashContent(minified)
|
||||
const slug = `component-${hash}`
|
||||
const filename = `${slug}.css`
|
||||
cssStringToFilename.set(cssString, filename)
|
||||
for (const cssString of componentCss) cssStringToFilename.set(cssString, filename)
|
||||
|
||||
yield write({
|
||||
ctx,
|
||||
|
||||
@@ -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á"] })]), {})
|
||||
})
|
||||
})
|
||||
@@ -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),
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { getCondition, hasBacklinks } from "./conditions"
|
||||
import { getCondition, hasBacklinks, registerCondition } from "./conditions"
|
||||
import type { QuartzComponentProps } from "../../components/types"
|
||||
|
||||
type Props = Pick<QuartzComponentProps, "fileData" | "allFiles">
|
||||
@@ -51,3 +51,68 @@ describe("has-backlinks condition", () => {
|
||||
assert.strictEqual(hasBacklinks({ fileData: { slug: "a" } } as unknown as Props), false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("index conditions (#2465)", () => {
|
||||
const run = (name: string, slug: string | undefined) =>
|
||||
getCondition(name)!({ fileData: { slug }, allFiles: [] } as unknown as QuartzComponentProps)
|
||||
|
||||
test("is-index is true only on the root index page", () => {
|
||||
assert.strictEqual(run("is-index", "index"), true)
|
||||
assert.strictEqual(run("is-index", "folder/index"), false)
|
||||
assert.strictEqual(run("is-index", "page"), false)
|
||||
assert.strictEqual(run("is-index", undefined), false)
|
||||
})
|
||||
|
||||
test("is-index and not-index are complements", () => {
|
||||
for (const slug of ["index", "folder/index", "a/b", undefined]) {
|
||||
assert.strictEqual(run("is-index", slug), !run("not-index", slug))
|
||||
}
|
||||
})
|
||||
|
||||
test("is-folder-index matches folder index pages, not the root index", () => {
|
||||
assert.strictEqual(run("is-folder-index", "folder/index"), true)
|
||||
assert.strictEqual(run("is-folder-index", "a/b/index"), true)
|
||||
assert.strictEqual(run("is-folder-index", "index"), false)
|
||||
assert.strictEqual(run("is-folder-index", "folder/indexes"), false)
|
||||
assert.strictEqual(run("is-folder-index", undefined), false)
|
||||
})
|
||||
|
||||
test("is-folder-index is false on tag pages (the all-tags page is tags/index)", () => {
|
||||
assert.strictEqual(run("is-folder-index", "tags/index"), false)
|
||||
assert.strictEqual(run("is-folder-index", "tags/a/index"), false)
|
||||
assert.strictEqual(run("is-folder-index", "tags/a"), false)
|
||||
assert.strictEqual(run("is-folder-index", "my-tags/index"), true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("not-<condition> negation", () => {
|
||||
const withTags = { fileData: { slug: "a", frontmatter: { tags: ["x"] } }, allFiles: [] }
|
||||
const noTags = { fileData: { slug: "a", frontmatter: {} }, allFiles: [] }
|
||||
const call = (name: string, p: unknown) => getCondition(name)!(p as QuartzComponentProps)
|
||||
|
||||
test("not-has-tags negates has-tags", () => {
|
||||
assert.strictEqual(call("not-has-tags", withTags), false)
|
||||
assert.strictEqual(call("not-has-tags", noTags), true)
|
||||
})
|
||||
|
||||
test("negates custom conditions too", () => {
|
||||
registerCondition("is-draft-test", (p) => p.fileData.slug === "draft")
|
||||
assert.strictEqual(call("not-is-draft-test", { fileData: { slug: "draft" } }), false)
|
||||
assert.strictEqual(call("not-is-draft-test", { fileData: { slug: "x" } }), true)
|
||||
})
|
||||
|
||||
test("an exact name wins over negation (not-index is its own built-in)", () => {
|
||||
assert.strictEqual(call("not-index", { fileData: { slug: "index" } }), false)
|
||||
assert.strictEqual(call("not-index", { fileData: { slug: "a" } }), true)
|
||||
})
|
||||
|
||||
test("unknown names stay unknown", () => {
|
||||
assert.strictEqual(getCondition("not-nonexistent"), undefined)
|
||||
assert.strictEqual(getCondition("not-"), undefined)
|
||||
assert.strictEqual(getCondition("nonexistent"), undefined)
|
||||
})
|
||||
|
||||
test("double negation works", () => {
|
||||
assert.strictEqual(call("not-not-has-tags", withTags), true)
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,15 @@ import { FullSlug, simplifySlug } from "../../util/path"
|
||||
export type ConditionPredicate = (props: QuartzComponentProps) => boolean
|
||||
|
||||
const builtinConditions: Record<string, ConditionPredicate> = {
|
||||
"is-index": (props) => props.fileData.slug === "index",
|
||||
"not-index": (props) => props.fileData.slug !== "index",
|
||||
// A folder's index page: `folder/index.md` or a generated folder page, not the root index.
|
||||
// Tag pages aren't folders: `tags/` belongs to them (the all-tags page `tags/index`, and
|
||||
// `tags/<tag>` pages), so nothing under it is a folder index.
|
||||
"is-folder-index": (props) => {
|
||||
const slug = props.fileData.slug
|
||||
return typeof slug === "string" && slug.endsWith("/index") && !slug.startsWith("tags/")
|
||||
},
|
||||
"has-tags": (props) => {
|
||||
const tags = props.fileData.frontmatter?.tags
|
||||
return Array.isArray(tags) && tags.length > 0
|
||||
@@ -36,8 +44,21 @@ export function registerCondition(name: string, predicate: ConditionPredicate):
|
||||
customConditions.set(name, predicate)
|
||||
}
|
||||
|
||||
const NEGATION_PREFIX = "not-"
|
||||
|
||||
/**
|
||||
* Look up a condition. Besides the registered names, `not-<name>` negates any other
|
||||
* condition (`not-has-tags`, `not-is-folder-index`, a custom `not-<custom>`), unless a
|
||||
* condition with that exact name exists (`not-index` is its own built-in).
|
||||
*/
|
||||
export function getCondition(name: string): ConditionPredicate | undefined {
|
||||
return customConditions.get(name) ?? builtinConditions[name]
|
||||
const direct = customConditions.get(name) ?? builtinConditions[name]
|
||||
if (direct) return direct
|
||||
if (name.startsWith(NEGATION_PREFIX)) {
|
||||
const inner = getCondition(name.slice(NEGATION_PREFIX.length))
|
||||
if (inner) return (props) => !inner(props)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function getAllConditionNames(): string[] {
|
||||
|
||||
@@ -0,0 +1,675 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import path from "path"
|
||||
import fs from "fs"
|
||||
import YAML from "yaml"
|
||||
import {
|
||||
ConfigExtendsError,
|
||||
deepMerge,
|
||||
mergeQuartzConfigs,
|
||||
pluginMatchKey,
|
||||
localExtendsFiles,
|
||||
resolveExtends,
|
||||
resolveTarget,
|
||||
fetchRemoteConfig,
|
||||
} from "./config-extends"
|
||||
import os from "os"
|
||||
import type { QuartzPluginsJson } from "./types"
|
||||
|
||||
const base = (): QuartzPluginsJson => ({
|
||||
configuration: {
|
||||
pageTitle: "Quartz",
|
||||
ignorePatterns: ["private", ".obsidian"],
|
||||
theme: { typography: { header: "Schibsted Grotesk", body: "Source Sans Pro" } },
|
||||
links: { markdownLinkResolution: "shortest" },
|
||||
},
|
||||
plugins: [
|
||||
{ source: "@quartz-community/explorer", enabled: true, options: { a: 1, nested: { x: 1 } } },
|
||||
{
|
||||
source: "github:quartz-community/graph",
|
||||
enabled: true,
|
||||
order: 50,
|
||||
layout: { position: "right", priority: 10 },
|
||||
},
|
||||
{ source: "@quartz-community/comments", enabled: false },
|
||||
],
|
||||
layout: { byPageType: { folder: { exclude: ["graph"] } } },
|
||||
})
|
||||
|
||||
describe("deepMerge", () => {
|
||||
test("objects merge, other values replace, null deletes", () => {
|
||||
assert.deepStrictEqual(
|
||||
deepMerge({ a: { b: 1, c: 2 }, l: [1, 2], k: 1 }, { a: { c: 3 }, l: [9], k: null }),
|
||||
{
|
||||
a: { b: 1, c: 3 },
|
||||
l: [9],
|
||||
},
|
||||
)
|
||||
})
|
||||
test("does not modify its inputs", () => {
|
||||
const b = { a: { b: 1 } }
|
||||
deepMerge(b, { a: { b: 2 } })
|
||||
assert.deepStrictEqual(b, { a: { b: 1 } })
|
||||
})
|
||||
})
|
||||
|
||||
describe("pluginMatchKey", () => {
|
||||
test("npm, GitHub, git URL and local sources of one plugin match", () => {
|
||||
for (const source of [
|
||||
"@quartz-community/explorer",
|
||||
"@quartz-community/explorer@^2.0.0",
|
||||
"github:quartz-community/explorer",
|
||||
"github:someone/explorer#v2",
|
||||
"git+https://github.com/quartz-community/explorer.git",
|
||||
"https://github.com/quartz-community/explorer",
|
||||
"./plugins/explorer/",
|
||||
"explorer",
|
||||
{ repo: "github:quartz-community/plugins", subdir: "x", name: "explorer" },
|
||||
]) {
|
||||
assert.strictEqual(pluginMatchKey(source as never), "explorer", JSON.stringify(source))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("pluginMatchKey for monorepo subdirectories", () => {
|
||||
test("two plugins of one repository without a name get different keys", () => {
|
||||
const a = pluginMatchKey({ repo: "github:me/quartz-plugins", subdir: "plugins/a" })
|
||||
const b = pluginMatchKey({ repo: "github:me/quartz-plugins", subdir: "plugins/b" })
|
||||
assert.notStrictEqual(a, b)
|
||||
assert.strictEqual(a, "quartz-plugins/plugins/a")
|
||||
})
|
||||
test("subdir spellings are normalised", () => {
|
||||
for (const subdir of ["plugins/a", "./plugins/a/", "plugins\\a", "/plugins//a"]) {
|
||||
assert.strictEqual(
|
||||
pluginMatchKey({ repo: "https://github.com/me/quartz-plugins.git", subdir }),
|
||||
"quartz-plugins/plugins/a",
|
||||
subdir,
|
||||
)
|
||||
}
|
||||
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(
|
||||
{
|
||||
configuration: {},
|
||||
plugins: [
|
||||
{ source: { repo: "github:me/mono", subdir: "a" }, enabled: true },
|
||||
{ source: { repo: "github:me/mono", subdir: "b" }, enabled: true },
|
||||
],
|
||||
},
|
||||
{ plugins: [{ source: { repo: "github:me/mono", subdir: "b" }, enabled: false }] },
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
merged.plugins.map((p) => p.enabled),
|
||||
[true, false],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("mergeQuartzConfigs", () => {
|
||||
test("configuration deep-merges; arrays replace; null resets a key", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
configuration: {
|
||||
pageTitle: "My garden",
|
||||
ignorePatterns: ["drafts"],
|
||||
theme: { typography: { header: "Inter" } },
|
||||
links: null,
|
||||
},
|
||||
})
|
||||
assert.strictEqual(merged.configuration.pageTitle, "My garden")
|
||||
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["drafts"])
|
||||
assert.deepStrictEqual(merged.configuration.theme, {
|
||||
typography: { header: "Inter", body: "Source Sans Pro" },
|
||||
})
|
||||
assert.ok(!("links" in merged.configuration))
|
||||
// the base plugins are kept when the overlay lists none
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("plugins match by name; enabled/order/source replace, options/layout merge", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
plugins: [
|
||||
{
|
||||
source: "github:quartz-community/explorer",
|
||||
options: { b: 2, nested: { y: 2 } },
|
||||
} as never,
|
||||
{ source: "@quartz-community/graph", enabled: false, order: 10, layout: { priority: 1 } },
|
||||
{ source: "@quartz-community/comments", enabled: true },
|
||||
],
|
||||
})
|
||||
const [explorer, graph, comments] = merged.plugins
|
||||
assert.strictEqual(explorer.source, "github:quartz-community/explorer")
|
||||
assert.strictEqual(explorer.enabled, true)
|
||||
assert.deepStrictEqual(explorer.options, { a: 1, b: 2, nested: { x: 1, y: 2 } })
|
||||
assert.strictEqual(graph.enabled, false)
|
||||
assert.strictEqual(graph.order, 10)
|
||||
assert.deepStrictEqual(graph.layout, { position: "right", priority: 1 })
|
||||
assert.strictEqual(comments.enabled, true)
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("new plugins are appended as written (no enabled → disabled, as in a full config)", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
plugins: [
|
||||
{ source: "github:me/my-plugin", enabled: true, order: 70 },
|
||||
{ source: "github:me/other" },
|
||||
],
|
||||
})
|
||||
assert.strictEqual(merged.plugins.length, 5)
|
||||
assert.deepStrictEqual(merged.plugins[3], {
|
||||
source: "github:me/my-plugin",
|
||||
enabled: true,
|
||||
order: 70,
|
||||
})
|
||||
assert.deepStrictEqual(merged.plugins[4], { source: "github:me/other" })
|
||||
})
|
||||
|
||||
test("null removes a plugin's options, layout or order (back to the plugin's defaults)", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
plugins: [
|
||||
{ source: "@quartz-community/graph", layout: null, order: null } as never,
|
||||
{ source: "@quartz-community/explorer", options: { nested: null } } as never,
|
||||
],
|
||||
})
|
||||
const [explorer, graph] = merged.plugins
|
||||
assert.ok(!("layout" in graph) && !("order" in graph))
|
||||
assert.deepStrictEqual(explorer.options, { a: 1 })
|
||||
})
|
||||
|
||||
test("layout merges; arrays like byPageType.*.exclude replace", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
layout: { byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } } },
|
||||
})
|
||||
assert.deepStrictEqual(merged.layout, {
|
||||
byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } },
|
||||
})
|
||||
})
|
||||
|
||||
test("does not modify the base", () => {
|
||||
const b = base()
|
||||
const before = JSON.stringify(b)
|
||||
mergeQuartzConfigs(b, {
|
||||
configuration: { pageTitle: "x" },
|
||||
plugins: [{ source: "@quartz-community/explorer", options: { a: 2 } } as never],
|
||||
})
|
||||
assert.strictEqual(JSON.stringify(b), before)
|
||||
})
|
||||
|
||||
test("a plugin entry without source is an error", () => {
|
||||
assert.throws(
|
||||
() => mergeQuartzConfigs(base(), { plugins: [{ enabled: false } as never] }),
|
||||
ConfigExtendsError,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("resolveExtends", () => {
|
||||
const files: Record<string, string> = {}
|
||||
const root = path.resolve("/site")
|
||||
const readFile = (f: string) => {
|
||||
const content = files[path.resolve(f)]
|
||||
if (content === undefined) throw new Error("ENOENT")
|
||||
return content
|
||||
}
|
||||
const put = (rel: string, data: unknown) => {
|
||||
files[path.join(root, rel)] = YAML.stringify(data)
|
||||
}
|
||||
put("quartz.config.default.yaml", base())
|
||||
|
||||
test("a config without extends is returned as is", async () => {
|
||||
const data = { configuration: { pageTitle: "x" }, plugins: [] }
|
||||
assert.strictEqual(
|
||||
await resolveExtends(data, path.join(root, "quartz.config.yaml")),
|
||||
data as never,
|
||||
)
|
||||
})
|
||||
|
||||
test("extends: default merges onto quartz.config.default.yaml", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "Mine" },
|
||||
plugins: [{ source: "@quartz-community/graph", enabled: false }],
|
||||
},
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Mine")
|
||||
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["private", ".obsidian"])
|
||||
assert.strictEqual(
|
||||
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
|
||||
false,
|
||||
)
|
||||
assert.ok(!("extends" in merged))
|
||||
})
|
||||
|
||||
test("relative paths, chains and lists (later wins)", async () => {
|
||||
put("configs/team.yaml", {
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "Team", locale: "cs-CZ" },
|
||||
})
|
||||
put("configs/dark.yaml", { configuration: { pageTitle: "Dark" } })
|
||||
const merged = await resolveExtends(
|
||||
{
|
||||
extends: ["./configs/team.yaml", "configs/dark.yaml"],
|
||||
configuration: { baseUrl: "x.org" },
|
||||
},
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Dark")
|
||||
assert.strictEqual(merged.configuration.locale, "cs-CZ")
|
||||
assert.strictEqual(merged.configuration.baseUrl, "x.org")
|
||||
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
|
||||
})
|
||||
|
||||
test("presets stack: each listed base adds its own changes; a shared base applies once", async () => {
|
||||
put("presets/title.yaml", {
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "Preset A", locale: "fr-FR" },
|
||||
plugins: [{ source: "@quartz-community/graph", enabled: false }],
|
||||
})
|
||||
put("presets/explorer.yaml", {
|
||||
extends: "default",
|
||||
configuration: { locale: "nl-NL" },
|
||||
plugins: [{ source: "@quartz-community/explorer", options: { b: 2 } }],
|
||||
})
|
||||
const merged = await resolveExtends(
|
||||
{ extends: ["./presets/title.yaml", "./presets/explorer.yaml"] },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
// a's changes survive b (both extend default)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Preset A")
|
||||
assert.strictEqual(
|
||||
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
|
||||
false,
|
||||
)
|
||||
// b wins where both change something
|
||||
assert.strictEqual(merged.configuration.locale, "nl-NL")
|
||||
assert.deepStrictEqual(
|
||||
merged.plugins.find((p) => pluginMatchKey(p.source) === "explorer")!.options,
|
||||
{ a: 1, nested: { x: 1 }, b: 2 },
|
||||
)
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("diamond: a base reached twice is applied once, at its first appearance", async () => {
|
||||
put("d/common.yaml", { extends: "default", configuration: { locale: "common" } })
|
||||
put("d/left.yaml", { extends: "./common.yaml", configuration: { pageTitle: "Left" } })
|
||||
put("d/right.yaml", { extends: "./common.yaml", configuration: { baseUrl: "right.org" } })
|
||||
const merged = await resolveExtends(
|
||||
{ extends: ["./d/left.yaml", "./d/right.yaml", "./d/left.yaml"] },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Left")
|
||||
assert.strictEqual(merged.configuration.baseUrl, "right.org")
|
||||
assert.strictEqual(merged.configuration.locale, "common")
|
||||
assert.deepStrictEqual(
|
||||
await localExtendsFiles(
|
||||
{ extends: ["./d/left.yaml", "./d/right.yaml"] },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
),
|
||||
["quartz.config.default.yaml", "d/common.yaml", "d/left.yaml", "d/right.yaml"].map((f) =>
|
||||
path.join(root, f),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
test("extends: [] is no base; an empty base file is an empty config", async () => {
|
||||
const data = { extends: [], configuration: { pageTitle: "x" }, plugins: [] }
|
||||
assert.deepStrictEqual(await resolveExtends(data, path.join(root, "quartz.config.yaml")), {
|
||||
configuration: { pageTitle: "x" },
|
||||
plugins: [],
|
||||
})
|
||||
files[path.join(root, "empty.yaml")] = "# nothing here yet\n"
|
||||
const merged = await resolveExtends(
|
||||
{ extends: ["default", "./empty.yaml"], configuration: { pageTitle: "E" } },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "E")
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("plugins that are not a list are reported clearly", async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends(
|
||||
{ extends: "default", plugins: { explorer: { enabled: false } } },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
),
|
||||
(err: Error) => err instanceof ConfigExtendsError && /must be a list/.test(err.message),
|
||||
)
|
||||
})
|
||||
|
||||
test("cycles and missing files are reported", async () => {
|
||||
put("a.yaml", { extends: "./b.yaml" })
|
||||
put("b.yaml", { extends: "./a.yaml" })
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends({ extends: "./a.yaml" }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
{
|
||||
name: "ConfigExtendsError",
|
||||
message: '"extends" cycle: quartz.config.yaml → a.yaml → b.yaml → a.yaml',
|
||||
},
|
||||
)
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends({ extends: "./nope.yaml" }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
/not found/,
|
||||
)
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends({ extends: 3 }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
ConfigExtendsError,
|
||||
)
|
||||
})
|
||||
|
||||
test("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"))
|
||||
const merged = await resolveExtends({ extends: "default" }, path.resolve("quartz.config.yaml"))
|
||||
assert.deepStrictEqual(merged, shipped)
|
||||
})
|
||||
|
||||
describe("https bases", () => {
|
||||
const remote: Record<string, string> = {
|
||||
"https://cfg.example/base/site.yaml": YAML.stringify({
|
||||
extends: "./common.yaml",
|
||||
configuration: { pageTitle: "Remote" },
|
||||
}),
|
||||
"https://cfg.example/base/common.yaml": YAML.stringify({
|
||||
extends: "default",
|
||||
configuration: { locale: "de-DE" },
|
||||
}),
|
||||
}
|
||||
const fetchRemote = async (url: string) => {
|
||||
if (!(url in remote)) throw new ConfigExtendsError(`404 ${url}`)
|
||||
return remote[url]
|
||||
}
|
||||
const opts = () => ({ quartzRoot: root, readFile, fetchRemote })
|
||||
|
||||
test("a URL base; its relative extends resolve against the URL; default stays local", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{ extends: "https://cfg.example/base/site.yaml", configuration: { baseUrl: "me.org" } },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
opts(),
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Remote")
|
||||
assert.strictEqual(merged.configuration.locale, "de-DE")
|
||||
assert.strictEqual(merged.configuration.baseUrl, "me.org")
|
||||
assert.strictEqual(merged.plugins.length, 3) // the local default, via the remote chain
|
||||
})
|
||||
|
||||
test("uppercase HTTPS:// is https", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{ extends: "HTTPS://CFG.example/base/site.yaml" },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
opts(),
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Remote")
|
||||
})
|
||||
|
||||
test("only https", async () => {
|
||||
await assert.rejects(
|
||||
resolveExtends({ extends: "http://cfg.example/x.yaml" }, path.join(root, "q.yaml"), opts()),
|
||||
/only https/,
|
||||
)
|
||||
assert.strictEqual(
|
||||
resolveTarget("../other.yaml", "https://cfg.example/base/site.yaml", root),
|
||||
"https://cfg.example/other.yaml",
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("fetchRemoteConfig", () => {
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
|
||||
const ok = (body: string) =>
|
||||
(async () => new Response(body, { status: 200 })) as unknown as typeof fetch
|
||||
const failing = (async () => {
|
||||
throw new Error("getaddrinfo ENOTFOUND")
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
test("caches a fetched copy and falls back to it when offline or failing", async () => {
|
||||
const cacheDir = tmp()
|
||||
const url = "https://cfg.example/a.yaml"
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: ok("a: 1\n"), offline: false }),
|
||||
"a: 1\n",
|
||||
)
|
||||
const warnings: string[] = []
|
||||
const other = tmp()
|
||||
fs.cpSync(cacheDir, other, { recursive: true })
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, {
|
||||
cacheDir: other,
|
||||
fetchImpl: failing,
|
||||
offline: false,
|
||||
warn: (m) => warnings.push(m),
|
||||
}),
|
||||
"a: 1\n",
|
||||
)
|
||||
assert.match(warnings[0], /using the cached copy/)
|
||||
// offline (QUARTZ_EXTENDS_OFFLINE=1, worker threads): the cache only
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig("https://cfg.example/a.yaml?x", {
|
||||
cacheDir: other,
|
||||
offline: true,
|
||||
}).catch((e: Error) => e.message),
|
||||
`"extends: https://cfg.example/a.yaml?x": no cached copy in ${other} (offline build). Build once online first.`,
|
||||
)
|
||||
})
|
||||
|
||||
test("without a cached copy a failed fetch stops the build", async () => {
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig("https://cfg.example/b.yaml", {
|
||||
cacheDir: tmp(),
|
||||
fetchImpl: failing,
|
||||
offline: false,
|
||||
}),
|
||||
/could not be fetched: getaddrinfo ENOTFOUND/,
|
||||
)
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig("https://cfg.example/c.yaml", { cacheDir: tmp(), offline: true }),
|
||||
/no cached copy/,
|
||||
)
|
||||
})
|
||||
|
||||
test("HTTP errors are failures, too", async () => {
|
||||
const notFound = (async () => new Response("nope", { status: 404 })) as unknown as typeof fetch
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig("https://cfg.example/d.yaml", {
|
||||
cacheDir: tmp(),
|
||||
fetchImpl: notFound,
|
||||
offline: false,
|
||||
}),
|
||||
/HTTP 404/,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
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,452 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { createHash } from "crypto"
|
||||
import { isMainThread } from "worker_threads"
|
||||
import YAML from "yaml"
|
||||
import type {
|
||||
PluginJsonEntry,
|
||||
PluginLayoutDeclaration,
|
||||
PluginSource,
|
||||
QuartzPluginsJson,
|
||||
} from "./types"
|
||||
|
||||
/**
|
||||
* `extends:` in quartz.config.yaml (#2440): start from another config and apply only the
|
||||
* differences on top.
|
||||
*
|
||||
* ```yaml
|
||||
* extends: default # quartz.config.default.yaml next to quartz.config.yaml's Quartz
|
||||
* configuration:
|
||||
* pageTitle: My garden
|
||||
* plugins:
|
||||
* - source: "@quartz-community/explorer"
|
||||
* options: { folderDefaultState: open }
|
||||
* - source: "@quartz-community/graph"
|
||||
* enabled: false
|
||||
* ```
|
||||
*
|
||||
* Merge rules (`mergeQuartzConfigs`):
|
||||
* - `configuration` and `layout`: objects merge key by key, recursively; any other value
|
||||
* (strings, numbers, arrays such as `ignorePatterns` or `byPageType.*.exclude`) replaces the
|
||||
* base value; `null` removes the key (back to the built-in default).
|
||||
* - `plugins`: an entry matches the base entry of the same plugin (by plugin name, so
|
||||
* `github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the
|
||||
* same name replaces the original). Of a matched entry, `source`, `enabled` and `order`
|
||||
* replace the base values, and `options` and `layout` merge like `configuration`. Entries
|
||||
* that match nothing are appended, as in a full config (so they need `enabled: true`). The base list keeps its order, which only matters as the
|
||||
* tie-break between plugins with the same `order`.
|
||||
* - `extends` lists stack (see resolveExtends): every file of the graph is applied once, after
|
||||
* its bases, so presets that share `default` each keep their own changes.
|
||||
* - A config without `extends` is used exactly as written, as before.
|
||||
*/
|
||||
|
||||
/** The name `extends: default` stands for. */
|
||||
export const DEFAULT_EXTENDS = "default"
|
||||
export const DEFAULT_CONFIG_FILE = "quartz.config.default.yaml"
|
||||
|
||||
/** A configuration mistake: reported by its message alone (no stack trace). */
|
||||
export class ConfigExtendsError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = "ConfigExtendsError"
|
||||
this.stack = `${this.name}: ${message}`
|
||||
}
|
||||
}
|
||||
|
||||
type PlainObject = Record<string, unknown>
|
||||
|
||||
/** A plugin entry in a config that extends another: only `source` is required. */
|
||||
export interface PluginOverlayEntry {
|
||||
source: PluginSource
|
||||
enabled?: boolean
|
||||
/** Merged into the base entry's options; `null` drops them (the plugin's defaults apply). */
|
||||
options?: Record<string, unknown> | null
|
||||
order?: number | null
|
||||
/** Replace the base entry's constraints; `null` removes them. */
|
||||
before?: string | string[] | null
|
||||
after?: string | string[] | null
|
||||
/** Merged into the base entry's layout; `null` drops it (the plugin's default placement). */
|
||||
layout?: Partial<PluginLayoutDeclaration> | null
|
||||
}
|
||||
|
||||
/** What a config with `extends` may contain: any part of a full config. */
|
||||
export interface QuartzConfigOverlay {
|
||||
$schema?: string
|
||||
extends?: string | string[] | null
|
||||
configuration?: Record<string, unknown>
|
||||
plugins?: PluginOverlayEntry[]
|
||||
layout?: Record<string, unknown>
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is PlainObject {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/** Recursive merge: objects merge, everything else replaces, `null` deletes. */
|
||||
export function deepMerge(base: unknown, overlay: unknown): unknown {
|
||||
if (overlay === undefined) return base
|
||||
if (!isPlainObject(base) || !isPlainObject(overlay)) return overlay
|
||||
const result: PlainObject = { ...base }
|
||||
for (const [key, value] of Object.entries(overlay)) {
|
||||
if (value === null) {
|
||||
delete result[key]
|
||||
} else {
|
||||
result[key] = deepMerge(base[key], value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* The name a plugin entry is matched by: the last path segment of its package or repository
|
||||
* (`@quartz-community/explorer`, `github:quartz-community/explorer#v2`, `./plugins/explorer` →
|
||||
* `explorer`), or the `name` of an object source. An object source without a `name` that
|
||||
* points at a `subdir` of a repository is matched by both (`plugins/explorer` in
|
||||
* `github:me/quartz-plugins` → `quartz-plugins/plugins/explorer`), so two plugins of one
|
||||
* monorepo stay apart.
|
||||
*/
|
||||
export function pluginMatchKey(source: PluginSource): string {
|
||||
if (typeof source === "object" && source !== null) {
|
||||
if (source.name) return source.name
|
||||
const repoKey = pluginMatchKey(source.repo)
|
||||
const subdir = normalizeSubdir(source.subdir)
|
||||
return subdir ? `${repoKey}/${subdir}` : repoKey
|
||||
}
|
||||
let s = String(source).trim()
|
||||
s = s.replace(/^git\+/i, "").replace(/^github:/i, "")
|
||||
s = s.split("#")[0]
|
||||
s = s.replace(/\.git$/i, "").replace(/[\\/]+$/, "")
|
||||
// an npm version/range: @scope/name@1.2.3, name@^1
|
||||
s = s.replace(/(.)@[^/]*$/, "$1")
|
||||
return s.slice(Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\")) + 1)
|
||||
}
|
||||
|
||||
/** `./plugins/x/`, `plugins\\x`, `/plugins/x` → `plugins/x`; empty or `.` → "". */
|
||||
function normalizeSubdir(subdir: unknown): string {
|
||||
if (typeof subdir !== "string") return ""
|
||||
return subdir
|
||||
.replace(/\\/g, "/")
|
||||
.split("/")
|
||||
.filter((part) => part !== "" && part !== ".")
|
||||
.join("/")
|
||||
}
|
||||
|
||||
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
|
||||
const merged: PlainObject = { ...base }
|
||||
for (const [key, value] of Object.entries(overlay)) {
|
||||
if (value === undefined) continue
|
||||
if (key === "options" || key === "layout") {
|
||||
const next = value === null ? undefined : deepMerge(merged[key], value)
|
||||
if (next === undefined) delete merged[key]
|
||||
else merged[key] = next
|
||||
} else if (value === null) {
|
||||
delete merged[key]
|
||||
} else {
|
||||
merged[key] = value
|
||||
}
|
||||
}
|
||||
return merged as unknown as PluginJsonEntry
|
||||
}
|
||||
|
||||
function pluginList<T>(value: T[] | null | undefined, where: string): T[] {
|
||||
if (value === undefined || value === null) return []
|
||||
if (!Array.isArray(value)) {
|
||||
throw new ConfigExtendsError(
|
||||
`"plugins" in ${where} must be a list of plugin entries (- source: …), not ${typeof value === "object" ? "an object" : JSON.stringify(value)}`,
|
||||
)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
|
||||
export function mergeQuartzConfigs(
|
||||
base: QuartzPluginsJson,
|
||||
overlay: QuartzConfigOverlay,
|
||||
): QuartzPluginsJson {
|
||||
const { extends: _extends, plugins: overlayPlugins, ...rest } = overlay
|
||||
const merged = deepMerge(
|
||||
{ ...base, plugins: undefined },
|
||||
{ ...rest, plugins: undefined },
|
||||
) as QuartzPluginsJson
|
||||
|
||||
const plugins = pluginList(base.plugins, "the base config").map((entry) => ({ ...entry }))
|
||||
for (const entry of pluginList(overlayPlugins, "the extending config")) {
|
||||
if (!entry || entry.source === undefined) {
|
||||
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
|
||||
}
|
||||
const key = pluginMatchKey(entry.source)
|
||||
const index = plugins.findIndex((p) => pluginMatchKey(p.source) === key)
|
||||
if (index === -1) {
|
||||
// a new plugin, read like an entry of a full config (no `enabled` → disabled, with a warning)
|
||||
plugins.push({ ...entry } as PluginJsonEntry)
|
||||
} else {
|
||||
plugins[index] = mergePluginEntry(plugins[index], entry)
|
||||
}
|
||||
}
|
||||
merged.plugins = plugins
|
||||
merged.configuration = (merged.configuration ?? {}) as QuartzPluginsJson["configuration"]
|
||||
return merged
|
||||
}
|
||||
|
||||
export interface ResolveExtendsOptions {
|
||||
/** Directory holding quartz.config.default.yaml (`extends: default`). Default: cwd. */
|
||||
quartzRoot?: string
|
||||
/** Local file reader, for tests. */
|
||||
readFile?: (file: string) => string
|
||||
/** Loader for `https://` bases; default `fetchRemoteConfig` (cached, with a timeout). */
|
||||
fetchRemote?: (url: string) => Promise<string>
|
||||
}
|
||||
|
||||
/** Where fetched remote bases are kept (offline builds, worker threads). */
|
||||
export const REMOTE_CACHE_DIR = path.join(".quartz-cache", "extends")
|
||||
const REMOTE_TIMEOUT_MS = 10_000
|
||||
const REMOTE_MAX_BYTES = 1024 * 1024
|
||||
|
||||
const isUrl = (s: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s)
|
||||
const isHttps = (s: string) => /^https:\/\//i.test(s)
|
||||
|
||||
function remoteCacheFile(url: string, cacheDir: string): string {
|
||||
return path.join(cacheDir, createHash("sha256").update(url).digest("hex").slice(0, 32) + ".yaml")
|
||||
}
|
||||
|
||||
export interface FetchRemoteOptions {
|
||||
cacheDir?: string
|
||||
timeoutMs?: number
|
||||
/** Only use the cache (QUARTZ_EXTENDS_OFFLINE=1; always in worker threads). */
|
||||
offline?: boolean
|
||||
fetchImpl?: typeof fetch
|
||||
warn?: (message: string) => void
|
||||
}
|
||||
|
||||
const fetched = new Map<string, Promise<string>>()
|
||||
|
||||
/**
|
||||
* Fetch a remote base config: once per process, with a timeout and a size limit. A successful
|
||||
* fetch is cached in `.quartz-cache/extends/`; when the fetch fails (offline, timeout, HTTP
|
||||
* error) the cached copy is used with a warning, and without one the build stops. Worker threads
|
||||
* and `QUARTZ_EXTENDS_OFFLINE=1` read only the cache, so every thread of a build sees the copy
|
||||
* the main thread fetched.
|
||||
*/
|
||||
export function fetchRemoteConfig(url: string, opts: FetchRemoteOptions = {}): Promise<string> {
|
||||
const cacheDir = opts.cacheDir ?? path.join(process.cwd(), REMOTE_CACHE_DIR)
|
||||
const key = `${cacheDir}\0${url}`
|
||||
let pending = fetched.get(key)
|
||||
if (!pending) {
|
||||
pending = fetchUncached(url, cacheDir, opts)
|
||||
fetched.set(key, pending)
|
||||
pending.catch(() => fetched.delete(key))
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOptions) {
|
||||
const cacheFile = remoteCacheFile(url, cacheDir)
|
||||
const cached = () => {
|
||||
try {
|
||||
return fs.readFileSync(cacheFile, "utf-8")
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
const offline = opts.offline ?? (process.env.QUARTZ_EXTENDS_OFFLINE === "1" || !isMainThread)
|
||||
if (offline) {
|
||||
const copy = cached()
|
||||
if (copy !== undefined) return copy
|
||||
throw new ConfigExtendsError(
|
||||
`"extends: ${url}": no cached copy in ${cacheDir} (offline build). Build once online first.`,
|
||||
)
|
||||
}
|
||||
const warn = opts.warn ?? ((m: string) => console.warn(`⚠ ${m}`))
|
||||
let failure: string
|
||||
try {
|
||||
const res = await (opts.fetchImpl ?? fetch)(url, {
|
||||
signal: AbortSignal.timeout(opts.timeoutMs ?? REMOTE_TIMEOUT_MS),
|
||||
headers: { accept: "application/yaml, application/json, text/plain, */*" },
|
||||
})
|
||||
if (res.url && !isHttps(res.url)) {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" redirected to ${res.url}, which is not https`)
|
||||
}
|
||||
if (!res.ok) {
|
||||
failure = `HTTP ${res.status}`
|
||||
} else {
|
||||
const text = await res.text()
|
||||
if (Buffer.byteLength(text) > REMOTE_MAX_BYTES) {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" is larger than 1 MB`)
|
||||
}
|
||||
fs.mkdirSync(cacheDir, { recursive: true })
|
||||
fs.writeFileSync(cacheFile, text)
|
||||
return text
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ConfigExtendsError) throw err
|
||||
failure = err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
const copy = cached()
|
||||
if (copy !== undefined) {
|
||||
warn(`"extends: ${url}" could not be fetched (${failure}); using the cached copy.`)
|
||||
return copy
|
||||
}
|
||||
throw new ConfigExtendsError(`"extends: ${url}" could not be fetched: ${failure}`)
|
||||
}
|
||||
|
||||
function parseConfigFile(file: string, raw: string): PlainObject {
|
||||
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
|
||||
// an empty file (or one with only comments) is an empty config
|
||||
if (data === null || data === undefined) return {}
|
||||
if (!isPlainObject(data)) {
|
||||
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
function extendsTargets(value: unknown, file: string): string[] {
|
||||
const list = Array.isArray(value) ? value : [value]
|
||||
for (const item of list) {
|
||||
if (typeof item !== "string" || item.trim() === "") {
|
||||
throw new ConfigExtendsError(
|
||||
`${file}: "extends" must be "${DEFAULT_EXTENDS}", a path to another config file, an https:// URL, or a list of them`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return list as string[]
|
||||
}
|
||||
|
||||
function normalizeUrl(url: string): string {
|
||||
try {
|
||||
return new URL(url).href
|
||||
} catch {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" is not a valid URL`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an `extends` target points, seen from the file (or URL) that names it: `default` is
|
||||
* the local quartz.config.default.yaml; a URL is used as is; a relative path is resolved
|
||||
* against the extending file's directory, or against its URL when that file was fetched (a
|
||||
* remote config cannot reach local files). Only https URLs are allowed. (A future
|
||||
* `npm:<package>` target would be one more case here.)
|
||||
*/
|
||||
export function resolveTarget(target: string, from: string, quartzRoot: string): string {
|
||||
if (target === DEFAULT_EXTENDS) return path.join(quartzRoot, DEFAULT_CONFIG_FILE)
|
||||
// URLs are normalised (`HTTPS://Example.org/x` → `https://example.org/x`)
|
||||
const resolved = isUrl(target)
|
||||
? normalizeUrl(target)
|
||||
: isUrl(from)
|
||||
? new URL(target, from).href
|
||||
: path.resolve(path.dirname(from), target)
|
||||
if (isUrl(resolved) && !isHttps(resolved)) {
|
||||
throw new ConfigExtendsError(
|
||||
`${from}: "extends: ${target}" — only https:// URLs can be extended`,
|
||||
)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
interface ConfigLayer {
|
||||
/** Resolved path or URL ("" for the config being resolved). */
|
||||
file: string
|
||||
/** The file's own content, without `extends`. */
|
||||
data: PlainObject
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply `extends` of `data` (read from `file`, a path or URL) and return the merged config.
|
||||
* Returns `data` itself when it has no `extends` (or an empty list), so configs without it
|
||||
* behave exactly as before.
|
||||
*
|
||||
* Every file in the `extends` graph is a layer of its own changes, applied once, after all of
|
||||
* its bases (depth first, in list order). A base that several entries share (usually
|
||||
* `default`) is applied at its first appearance, so for `extends: [./a.yaml, ./b.yaml]` where
|
||||
* both extend `default` the order is default → a → b → this file: what a.yaml changes stays
|
||||
* unless b.yaml changes the same thing (later entries win), and this file wins over all.
|
||||
*/
|
||||
export async function resolveExtends(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions = {},
|
||||
): Promise<QuartzPluginsJson> {
|
||||
const targets = data.extends === undefined || data.extends === null ? [] : data.extends
|
||||
if (Array.isArray(targets) && targets.length === 0) {
|
||||
const { extends: _drop, ...rest } = data
|
||||
return ("extends" in data ? rest : data) as unknown as QuartzPluginsJson
|
||||
}
|
||||
const layers = await extendsLayers(data, file, options)
|
||||
const [first, ...rest] = layers
|
||||
let merged = first.data as unknown as QuartzPluginsJson
|
||||
pluginList(merged.plugins, first.file)
|
||||
for (const layer of rest) {
|
||||
merged = mergeQuartzConfigs(merged, layer.data as QuartzConfigOverlay)
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
/**
|
||||
* The local files (absolute paths) `data` extends, directly or through other bases; URLs are
|
||||
* left out. For `--serve`, which rebuilds when one of them changes.
|
||||
*/
|
||||
export async function localExtendsFiles(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions = {},
|
||||
): Promise<string[]> {
|
||||
if (data.extends === undefined || data.extends === null) return []
|
||||
const layers = await extendsLayers(data, file, options)
|
||||
return layers.map((l) => l.file).filter((f) => f !== "" && !isUrl(f))
|
||||
}
|
||||
|
||||
/** The layers of `data` in the order they are applied: bases first, `data` itself last. */
|
||||
async function extendsLayers(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions,
|
||||
): Promise<ConfigLayer[]> {
|
||||
const readFile = options.readFile ?? ((f: string) => fs.readFileSync(f, "utf-8"))
|
||||
const fetchRemote = options.fetchRemote ?? ((url: string) => fetchRemoteConfig(url))
|
||||
const quartzRoot = options.quartzRoot ?? process.cwd()
|
||||
const layers: ConfigLayer[] = []
|
||||
const applied = new Set<string>()
|
||||
|
||||
const visit = async (node: PlainObject, nodeFile: string, chain: string[]) => {
|
||||
const self = isUrl(nodeFile) ? nodeFile : path.resolve(nodeFile)
|
||||
const here = [...chain, self]
|
||||
const raw = node.extends
|
||||
const targets = raw === undefined || raw === null ? [] : extendsTargets(raw, nodeFile)
|
||||
for (const target of targets) {
|
||||
const targetFile = resolveTarget(target, nodeFile, quartzRoot)
|
||||
if (here.includes(targetFile)) {
|
||||
throw new ConfigExtendsError(
|
||||
`"extends" cycle: ${[...here, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
|
||||
)
|
||||
}
|
||||
if (applied.has(targetFile)) continue
|
||||
let text: string
|
||||
if (isUrl(targetFile)) {
|
||||
text = await fetchRemote(targetFile)
|
||||
} else {
|
||||
try {
|
||||
text = readFile(targetFile)
|
||||
} catch {
|
||||
throw new ConfigExtendsError(
|
||||
`${nodeFile}: "extends: ${target}" — ${targetFile} not found`,
|
||||
)
|
||||
}
|
||||
}
|
||||
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
|
||||
let parsed: PlainObject
|
||||
try {
|
||||
parsed = parseConfigFile(parsePath, text)
|
||||
} catch (err) {
|
||||
throw new ConfigExtendsError(
|
||||
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
|
||||
)
|
||||
}
|
||||
await visit(parsed, targetFile, here)
|
||||
}
|
||||
const { extends: _drop, ...own } = node
|
||||
layers.push({ file: chain.length === 0 ? "" : self, data: own })
|
||||
applied.add(self)
|
||||
}
|
||||
|
||||
await visit(data, file, [])
|
||||
return layers
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
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 { getDiagnostics, resetDiagnostics } from "../../util/diagnostics"
|
||||
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"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("loadQuartzConfig: configuration, options and loading", () => {
|
||||
let dir: string
|
||||
before(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-config-"))
|
||||
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 = (content: string) => {
|
||||
const file = path.join(dir, "quartz.config.yaml")
|
||||
fs.writeFileSync(file, content)
|
||||
process.env.QUARTZ_CONFIG_PATH = file
|
||||
}
|
||||
const instance = (cfg: Awaited<ReturnType<typeof loadQuartzConfig>>, name: string) =>
|
||||
cfg.plugins.transformers.find((p) => p.name === name)
|
||||
|
||||
test("CLI overrides win over the YAML configuration; built-ins are exposed with their settings", async () => {
|
||||
useConfig(`configuration:
|
||||
pageTitle: From YAML
|
||||
baseUrl: yaml.example.com
|
||||
links:
|
||||
prettyLinks: false
|
||||
plugins: []
|
||||
`)
|
||||
const cfg = await loadQuartzConfig({ baseUrl: "cli.example.com" })
|
||||
assert.equal(cfg.configuration.baseUrl, "cli.example.com")
|
||||
assert.equal(cfg.configuration.pageTitle, "From YAML")
|
||||
// configuration.links: the configured options over the built-in's defaults, enabled and order
|
||||
assert.deepEqual(cfg.configuration.links, {
|
||||
markdownLinkResolution: "shortest",
|
||||
prettyLinks: false,
|
||||
openLinksInNewTab: false,
|
||||
lazyLoad: false,
|
||||
externalLinkIcon: true,
|
||||
disableBrokenWikilinks: true,
|
||||
enabled: true,
|
||||
order: 60,
|
||||
})
|
||||
assert.deepEqual(names(cfg.plugins.transformers), ["Frontmatter", "Links"])
|
||||
// the built-in emitters, then the page renderer last; the 404 page type is always there
|
||||
assert.deepEqual(names(cfg.plugins.emitters), [
|
||||
"ComponentResources",
|
||||
"Assets",
|
||||
"Static",
|
||||
"SlugRedirects",
|
||||
"ContentIndex",
|
||||
"Fonts",
|
||||
"PageTypeDispatcher",
|
||||
])
|
||||
assert.deepEqual(names(cfg.plugins.pageTypes ?? []), ["404"])
|
||||
})
|
||||
|
||||
test("a former crawl-links entry configures the built-in with crawl-links' defaults and isn't loaded", async () => {
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/crawl-links"
|
||||
enabled: true
|
||||
options:
|
||||
openLinksInNewTab: true
|
||||
`)
|
||||
resetDiagnostics()
|
||||
const cfg = await loadQuartzConfig()
|
||||
// not installed, and not tried: no load error
|
||||
assert.deepEqual(
|
||||
getDiagnostics().filter((d) => d.severity === "error"),
|
||||
[],
|
||||
)
|
||||
const links = cfg.configuration.links as unknown as Record<string, unknown>
|
||||
assert.equal(links.markdownLinkResolution, "absolute")
|
||||
assert.equal(links.openLinksInNewTab, true)
|
||||
assert.deepEqual(names(cfg.plugins.transformers), ["Frontmatter", "Links"])
|
||||
})
|
||||
|
||||
test("an entry's options override the manifest's defaultOptions", async () => {
|
||||
// Latex' defaultOptions say renderEngine: katex, whose stylesheet it adds as a resource;
|
||||
// with mathjax it adds none
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/latex"
|
||||
enabled: true
|
||||
`)
|
||||
const katex = instance(await loadQuartzConfig(), "Latex")
|
||||
assert.ok(katex?.externalResources?.({} as never), "katex resources")
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/latex"
|
||||
enabled: true
|
||||
options:
|
||||
renderEngine: mathjax
|
||||
`)
|
||||
const mathjax = instance(await loadQuartzConfig(), "Latex")
|
||||
assert.ok(mathjax, "Latex is loaded")
|
||||
assert.equal(mathjax.externalResources?.({} as never), undefined)
|
||||
})
|
||||
|
||||
test("plugins run by entry order, then defaultOrder; disabled entries aren't loaded", async () => {
|
||||
// defaultOrder: description 70, latex 80, table-of-contents 50
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/latex"
|
||||
enabled: true
|
||||
order: 5
|
||||
- source: "@quartz-community/description"
|
||||
enabled: true
|
||||
- source: "@quartz-community/table-of-contents"
|
||||
enabled: true
|
||||
- source: "@quartz-community/hard-line-breaks"
|
||||
enabled: false
|
||||
`)
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.deepEqual(names(cfg.plugins.transformers), [
|
||||
"Frontmatter",
|
||||
"Latex",
|
||||
"TableOfContents",
|
||||
"Links",
|
||||
"Description",
|
||||
])
|
||||
})
|
||||
|
||||
test("a plugin that can't be loaded is skipped locally and fails the build in CI", async () => {
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/does-not-exist"
|
||||
enabled: true
|
||||
- source: "@quartz-community/description"
|
||||
enabled: true
|
||||
`)
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.ok(names(cfg.plugins.transformers).includes("Description"))
|
||||
|
||||
const saved = { ...process.env }
|
||||
try {
|
||||
delete process.env.QUARTZ_CONFIG_QUIET
|
||||
delete process.env.QUARTZ_ALLOW_BROKEN_PLUGINS
|
||||
process.env.CI = "true"
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
message:
|
||||
/^1 enabled plugin could not be loaded: @quartz-community\/does-not-exist \(see above\)/,
|
||||
})
|
||||
process.env.QUARTZ_ALLOW_BROKEN_PLUGINS = "1"
|
||||
await loadQuartzConfig()
|
||||
} finally {
|
||||
for (const key of ["CI", "QUARTZ_ALLOW_BROKEN_PLUGINS", "QUARTZ_CONFIG_QUIET"]) {
|
||||
if (saved[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = saved[key]
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("loadQuartzConfig: a local plugin's manifest (package.json → quartz)", () => {
|
||||
let dir: string
|
||||
const linked: string[] = []
|
||||
// .quartz/plugins and .quartz, where this test creates them
|
||||
const pluginsDir = path.join(process.cwd(), ".quartz", "plugins")
|
||||
const created = [pluginsDir, path.dirname(pluginsDir)].filter((d) => !fs.existsSync(d))
|
||||
before(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-local-plugin-"))
|
||||
process.env.QUARTZ_CONFIG_QUIET = "1"
|
||||
})
|
||||
afterEach(() => {
|
||||
delete process.env.QUARTZ_CONFIG_PATH
|
||||
})
|
||||
after(() => {
|
||||
delete process.env.QUARTZ_CONFIG_QUIET
|
||||
// the symlinks installPlugin made in .quartz/plugins
|
||||
for (const link of linked)
|
||||
if (fs.lstatSync(link, { throwIfNoEntry: false })) fs.unlinkSync(link)
|
||||
for (const d of created) if (fs.readdirSync(d).length === 0) fs.rmdirSync(d)
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
})
|
||||
|
||||
/** A transformer plugin in `dir/<name>` whose instance records the options it got. */
|
||||
function localPlugin(name: string, quartz: Record<string, unknown>) {
|
||||
const root = path.join(dir, name)
|
||||
fs.mkdirSync(root)
|
||||
fs.writeFileSync(
|
||||
path.join(root, "package.json"),
|
||||
JSON.stringify({ name, version: "2.3.4", type: "module", main: "index.js", quartz }),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(root, "index.js"),
|
||||
`export default (opts) => ({ name: ${JSON.stringify(name)}, opts, textTransform: (_c, s) => s })\n`,
|
||||
)
|
||||
linked.push(path.join(process.cwd(), ".quartz", "plugins", name))
|
||||
return root
|
||||
}
|
||||
const useConfig = (plugins: { source: string; options?: object }[]) => {
|
||||
const file = path.join(dir, `config-${Math.random().toString(36).slice(2)}.yaml`)
|
||||
fs.writeFileSync(
|
||||
file,
|
||||
`plugins:\n${plugins.map((p) => ` - source: ${JSON.stringify(p.source)}\n enabled: true\n options: ${JSON.stringify(p.options ?? {})}\n`).join("")}`,
|
||||
)
|
||||
process.env.QUARTZ_CONFIG_PATH = file
|
||||
}
|
||||
const withEnv = async (env: Record<string, string | undefined>, fn: () => Promise<void>) => {
|
||||
const saved = Object.fromEntries(Object.keys(env).map((k) => [k, process.env[k]]))
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (v === undefined) delete process.env[k]
|
||||
else process.env[k] = v
|
||||
}
|
||||
try {
|
||||
await fn()
|
||||
} finally {
|
||||
for (const [k, v] of Object.entries(saved)) {
|
||||
if (v === undefined) delete process.env[k]
|
||||
else process.env[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("its defaultOptions are the base of the entry's options", async () => {
|
||||
const root = localPlugin("audit-options", {
|
||||
name: "audit-options",
|
||||
category: "transformer",
|
||||
defaultOptions: { greeting: "hello", size: 1 },
|
||||
})
|
||||
useConfig([{ source: root, options: { size: 2 } }])
|
||||
const cfg = await loadQuartzConfig()
|
||||
const plugin = cfg.plugins.transformers.find((p) => p.name === "audit-options") as unknown as {
|
||||
opts: unknown
|
||||
}
|
||||
assert.deepEqual(plugin.opts, { greeting: "hello", size: 2 })
|
||||
})
|
||||
|
||||
test("a plugin that needs a newer Quartz warns locally and fails the build in CI", async () => {
|
||||
const root = localPlugin("audit-future", {
|
||||
name: "audit-future",
|
||||
category: "transformer",
|
||||
quartzVersion: ">=99.0.0",
|
||||
})
|
||||
useConfig([{ source: root }])
|
||||
await withEnv({ CI: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: undefined }, async () => {
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.ok(names(cfg.plugins.transformers).includes("audit-future"))
|
||||
})
|
||||
await withEnv(
|
||||
{ CI: "true", QUARTZ_CONFIG_QUIET: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: undefined },
|
||||
async () => {
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
message: /^1 enabled plugin does not support Quartz [^:]+: audit-future \(see above\)/,
|
||||
})
|
||||
},
|
||||
)
|
||||
await withEnv(
|
||||
{ CI: "true", QUARTZ_CONFIG_QUIET: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: "1" },
|
||||
async () => {
|
||||
await loadQuartzConfig()
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("a missing dependency fails the build", async () => {
|
||||
const root = localPlugin("audit-deps", {
|
||||
name: "audit-deps",
|
||||
category: "transformer",
|
||||
dependencies: ["github:someone/not-configured"],
|
||||
})
|
||||
useConfig([{ source: root }])
|
||||
await withEnv({ QUARTZ_CONFIG_QUIET: undefined }, async () => {
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
message: "Plugin dependency validation failed with 1 error(s). See above for details.",
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -14,6 +14,9 @@ import type { PluginManifest } from "./types"
|
||||
import { componentRegistry } from "../../components/registry"
|
||||
import type { QuartzComponent, QuartzComponentConstructor } from "../../components/types"
|
||||
import { PluginJsonEntry, LayoutPosition } from "./types"
|
||||
import { LayoutDiagnostics } from "./layoutReport"
|
||||
import { h } from "preact"
|
||||
import { render } from "preact-render-to-string"
|
||||
|
||||
describe("resolveConfigPath", () => {
|
||||
afterEach(() => {
|
||||
@@ -432,3 +435,302 @@ describe("async plugin factories", () => {
|
||||
assert.strictEqual(detectCategoryFromModule({ default: factory }), "transformer")
|
||||
})
|
||||
})
|
||||
|
||||
describe("dependency order between plugins", () => {
|
||||
const validate = (
|
||||
plugin: Partial<PluginManifest>,
|
||||
dep: Partial<PluginManifest>,
|
||||
order?: { plugin?: number; dep?: number },
|
||||
) => {
|
||||
const entries: PluginJsonEntry[] = [
|
||||
{ source: "github:someone/x", enabled: true, options: {}, order: order?.plugin },
|
||||
{ source: "github:someone/y", enabled: true, options: {}, order: order?.dep },
|
||||
]
|
||||
const manifests = new Map<string, PluginManifest>([
|
||||
[
|
||||
"github:someone/x",
|
||||
{ name: "x", dependencies: ["github:someone/y"], ...plugin } as PluginManifest,
|
||||
],
|
||||
["github:someone/y", { name: "y", ...dep } as PluginManifest],
|
||||
])
|
||||
return validateDependencies(entries, manifests, [])
|
||||
}
|
||||
|
||||
test("a dependency of the same stage must run first: entry order, else defaultOrder, else 50", () => {
|
||||
const transformer = { category: "transformer" } as const
|
||||
assert.deepStrictEqual(validate(transformer, { ...transformer, defaultOrder: 40 }).errors, [])
|
||||
assert.match(
|
||||
validate(transformer, { ...transformer, defaultOrder: 60 }).errors[0],
|
||||
/"x" \(order: 50\) depends on "y" \(order: 60\)/,
|
||||
)
|
||||
// the entry's order wins over the manifest's defaultOrder, on both sides
|
||||
assert.deepStrictEqual(
|
||||
validate(
|
||||
{ ...transformer, defaultOrder: 10 },
|
||||
{ ...transformer, defaultOrder: 60 },
|
||||
{
|
||||
plugin: 70,
|
||||
},
|
||||
).errors,
|
||||
[],
|
||||
)
|
||||
assert.match(
|
||||
validate(transformer, { ...transformer, defaultOrder: 10 }, { dep: 55 }).errors[0],
|
||||
/\(order: 50\) depends on "y" \(order: 55\)/,
|
||||
)
|
||||
// equal order: stable, the dependency is not after the plugin
|
||||
assert.deepStrictEqual(validate(transformer, transformer).errors, [])
|
||||
})
|
||||
|
||||
test("a dependency cycle fails the build", () => {
|
||||
const entries: PluginJsonEntry[] = [
|
||||
{ source: "github:someone/x", enabled: true, options: {} },
|
||||
{ source: "github:someone/y", enabled: true, options: {} },
|
||||
]
|
||||
const manifests = new Map<string, PluginManifest>([
|
||||
["github:someone/x", { name: "x", dependencies: ["github:someone/y"] } as PluginManifest],
|
||||
["github:someone/y", { name: "y", dependencies: ["github:someone/x"] } as PluginManifest],
|
||||
])
|
||||
assert.deepStrictEqual(validateDependencies(entries, manifests, []).errors, [
|
||||
"Circular dependency detected: x → y → x",
|
||||
])
|
||||
})
|
||||
|
||||
// Order only decides between plugins of the same stage: all transformers run before any filter or
|
||||
// emitter, and a component-only plugin has no place in the pipeline. An emitter (or a component)
|
||||
// depending on a transformer with a higher order used to fail the build with "is configured to
|
||||
// run first", although the transformer always runs first.
|
||||
test("a dependency of another stage is not ordered against the plugin", () => {
|
||||
const transformer = { category: "transformer", defaultOrder: 60 } as const
|
||||
assert.deepStrictEqual(validate({ category: "emitter" }, transformer).errors, [])
|
||||
assert.deepStrictEqual(validate({ category: "component" }, transformer).errors, [])
|
||||
assert.deepStrictEqual(
|
||||
validate({ category: "component" }, { category: "component", defaultOrder: 60 }).errors,
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test("a plugin of several stages is ordered against a dependency in a stage they share", () => {
|
||||
const transformer = { category: "transformer", defaultOrder: 60 } as const
|
||||
assert.match(
|
||||
validate({ category: ["transformer", "emitter"] }, transformer).errors[0],
|
||||
/"x" \(order: 50\) depends on "y" \(order: 60\)/,
|
||||
)
|
||||
// without a category the stage is unknown: still compared
|
||||
assert.match(validate({}, { defaultOrder: 60 }).errors[0], /depends on "y" \(order: 60\)/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin names of each source form", () => {
|
||||
test("github:, git+…, https:// URLs, local paths and { repo, name } objects", () => {
|
||||
const cases: [Parameters<typeof isExcluded>[0], string][] = [
|
||||
["github:someone/my-plugin#v2", "my-plugin"],
|
||||
["git+https://github.com/someone/my-plugin.git", "my-plugin"],
|
||||
["https://gitlab.com/group/my-plugin.git#main", "my-plugin"],
|
||||
["https://github.com/someone/my-plugin", "my-plugin"],
|
||||
["./plugins/my-plugin/", "my-plugin"],
|
||||
[{ repo: "github:someone/repo", name: "my-plugin" }, "my-plugin"],
|
||||
[{ repo: "github:someone/my-plugin" }, "my-plugin"],
|
||||
]
|
||||
for (const [source, name] of cases) {
|
||||
assert.ok(isExcluded(source, [name]), JSON.stringify(source))
|
||||
assert.ok(!isExcluded(source, ["someone"]), JSON.stringify(source))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("validateDependencies: which plugins are checked", () => {
|
||||
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
|
||||
source,
|
||||
enabled: true,
|
||||
options: {},
|
||||
...extra,
|
||||
})
|
||||
const m = (extra: Partial<PluginManifest>) => ({ name: "n", ...extra }) as PluginManifest
|
||||
|
||||
test("a disabled plugin's dependencies are not required", () => {
|
||||
const { errors } = validateDependencies(
|
||||
[entry("github:a/x", { enabled: false })],
|
||||
new Map([["github:a/x", m({ dependencies: ["github:a/missing"] })]]),
|
||||
)
|
||||
assert.deepStrictEqual(errors, [])
|
||||
})
|
||||
|
||||
test("messages name the plugin by its displayName", () => {
|
||||
const { errors } = validateDependencies(
|
||||
[entry("github:a/x")],
|
||||
new Map([["github:a/x", m({ displayName: "Fancy X", dependencies: ["github:a/missing"] })]]),
|
||||
)
|
||||
assert.deepStrictEqual(errors, [
|
||||
'Plugin "Fancy X" requires "missing". Run: npx quartz plugin add github:a/missing',
|
||||
])
|
||||
})
|
||||
|
||||
test("a disabled dependency with a higher order is only a warning", () => {
|
||||
const { errors, warnings } = validateDependencies(
|
||||
[entry("github:a/x"), entry("github:a/y", { enabled: false, order: 90 })],
|
||||
new Map([["github:a/x", m({ dependencies: ["github:a/y"] })]]),
|
||||
)
|
||||
assert.deepStrictEqual(errors, [])
|
||||
assert.strictEqual(warnings.length, 1)
|
||||
})
|
||||
|
||||
test("a plugin at the same order as the built-in it depends on runs after it", () => {
|
||||
const plan = planBuiltins({
|
||||
configuration: {},
|
||||
entries: [],
|
||||
nameOf: () => "",
|
||||
providesOf: () => undefined,
|
||||
})
|
||||
const { errors } = validateDependencies(
|
||||
[entry("github:a/x", { order: 60 })],
|
||||
new Map([
|
||||
[
|
||||
"github:a/x",
|
||||
m({ category: "transformer", dependencies: ["@quartz-community/crawl-links"] }),
|
||||
],
|
||||
]),
|
||||
plan.builtins,
|
||||
)
|
||||
assert.deepStrictEqual(errors, [])
|
||||
})
|
||||
|
||||
test("cycles of any length are found once; shared dependencies are no cycle", () => {
|
||||
const deps = (map: Record<string, string[]>) =>
|
||||
new Map(Object.entries(map).map(([k, d]) => [k, m({ dependencies: d })]))
|
||||
const sources = ["github:a/w", "github:a/x", "github:a/y", "github:a/z"]
|
||||
const entries = sources.map((s) => entry(s))
|
||||
// w → x → y → z, and w → y: a diamond, no cycle
|
||||
assert.deepStrictEqual(
|
||||
validateDependencies(
|
||||
entries,
|
||||
deps({
|
||||
"github:a/w": ["github:a/x", "github:a/y"],
|
||||
"github:a/x": ["github:a/y"],
|
||||
"github:a/y": ["github:a/z"],
|
||||
}),
|
||||
).errors,
|
||||
[],
|
||||
)
|
||||
// w → x → y → z → x
|
||||
assert.deepStrictEqual(
|
||||
validateDependencies(
|
||||
entries,
|
||||
deps({
|
||||
"github:a/w": ["github:a/x"],
|
||||
"github:a/x": ["github:a/y"],
|
||||
"github:a/y": ["github:a/z"],
|
||||
"github:a/z": ["github:a/x"],
|
||||
}),
|
||||
).errors,
|
||||
["Circular dependency detected: x → y → z → x"],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildLayoutForEntries: components and options", () => {
|
||||
const place = (layout: Record<string, unknown>, manifest?: Record<string, unknown>) => {
|
||||
componentRegistry.register("p", makeComponent("P"), "test-source", manifest as never)
|
||||
return buildLayoutForEntries(
|
||||
[{ source: "p", enabled: true, options: {}, layout: layout as never }],
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
test("mobile-only and desktop-only wrap the component in their class", () => {
|
||||
const html = (layout: Record<string, unknown>) => {
|
||||
const [C] = place({ position: "left", ...layout }).left!
|
||||
return render(h(C as never, {} as never))
|
||||
}
|
||||
assert.strictEqual(html({ display: "mobile-only" }), '<div class="mobile-only"></div>')
|
||||
assert.strictEqual(html({ display: "desktop-only" }), '<div class="desktop-only"></div>')
|
||||
assert.strictEqual(html({ display: "all" }), "")
|
||||
assert.strictEqual(html({ display: null }), "")
|
||||
})
|
||||
|
||||
test("display all / null raise no warning; a non-numeric priority is 50 with a warning", () => {
|
||||
const diag = new LayoutDiagnostics()
|
||||
componentRegistry.register("q", makeComponent("Q"), "test-source")
|
||||
componentRegistry.register("r", makeComponent("R"), "test-source")
|
||||
componentRegistry.register("s", makeComponent("S"), "test-source")
|
||||
const result = buildLayoutForEntries(
|
||||
[
|
||||
{
|
||||
source: "q",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: "high", display: "all" } as never,
|
||||
},
|
||||
{
|
||||
source: "r",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: 60, display: null } as never,
|
||||
},
|
||||
{
|
||||
source: "s",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: 40 } as never,
|
||||
},
|
||||
],
|
||||
{},
|
||||
diag,
|
||||
)
|
||||
assert.deepStrictEqual(diag.warnings, [
|
||||
'plugin "q": layout priority "high" is not a number — using 50.',
|
||||
])
|
||||
assert.deepStrictEqual(
|
||||
result.left!.map((c) => c.displayName),
|
||||
["S", "Q", "R"],
|
||||
)
|
||||
})
|
||||
|
||||
test("layout.position: null falls back to the manifest's defaultPosition", () => {
|
||||
const result = place({ position: null, priority: 1 }, { defaultPosition: "right" })
|
||||
assert.strictEqual(result.right!.length, 1)
|
||||
})
|
||||
|
||||
test("a component registered under the PascalCase name of a kebab-case plugin is found", () => {
|
||||
componentRegistry.register("TagList", makeComponent("TagListC"), "test-source")
|
||||
const result = buildLayoutForEntries(
|
||||
[
|
||||
{
|
||||
source: "tag-list",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: 1 },
|
||||
},
|
||||
],
|
||||
{},
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
result.left!.map((c) => c.displayName),
|
||||
["TagListC"],
|
||||
)
|
||||
})
|
||||
|
||||
test("a constructor gets the entry's options with quartz.ts overrides on top, or none", () => {
|
||||
const received: unknown[] = []
|
||||
const ctor = ((opts?: unknown) => {
|
||||
received.push(opts)
|
||||
return makeComponent(`C${received.length}`)
|
||||
}) as QuartzComponentConstructor
|
||||
componentRegistry.register("ctor-a", ctor, "test-source")
|
||||
componentRegistry.register("ctor-b", ctor, "test-source")
|
||||
componentRegistry.setOptionOverrides("ctor-a", { extra: true, base: 2 })
|
||||
buildLayoutForEntries(
|
||||
[
|
||||
{
|
||||
source: "ctor-a",
|
||||
enabled: true,
|
||||
options: { base: 1, own: "x" },
|
||||
layout: { position: "left", priority: 1 },
|
||||
},
|
||||
{ source: "ctor-b", enabled: true, options: {}, layout: { position: "left", priority: 2 } },
|
||||
],
|
||||
{},
|
||||
)
|
||||
assert.deepStrictEqual(received, [{ base: 2, own: "x", extra: true }, undefined])
|
||||
})
|
||||
})
|
||||
@@ -61,6 +61,9 @@ import {
|
||||
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
|
||||
import { componentRegistry, RegisteredComponent } from "../../components/registry"
|
||||
import { frameRegistry } from "../../components/frames/registry"
|
||||
import { OrderItem, constraintList, normalizePluginName, orderPlugins } from "./plugin-order"
|
||||
import { resolveExtends } from "./config-extends"
|
||||
import { setSlugOptions } from "../../util/path"
|
||||
import { getCondition, getAllConditionNames } from "./conditions"
|
||||
import {
|
||||
LAYOUT_SLOTS,
|
||||
@@ -92,16 +95,18 @@ export function resolveConfigPath(): string {
|
||||
if (fs.existsSync(LEGACY_DEFAULT_PLUGINS_JSON_PATH)) return LEGACY_DEFAULT_PLUGINS_JSON_PATH
|
||||
return CONFIG_YAML_PATH
|
||||
}
|
||||
function readPluginsJson(): QuartzPluginsJson | null {
|
||||
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
|
||||
const configPath = resolveConfigPath()
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return null
|
||||
}
|
||||
const raw = fs.readFileSync(configPath, "utf-8")
|
||||
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
|
||||
return YAML.parse(raw) as QuartzPluginsJson
|
||||
}
|
||||
return JSON.parse(raw) as QuartzPluginsJson
|
||||
const data =
|
||||
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
|
||||
// `extends:` (#2440): merge onto the base config; a config without it is used as written
|
||||
return data && typeof data === "object" && "extends" in data
|
||||
? resolveExtends(data, configPath)
|
||||
: (data as QuartzPluginsJson)
|
||||
}
|
||||
|
||||
function extractPluginName(source: PluginSource): string {
|
||||
@@ -154,6 +159,22 @@ interface DependencyValidationResult {
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
/** The pipeline stages a plugin's `order` decides its place in (a component has none). */
|
||||
const ORDERED_STAGES = ["transformer", "filter", "emitter", "pageType"] as const
|
||||
|
||||
/**
|
||||
* Whether `order` decides between the two plugins: they run in a stage they share (all
|
||||
* transformers run before any filter or emitter, whatever their order). Without a category on
|
||||
* either side the stage is unknown, and they are compared.
|
||||
*/
|
||||
function sameStage(a: PluginManifest, b: PluginManifest | undefined): boolean {
|
||||
if (!a.category || !b?.category) return true
|
||||
const stagesOfB = [b.category].flat()
|
||||
return [a.category]
|
||||
.flat()
|
||||
.some((c) => stagesOfB.includes(c) && (ORDERED_STAGES as readonly string[]).includes(c))
|
||||
}
|
||||
|
||||
export function validateDependencies(
|
||||
entries: PluginJsonEntry[],
|
||||
manifests: Map<string, PluginManifest>,
|
||||
@@ -224,7 +245,7 @@ export function validateDependencies(
|
||||
const depManifest = manifests.get(dep)
|
||||
const depOrder = depEntry.order ?? depManifest?.defaultOrder ?? 50
|
||||
|
||||
if (pluginOrder < depOrder) {
|
||||
if (pluginOrder < depOrder && sameStage(manifest, depManifest)) {
|
||||
errors.push(
|
||||
`Plugin "${pluginName}" (order: ${pluginOrder}) depends on "${depName}" (order: ${depOrder}), ` +
|
||||
`but "${pluginName}" is configured to run first. Either increase "${pluginName}"'s order above ${depOrder} ` +
|
||||
@@ -360,11 +381,12 @@ async function getManifest(source: PluginSource): Promise<PluginManifest | null>
|
||||
export async function loadQuartzConfig(
|
||||
configOverrides?: Partial<GlobalConfiguration>,
|
||||
): Promise<QuartzConfig> {
|
||||
const json = readPluginsJson()
|
||||
const json = await readPluginsJson()
|
||||
|
||||
if (!json) {
|
||||
// Fallback: import old-style config directly
|
||||
const oldConfig = await import("../../../quartz")
|
||||
setSlugOptions(oldConfig.default?.configuration?.slugs)
|
||||
return oldConfig.default
|
||||
}
|
||||
|
||||
@@ -372,6 +394,8 @@ export async function loadQuartzConfig(
|
||||
...(json.configuration as unknown as GlobalConfiguration),
|
||||
...configOverrides,
|
||||
}
|
||||
// before anything computes a slug (this runs in the main thread and in every worker)
|
||||
setSlugOptions(configuration.slugs)
|
||||
|
||||
// Entries of official plugins that are now built into core (crawl-links, remove-draft,
|
||||
// content-index) are handled by the built-ins below and never installed or loaded.
|
||||
@@ -656,7 +680,7 @@ export async function loadQuartzConfig(
|
||||
items: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[],
|
||||
expectedCategory: ProcessingCategory,
|
||||
) => {
|
||||
const instances: { order: number; instance: any }[] = []
|
||||
const instances: OrderItem<any>[] = []
|
||||
for (const { entry, manifest } of items) {
|
||||
try {
|
||||
const spec = parsePluginSource(entry.source)
|
||||
@@ -715,7 +739,19 @@ export async function loadQuartzConfig(
|
||||
issues: manifest?.issues,
|
||||
quartzVersion: manifest?.quartzVersion,
|
||||
})
|
||||
instances.push({ order: entry.order ?? manifest?.defaultOrder ?? 50, instance })
|
||||
const label = extractPluginName(entry.source)
|
||||
instances.push({
|
||||
order: entry.order ?? manifest?.defaultOrder ?? 50,
|
||||
instance,
|
||||
label,
|
||||
names: [
|
||||
label,
|
||||
manifest?.name,
|
||||
typeof instance.name === "string" ? instance.name : "",
|
||||
].filter((n): n is string => typeof n === "string" && n !== ""),
|
||||
before: constraintList(entry.before, "before", label),
|
||||
after: constraintList(entry.after, "after", label),
|
||||
})
|
||||
} catch (err) {
|
||||
pluginLoadFailed(entry, manifest, "was skipped: it failed to initialise", err)
|
||||
}
|
||||
@@ -729,19 +765,38 @@ export async function loadQuartzConfig(
|
||||
builtinPlugins.ComponentResources(),
|
||||
builtinPlugins.Assets(),
|
||||
builtinPlugins.Static(),
|
||||
builtinPlugins.SlugRedirects(),
|
||||
]
|
||||
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
|
||||
|
||||
// Built-in processing steps take their place in plugin order (frontmatter at 0, links at 60 …);
|
||||
// on equal order a built-in runs before plugins (stable sort, built-ins listed first).
|
||||
// on equal order a built-in runs before plugins (stable sort, built-ins listed first), unless
|
||||
// `before`/`after` on an entry say otherwise (see plugin-order.ts).
|
||||
const knownPluginNames = new Set(
|
||||
[
|
||||
...json.plugins.map((e) => extractPluginName(e.source)),
|
||||
...builtinPlan.builtins.flatMap((b) => [b.spec.configKey, ...b.spec.absorbs]),
|
||||
"Frontmatter",
|
||||
"Links",
|
||||
"Drafts",
|
||||
"ContentIndex",
|
||||
"Fonts",
|
||||
].map(normalizePluginName),
|
||||
)
|
||||
const withBuiltins = <T>(
|
||||
builtins: { order: number; instance: unknown }[],
|
||||
instances: { order: number; instance: T }[],
|
||||
builtins: { order: number; instance: unknown; names?: string[] }[],
|
||||
instances: OrderItem<T>[],
|
||||
): T[] =>
|
||||
[...builtins, ...instances]
|
||||
.map((item, index) => ({ ...item, index }))
|
||||
.sort((a, b) => a.order - b.order || a.index - b.index)
|
||||
.map((item) => item.instance as T)
|
||||
orderPlugins(
|
||||
[
|
||||
...builtins.map(({ order, instance, names }) => {
|
||||
const name = (instance as { name: string }).name
|
||||
return { order, instance: instance as T, label: name, names: names ?? [name] }
|
||||
}),
|
||||
...instances,
|
||||
],
|
||||
knownPluginNames,
|
||||
)
|
||||
|
||||
const plugins: PluginTypes = {
|
||||
transformers: withBuiltins(
|
||||
@@ -760,7 +815,7 @@ export async function loadQuartzConfig(
|
||||
),
|
||||
],
|
||||
pageTypes: [
|
||||
...(await instantiate(pageTypes, "pageType")).map((item) => item.instance),
|
||||
...orderPlugins(await instantiate(pageTypes, "pageType"), knownPluginNames),
|
||||
...builtinPageTypes,
|
||||
],
|
||||
}
|
||||
@@ -1175,7 +1230,7 @@ export function buildQuartzLayout(
|
||||
* the renderer's layout is updated in place with the overrides applied.
|
||||
*/
|
||||
export async function loadQuartzLayout(layoutOverrides?: LayoutOverrides): Promise<QuartzLayout> {
|
||||
const json = readPluginsJson()
|
||||
const json = await readPluginsJson()
|
||||
|
||||
if (!json) {
|
||||
// Fallback: import old-style layout directly
|
||||
|
||||
@@ -5,6 +5,7 @@ import YAML from "yaml"
|
||||
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
|
||||
import type { PluginSource, QuartzPluginsJson } from "./types.js"
|
||||
import { absorbingBuiltin } from "../builtins/index.js"
|
||||
import { resolveExtends } from "./config-extends.js"
|
||||
|
||||
function resolveConfigPath(): string {
|
||||
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
|
||||
@@ -20,14 +21,15 @@ function resolveConfigPath(): string {
|
||||
return configYamlPath
|
||||
}
|
||||
|
||||
function readPluginsJson(): QuartzPluginsJson | null {
|
||||
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
|
||||
const configPath = resolveConfigPath()
|
||||
if (!fs.existsSync(configPath)) return null
|
||||
const raw = fs.readFileSync(configPath, "utf-8")
|
||||
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
|
||||
return YAML.parse(raw)
|
||||
}
|
||||
return JSON.parse(raw)
|
||||
const data =
|
||||
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
|
||||
return data && typeof data === "object" && "extends" in data
|
||||
? resolveExtends(data, configPath)
|
||||
: data
|
||||
}
|
||||
|
||||
async function getExternalPluginSources(): Promise<PluginSource[]> {
|
||||
@@ -45,7 +47,7 @@ async function getExternalPluginSources(): Promise<PluginSource[]> {
|
||||
// fall back to config yaml parsing
|
||||
}
|
||||
|
||||
const pluginsJson = readPluginsJson()
|
||||
const pluginsJson = await readPluginsJson()
|
||||
const entries = pluginsJson?.plugins ?? []
|
||||
return entries.filter((entry) => entry.enabled !== false).map((entry) => entry.source)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import {
|
||||
OrderItem,
|
||||
PluginOrderError,
|
||||
constraintList,
|
||||
normalizePluginName,
|
||||
orderPlugins,
|
||||
} from "./plugin-order"
|
||||
|
||||
const item = (
|
||||
name: string,
|
||||
order: number,
|
||||
c: { before?: string[]; after?: string[] } = {},
|
||||
): OrderItem<string> => ({ instance: name, order, label: name, names: [name], ...c })
|
||||
const known = (...names: string[]) => new Set(names.map(normalizePluginName))
|
||||
|
||||
describe("orderPlugins", () => {
|
||||
test("numeric order, then list position, as before", () => {
|
||||
const items = [item("c", 50), item("a", 10), item("b", 50)]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "c", "b"])
|
||||
})
|
||||
|
||||
test("before/after decide between plugins with the same order", () => {
|
||||
const items = [item("x", 50, { after: ["y"] }), item("y", 50), item("z", 50, { before: ["y"] })]
|
||||
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"])
|
||||
})
|
||||
|
||||
test("a contradiction with order is an error naming both orders", () => {
|
||||
assert.throws(
|
||||
() => orderPlugins([item("a", 30, { after: ["b"] }), item("b", 60)], known("a", "b")),
|
||||
(err: Error) =>
|
||||
err instanceof PluginOrderError &&
|
||||
/"a" \(order 30\) must run after "b", but "b" has order 60/.test(err.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => orderPlugins([item("a", 60, { before: ["b"] }), item("b", 30)], known("a", "b")),
|
||||
/"a" \(order 60\) must run before "b", but "b" has order 30/,
|
||||
)
|
||||
})
|
||||
|
||||
test("a cycle among equal orders is an error", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
orderPlugins(
|
||||
[item("a", 50, { after: ["b"] }), item("b", 50, { after: ["a"] })],
|
||||
known("a", "b"),
|
||||
),
|
||||
/cycle among plugins with order 50: a, b/,
|
||||
)
|
||||
})
|
||||
|
||||
test("names match loosely: package name, kebab-case, instance name", () => {
|
||||
const ofm: OrderItem<string> = {
|
||||
instance: "ofm",
|
||||
order: 40,
|
||||
label: "obsidian-flavored-markdown",
|
||||
names: ["obsidian-flavored-markdown", "ObsidianFlavoredMarkdown"],
|
||||
}
|
||||
for (const ref of [
|
||||
"ObsidianFlavoredMarkdown",
|
||||
"obsidian-flavored-markdown",
|
||||
"@quartz-community/obsidian-flavored-markdown",
|
||||
]) {
|
||||
const mine = item("mine", 40, { after: [ref] })
|
||||
assert.deepStrictEqual(orderPlugins([mine, ofm], known("obsidian-flavored-markdown")), [
|
||||
"ofm",
|
||||
"mine",
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
test("unknown names are errors; disabled or other-category plugins are skipped", () => {
|
||||
assert.throws(
|
||||
() => orderPlugins([item("a", 50, { after: ["typo"] })], known("a")),
|
||||
/"a": after: "typo" is not a plugin in this config/,
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
orderPlugins([item("a", 50, { after: ["disabled"] })], known("a", "disabled")),
|
||||
["a"],
|
||||
)
|
||||
})
|
||||
|
||||
test("a plugin cannot be ordered against itself", () => {
|
||||
assert.throws(() => orderPlugins([item("a", 50, { after: ["a"] })], known("a")), /itself/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("constraintList", () => {
|
||||
test("accepts a name or a list", () => {
|
||||
assert.deepStrictEqual(constraintList("x", "after", "p"), ["x"])
|
||||
assert.deepStrictEqual(constraintList(["x", "y"], "after", "p"), ["x", "y"])
|
||||
assert.deepStrictEqual(constraintList(undefined, "after", "p"), [])
|
||||
})
|
||||
test("rejects other values", () => {
|
||||
assert.throws(() => constraintList(3, "after", "p"), PluginOrderError)
|
||||
assert.throws(() => constraintList([""], "before", "p"), /"before" must be/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Plugin order: numeric `order` first, then checked `before:` / `after:` constraints (#2440).
|
||||
*
|
||||
* - Plugins run by `order` (lower first), as before. `before`/`after` never move a plugin past
|
||||
* a plugin with a different `order`: they are checked against it, and a contradiction
|
||||
* (`after: X` while X has a higher order) is an error that names both orders.
|
||||
* - Between plugins with the same `order`, the constraints decide; otherwise the list order does
|
||||
* (built-ins first, then the config's order), as before.
|
||||
* - Names are plugin names, matched loosely (`obsidian-flavored-markdown`,
|
||||
* `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` are the same;
|
||||
* built-ins answer to their instance name and config key, e.g. `Links` / `links`).
|
||||
* - A name that is not in the config at all is an error (likely a typo). A plugin that is in
|
||||
* the config but disabled, or runs in another category, is skipped: the constraint only
|
||||
* applies where both plugins run. A cycle among equal orders is an error.
|
||||
*
|
||||
* Constraints are plain data on config entries, so a later dependency-based scheme (e.g. from
|
||||
* the manifests' `dependencies`) can feed the same checks.
|
||||
*/
|
||||
|
||||
/** A configuration mistake: reported by its message alone (no stack trace). */
|
||||
export class PluginOrderError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = "PluginOrderError"
|
||||
this.stack = `${this.name}: ${message}`
|
||||
}
|
||||
}
|
||||
|
||||
/** Loose plugin name: lowercase, scope and punctuation removed. */
|
||||
export function normalizePluginName(name: string): string {
|
||||
const bare = name.trim().replace(/^@[^/]+\//, "")
|
||||
return bare.toLowerCase().replace(/[^a-z0-9]/g, "")
|
||||
}
|
||||
|
||||
export interface OrderItem<T> {
|
||||
instance: T
|
||||
order: number
|
||||
/** Display name used in messages. */
|
||||
label: string
|
||||
/** Every name this plugin answers to. */
|
||||
names: string[]
|
||||
before?: string[]
|
||||
after?: string[]
|
||||
}
|
||||
|
||||
/** Accepts `before: X` and `before: [X, Y]`; anything else is an error. */
|
||||
export function constraintList(value: unknown, field: string, label: string): string[] {
|
||||
if (value === undefined || value === null) return []
|
||||
const list = Array.isArray(value) ? value : [value]
|
||||
for (const v of list) {
|
||||
if (typeof v !== "string" || v.trim() === "") {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${label}": "${field}" must be a plugin name or a list of plugin names`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return list as string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort one category's plugins. `known` holds the normalized names of every plugin in the
|
||||
* config (enabled or not, any category) and of the built-ins, to tell typos from plugins that
|
||||
* just don't run here.
|
||||
*/
|
||||
export function orderPlugins<T>(items: OrderItem<T>[], known: ReadonlySet<string>): T[] {
|
||||
const indexed = items.map((item, index) => ({ ...item, index }))
|
||||
const byName = new Map<string, (typeof indexed)[number]>()
|
||||
for (const item of indexed) {
|
||||
for (const name of item.names) {
|
||||
const key = normalizePluginName(name)
|
||||
if (!byName.has(key)) byName.set(key, item)
|
||||
}
|
||||
}
|
||||
|
||||
// edges: earlier → later
|
||||
const later = new Map<number, Set<number>>()
|
||||
const addEdge = (
|
||||
first: (typeof indexed)[number],
|
||||
second: (typeof indexed)[number],
|
||||
why: string,
|
||||
) => {
|
||||
if (first === second) {
|
||||
throw new PluginOrderError(`plugin "${first.label}": ${why} names the plugin itself`)
|
||||
}
|
||||
if (first.order > second.order) {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${second.label}" (order ${second.order}) ${why}, but "${first.label}" has order ${first.order}, so it runs later. ` +
|
||||
`Give "${second.label}" an order above ${first.order}, or "${first.label}" one below ${second.order}.`,
|
||||
)
|
||||
}
|
||||
if (!later.has(first.index)) later.set(first.index, new Set())
|
||||
later.get(first.index)!.add(second.index)
|
||||
}
|
||||
|
||||
for (const item of indexed) {
|
||||
for (const [field, names] of [
|
||||
["after", item.after ?? []],
|
||||
["before", item.before ?? []],
|
||||
] as const) {
|
||||
for (const name of names) {
|
||||
const key = normalizePluginName(name)
|
||||
const other = byName.get(key)
|
||||
if (!other) {
|
||||
if (!known.has(key)) {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${item.label}": ${field}: "${name}" is not a plugin in this config`,
|
||||
)
|
||||
}
|
||||
continue // disabled, or not in this category
|
||||
}
|
||||
if (field === "after") addEdge(other, item, `must run after "${other.label}"`)
|
||||
else {
|
||||
// phrase the message from the constrained plugin's point of view
|
||||
if (item.order > other.order) {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${item.label}" (order ${item.order}) must run before "${other.label}", but "${other.label}" has order ${other.order}, so it runs earlier. ` +
|
||||
`Give "${item.label}" an order below ${other.order}, or "${other.label}" one above ${item.order}.`,
|
||||
)
|
||||
}
|
||||
addEdge(item, other, `must run before "${other.label}"`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// numeric order, then list position; within one order, a stable topological sort
|
||||
const sorted = [...indexed].sort((a, b) => a.order - b.order || a.index - b.index)
|
||||
if (later.size === 0) return sorted.map((i) => i.instance)
|
||||
|
||||
const result: (typeof indexed)[number][] = []
|
||||
let start = 0
|
||||
while (start < sorted.length) {
|
||||
let end = start
|
||||
while (end < sorted.length && sorted[end].order === sorted[start].order) end++
|
||||
const group = sorted.slice(start, end)
|
||||
const inGroup = new Set(group.map((g) => g.index))
|
||||
const indegree = new Map(group.map((g) => [g.index, 0]))
|
||||
for (const g of group) {
|
||||
for (const next of later.get(g.index) ?? []) {
|
||||
if (inGroup.has(next)) indegree.set(next, indegree.get(next)! + 1)
|
||||
}
|
||||
}
|
||||
const remaining = [...group]
|
||||
while (remaining.length > 0) {
|
||||
const pos = remaining.findIndex((g) => indegree.get(g.index) === 0)
|
||||
if (pos === -1) {
|
||||
throw new PluginOrderError(
|
||||
`"before"/"after" form a cycle among plugins with order ${group[0].order}: ${remaining.map((g) => g.label).join(", ")}`,
|
||||
)
|
||||
}
|
||||
const [next] = remaining.splice(pos, 1)
|
||||
result.push(next)
|
||||
for (const n of later.get(next.index) ?? []) {
|
||||
if (inGroup.has(n)) indegree.set(n, indegree.get(n)! - 1)
|
||||
}
|
||||
}
|
||||
start = end
|
||||
}
|
||||
return result.map((i) => i.instance)
|
||||
}
|
||||
@@ -165,6 +165,9 @@ export interface PluginJsonEntry {
|
||||
enabled: boolean
|
||||
options?: Record<string, unknown>
|
||||
order?: number
|
||||
/** Plugins this one must run before / after (checked against `order`; see plugin-order.ts). */
|
||||
before?: string | string[]
|
||||
after?: string | string[]
|
||||
layout?: PluginLayoutDeclaration
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
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 test, { after, describe } from "node:test"
|
||||
import { h } from "preact"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { QuartzComponent, QuartzComponentProps } from "../../components/types"
|
||||
import type { QuartzPageTypePluginInstance } from "../types"
|
||||
import type { FilePath, FullSlug } from "../../util/path"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { ChangeEvent } from "../types"
|
||||
import type { Element, Root } from "hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
|
||||
// Rendering a page imports components with SCSS and inline browser scripts, which 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 { PageTypeDispatcher } = await import("./dispatcher")
|
||||
const { defaultProcessedContent } = await import("../vfile")
|
||||
|
||||
const Head: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
|
||||
h("head", null, h("title", null, String(fileData.frontmatter?.title ?? "")))
|
||||
|
||||
/** A page type whose body names it, so the emitted HTML tells which page type rendered a page. */
|
||||
function pageType(
|
||||
name: string,
|
||||
overrides: Partial<QuartzPageTypePluginInstance> = {},
|
||||
): QuartzPageTypePluginInstance {
|
||||
const Body: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
|
||||
h("article", { "data-type": name }, `${name}:${fileData.slug}`)
|
||||
return {
|
||||
name,
|
||||
layout: name,
|
||||
match: () => true,
|
||||
body: () => Body,
|
||||
...overrides,
|
||||
} as QuartzPageTypePluginInstance
|
||||
}
|
||||
|
||||
const dirs: string[] = []
|
||||
after(() => {
|
||||
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function setup(
|
||||
pageTypes: QuartzPageTypePluginInstance[],
|
||||
removedPages?: Map<string, string>,
|
||||
transformers: unknown[] = [],
|
||||
) {
|
||||
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-dispatcher-"))
|
||||
dirs.push(output)
|
||||
const ctx = {
|
||||
argv: { output, serve: false, directory: "content" },
|
||||
cfg: {
|
||||
configuration: { baseUrl: "example.com/sub", locale: "en-US" },
|
||||
plugins: { pageTypes, transformers },
|
||||
},
|
||||
allSlugs: [],
|
||||
virtualPages: [],
|
||||
removedPages,
|
||||
} as unknown as BuildCtx
|
||||
const read = (slug: string) => fs.readFileSync(path.join(output, `${slug}.html`), "utf8")
|
||||
return { ctx, output, read }
|
||||
}
|
||||
|
||||
const resources: StaticResources = { css: [], js: [], additionalHead: [] }
|
||||
const dispatcher = () => PageTypeDispatcher({ defaults: { head: Head } })
|
||||
|
||||
function page(slug: string, html = "", links: string[] = []) {
|
||||
return defaultProcessedContent({
|
||||
slug: slug as FullSlug,
|
||||
relativePath: `${slug}.md` as FilePath,
|
||||
filePath: `content/${slug}.md` as FilePath,
|
||||
frontmatter: { title: slug, tags: [] },
|
||||
links: links as never,
|
||||
htmlAst: { type: "root", children: [] },
|
||||
}).map((x, i) =>
|
||||
i === 0 && html
|
||||
? {
|
||||
type: "root",
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${html}`, "data-slug": html, className: ["internal"] },
|
||||
children: [{ type: "text", value: html }],
|
||||
},
|
||||
],
|
||||
}
|
||||
: x,
|
||||
) as ReturnType<typeof defaultProcessedContent>
|
||||
}
|
||||
|
||||
const linkOf = ([tree]: ReturnType<typeof page>) => (tree as Root).children[0] as Element
|
||||
|
||||
async function collect(gen: AsyncGenerator<FilePath> | AsyncIterable<FilePath>, output: string) {
|
||||
const out: string[] = []
|
||||
for await (const fp of gen) out.push(path.relative(output, fp).split(path.sep).join("/"))
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
describe("PageTypeDispatcher.emit", () => {
|
||||
test("each page is rendered by the first matching page type in priority order", async () => {
|
||||
const types = [
|
||||
pageType("low", { priority: 1 }),
|
||||
pageType("high", { priority: 10, match: ({ slug }) => slug.startsWith("special/") }),
|
||||
pageType("none", { match: () => false, priority: 100 }),
|
||||
]
|
||||
const { ctx, output, read } = setup(types)
|
||||
const content = [page("index"), page("special/a")]
|
||||
const files = await collect(dispatcher().emit(ctx, content, resources) as never, output)
|
||||
assert.deepEqual(files, ["index.html", "special/a.html"])
|
||||
assert.match(read("index"), /<article data-type="low">low:index<\/article>/)
|
||||
assert.match(read("special/a"), /<article data-type="high">high:special\/a<\/article>/)
|
||||
assert.match(read("special/a"), /<title>special\/a<\/title>/)
|
||||
})
|
||||
|
||||
test("virtual pages are emitted with their page type's body; the 404 page uses the site's base path", async () => {
|
||||
const generated = pageType("tags", {
|
||||
match: () => false,
|
||||
generate: () => [
|
||||
{ slug: "tags/x" as FullSlug, title: "Tag x", data: {} },
|
||||
{ slug: "404" as FullSlug, title: "Not found", data: {} },
|
||||
],
|
||||
})
|
||||
const { ctx, output, read } = setup([pageType("content"), generated])
|
||||
const files = await collect(dispatcher().emit(ctx, [page("a/b")], resources) as never, output)
|
||||
assert.deepEqual(files, ["404.html", "a/b.html", "tags/x.html"])
|
||||
assert.match(read("tags/x"), /tags:tags\/x/)
|
||||
assert.match(read("tags/x"), /<title>Tag x<\/title>/)
|
||||
// the 404 page is served from any depth: its assets are under the absolute base path
|
||||
assert.match(read("404"), /<script src="\/sub\/postscript\.js"/)
|
||||
assert.match(read("a/b"), /<script src="\.\.\/postscript\.js"/)
|
||||
assert.deepEqual(
|
||||
ctx.virtualPages.map(([, f]) => f.data.slug),
|
||||
["tags/x"],
|
||||
)
|
||||
})
|
||||
|
||||
test("links to a draft are marked broken in the emitted page", async () => {
|
||||
const removed = new Map([["draft", "Drafts"]])
|
||||
const { ctx, output } = setup([pageType("content")], removed)
|
||||
const a = page("a", "draft")
|
||||
await collect(dispatcher().emit(ctx, [a], resources) as never, output)
|
||||
assert.deepEqual(linkOf(a).properties, {
|
||||
href: "./draft",
|
||||
"data-slug": "draft",
|
||||
className: ["internal", "broken"],
|
||||
"data-filtered": "Drafts",
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher: pages that stand for files", () => {
|
||||
test("virtualPageHtmlPlugins' result is what the page shows; a page whose body fails isn't emitted", async () => {
|
||||
const Board: QuartzComponent = ({ fileData }: QuartzComponentProps) => {
|
||||
if (fileData.slug === "broken.canvas") throw new Error("cannot render")
|
||||
return h("p", null, `board ${fileData.slug}`)
|
||||
}
|
||||
const canvas = pageType("canvas", {
|
||||
match: () => false,
|
||||
fileExtensions: [".canvas"],
|
||||
body: () => Board,
|
||||
generate: () =>
|
||||
["a.canvas", "secret.canvas", "broken.canvas"].map((slug) => ({
|
||||
slug: slug as FullSlug,
|
||||
title: slug,
|
||||
data: {},
|
||||
})),
|
||||
})
|
||||
const encrypt = {
|
||||
name: "Encrypt",
|
||||
virtualPageHtmlPlugins: () => [
|
||||
() => (tree: Root, file: { data: { slug?: string } }) => {
|
||||
if (file.data.slug === "secret.canvas") {
|
||||
tree.children = [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: {},
|
||||
children: [{ type: "text", value: "ciphertext" }],
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
],
|
||||
}
|
||||
// transformers without virtualPageHtmlPlugins are skipped
|
||||
const { ctx, output, read } = setup([pageType("content"), canvas], undefined, [
|
||||
{ name: "Plain" },
|
||||
encrypt,
|
||||
])
|
||||
const files = await collect(dispatcher().emit(ctx, [page("index")], resources) as never, output)
|
||||
assert.deepEqual(files, ["a.canvas.html", "index.html", "secret.canvas.html"])
|
||||
assert.match(read("a.canvas"), /<p>board a\.canvas<\/p>/)
|
||||
assert.match(read("secret.canvas"), /<div>ciphertext<\/div>/)
|
||||
assert.doesNotMatch(read("secret.canvas"), /board/)
|
||||
// later emitters read the processed tree from ctx.virtualPages; the failed page is gone
|
||||
const trees = Object.fromEntries(
|
||||
ctx.virtualPages.map(([tree, f]) => [f.data.slug, toHtml(tree as Root)]),
|
||||
)
|
||||
assert.deepEqual(Object.keys(trees), ["a.canvas", "secret.canvas"])
|
||||
assert.equal(trees["secret.canvas"], "<div>ciphertext</div>")
|
||||
assert.equal(trees["a.canvas"], "")
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher: what page bodies see", () => {
|
||||
// a body listing the pages it can embed (allFiles) and the files of folder "f" (ctx.trie)
|
||||
const Lister: QuartzComponent = ({ allFiles, ctx }: QuartzComponentProps) =>
|
||||
h(
|
||||
"article",
|
||||
null,
|
||||
`files:${allFiles.map((f) => f.slug).join(",")};` +
|
||||
`f:${(ctx.trie?.findNode(["f"])?.children ?? []).map((c) => c.slug).join(",")}`,
|
||||
)
|
||||
const types = () => [
|
||||
pageType("content", { body: () => Lister }),
|
||||
pageType("canvas", {
|
||||
match: () => false,
|
||||
fileExtensions: [".canvas"],
|
||||
generate: () => [{ slug: "f/board.canvas" as FullSlug, title: "Board", data: {} }],
|
||||
}),
|
||||
pageType("tags", {
|
||||
match: () => false,
|
||||
generate: () => [{ slug: "tags/t" as FullSlug, title: "t", data: {} }],
|
||||
}),
|
||||
]
|
||||
const expected = "files:f/note,f/board.canvas,tags/t;f:f/note,f/board.canvas"
|
||||
|
||||
test("emit: virtual pages are in allFiles; the folder trie holds the pages that stand for files", async () => {
|
||||
const { ctx, output, read } = setup(types())
|
||||
await collect(dispatcher().emit(ctx, [page("f/note")], resources) as never, output)
|
||||
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
|
||||
})
|
||||
|
||||
test("partialEmit: the same, for the pages it re-emits", async () => {
|
||||
const { ctx, output, read } = setup(types())
|
||||
const note = page("f/note")
|
||||
const events = [
|
||||
{ type: "change", path: "f/note.md", file: note[1] },
|
||||
] as unknown as ChangeEvent[]
|
||||
await collect(dispatcher().partialEmit!(ctx, [note], resources, events) as never, output)
|
||||
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
|
||||
})
|
||||
|
||||
test("partialEmit renders a changed page with the first matching page type by priority", async () => {
|
||||
const { ctx, output, read } = setup([
|
||||
pageType("low", { priority: 1 }),
|
||||
pageType("high", { priority: 10, match: ({ slug }) => slug === "special" }),
|
||||
])
|
||||
const [a, b] = [page("special"), page("plain")]
|
||||
const events = [
|
||||
{ type: "change", path: "special.md", file: a[1] },
|
||||
{ type: "change", path: "plain.md", file: b[1] },
|
||||
] as unknown as ChangeEvent[]
|
||||
await collect(dispatcher().partialEmit!(ctx, [a, b], resources, events) as never, output)
|
||||
assert.match(read("special"), /data-type="high"/)
|
||||
assert.match(read("plain"), /data-type="low"/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher.partialEmit", () => {
|
||||
test("re-emits changed Markdown pages and all virtual pages, removes deleted pages' output", async () => {
|
||||
const generated = pageType("folder", {
|
||||
match: () => false,
|
||||
generate: () => [{ slug: "f/index" as FullSlug, title: "F", data: {} }],
|
||||
})
|
||||
const { ctx, output } = setup([pageType("content"), generated])
|
||||
const [a, b] = [page("a"), page("b")]
|
||||
await collect(dispatcher().emit(ctx, [a, b], resources) as never, output)
|
||||
fs.writeFileSync(path.join(output, "gone.html"), "stale")
|
||||
|
||||
const events = [
|
||||
{ type: "change", path: "a.md", file: a[1] },
|
||||
{ type: "delete", path: "gone.md" },
|
||||
// not Markdown: no page of its own
|
||||
{ type: "change", path: "image.png" },
|
||||
] as unknown as ChangeEvent[]
|
||||
ctx.virtualPages = []
|
||||
const files = await collect(
|
||||
dispatcher().partialEmit!(ctx, [a, b], resources, events) as never,
|
||||
output,
|
||||
)
|
||||
assert.deepEqual(files, ["a.html", "f/index.html"])
|
||||
assert.ok(!fs.existsSync(path.join(output, "gone.html")))
|
||||
})
|
||||
|
||||
test("a page whose link to a removed page changed is re-emitted although its source didn't", async () => {
|
||||
const removed = new Map([["draft", "Drafts"]])
|
||||
const { ctx, output } = setup([pageType("content")], removed)
|
||||
const linking = page("linking", "draft")
|
||||
const files = await collect(
|
||||
dispatcher().partialEmit!(ctx, [linking, page("other")], resources, []) as never,
|
||||
output,
|
||||
)
|
||||
assert.deepEqual(files, ["linking.html"])
|
||||
assert.equal(linkOf(linking).properties["data-filtered"], "Drafts")
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
collectTreeTransforms,
|
||||
folderTrie,
|
||||
generateVirtualPages,
|
||||
markLinksToUnpublishedPages,
|
||||
pageOutputPath,
|
||||
processVirtualPageHtml,
|
||||
referencesByTarget,
|
||||
@@ -16,10 +17,13 @@ import {
|
||||
} from "./dispatcher"
|
||||
import { QuartzPageTypePluginInstance } from "../types"
|
||||
import { QuartzComponent } from "../../components/types"
|
||||
import { FilePath, FullSlug, SimpleSlug } from "../../util/path"
|
||||
import { FilePath, FullSlug, SimpleSlug, setSlugOptions } from "../../util/path"
|
||||
import { Root as HtmlRoot } from "hast"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { defaultProcessedContent } from "../vfile"
|
||||
import { defaultProcessedContent, ProcessedContent } from "../vfile"
|
||||
import { removedPages } from "../builtins/links"
|
||||
import { Element, Root } from "hast"
|
||||
import { VFile } from "vfile"
|
||||
|
||||
const StubA: QuartzComponent = (() => null) as unknown as QuartzComponent
|
||||
const StubB: QuartzComponent = (() => null) as unknown as QuartzComponent
|
||||
@@ -278,6 +282,27 @@ describe("generateVirtualPages", () => {
|
||||
assert.strictEqual(ctx.virtualPages.length, 2)
|
||||
})
|
||||
|
||||
test("slugs.stripDiacritics moves folder pages to the stripped folder slug (#2410)", async () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
const entries = await generateVirtualPages(
|
||||
[makePageType({ generate: () => [page("české/index"), page("tags/čeština")] })],
|
||||
[],
|
||||
makeCtx(),
|
||||
{ head: StubHead },
|
||||
{},
|
||||
)
|
||||
// tag pages keep their slugs: tag links are slugged by the plugins that render them
|
||||
assert.deepStrictEqual(
|
||||
entries.map((e) => e.vpSlug),
|
||||
["ceske/index", "tags/čeština"],
|
||||
)
|
||||
assert.strictEqual(entries[0].vfile.data.slug, "ceske/index")
|
||||
} finally {
|
||||
setSlugOptions(undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps the 404 page out of ctx.virtualPages", async () => {
|
||||
const ctx = makeCtx()
|
||||
const entries = await generateVirtualPages(
|
||||
@@ -536,3 +561,112 @@ describe("publish filters on pages that stand for files (bases-page#11)", () =>
|
||||
assert.strictEqual(processVirtualPageHtml(ve, makeCtx(), []), true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("links to unpublished pages, after the page types ran (crawl-links#7)", () => {
|
||||
const link = (slug: string): Element => ({
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${slug}`, "data-slug": slug, className: ["internal"] },
|
||||
children: [],
|
||||
})
|
||||
const content = (slug: string, links: string[] = []): ProcessedContent => {
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug, frontmatter: { title: slug } } as VFile["data"]
|
||||
return [{ type: "root", children: links.map(link) } as Root, file]
|
||||
}
|
||||
const marks = (item: ProcessedContent) =>
|
||||
((item[0] as Root).children as Element[]).map((a) =>
|
||||
(a.properties.className as string[]).includes("broken")
|
||||
? (a.properties["data-filtered"] ?? (a.properties["data-missing"] === "" ? "missing" : "?"))
|
||||
: "ok",
|
||||
)
|
||||
// a folder page type that generates a page for each folder with a published note, as folder-page does
|
||||
const folders = makePageType({
|
||||
name: "folders",
|
||||
generate: ({ content }) =>
|
||||
[...new Set(content.map(([, f]) => f.data.slug!.split("/").slice(0, -1).join("/")))]
|
||||
.filter((f) => f !== "" && !content.some(([, g]) => g.data.slug === `${f}/index`))
|
||||
.map((f) => ({ slug: `${f}/index` as FullSlug, title: f, data: {} })),
|
||||
})
|
||||
|
||||
const setup = async (removedBy: ((slug: string) => string | undefined) | undefined) => {
|
||||
const home = content("index", [
|
||||
"notes/a",
|
||||
"notes/index",
|
||||
"drafts/index",
|
||||
"drafts/b",
|
||||
"projects/index",
|
||||
"missing-in-source",
|
||||
])
|
||||
const all = [home, content("notes/a"), content("drafts/b"), content("projects/index")]
|
||||
const published = all.filter(([, f]) => f.data.slug !== "drafts/b")
|
||||
const ctx = {
|
||||
cfg: { configuration: {} },
|
||||
virtualPages: [],
|
||||
removedPages: removedBy ? removedPages(all, published, removedBy) : undefined,
|
||||
} as unknown as BuildCtx
|
||||
const entries = await generateVirtualPages([folders], published, ctx, { head: StubHead }, {})
|
||||
return { home, ctx, published, entries }
|
||||
}
|
||||
|
||||
test("marks drafts with their filter and folders no page type generated as missing", async () => {
|
||||
const { home, ctx, published, entries } = await setup(() => "RemoveDrafts")
|
||||
assert.deepStrictEqual(
|
||||
entries.map((e) => e.vpSlug),
|
||||
["notes/index"],
|
||||
)
|
||||
const changed = markLinksToUnpublishedPages(ctx, published, entries)
|
||||
assert.deepStrictEqual(marks(home), [
|
||||
"ok", // notes/a: published
|
||||
"ok", // notes/index: generated folder page
|
||||
"missing", // drafts/index: its only note is a draft, so no folder page
|
||||
"RemoveDrafts", // drafts/b
|
||||
"ok", // projects/index: a published folder note
|
||||
"ok", // not in the content: the Links transformer's own check, not this one
|
||||
])
|
||||
assert.deepStrictEqual([...changed], ["index"])
|
||||
// run again (watch mode, nothing changed): nothing to re-emit
|
||||
assert.deepStrictEqual([...markLinksToUnpublishedPages(ctx, published, entries)], [])
|
||||
})
|
||||
|
||||
test("marks nothing when the Links transformer doesn't mark broken links", async () => {
|
||||
const { home, ctx, published, entries } = await setup(undefined)
|
||||
assert.deepStrictEqual([...markLinksToUnpublishedPages(ctx, published, entries)], [])
|
||||
assert.ok(marks(home).every((m) => m === "ok"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("resolveLayout: every slot", () => {
|
||||
test("a page type's override replaces each default slot; the page type's body is the page body", () => {
|
||||
const Body = (() => null) as unknown as QuartzComponent
|
||||
const pt = makePageType({ body: () => Body })
|
||||
const slots = ["header", "beforeBody", "afterBody", "left", "right", "footer"] as const
|
||||
const defaults = Object.fromEntries(slots.map((s) => [s, [StubA]]))
|
||||
const overrides = Object.fromEntries(slots.map((s) => [s, [StubB]]))
|
||||
const OtherHead = (() => null) as unknown as QuartzComponent
|
||||
const layout = resolveLayout(
|
||||
pt,
|
||||
{ head: StubHead, ...defaults },
|
||||
{ [pt.layout]: { head: OtherHead, ...overrides } },
|
||||
)
|
||||
for (const slot of slots) assert.deepStrictEqual(layout[slot], [StubB], slot)
|
||||
assert.strictEqual(layout.head, OtherHead)
|
||||
assert.strictEqual(layout.pageBody, Body)
|
||||
// without an override, the defaults
|
||||
const plain = resolveLayout(pt, { head: StubHead, ...defaults }, {})
|
||||
for (const slot of slots) assert.deepStrictEqual(plain[slot], [StubA], slot)
|
||||
})
|
||||
|
||||
test("collectComponents leaves out a missing head", () => {
|
||||
const components = collectComponents([makePageType()], { left: [StubA] }, {})
|
||||
assert.ok(!components.includes(undefined as never))
|
||||
assert.strictEqual(components.length, 2)
|
||||
})
|
||||
|
||||
test("collectTreeTransforms: page types without treeTransforms add none", () => {
|
||||
const t = (() => {}) as never
|
||||
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
|
||||
const result = collectTreeTransforms(ctx, [{}, { treeTransforms: () => [t] }])
|
||||
assert.deepStrictEqual(result, { before: [], treeTransforms: [t], after: [] })
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
pathToRoot,
|
||||
simplifySlug,
|
||||
slugifyFilePath,
|
||||
applySlugOptions,
|
||||
} from "../../util/path"
|
||||
import { ProcessedContent, defaultProcessedContent } from "../vfile"
|
||||
import { write } from "../emitters/helpers"
|
||||
@@ -29,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"
|
||||
|
||||
@@ -215,7 +217,9 @@ export async function generateVirtualPages(
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
const fileBacked = (pt.fileExtensions?.length ?? 0) > 0
|
||||
for (const vp of virtualPages) {
|
||||
const vpSlug = vp.slug as FullSlug
|
||||
// A folder's page lives at the folder's slug; with `slugs.stripDiacritics` that is the
|
||||
// stripped one, whatever the page type computed from the file path (folder-page).
|
||||
const vpSlug = (vp.slug.endsWith("/index") ? applySlugOptions(vp.slug) : vp.slug) as FullSlug
|
||||
const vpRelativePath = (vpSlug + ".md") as FilePath
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug: vpSlug,
|
||||
@@ -291,9 +295,10 @@ const RenderedBody: QuartzComponent = ({ fileData, tree }: QuartzComponentProps)
|
||||
*
|
||||
* Run the transformers' `virtualPageHtmlPlugins` on the rendered body (`file.data.htmlAst`) of a
|
||||
* page that stands for a file — e.g. encrypted-pages encrypting a canvas. When they change the
|
||||
* tree, the page shows the changed tree instead of rendering its body again. A page whose body
|
||||
* failed to render, or that a plugin throws on, is left unpublished: emitting it unprocessed could
|
||||
* publish what the plugin protects.
|
||||
* tree, the page shows the changed tree instead of rendering its body again. Both failures fail
|
||||
* closed, as emitting the page unprocessed could publish what the plugin protects: a page whose
|
||||
* body failed to render is left unpublished (returns false), and a plugin that throws fails the
|
||||
* whole build (`trace` reports the error and exits the process, or throws in a worker).
|
||||
*/
|
||||
export function processVirtualPageHtml(
|
||||
ve: VirtualEntry,
|
||||
@@ -336,7 +341,8 @@ export function processVirtualPageHtml(
|
||||
* Render each virtual page's Body component to HTML and parse it to a hast tree,
|
||||
* populating vfile.data.htmlAst so that transclusion (e.g. ![[file.canvas]]) can inline the
|
||||
* virtual page's content, then run `virtualPageHtmlPlugins` on it (pages that stand for files).
|
||||
* Returns the entries to emit: those whose processing failed are removed from `ctx.virtualPages`.
|
||||
* Returns the entries to emit: those whose body failed to render (so they can't be processed) are
|
||||
* removed from `ctx.virtualPages`. A plugin throwing while processing fails the build.
|
||||
*/
|
||||
function populateVirtualPageHtmlAst(
|
||||
virtualEntries: VirtualEntry[],
|
||||
@@ -379,6 +385,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.
|
||||
*/
|
||||
export 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 ?? {}
|
||||
@@ -410,6 +434,8 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
|
||||
byPageType,
|
||||
)
|
||||
|
||||
markLinksToUnpublishedPages(ctx, content, virtualEntries)
|
||||
|
||||
if (virtualEntries.some((ve) => ve.fileBacked)) {
|
||||
ctx.trie = folderTrie(allFiles, virtualEntries)
|
||||
}
|
||||
@@ -504,6 +530,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
|
||||
|
||||
@@ -3,16 +3,54 @@
|
||||
"title": "Quartz Plugins Configuration Schema",
|
||||
"description": "Schema for validating quartz.config.yaml (and legacy quartz.plugins.json) configuration files",
|
||||
"type": "object",
|
||||
"required": ["configuration", "plugins"],
|
||||
"additionalProperties": false,
|
||||
"if": {
|
||||
"required": ["extends"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"plugins": {
|
||||
"items": {
|
||||
"required": ["source"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"else": {
|
||||
"required": ["configuration", "plugins"],
|
||||
"properties": {
|
||||
"configuration": {
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"]
|
||||
},
|
||||
"plugins": {
|
||||
"items": {
|
||||
"required": ["source", "enabled"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "JSON Schema reference"
|
||||
},
|
||||
"extends": {
|
||||
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml) or a path relative to this file, or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Without extends, this file is the whole configuration.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"configuration": {
|
||||
"type": "object",
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"pageTitle": {
|
||||
@@ -195,6 +233,18 @@
|
||||
"default": "all",
|
||||
"description": "Controls which assets are copied to public. \"all\" copies all non-markdown files; \"referenced\" only copies assets referenced by published pages"
|
||||
},
|
||||
"slugs": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"description": "How file paths become URLs (slugs).",
|
||||
"properties": {
|
||||
"stripDiacritics": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Strip accents and other diacritics from generated slugs (české/čeština.md → ceske/cestina). Applies to file and folder names, aliases and permalinks; links are resolved the same way."
|
||||
}
|
||||
}
|
||||
},
|
||||
"frontmatter": {
|
||||
"description": "Built-in frontmatter parsing: titles, tags, aliases, dates, drafts. Default order 0.",
|
||||
"oneOf": [
|
||||
@@ -277,7 +327,7 @@
|
||||
},
|
||||
"disableBrokenWikilinks": {
|
||||
"type": "boolean",
|
||||
"description": "Add a `broken` class to internal links whose target does not exist. Default false."
|
||||
"description": "Add a `broken` class to internal links whose target does not exist, as Obsidian marks unresolved links. Default true."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -362,7 +412,6 @@
|
||||
"description": "Array of plugin configurations",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["source", "enabled"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"source": {
|
||||
@@ -407,6 +456,36 @@
|
||||
"minimum": 0,
|
||||
"description": "Plugin execution order"
|
||||
},
|
||||
"before": {
|
||||
"description": "Plugin name(s) this plugin must run before. Checked against order: between plugins with the same order it decides, a contradiction with order is an error.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"after": {
|
||||
"description": "Plugin name(s) this plugin must run after. Checked against order: between plugins with the same order it decides, a contradiction with order is an error.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
@@ -432,7 +511,7 @@
|
||||
},
|
||||
"condition": {
|
||||
"type": "string",
|
||||
"description": "Render only when this condition holds. Built-in: not-index, has-tags, has-backlinks, has-toc; plugins may register more."
|
||||
"description": "Render only when this condition holds. Built-in: is-index, not-index, is-folder-index, has-tags, has-backlinks, has-toc; plugins may register more. Prefix any condition with not- to negate it (not-has-tags)."
|
||||
},
|
||||
"group": {
|
||||
"type": "string",
|
||||
|
||||
@@ -31,7 +31,10 @@ export type ContentDetails = {
|
||||
tags: string[]
|
||||
content: string
|
||||
richContent?: string
|
||||
/** RSS / sitemap only — not written to contentIndex.json. */
|
||||
/**
|
||||
* The page's date (see `defaultDateType`). Written to contentIndex.json as an ISO 8601
|
||||
* string, and only for pages that have a date.
|
||||
*/
|
||||
date?: Date
|
||||
/** RSS / sitemap only — not written to contentIndex.json. */
|
||||
description?: string
|
||||
|
||||
@@ -3,7 +3,12 @@ import assert from "node:assert"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { readContentFile } from "./parse"
|
||||
import { createHtmlProcessor, createMdProcessor, parseMarkdown, readContentFile } from "./parse"
|
||||
import type { Root as MdRoot } from "mdast"
|
||||
import type { Root as HtmlRoot } from "hast"
|
||||
import type { VFile } from "vfile"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import type { BuildCtx } from "../util/ctx"
|
||||
import { isContentError } from "../util/pluginErrors"
|
||||
import type { FilePath } from "../util/path"
|
||||
|
||||
@@ -39,3 +44,93 @@ describe("readContentFile", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("parseMarkdown (one thread)", () => {
|
||||
// a transformer that records which of its hooks ran, in which order
|
||||
const recorder = (name: string, log: string[]) => ({
|
||||
name,
|
||||
textTransform: (_ctx: unknown, src: string) => {
|
||||
log.push(`${name}:text`)
|
||||
return `${src}\n\n${name}`
|
||||
},
|
||||
markdownPlugins: () => [
|
||||
() => (tree: MdRoot) => {
|
||||
log.push(`${name}:md`)
|
||||
tree.children.push({ type: "paragraph", children: [{ type: "text", value: `md-${name}` }] })
|
||||
},
|
||||
],
|
||||
htmlPlugins: () => [
|
||||
() => (tree: HtmlRoot, file: VFile) => {
|
||||
log.push(`${name}:html`)
|
||||
file.data[`html-${name}` as "slug"] = toHtml(tree) as never
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
test("runs text, Markdown and HTML transforms in plugin order and sets the file's paths", async () => {
|
||||
// Quartz passes POSIX-style paths (its glob yields them on Windows too)
|
||||
const posix = (p: string) => p.split(path.sep).join("/")
|
||||
const dir = posix(await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-parse-")))
|
||||
try {
|
||||
await fs.promises.mkdir(`${dir}/Sub Folder`)
|
||||
const a = `${dir}/Sub Folder/My Note.md`
|
||||
const b = `${dir}/other.md`
|
||||
await fs.promises.writeFile(a, "\n\n # Title \n\n")
|
||||
await fs.promises.writeFile(b, "text")
|
||||
const log: string[] = []
|
||||
const ctx = {
|
||||
argv: { directory: dir, verbose: false, concurrency: 1 },
|
||||
// a transformer may implement any subset of the hooks
|
||||
cfg: {
|
||||
plugins: { transformers: [recorder("one", log), { name: "bare" }, recorder("two", log)] },
|
||||
},
|
||||
// a frontmatter permalink is the page's address
|
||||
permalinks: { "other.md": "elsewhere/page" },
|
||||
} as unknown as BuildCtx
|
||||
const res = await parseMarkdown(ctx, [a, b] as FilePath[])
|
||||
|
||||
assert.deepStrictEqual(
|
||||
res.map(([, file]) => [file.data.relativePath, file.data.slug, file.data.filePath]),
|
||||
[
|
||||
["Sub Folder/My Note.md", "sub-folder/my-note", a],
|
||||
["other.md", "elsewhere/page", b],
|
||||
],
|
||||
)
|
||||
// the text is trimmed before the first textTransform, which sees what the one before returned
|
||||
assert.strictEqual(String(res[0][1].value), "# Title\n\none\n\ntwo")
|
||||
// per file: all text transforms, then Markdown plugins, then (after all files) HTML plugins
|
||||
assert.deepStrictEqual(log, [
|
||||
"one:text",
|
||||
"two:text",
|
||||
"one:md",
|
||||
"two:md",
|
||||
"one:text",
|
||||
"two:text",
|
||||
"one:md",
|
||||
"two:md",
|
||||
"one:html",
|
||||
"two:html",
|
||||
"one:html",
|
||||
"two:html",
|
||||
])
|
||||
const data = res[0][1].data as Record<string, string>
|
||||
// Markdown plugins ran in order, and remark-rehype turned the Markdown AST into HTML
|
||||
assert.strictEqual(
|
||||
data["html-one"],
|
||||
"<h1>Title</h1>\n<p>one</p>\n<p>two</p>\n<p>md-one</p>\n<p>md-two</p>",
|
||||
)
|
||||
assert.strictEqual(res[0][0].type, "root")
|
||||
assert.strictEqual(toHtml(res[0][0] as HtmlRoot), data["html-two"])
|
||||
} finally {
|
||||
await fs.promises.rm(dir, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("raw HTML in Markdown is kept (allowDangerousHtml)", async () => {
|
||||
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
|
||||
const md = createMdProcessor(ctx)
|
||||
const ast = md.parse('<div class="x">hi</div>')
|
||||
const html = await createHtmlProcessor(ctx).run(await md.run(ast))
|
||||
assert.strictEqual(toHtml(html, { allowDangerousHtml: true }), '<div class="x">hi</div>')
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import esbuild from "esbuild"
|
||||
import remarkParse from "remark-parse"
|
||||
import remarkRehype from "remark-rehype"
|
||||
import { Processor, unified } from "unified"
|
||||
import { Root as MDRoot } from "remark-parse/lib"
|
||||
import { Root as MDRoot } from "mdast"
|
||||
import { Root as HTMLRoot } from "hast"
|
||||
import { MarkdownContent, ProcessedContent } from "../plugins/vfile"
|
||||
import { PerfTimer } from "../util/perf"
|
||||
|
||||
+38
-3
@@ -51,7 +51,8 @@ body {
|
||||
border-radius: 5px;
|
||||
}
|
||||
::selection {
|
||||
background: color-mix(in srgb, var(--tertiary) 60%, rgba(255, 255, 255, 0));
|
||||
// 40%: text stays readable on it (4.5:1 for --darkgray in both default palettes).
|
||||
background: color-mix(in srgb, var(--tertiary) 40%, rgba(255, 255, 255, 0));
|
||||
color: var(--darkgray);
|
||||
}
|
||||
|
||||
@@ -85,8 +86,12 @@ path[class~="typst-shape"] {
|
||||
}
|
||||
|
||||
article {
|
||||
// callouts are <div class="callout"> since obsidian-flavored-markdown 2.3, <blockquote> before
|
||||
// callouts are <div class="callout"> since obsidian-flavored-markdown 2.3, <blockquote> before;
|
||||
// a note's blocks are in Obsidian's wrappers (div.el-div) since rehype-obsidian 1.5, and
|
||||
// display maths in Obsidian's div.math-block since @quartz-community/latex 1.1
|
||||
> mjx-container.MathJax,
|
||||
.el-div > mjx-container.MathJax,
|
||||
.math-block > mjx-container.MathJax,
|
||||
:is(blockquote, .callout) > div > mjx-container.MathJax {
|
||||
display: flex;
|
||||
> svg {
|
||||
@@ -94,7 +99,10 @@ article {
|
||||
margin-right: auto;
|
||||
}
|
||||
}
|
||||
:is(blockquote, .callout) > div > mjx-container.MathJax > svg {
|
||||
:is(blockquote, .callout)
|
||||
> div
|
||||
> :is(mjx-container.MathJax, .math-block > mjx-container.MathJax)
|
||||
> svg {
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
@@ -484,6 +492,13 @@ h6 {
|
||||
}
|
||||
}
|
||||
|
||||
// Obsidian's fold arrows in headings and in list items with a sublist; hidden unless
|
||||
// obsidian-flavored-markdown's foldHeadings / foldLists turn folding on
|
||||
.heading-collapse-indicator,
|
||||
.list-collapse-indicator {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// typography improvements
|
||||
h1 {
|
||||
font-size: 1.75rem;
|
||||
@@ -720,6 +735,26 @@ ol.overflow {
|
||||
ul {
|
||||
padding-left: 1rem;
|
||||
}
|
||||
|
||||
// Obsidian's embed title (the note's title, for a whole-note embed), styled as the
|
||||
// heading it replaces
|
||||
> .markdown-embed-title {
|
||||
font-family: var(--headerFont);
|
||||
color: var(--dark);
|
||||
font-size: 1.75rem;
|
||||
font-weight: bold;
|
||||
margin: 2.25rem 0 1rem;
|
||||
|
||||
&:empty {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
// Obsidian's icon link to the embedded note, for Obsidian themes (whose styles show
|
||||
// it); Quartz links to the original below the content instead
|
||||
> .markdown-embed-link {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.katex-display {
|
||||
|
||||
@@ -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(), [])
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { dateIsFromFrontmatter, realDate } from "./dates"
|
||||
import type { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
const data = (d: Record<string, unknown>) => d as unknown as QuartzPluginData
|
||||
|
||||
describe("realDate", () => {
|
||||
const now = new Date()
|
||||
const fm = new Date("2024-05-06T00:00:00")
|
||||
|
||||
test("drops dates the date plugin lists in fallbackDates", () => {
|
||||
const d = data({ dates: { modified: now, published: now }, fallbackDates: ["published"] })
|
||||
assert.strictEqual(realDate(d, "published"), undefined)
|
||||
assert.strictEqual(realDate(d, "modified"), now)
|
||||
})
|
||||
|
||||
test("without fallbackDates (older plugin), published needs a matching frontmatter value", () => {
|
||||
assert.strictEqual(realDate(data({ dates: { published: now } }), "published"), undefined)
|
||||
assert.strictEqual(
|
||||
realDate(
|
||||
data({ frontmatter: { published: "nope" }, dates: { published: now } }),
|
||||
"published",
|
||||
),
|
||||
undefined,
|
||||
)
|
||||
assert.strictEqual(
|
||||
realDate(
|
||||
data({ frontmatter: { published: "2024-05-06" }, dates: { published: fm } }),
|
||||
"published",
|
||||
),
|
||||
fm,
|
||||
)
|
||||
assert.strictEqual(realDate(data({ dates: { modified: now } }), "modified"), now)
|
||||
})
|
||||
|
||||
test("missing and invalid dates", () => {
|
||||
assert.strictEqual(realDate(data({}), "modified"), undefined)
|
||||
assert.strictEqual(
|
||||
realDate(data({ dates: { modified: new Date(NaN) } }), "modified"),
|
||||
undefined,
|
||||
)
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
export type DateType = "created" | "modified" | "published"
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
/**
|
||||
* Dates in `dates` that no source gave, so the date plugin filled them with the build time
|
||||
* (created-modified-date ≥ 1.0.5). Absent with older versions.
|
||||
*/
|
||||
fallbackDates: DateType[]
|
||||
}
|
||||
}
|
||||
|
||||
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
|
||||
|
||||
/**
|
||||
* Whether the page's `dates[type]` is the one its frontmatter sets for that type (after the
|
||||
* frontmatter built-in's aliases such as `date` or `lastmod`), rather than one from git or the
|
||||
* file system. Compared by value, so it holds whatever `priority` the date plugin uses.
|
||||
* Date-only values (`2024-01-02`) are local midnight, as the date plugin reads them.
|
||||
*/
|
||||
export function dateIsFromFrontmatter(
|
||||
data: QuartzPluginData,
|
||||
date: Date | undefined,
|
||||
type: string | undefined = data.defaultDateType as string | undefined,
|
||||
): boolean {
|
||||
if (!(date instanceof Date) || isNaN(date.getTime())) return false
|
||||
const frontmatter = data.frontmatter as Record<string, unknown> | undefined
|
||||
if (!type || !frontmatter) return false
|
||||
let raw = frontmatter[type]
|
||||
if (raw === undefined || raw === null || raw === "") return false
|
||||
if (typeof raw === "string" && DATE_ONLY.test(raw)) raw = `${raw}T00:00:00`
|
||||
if (!(raw instanceof Date) && typeof raw !== "string" && typeof raw !== "number") return false
|
||||
const fromFrontmatter = new Date(raw)
|
||||
return !isNaN(fromFrontmatter.getTime()) && fromFrontmatter.getTime() === date.getTime()
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's date of this type when it is a real one, `undefined` when it is missing, invalid
|
||||
* or a stand-in (the build time the date plugin fills in for a date no source gave).
|
||||
*
|
||||
* The date plugin lists stand-ins in `fallbackDates`. Older versions don't, so without that
|
||||
* list a `published` date only counts when it is the frontmatter's (frontmatter is its only
|
||||
* source); `created` and `modified` are taken as they are.
|
||||
*/
|
||||
export function realDate(data: QuartzPluginData, type: string | undefined): Date | undefined {
|
||||
if (!type) return undefined
|
||||
const date = (data.dates as Record<string, unknown> | undefined)?.[type]
|
||||
if (!(date instanceof Date) || isNaN(date.getTime())) return undefined
|
||||
const fallbacks = data.fallbackDates
|
||||
if (Array.isArray(fallbacks)) return fallbacks.includes(type as DateType) ? undefined : date
|
||||
if (type === "published" && !dateIsFromFrontmatter(data, date, "published")) return undefined
|
||||
return date
|
||||
}
|
||||
@@ -392,3 +392,118 @@ describe("resolveRelative", () => {
|
||||
assert.strictEqual(path.resolveRelative("abc/def" as FullSlug, "ghi/" as SimpleSlug), "../ghi/")
|
||||
})
|
||||
})
|
||||
|
||||
describe("slugs.stripDiacritics (#2410)", () => {
|
||||
const withStrip = <T>(fn: () => T): T => {
|
||||
path.setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
return fn()
|
||||
} finally {
|
||||
path.setSlugOptions(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
test("off by default: slugs keep their diacritics", () => {
|
||||
assert.strictEqual(path.slugifyFilePath("české/čeština.md" as path.FilePath), "české/čeština")
|
||||
})
|
||||
|
||||
test("strips diacritics from folder and file names", () => {
|
||||
withStrip(() => {
|
||||
const slug = (fp: string) => path.slugifyFilePath(fp as path.FilePath)
|
||||
assert.strictEqual(slug("české/Čeština.md"), "ceske/cestina")
|
||||
assert.strictEqual(slug("Příliš žluťoučký kůň.md"), "prilis-zlutoucky-kun")
|
||||
assert.strictEqual(slug("Café/Crème brûlée.md"), "cafe/creme-brulee")
|
||||
assert.strictEqual(slug("Tiếng Việt.md"), "tieng-viet")
|
||||
assert.strictEqual(slug("obrázek.PNG"), "obrazek.PNG")
|
||||
// decomposed input (macOS file names) gives the same slug
|
||||
assert.strictEqual(slug("čeština.md"), "cestina")
|
||||
})
|
||||
})
|
||||
|
||||
test("keeps scripts whose marks are not Latin diacritics", () => {
|
||||
withStrip(() => {
|
||||
const slug = (fp: string) => path.slugifyFilePath(fp as path.FilePath)
|
||||
assert.strictEqual(slug("한국어.md"), "한국어")
|
||||
assert.strictEqual(slug("がぎぐ.md"), "がぎぐ")
|
||||
assert.strictEqual(slug("हिन्दी.md"), "हिन्दी")
|
||||
assert.strictEqual(slug("日本語/中文.md"), "日本語/中文")
|
||||
// Latin letters without a decomposition fold to ASCII (utils 1.3.1)
|
||||
assert.strictEqual(slug("Łódź ø ß.md"), "lodz-o-ss")
|
||||
assert.strictEqual(slug("Æsir.md"), "aesir")
|
||||
})
|
||||
})
|
||||
|
||||
test("is idempotent", () => {
|
||||
withStrip(() => {
|
||||
const once = path.slugifyFilePath("Čeština/Ž.md" as path.FilePath)
|
||||
assert.strictEqual(path.slugifyFilePath(`${once}.md` as path.FilePath), once)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("normalizeRelativeURLs (SPA navigation and popovers)", () => {
|
||||
// A minimal stand-in for a parsed page: querySelectorAll understands the attribute selectors
|
||||
// `[a=""]` and `[a^="v"]`, comma-separated, as a browser does.
|
||||
function fakePage(attrs: Record<string, string>[]) {
|
||||
const els = attrs.map((a) => ({
|
||||
attrs: { ...a },
|
||||
getAttribute(name: string) {
|
||||
return this.attrs[name] ?? null
|
||||
},
|
||||
setAttribute(name: string, value: string) {
|
||||
this.attrs[name] = value
|
||||
},
|
||||
}))
|
||||
const matches = (el: (typeof els)[number], selector: string) =>
|
||||
selector.split(",").some((part) => {
|
||||
const m = part.trim().match(/^\[(\w+)(\^?)="([^"]*)"\]$/)
|
||||
if (!m) throw new SyntaxError(`unsupported selector ${part}`)
|
||||
const value = el.getAttribute(m[1])
|
||||
if (value === null) return false
|
||||
return m[2] ? value.startsWith(m[3]) : value === m[3]
|
||||
})
|
||||
const page = {
|
||||
querySelectorAll: (selector: string) => els.filter((el) => matches(el, selector)),
|
||||
}
|
||||
return { page: page as unknown as Element, els }
|
||||
}
|
||||
|
||||
test("rebases relative href and src onto the page's URL, keeping fragments; others are left", () => {
|
||||
const { page, els } = fakePage([
|
||||
{ href: "./sibling" },
|
||||
{ href: "../up/page#part" },
|
||||
{ href: "" },
|
||||
{ src: "./img.png" },
|
||||
{ src: "../media/v.mp4" },
|
||||
{ href: "https://example.com/x" },
|
||||
{ href: "/absolute" },
|
||||
{ href: "#local" },
|
||||
{ src: "plain.png" },
|
||||
])
|
||||
path.normalizeRelativeURLs(page, "https://garden.example/notes/deep/page?q=1#h")
|
||||
assert.deepStrictEqual(
|
||||
els.map((e) => e.attrs),
|
||||
[
|
||||
{ href: "/notes/deep/sibling" },
|
||||
{ href: "/notes/up/page#part" },
|
||||
// an empty href is the page itself, its query string included (as in the browser)
|
||||
{ href: "/notes/deep/page?q=1" },
|
||||
{ src: "/notes/deep/img.png" },
|
||||
{ src: "/notes/media/v.mp4" },
|
||||
{ href: "https://example.com/x" },
|
||||
{ href: "/absolute" },
|
||||
{ href: "#local" },
|
||||
{ src: "plain.png" },
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
// _rebaseHtmlElement used to keep only `pathname + hash` of the resolved URL, so a relative
|
||||
// link or embed with a query string lost it after SPA navigation or in a popover
|
||||
// (`./static/viewer.html?file=a.pdf` → `/notes/static/viewer.html`).
|
||||
test("keeps the query string of a relative URL", () => {
|
||||
const { page, els } = fakePage([{ src: "./viewer.html?file=a.pdf#p2" }])
|
||||
path.normalizeRelativeURLs(page, "https://garden.example/notes/page")
|
||||
assert.deepStrictEqual(els[0].attrs, { src: "/notes/viewer.html?file=a.pdf#p2" })
|
||||
})
|
||||
})
|
||||
+18
-2
@@ -6,7 +6,6 @@ export {
|
||||
isRelativeURL,
|
||||
isAbsoluteURL,
|
||||
getFullSlug,
|
||||
slugifyFilePath,
|
||||
simplifySlug,
|
||||
joinSegments,
|
||||
endsWith,
|
||||
@@ -35,13 +34,30 @@ export type {
|
||||
|
||||
// --- v5-specific exports below ---
|
||||
|
||||
// `configuration.slugs` (stripDiacritics) lives in @quartz-community/utils, on a global shared by
|
||||
// every copy of the package, so core's slugs and plugins' slugs (tag pages, canvas, bases,
|
||||
// alias-redirects …) agree. The config loader sets it in the main thread and in every worker.
|
||||
import { getSlugOptions, stripDiacritics } from "@quartz-community/utils"
|
||||
export {
|
||||
getSlugOptions,
|
||||
setSlugOptions,
|
||||
slugifyFilePath,
|
||||
stripDiacritics,
|
||||
} from "@quartz-community/utils"
|
||||
export type { SlugOptions } from "@quartz-community/utils"
|
||||
|
||||
/** `stripDiacritics` when `configuration.slugs.stripDiacritics` is on, else unchanged. */
|
||||
export function applySlugOptions(s: string): string {
|
||||
return getSlugOptions().stripDiacritics ? stripDiacritics(s) : s
|
||||
}
|
||||
|
||||
export const QUARTZ = "quartz"
|
||||
|
||||
// from micromorph/src/utils.ts
|
||||
// https://github.com/natemoo-re/micromorph/blob/main/src/utils.ts#L5
|
||||
const _rebaseHtmlElement = (el: Element, attr: string, newBase: string | URL) => {
|
||||
const rebased = new URL(el.getAttribute(attr)!, newBase)
|
||||
el.setAttribute(attr, rebased.pathname + rebased.hash)
|
||||
el.setAttribute(attr, rebased.pathname + rebased.search + rebased.hash)
|
||||
}
|
||||
export function normalizeRelativeURLs(el: Element | Document, destination: string | URL) {
|
||||
el.querySelectorAll('[href=""], [href^="./"], [href^="../"]').forEach((item) => {
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user