mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-30 22:44:41 +01:00
Compare commits
220
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
706b6fd30a | ||
|
|
6487fc2415 | ||
|
|
87ee900f05 | ||
|
|
92ff583098 | ||
|
|
c92fed97c0 | ||
|
|
79d3ea9875 | ||
|
|
f2015a4c76 | ||
|
|
2e69d52f76 | ||
|
|
8c81436188 | ||
|
|
fe47fb1239 | ||
|
|
fb4dbab487 | ||
|
|
9ca6f4ee69 | ||
|
|
cc8d104cc7 | ||
|
|
b86276f52b | ||
|
|
9ebfc67c1b | ||
|
|
ffc6bfd3ed | ||
|
|
ea4b07518c | ||
|
|
afebc38b3b | ||
|
|
c7131c909f | ||
|
|
5a740b3ae0 | ||
|
|
6f67702b3e | ||
|
|
685a5c3461 | ||
|
|
114923ac6a | ||
|
|
a7d7389f57 | ||
|
|
699c668cba | ||
|
|
9889d3fb04 | ||
|
|
c68a4945ab | ||
|
|
ce108c8c95 | ||
|
|
57b3b5d0af | ||
|
|
c317915450 | ||
|
|
1e1a3561b3 | ||
|
|
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 | ||
|
|
2386362d57 | ||
|
|
d533468802 | ||
|
|
048519774a | ||
|
|
ee1cdffd0d | ||
|
|
08fddad0e8 | ||
|
|
506a7caa8c | ||
|
|
678398d235 | ||
|
|
6f82d03fd4 | ||
|
|
95e96b4871 | ||
|
|
23b70cdba0 | ||
|
|
829bec461f | ||
|
|
c392e177a7 | ||
|
|
3f8104fb50 | ||
|
|
7531e678f5 | ||
|
|
568004496b | ||
|
|
d80bb003f1 | ||
|
|
6f79e008e2 | ||
|
|
166d09b876 | ||
|
|
3960252445 | ||
|
|
436cce7610 | ||
|
|
4ed26b3943 | ||
|
|
8f469ed237 | ||
|
|
cdc5a0297f | ||
|
|
1dfe7fcdb0 | ||
|
|
7453f7f0d0 | ||
|
|
9c46b01c57 | ||
|
|
842a293ab1 | ||
|
|
6f872d4302 | ||
|
|
8578f2fdb2 | ||
|
|
5b863b0752 | ||
|
|
d092a3179b | ||
|
|
dacfeba928 | ||
|
|
5fafbf37b7 | ||
|
|
2e4ef40bc0 | ||
|
|
99685cf741 | ||
|
|
b58a7f20fe | ||
|
|
49d05638f2 | ||
|
|
d7d6c7b17f | ||
|
|
db2ce262b7 | ||
|
|
29a5bdf4b9 | ||
|
|
97059690a0 | ||
|
|
e2e248b9b8 | ||
|
|
9a04652b4f | ||
|
|
b19cdb8a09 | ||
|
|
64dde0cb9c | ||
|
|
46312a6197 | ||
|
|
f690faad9e | ||
|
|
546703340e |
No files matched your search
@@ -1,9 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Bases (bases-page 1.4.0) render closer to Obsidian:
|
||||
|
||||
- custom summaries are evaluated, and summaries show their name and appear per group;
|
||||
- `html()`, `image()`, `icon()`, regular expressions and `file.backlinks` work in formulas;
|
||||
- `kanban` views, `groupOrder`, grouped list and cards views, and the list and row height options work.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
The config schema (editor validation of `quartz.config.yaml`) accepts `configuration.fonts`, `theme.typography.title`, and fonts given with their weights (`{ name, weights, includeItalic }`), which the build already supported. With `extends`, a partial `theme` (for example one colour) is no longer reported as missing `fontOrigin`, `typography` or `darkMode`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Reinstalling an npm plugin at the version pinned in `quartz.lock.json` (after a fresh clone, or on a CI runner) no longer rewrites its `installedAt`, so `npx quartz plugin install` leaves the lockfile unchanged, as it does for Git plugins.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Updated plugins that rely on Quartz 5.1 and now declare it (`quartzVersion: ">=5.1.0"`): encrypted-pages 1.2.0, explicit-publish 1.2.0, unlisted-pages 1.2.0, obsidian-flavored-markdown 2.2.0, folder-page 1.1.0 and bases-page 1.3.0.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Popovers show next to their link with Obsidian themes (quartz-themes-core) too: its Obsidian base styles made them `position: absolute`, so on a scrolled page they appeared a scroll's height above the link, often off screen — links to headings and an embed's "link to original" seemed to show no popover. A popover for a link to a heading now also scrolls the heading to the top of the popover when the theme positions the page's content box.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": minor
|
||||
---
|
||||
|
||||
Theme support for Obsidian themes: plugin factories may be async (Quartz awaits them); font loading is built in as `configuration.fonts` (formerly the `@quartz-community/quartz-fonts` plugin, whose config entry is applied automatically); callouts and transclusions render as `<div>` like in Obsidian; popovers carry Obsidian's `hover-popover`/`markdown-embed` classes.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Links resolve as in Obsidian in more cases (`@quartz-community/utils` 1.3.5): `[[./index|index]]` in a subfolder links to that folder's index page instead of the home page; when several notes share a name, a link prefers the one under the linking note's folder, then the shortest path, instead of pointing to a page that doesn't exist (for example `[Status](current.md)` in a vault where several folders have a `current.md`); a `../` link that names no note resolves from the folder it leads to; and a link starting with `/` is a path from the root.
|
||||
@@ -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') }}
|
||||
@@ -64,27 +64,3 @@ jobs:
|
||||
run: |
|
||||
npx changeset status --since=origin/v5 >/dev/null 2>&1 \
|
||||
|| echo "::warning::No changeset in this PR. If it changes how Quartz behaves, run 'npx changeset' (see .changeset/README.md)."
|
||||
|
||||
publish-tag:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v5' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
- name: Get package version
|
||||
run: node -p -e '`PACKAGE_VERSION=${require("./package.json").version}`' >> $GITHUB_ENV
|
||||
- name: Create release tag
|
||||
uses: pkgdeps/git-tag-action@v3
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
github_repo: ${{ github.repository }}
|
||||
version: ${{ env.PACKAGE_VERSION }}
|
||||
git_commit_sha: ${{ github.sha }}
|
||||
git_tag_prefix: "v"
|
||||
@@ -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,25 @@ 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.
|
||||
# This is the only place that tags a release: ci.yaml's old `publish-tag` job (an annotated
|
||||
# tag through pkgdeps/git-tag-action) ran first and kept every release tag unverified.
|
||||
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
|
||||
+178
@@ -1,5 +1,183 @@
|
||||
# @jackyzha0/quartz
|
||||
|
||||
## 5.4.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 9ebfc67: `extends` in `quartz.config.yaml` is stable for `default` and local paths: its merge rules won't change in a minor release. `https://` URLs stay experimental. Keys starting with `$` are now reserved in every file of an `extends` chain (the top-level `$schema` aside), so merge operators such as appending to a list can be added later without changing existing configs; a config that uses one stops with an error naming the key. Configs without `extends` are not affected.
|
||||
- cc8d104: `quartz.lock.json` is read and written next to the config file Quartz uses, and every `npx quartz plugin` command takes `--config` / `-C` like `build`. A site's repository can hold its content, `quartz.config.yaml` and `quartz.lock.json` while Quartz is checked out elsewhere (as the GitHub Action will). With the config in Quartz's folder nothing changes, and a config elsewhere keeps using an existing lockfile in Quartz's folder until its own folder has one. Plugin commands with a config chosen by `QUARTZ_CONFIG_PATH` now also edit that file; they used to write their changes to `./quartz.config.yaml`.
|
||||
- b86276f: npm plugins that Quartz's `package.json` doesn't list are pinned in `quartz.lock.json` (version and integrity) and installed into `.quartz/plugins/@scope/name`, like Git plugins. `plugin add`, and `plugin install --from-config` (e.g. for the `obsidian` and `ttrpg` templates' Excalidraw plugin), no longer write them into Quartz's `package.json`, so `npx quartz upgrade` doesn't conflict with your plugins, and `npm install` / `npm ci` can't remove them. `plugin install`, `--latest`, `restore`, `remove`, `prune`, `list`, `doctor` and `npx quartz plugin` handle them alongside Git plugins, and a build installs a missing one at its pinned version. npm plugins in `package.json` (the default plugins, and any you `npm install` yourself) are versioned there and load from `node_modules`, as before: when a plugin is in both, `package.json` wins.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ea4b075: Plugin update: og-image 1.2.0. A page's social image (`socialImage`, or Obsidian's `image` / `cover` property) can be an image in the content folder, written as a wikilink (`[[cover.png]]`), a path from the content folder, a path relative to the note, or a bare file name. Before, every value that was not a URL was read as a path in `quartz/static/`.
|
||||
|
||||
## 5.3.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- f285e12: 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.
|
||||
- ce108c8: A `locale` that Quartz has no translation for (such as `sv-SE`, `da-DK` or `es-MX`) no longer crashes the build. Quartz uses a translation of the same language (`es-MX` uses `es-ES`), else English, and prints one warning; dates still use the configured locale.
|
||||
- 9889d3f: Plugin updates: folder-page 1.1.5 (a folder's unlisted `index.md` is no longer replaced by a generated folder page), canvas-page 1.1.7 (edges drawn as in Obsidian), search 1.1.5 (Escape with tag suggestions open closes only the suggestions), graph 1.0.10 (the local graph is drawn once per page), stacked-pages 1.0.5 (unused template exports removed) and remark-obsidian 2.2.6.
|
||||
- 37a61cf: 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.
|
||||
|
||||
- 6729a1e: 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`).
|
||||
- c68a494: Some fixes in this release change how existing pages look, mostly to match Obsidian: Bases sorting (natural text order, empty values last, mixed types), Bases `not:` filters and `== null`, Bases group headings, canvas edges, and folders with an unlisted `index.md`. See [Upgrading from 5.3.0 to 5.3.1](https://quartz.jzhao.xyz/getting-started/upgrading#upgrading-from-530-to-531).
|
||||
- 57b3b5d: `npx quartz plugin install --latest` (and `plugin update`) no longer fails because a disabled plugin can't be updated, for example an old `quartz-themes` entry whose repository moved its plugin. The build doesn't load disabled plugins, so this is now a warning that says how to remove the entry. A failing enabled plugin still fails the command.
|
||||
- 1e1a356: utils 1.3.4: inline `#tag` links from notes two or more folders deep stay under the site's base path. They went to `/tags/…` instead of `/<base>/tags/…`, a 404 on sites served under a sub-path such as GitHub Pages project sites.
|
||||
|
||||
## 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
|
||||
|
||||
- ee1cdff: Updates `@quartz-themes/core` to 3.1.1: the Obsidian template (`theme: default`) works again (since 3.0 the plugin failed to initialise looking "default" up as a community theme); `default`, `obsidian` and `Obsidian default` use Obsidian's built-in theme.
|
||||
|
||||
## 5.2.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3f8104f: Fonts: explicitly configured `body`, `code` and `interface` fonts now apply with an Obsidian theme. They are also written to Obsidian's `--font-*-override` variables on `body`, which the theme's styles read; before, the theme's own `body` font variables won over Quartz's `:root` ones.
|
||||
- c392e17: Fonts: the `interface` font and per-heading fonts (`h1` … `h6`) are now loaded from Google Fonts (or self-hosted with `fontOrigin: selfHosted`) like the other fonts; before, they only rendered if installed locally. A font with a single weight now loads that weight (`weights: [700]` loaded 400), and a single-weight italic font no longer makes the Google Fonts request fail.
|
||||
- 7531e67: On phones and tablets, one too-wide item in the header row (a long page title, or an Obsidian theme's styled header) no longer widens the page past the screen. The content column is `minmax(0, 1fr)` instead of `auto` (also in the full-width and minimal frames), and text in the phone header row may break anywhere.
|
||||
- 95e96b4: Updates `@quartz-themes/core` to 3.1, which converts any Obsidian community theme at build time: name a theme as Obsidian lists it (`Minimal`, `AnuPpuccin`), a GitHub repository, a URL or a local `theme.css`; Style Settings exports and CSS snippets apply as in Obsidian. Theme ids from 2.x (`tokyo-night`) keep working; `aspects`, `include`, `calloutStyle` and `fonts` were removed, and the `@quartz-themes/<theme>` packages are no longer needed. Quartz keeps its own page layout under a theme, `themeFonts: false` uses the site's Quartz fonts, and a theme's embedded fonts ship as separate files. See [ThemesCore](https://quartz.jzhao.xyz/plugins/ThemesCore).
|
||||
|
||||
## 5.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 4ed26b3: `quartz build --config <path>` (or `-C`) reads the site configuration from another file than `./quartz.config.yaml`, so the config can live with the content outside the Quartz folder, and one Quartz install can build several content repositories (#2646). With `--watch`/`--serve`, changes to that file trigger a rebuild.
|
||||
- 607ccb8: Theme support for Obsidian themes: plugin factories may be async (Quartz awaits them); font loading is built in as `configuration.fonts` (formerly the `@quartz-community/quartz-fonts` plugin, whose config entry is applied automatically); callouts and transclusions render as `<div>` like in Obsidian; popovers carry Obsidian's `hover-popover`/`markdown-embed` classes.
|
||||
- 9705969: Transformers can declare `renderTransforms`: transforms of a page's content when it is rendered, `before` transclusions are inlined and page types' `treeTransforms` run (bases are filled in), and `after` them, on the finished content. encrypted-pages uses them to encrypt a note's finished content, so bases and transclusions in encrypted notes show when unlocked (quartz-community/encrypted-pages#2).
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ed4f653: Bases (bases-page 1.4.0) render closer to Obsidian:
|
||||
|
||||
- custom summaries are evaluated, and summaries show their name and appear per group;
|
||||
- `html()`, `image()`, `icon()`, regular expressions and `file.backlinks` work in formulas;
|
||||
- `kanban` views, `groupOrder`, grouped list and cards views, and the list and row height options work.
|
||||
|
||||
- 99685cf: Bases inside a transcluded note render that note's own base, and links in bases follow `configuration.links` (external-link icon, new tab, lazy images, popovers) (bases-page 1.5.1).
|
||||
- 9a04652: Bases columns are labelled with the property's name, as in Obsidian (`priority`, `file name`), instead of title-cased (`Priority`, `Name`); bases-page's new `propertyLabels: title` option keeps the title-cased labels (bases-page 1.5.0).
|
||||
- 9c46b01: Updates `@quartz-community/obsidian-flavored-markdown` to 2.3.1, which renders callout titles in `.callout-title-inner` without a `<p>`, as in Obsidian (themes put the title below its icon otherwise). Callout titles are styled on `.callout-title-inner` itself (colour, margin, line height); the `> p` rule stays for sites on an older obsidian-flavored-markdown.
|
||||
- cdc5a02: Updates dependencies with minor and patch releases: `@clack/prompts` 1.9.0, `@napi-rs/simple-git` 1.2.0, `isomorphic-git` 1.44.18, `minimatch` 11.0.9, `preact-render-to-string` 6.8.3 and `prettier` 3.10.1.
|
||||
- 8578f2f: Permalinks work on large sites: sites of 192 or more files are parsed in worker threads, which didn't receive the permalinks, so a note with a `permalink` was published at its file path (#2644). A permalink with `.` or `..` segments is ignored with a warning instead of writing pages outside the output folder (#2641). With `prettyLinks`, a wikilink to a note whose name has a space or a non-ASCII letter reads as the note's name without its folder, as other links do (#2643).
|
||||
- 166d09b: `quartz plugin install` moves a plugin to its pinned commit even when the plugin's build left tracked files changed (its `package-lock.json`). In CI, a plugin cache restored through `restore-keys` kept those changes, and installing an updated plugin failed with "Please commit your changes or stash them" (#2639).
|
||||
- 6f872d4: Updates `@quartz-community/alias-redirects` to 1.0.4 (aliases that point outside the site are skipped, #2641) and `@quartz-community/note-properties` to 1.1.5 (links in properties to missing pages get the `broken` class with `disableBrokenWikilinks`, #2635).
|
||||
- 0ab525c: Updated plugins that rely on Quartz 5.1 and now declare it (`quartzVersion: ">=5.1.0"`): encrypted-pages 1.2.0, explicit-publish 1.2.0, unlisted-pages 1.2.0, obsidian-flavored-markdown 2.2.0, folder-page 1.1.0 and bases-page 1.3.0.
|
||||
- 49d0563: Transcluded content no longer duplicates ids. Headings and footnotes inside a transclusion get ids unique on the page, and the links inside it go to them, so the host's footnotes and a `[[#Heading]]` link inside a transclusion jump to the right place. A same-page link whose target isn't in the transcluded section links to the transcluded page. A heading transclusion (`![[note#Heading]]`) holds only the footnotes it references instead of the page's whole footnotes section.
|
||||
|
||||
## 5.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -41,7 +41,7 @@ This question is best answered by tracing what happens when a user (you!) runs `
|
||||
2. The `PageTypeDispatcher` emitter renders the HTML pages (`quartz/plugins/pageTypes/dispatcher.ts`):
|
||||
1. Each page type's `generate` runs, one after another in priority order, and returns virtual pages (folder and tag pages, `.base` and `.canvas` pages, …). They are collected in `ctx.virtualPages`. Pages that stand for a file (page types with `fileExtensions`) first go through the site's filters, with `file.data.referencedBy` set to the pages that link to them.
|
||||
2. The bodies of the virtual pages are rendered (so they can be embedded), and the transformers' `virtualPageHtmlPlugins` run on those of file-backed pages.
|
||||
3. Every content page is rendered by the first page type (highest priority) whose `match` accepts it, and every virtual page by the page type that generated it. Rendering transforms the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime, applies the page types' `treeTransforms`, assembles the page [[layout]] and [[layout#Page Frames|frame]], and renders the JSX to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) (statically: `useState`, `useEffect` and other interactive bits don't run). The bulk of this logic can be found in `quartz/components/renderPage.tsx`.
|
||||
3. Every content page is rendered by the first page type (highest priority) whose `match` accepts it, and every virtual page by the page type that generated it. Rendering transforms the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime, applies the transformers' `renderTransforms` (`before`), inlines transclusions, applies the page types' `treeTransforms` and the transformers' `renderTransforms` (`after`), assembles the page [[layout]] and [[layout#Page Frames|frame]], and renders the JSX to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) (statically: `useState`, `useEffect` and other interactive bits don't run). The bulk of this logic can be found in `quartz/components/renderPage.tsx`.
|
||||
3. The content index is built once from the published and virtual pages (`ctx.contentIndex`), then all other emitters run in parallel over the same content (virtual pages included). The built-in content index emitter writes `static/contentIndex.json`, the sitemap and the RSS feed; plugin emitters write their own files.
|
||||
7. If the `--serve` flag was detected, we also set up another file watcher to detect content changes (only `.md` files). We keep a content map that tracks the parsed AST and plugin data for each slug and update this on file changes. Newly added or modified paths are rebuilt and added to the content map. Then, all the filters and emitters are run over the resulting content map. This file watcher is debounced with a threshold of 250ms. On success, we send a client refresh signal using the passed in callback function.
|
||||
|
||||
|
||||
@@ -107,6 +107,7 @@ export type QuartzTransformerPluginInstance = {
|
||||
markdownPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
htmlPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
virtualPageHtmlPlugins?: (ctx: BuildCtx, content: ProcessedContent[]) => PluggableList
|
||||
renderTransforms?: (ctx: BuildCtx) => { before?: TreeTransform[]; after?: TreeTransform[] }
|
||||
externalResources?: (ctx: BuildCtx) => Partial<StaticResources> | undefined
|
||||
extendContentIndex?: ContentIndexExtension // any plugin type, see below
|
||||
}
|
||||
@@ -118,6 +119,7 @@ All transformer plugins must define at least a `name` field to register the plug
|
||||
- `markdownPlugins` defines a list of [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md). `remark` is a tool that transforms Markdown to Markdown in a structured way.
|
||||
- `htmlPlugins` defines a list of [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md). Similar to how `remark` works, `rehype` is a tool that transforms HTML to HTML in a structured way.
|
||||
- `virtualPageHtmlPlugins` (Quartz 5.1+) defines rehype plugins for the pages that page types render from files (`.base`, `.canvas`, Excalidraw drawings). Those pages are rendered when emitting and never pass through `htmlPlugins`, so a plugin that should also act on them (e.g. encryption) registers its rehype plugin here too. They run on the page's rendered body, with the page's vfile (`file.data.frontmatter`, `file.data.referencedBy`), after the filters published the page; the page then shows the resulting tree. `content` is the published content.
|
||||
- `renderTransforms` (Quartz 5.2+) defines transforms of a page's content tree when the page is rendered, when other pages' content and `allFiles` are available. Each is a function `(root, slug, componentData) => void` that changes `root`, a copy of the page's tree. `before` transforms run before transclusions are inlined and page types' `treeTransforms` run (bases are filled in, for example); `after` transforms run on the finished content. [encrypted-pages](https://github.com/quartz-community/encrypted-pages) uses both: `before` puts its page's content back, `after` encrypts the finished content, transclusions and bases included. Something that only needs the finished content, such as rewriting all links in it, needs only `after`.
|
||||
- `externalResources` defines any external resources the plugin may need to load on the client-side for it to work properly.
|
||||
|
||||
Transformers run in plugin order (see [[plugin manifest#defaultOrder]]); the built-in frontmatter parsing runs at order 0 and the built-in link processing, which sets `file.data.links`, at 60.
|
||||
@@ -554,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>
|
||||
)
|
||||
},
|
||||
}
|
||||
@@ -567,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.
|
||||
@@ -42,7 +42,7 @@ and says whether to update Quartz (`npx quartz upgrade`) or the plugin. If an in
|
||||
|
||||
### For plugin authors
|
||||
|
||||
- Set `quartzVersion` to the **oldest Quartz version your plugin works with**. Raise it when you start using a newer API — for example a plugin that relies on [[built-in processing]] (core-parsed frontmatter, `ctx.contentIndex`, `extendContentIndex`), an async page type `generate`, `virtualPageHtmlPlugins`, `assets` or `window.quartzStaticUrl` needs `">=5.1.0"`. The [plugin template](https://github.com/quartz-community/plugin-template) starts with `">=5.0.0"`.
|
||||
- Set `quartzVersion` to the **oldest Quartz version your plugin works with**. Raise it when you start using a newer API — for example a plugin that relies on [[built-in processing]] (core-parsed frontmatter, `ctx.contentIndex`, `extendContentIndex`), an async page type `generate`, `virtualPageHtmlPlugins`, `assets` or `window.quartzStaticUrl` needs `">=5.1.0"`; one that relies on `renderTransforms` needs `">=5.2.0"` (or treats the hook as optional, as Quartz 5.1 never calls it). The [plugin template](https://github.com/quartz-community/plugin-template) starts with `">=5.0.0"`.
|
||||
- Prefer a lower bound (`>=5.1.0`) over a caret range: minor Quartz releases don't break plugins, so `^5` would only add an upper bound you'd have to bump at every major release. Add an upper bound when you know a major version breaks you.
|
||||
- Raising `quartzVersion` is a breaking change for users on older Quartz versions: release it as a new major (or at least minor) version of your plugin and say so in its changelog.
|
||||
- Pre-releases count: Quartz `5.2.0-beta.1` satisfies `>=5.1.0`.
|
||||
|
||||
@@ -11,6 +11,7 @@ The `build` command transforms your Markdown content into a static HTML website.
|
||||
| Flag | Shorthand | Description | Default |
|
||||
| ----------------- | --------- | ---------------------------------------------------------------------------------- | ------------------ |
|
||||
| `--directory` | `-d` | The content folder | `content` |
|
||||
| `--config` | `-C` | Path to the config file to load (see [[#Custom config file]]) | quartz.config.yaml |
|
||||
| `--verbose` | `-v` | Print detailed build information (see [[#Verbose output]]) | `false` |
|
||||
| `--output` | `-o` | The directory where the built site will be saved | `public` |
|
||||
| `--serve` | | Start a local development server | `false` |
|
||||
@@ -56,6 +57,24 @@ If you have a very large vault, you can limit the number of concurrent workers t
|
||||
npx quartz build --concurrency 2
|
||||
```
|
||||
|
||||
### Custom config file
|
||||
|
||||
By default Quartz loads `quartz.config.yaml` from the current working directory. Use `--config` (or `-C`) to point at a config file elsewhere — for example when the config lives alongside your content rather than inside the Quartz install.
|
||||
|
||||
```shell
|
||||
npx quartz build --config ../my-vault/quartz.config.yaml
|
||||
```
|
||||
|
||||
`quartz.lock.json` is read from the same folder as the config, so a site's repository can hold its content, `quartz.config.yaml` and `quartz.lock.json` together while Quartz is checked out elsewhere. Plugins are still installed into Quartz's `.quartz/plugins/`. Use the same `--config` with the [[cli/plugin|plugin]] commands, which pin plugins in that lockfile. (A config in a folder without a lockfile keeps using an existing `quartz.lock.json` in Quartz's folder.) The [[github-action|Quartz GitHub Action]] builds sites this way.
|
||||
|
||||
```shell
|
||||
npx quartz plugin install --config ../my-vault/quartz.config.yaml
|
||||
npx quartz build --config ../my-vault/quartz.config.yaml -d ../my-vault/content
|
||||
```
|
||||
|
||||
> [!note]
|
||||
> The shorthand for `--config` is an uppercase `-C`. A lowercase `-c` is the shorthand for `--concurrency`, so the two are distinct.
|
||||
|
||||
### Verbose output
|
||||
|
||||
`npx quartz build --verbose` also prints:
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ These flags are accepted by every Quartz command:
|
||||
| `--verbose` | `-v` | Enable detailed logging for debugging | `false` |
|
||||
| `--concurrency` | `-c` | Max parallel workers for operations that run in parallel (e.g. `build`, `plugin install`, `plugin add`) | CPU core count |
|
||||
|
||||
Commands that don't perform parallel work accept `-c` as a no-op, so it's always safe to pass. See [[build#Performance Tuning|build]] and [[cli/plugin#Installing on low-end hardware|plugin]] for practical examples.
|
||||
Commands that don't perform parallel work accept `-c` as a no-op, so it's always safe to pass. See [[cli/build#Performance Tuning|build]] and [[cli/plugin#Installing on low-end hardware|plugin]] for practical examples.
|
||||
|
||||
## Help and Versioning
|
||||
|
||||
|
||||
+11
-7
@@ -6,18 +6,20 @@ The `plugin` command is the heart of the Quartz v5 plugin management system. it
|
||||
|
||||
Quartz plugins come from two kinds of sources:
|
||||
|
||||
- **npm packages** (`@quartz-community/explorer`) — the default plugins. They are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`.
|
||||
- **npm packages** (`@quartz-community/explorer`). Those in Quartz's `package.json` — the default plugins, and any you install with `npm install` yourself — are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`. Other npm plugins are pinned in `quartz.lock.json` (version and integrity) and installed into `.quartz/plugins/@scope/name`, like Git plugins: `plugin add` doesn't change Quartz's `package.json`, so `npx quartz upgrade` doesn't conflict with your plugins, and `npm install` / `npm ci` can't remove them. When a plugin is in both, `package.json` wins.
|
||||
- **Git repositories and local directories** (`github:owner/repo`, `./my-plugin`) — cloned or symlinked into `.quartz/plugins/`. Their exact commits are pinned in `quartz.lock.json`.
|
||||
|
||||
Wherever a command takes a plugin name you can use the full name (`@quartz-community/explorer`), the source as written in `quartz.config.yaml`, or the short name (`explorer`). Misspelled names get a "did you mean" suggestion.
|
||||
|
||||
Every subcommand takes `--config` / `-C`, like [[cli/build#Custom config file|build]]: it reads and edits that config file, and the `quartz.lock.json` next to it, instead of `./quartz.config.yaml` and `./quartz.lock.json`.
|
||||
|
||||
Every subcommand exits with a non-zero status when something fails (a clone, a build, an unknown plugin name), so `npx quartz plugin install && npx quartz build` stops in CI instead of building a site with missing plugins.
|
||||
|
||||
## Subcommands
|
||||
|
||||
### list
|
||||
|
||||
List all configured plugins: Git/local plugins with their pinned commit, npm plugins with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
|
||||
List all configured plugins: plugins pinned in `quartz.lock.json` (Git/local plugins with their commit, npm plugins with their version), npm plugins from `package.json` with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
|
||||
|
||||
```shell
|
||||
npx quartz plugin list
|
||||
@@ -25,7 +27,7 @@ npx quartz plugin list
|
||||
|
||||
### add
|
||||
|
||||
Add a new plugin from npm or a Git repository. The plugin is installed (Git plugins are pinned in `quartz.lock.json`, npm packages recorded in `package.json`), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
|
||||
Add a new plugin from npm or a Git repository. The plugin is installed and pinned in `quartz.lock.json` (Git plugins by commit, npm packages by version; an npm package already in `package.json` stays versioned there), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
|
||||
|
||||
```shell
|
||||
npx quartz plugin add @quartz-community/graph # an npm package, as the default config uses
|
||||
@@ -67,7 +69,7 @@ npx quartz plugin remove plugin-name
|
||||
npx quartz plugin remove explorer # short name of @quartz-community/explorer
|
||||
```
|
||||
|
||||
For npm plugins the package stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
|
||||
A pinned npm plugin is removed from `.quartz/plugins/` and `quartz.lock.json`; an npm plugin from `package.json` stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
|
||||
|
||||
### install
|
||||
|
||||
@@ -77,7 +79,9 @@ Install plugins for your Quartz project. By default, this installs all plugins l
|
||||
npx quartz plugin install
|
||||
```
|
||||
|
||||
If there is no `quartz.lock.json` yet, `install` falls back to installing the Git/local plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists Git plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
|
||||
If there is no `quartz.lock.json` yet, `install` falls back to installing the plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins from `package.json` are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
|
||||
|
||||
`npx quartz build` also installs a pinned npm plugin that is missing from `.quartz/plugins/`, at the version the lockfile pins.
|
||||
|
||||
> [!note]
|
||||
> `npx quartz build` also installs any configured Git plugin that is missing from `.quartz/plugins/`, and checks out the commit pinned in `quartz.lock.json` when there is one. Running `plugin install` first is still recommended in CI, because it fails loudly when a plugin cannot be installed.
|
||||
@@ -85,7 +89,7 @@ If there is no `quartz.lock.json` yet, `install` falls back to installing the Gi
|
||||
#### Flags
|
||||
|
||||
- `--from-config`: Synchronize plugins with `quartz.config.yaml` instead of the lockfile. This will install missing plugins and prune orphaned ones.
|
||||
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile.
|
||||
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile (for a pinned npm plugin, the version npm's `latest` tag points at).
|
||||
- `--clean`: Only restore plugins whose directory is missing; existing directories are left untouched.
|
||||
- `--dry-run`: Preview the changes without actually installing or removing any files.
|
||||
- `--concurrency`, `-c`: Maximum number of plugins to clone, fetch, and build in parallel. Defaults to the number of CPU cores. Lower this (e.g. `-c 1` or `-c 2`) on memory- or CPU-constrained machines where the default parallelism causes failures, OOMs, or hangs. See [[#Installing on low-end hardware]] below.
|
||||
@@ -348,4 +352,4 @@ Running the plugin command without any subcommand shows a status dashboard of al
|
||||
npx quartz plugin
|
||||
```
|
||||
|
||||
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks Git plugins for available updates in parallel. npm plugins are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
|
||||
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks pinned plugins for available updates in parallel (Git plugins against their repository, npm plugins against npm). npm plugins in `package.json` are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
|
||||
+73
-27
@@ -23,6 +23,42 @@ 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.
|
||||
- **Experimental:** `https://` URLs. How they are fetched, cached and trusted may still change. 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. (An editor that validates the file against Quartz's schema may flag such a `null`; the build accepts it.)
|
||||
- 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.
|
||||
- Keys starting with `$` are reserved in every file of an `extends` chain, at any depth (the top-level `$schema` aside): they are kept free for merge operators, such as adding to a list instead of replacing it. A config that uses one stops with an error naming the key. Values may contain `$` freely.
|
||||
- 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. The [[github-action|GitHub Action]] builds with the defaults of the Quartz release it uses, so a config that extends `default` follows them too.
|
||||
|
||||
- `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.
|
||||
|
||||
> [!note] Stability
|
||||
> `extends` with `default` and local paths is stable: the merge rules above don't change in a minor release. `https://` URLs are experimental.
|
||||
>
|
||||
> A Quartz upgrade can change the defaults your site extends. A changed default applies to your site unless your file sets that value itself.
|
||||
|
||||
## 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 +90,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.
|
||||
@@ -70,7 +111,7 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
|
||||
Use a path relative to the site root like above (no leading `/`) so it also works when the site is served from a subpath. To have Quartz download Google Fonts at build time and serve them from your site instead, set `configuration.fonts.fontOrigin: selfHosted` (see [[plugins/Fonts|Fonts]]).
|
||||
- `cdnCaching`: if `true` (default), use Google CDN to cache the fonts. This will generally be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained.
|
||||
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here.
|
||||
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here, as a name or with its weights (see [[#Fonts]]).
|
||||
- `title`: font for the title of the site (optional, same as `header` by default)
|
||||
- `header`: font to use for headers
|
||||
- `code`: font for inline and block quotes
|
||||
@@ -85,8 +126,8 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `tertiary`: hover states and visited [[graph view|graph]] nodes
|
||||
- `highlight`: internal link background, highlighted text, [[syntax highlighting|highlighted lines of code]]
|
||||
- `textHighlight`: markdown highlighted text background
|
||||
- `frontmatter`, `links`, `drafts`, `contentIndex`: options for Quartz's [[built-in processing]] — frontmatter parsing ([[Frontmatter]]), link resolution ([[CrawlLinks]]), draft handling ([[RemoveDrafts]]) and the content index, sitemap and RSS feed ([[ContentIndex]]). They are on by default. Each takes an object of options (plus `enabled` and `order`) or a boolean shorthand: set e.g. `links: { markdownLinkResolution: relative }` to change an option or `contentIndex: false` to turn one off.
|
||||
- `links.markdownLinkResolution` defaults to `shortest` (Obsidian's default). An old `crawl-links` plugin entry that Quartz migrates keeps that plugin's default, `absolute`, unless it sets another value.
|
||||
- `frontmatter`, `links`, `drafts`, `contentIndex`, `fonts`: options for Quartz's [[built-in processing]] — frontmatter parsing ([[Frontmatter]]), link resolution ([[CrawlLinks]]), draft handling ([[RemoveDrafts]]), the content index, sitemap and RSS feed ([[ContentIndex]]) and font loading ([[plugins/Fonts|Fonts]]). They are on by default. Each takes an object of options (plus `enabled` and `order`) or a boolean shorthand: set e.g. `links: { markdownLinkResolution: relative }` to change an option or `contentIndex: false` to turn one off.
|
||||
- `links.markdownLinkResolution` defaults to `shortest`, which resolves links as Obsidian does (see [[CrawlLinks]]). An old `crawl-links` plugin entry that Quartz migrates keeps that plugin's default, `absolute`, unless it sets another value.
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
configuration:
|
||||
@@ -133,6 +174,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`:
|
||||
>
|
||||
@@ -180,7 +235,7 @@ plugins:
|
||||
dark: github-dark
|
||||
```
|
||||
|
||||
Frontmatter parsing, link resolution, drafts and the content index are not plugins: they are [[built-in processing|built into Quartz]] and configured under `configuration.frontmatter`, `.links`, `.drafts` and `.contentIndex`. Everything else is a plugin, referenced by its source: npm plugins (all the default ones) are installed in `node_modules`, Git and local plugins in `.quartz/plugins/`.
|
||||
Frontmatter parsing, link resolution, drafts and the content index are not plugins: they are [[built-in processing|built into Quartz]] and configured under `configuration.frontmatter`, `.links`, `.drafts` and `.contentIndex`. Everything else is a plugin, referenced by its source. npm plugins in Quartz's `package.json` (all the default ones) are installed in `node_modules`; other npm plugins, and Git and local plugins, are installed in `.quartz/plugins/` and pinned in `quartz.lock.json`.
|
||||
|
||||
### Community Plugins
|
||||
|
||||
@@ -191,7 +246,9 @@ npx quartz plugin add @quartz-community/explorer # an npm package
|
||||
npx quartz plugin add github:username/repo # a Git repository
|
||||
```
|
||||
|
||||
This adds the plugin to `quartz.config.yaml` and installs it to `.quartz/plugins/`.
|
||||
This adds the plugin to `quartz.config.yaml`, installs it to `.quartz/plugins/`, and pins it in `quartz.lock.json`: a Git plugin by commit, an npm plugin by version. Commit the lockfile, so that every build, on any machine or in CI, uses the same plugin versions.
|
||||
|
||||
`quartz.lock.json` sits next to `quartz.config.yaml`. For a config file elsewhere, pass the same `--config` to the plugin commands as to `build` (see [[cli/build#Custom config file]]).
|
||||
|
||||
To install all plugins referenced in your config that aren't yet installed (useful when cloning a project or setting up CI):
|
||||
|
||||
@@ -336,29 +393,18 @@ configuration:
|
||||
code: IBM Plex Mono
|
||||
```
|
||||
|
||||
> [!note]
|
||||
> Quartz uses `title`, but the config's JSON schema doesn't list it yet, so an editor with YAML validation may flag it. The warning can be ignored.
|
||||
For more control over font weights and italics, give a font as an object with `name`, `weights` and `includeItalic`:
|
||||
|
||||
For more control over font weights and italics, use the TS override in `quartz.ts`:
|
||||
|
||||
```ts title="quartz.ts"
|
||||
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
|
||||
|
||||
const config = await loadQuartzConfig({
|
||||
theme: {
|
||||
typography: {
|
||||
header: {
|
||||
name: "Schibsted Grotesk",
|
||||
weights: [400, 700],
|
||||
includeItalic: true,
|
||||
},
|
||||
body: "Source Sans Pro",
|
||||
code: "IBM Plex Mono",
|
||||
},
|
||||
},
|
||||
})
|
||||
export default config
|
||||
export const layout = await loadQuartzLayout()
|
||||
```yaml title="quartz.config.yaml"
|
||||
configuration:
|
||||
theme:
|
||||
typography:
|
||||
header:
|
||||
name: Schibsted Grotesk
|
||||
weights: [400, 700]
|
||||
includeItalic: true
|
||||
body: Source Sans Pro
|
||||
code: IBM Plex Mono
|
||||
```
|
||||
|
||||
> [!tip]
|
||||
|
||||
@@ -6,12 +6,23 @@ tags:
|
||||
|
||||
Quartz comes shipped with a Docker image that will allow you to preview your Quartz locally without installing Node.
|
||||
|
||||
You can run the below one-liner to run Quartz in Docker.
|
||||
From your copy of Quartz, run the below one-liner to build the image and run Quartz in Docker.
|
||||
|
||||
```sh
|
||||
docker run --rm -itp 8080:8080 -p 3001:3001 -v ./content:/usr/src/app/content $(docker build -q .)
|
||||
```
|
||||
|
||||
Each Quartz release is also published as an image, `ghcr.io/jackyzha0/quartz`, tagged with its version (`5.4.1`), its minor version (`5.4`) and `latest`. To preview a folder of notes and your configuration with it:
|
||||
|
||||
```sh
|
||||
docker run --rm -itp 8080:8080 -p 3001:3001 \
|
||||
-v ./content:/usr/src/app/content \
|
||||
-v ./quartz.config.yaml:/usr/src/app/quartz.config.yaml \
|
||||
ghcr.io/jackyzha0/quartz:5.4
|
||||
```
|
||||
|
||||
Leave out the second `-v` to use Quartz's default configuration.
|
||||
|
||||
> [!warning] Not to be used for production
|
||||
> Serve mode is intended for local previews only.
|
||||
> For production workloads, see the page on [[hosting]].
|
||||
@@ -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`)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Additionally, Quartz will also generate pages for subfolders. Say you have a not
|
||||
|
||||
You can link to the folder listing by referencing its name, plus a trailing slash, like this: `[[advanced/]]` (results in [[advanced/]]).
|
||||
|
||||
By default, Quartz will title the page with the folder name (set the [[FolderPage]] option `prefixFolders: true` for `Folder: <folder name>`) and no description. You can override this by creating an `index.md` file in the folder with the `title` [[authoring content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the folder description.
|
||||
By default, Quartz will title the page with the folder name (set the [[FolderPage]] option `prefixFolders: true` for `Folder: <folder name>`) and no description. You can override this by creating an `index.md` file in the folder with the `title` [[getting-started/authoring-content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the folder description.
|
||||
|
||||
For example, for the folder `content/posts`, you can add another file `content/posts/index.md` to add a specific description for it.
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ Quartz supports Wikilinks by default and these links are resolved by Quartz's bu
|
||||
|
||||
Parsing wikilinks is part of [[Obsidian compatibility]] ([[ObsidianFlavoredMarkdown]]). How links are resolved (`markdownLinkResolution`, pretty link text, broken-link styling, …) is configured under `configuration.links` (see [[CrawlLinks]]).
|
||||
|
||||
A link names a note by its file name (`[[My Note]]`) or a path (`[[folder/My Note]]`). When several notes match, the link goes, as in Obsidian, to the note whose path is exactly the link (`[[note]]` → `note.md` at the root), else to one under the linking note's folder, else to the one with the shortest path; see `markdownLinkResolution` in [[CrawlLinks]].
|
||||
|
||||
Wikilink matching is case-insensitive to mirror Obsidian: `[[My Note]]`, `[[my note]]`, and `[[MY NOTE]]` all resolve to the same file. The generated URL is lowercased (e.g. `my-note`).
|
||||
|
||||
Links behave as in Obsidian in a few more ways:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -30,6 +30,9 @@ Follow these in order:
|
||||
3. **[[installation#Setting Up Your GitHub Repository|Push to GitHub]]** — Create a repository and push your site with `npx quartz sync`
|
||||
4. **[[hosting|Deploy]]** — Host your site for free on GitHub Pages, Cloudflare, Netlify, or Vercel
|
||||
|
||||
> [!tip]
|
||||
> To publish notes from a GitHub repository without a copy of Quartz, skip these steps and use the [[github-action|Quartz GitHub Action]].
|
||||
|
||||
## Upgrading & Migrating
|
||||
|
||||
- **[[whats-new|What's New in Quartz 5]]** — Overview of new features and changes
|
||||
|
||||
@@ -6,6 +6,9 @@ aliases:
|
||||
|
||||
This page walks you through the full Quartz setup: from getting the source code to previewing your site locally, then pushing it to GitHub.
|
||||
|
||||
> [!tip] Only want to publish your notes?
|
||||
> To publish an Obsidian vault or a `docs/` folder on GitHub Pages without changing Quartz itself, you don't need your own copy of Quartz: the [[github-action|Quartz GitHub Action]] builds the site from a repository that holds only your notes. Follow this page to preview your site locally, customize Quartz's code, or host it elsewhere.
|
||||
|
||||
## 1. Get Quartz
|
||||
|
||||
There are two ways to get started. Pick whichever you prefer:
|
||||
@@ -39,7 +42,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
|
||||
|
||||
@@ -158,7 +158,7 @@ Here's the recommended pattern, based on the project's own GitHub Actions:
|
||||
|
||||
```yaml
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@@ -166,7 +166,7 @@ Here's the recommended pattern, based on the project's own GitHub Actions:
|
||||
${{ 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') }}
|
||||
@@ -190,7 +190,7 @@ For non-GitHub CI providers (Cloudflare, Vercel, Netlify), the build command sho
|
||||
npx quartz plugin install && npx quartz build
|
||||
```
|
||||
|
||||
See [[hosting]] for provider-specific setup details.
|
||||
See [[hosting]] for provider-specific setup details. If your repository only needs your notes and settings, the [[github-action|Quartz GitHub Action]] can build it instead, without a copy of Quartz.
|
||||
|
||||
## Setting Your Default Branch to v5
|
||||
|
||||
|
||||
@@ -28,6 +28,140 @@ npx quartz plugin install --latest
|
||||
|
||||
See the [[upgrade|CLI reference for upgrade]] for more details on available flags.
|
||||
|
||||
## Upgrading from 5.4.0 to 5.4.1
|
||||
|
||||
5.4.1 is a patch release. Upgrade as usual:
|
||||
|
||||
```bash
|
||||
npx quartz upgrade
|
||||
```
|
||||
|
||||
### Changes you may notice
|
||||
|
||||
- **Links resolve as in Obsidian in more cases** (with the default `markdownLinkResolution: shortest`; see [[CrawlLinks]]). A link can now reach a different page than before:
|
||||
- `[[./index|index]]` in a subfolder links to that folder's index page. It went to the home page.
|
||||
- When several notes share a name, a link reaches the one under the linking note's folder, else the one with the shortest path. Before, a link such as `[Status](current.md)` in a vault where several folders have a `current.md` could point to a page that doesn't exist.
|
||||
- A `../` link that names no note there resolves from the folder it leads to, and a link starting with `/` is a path from the content folder's root.
|
||||
- **Popovers with an Obsidian theme** ([[ThemesCore]]) show next to their link. On a scrolled page they appeared too high, often off screen, so links to headings and an embed's "link to original" seemed to show no popover.
|
||||
- **`npx quartz plugin install`** no longer changes `quartz.lock.json` when it reinstalls a pinned npm plugin (after a fresh clone or in CI).
|
||||
|
||||
## Upgrading from 5.3 to 5.4
|
||||
|
||||
```bash
|
||||
npx quartz upgrade
|
||||
npx quartz plugin install --latest
|
||||
```
|
||||
|
||||
### Changes you may notice
|
||||
|
||||
- **npm plugins are pinned in `quartz.lock.json`**: `npx quartz plugin add @scope/plugin` and `plugin install --from-config` no longer add npm plugins to Quartz's `package.json`. They are pinned in `quartz.lock.json` and installed into `.quartz/plugins/`, like Git plugins, so `npx quartz upgrade` can't conflict with them in `package.json` and `npm ci` can't remove them. See [[cli/plugin]].
|
||||
|
||||
npm plugins that are already in your `package.json` (added by `plugin add` before 5.4, or the Excalidraw plugin of the `obsidian` and `ttrpg` templates) keep working from there: when a plugin is in both, `package.json` wins. To move one to the lockfile, uninstall it and let Quartz pin it, then commit `package.json`, `package-lock.json` and `quartz.lock.json`:
|
||||
|
||||
```bash
|
||||
npm uninstall @quartz-community/obsidian-plugin-excalidraw
|
||||
npx quartz plugin install --from-config
|
||||
```
|
||||
|
||||
- **`extends` is stable** for `default` and local paths: its merge rules won't change in a minor release. `https://` URLs stay experimental. See [[configuration#Extending the default configuration]].
|
||||
- **Keys starting with `$` are reserved** in every file of an `extends` chain (the top-level `$schema` aside), for future merge operators. A config that uses one stops with an error naming the key; rename it. Configs without `extends` are not affected.
|
||||
- **`quartz.lock.json` sits next to the config file**. With `quartz.config.yaml` in Quartz's folder nothing changes. With `--config` pointing elsewhere, the lockfile is read and written in that folder. An existing `quartz.lock.json` in Quartz's folder is still used until that folder has one of its own. Plugin commands now take `--config` / `-C` too, and with `QUARTZ_CONFIG_PATH` they edit that file instead of `./quartz.config.yaml`. See [[cli/build#Custom config file]].
|
||||
|
||||
### New
|
||||
|
||||
- The [[github-action|Quartz GitHub Action]] builds a site from a repository that holds only your notes.
|
||||
|
||||
See [[whats-new#New in 5.4|What's new in 5.4]].
|
||||
|
||||
## Upgrading from 5.3.0 to 5.3.1
|
||||
|
||||
5.3.1 is a patch release: fixes from a test audit of Quartz and its plugins, many checked against Obsidian. Upgrade as usual:
|
||||
|
||||
```bash
|
||||
npx quartz upgrade
|
||||
npx quartz plugin install --latest
|
||||
```
|
||||
|
||||
### Changes you may notice
|
||||
|
||||
Most of these make a page look the way Obsidian shows it, so an existing site can look different after the upgrade.
|
||||
|
||||
- **[[Bases]] sorting**: text sorts naturally ("Chapter 2" before "Chapter 10") and ignores case, also for the default order by file name. Empty values come last in both directions, including descending sorts. A column that mixes types sorts numbers, dates and durations by value and everything else as text. Group order follows the same rules.
|
||||
- **[[Bases]] filters and formulas**, as in Obsidian:
|
||||
- `not:` leaves out a note that matches _any_ of its conditions (it left out only notes matching all of them).
|
||||
- `status == null` matches notes without `status`, and `status != null` no longer keeps them.
|
||||
- `"5" == 5` and `1 == true` are true, two strings compare as text (`"10" > "9"` is false), and an empty list counts as false.
|
||||
- A formula can use a formula defined after it. `x / 0` shows ∞. `sum()`, `mean()`, `min()` and `max()` skip text and booleans, and are empty without numbers. `number("abc")` is an error.
|
||||
- **[[Bases]] group headings** show their value as a cell does: dates in the local format (not an ISO timestamp, sometimes of the previous day), durations as "4 days", links as the note's name, booleans as a checkbox.
|
||||
- **[[CanvasPage|Canvas]] edges** leave and enter each card through the side they name, with Obsidian's curve, and the arrow points into that side. An edge without sides joins the sides that face each other (it joined the cards' centres).
|
||||
- **Folder pages**: a folder whose own `index.md` is unlisted shows that note, with the folder listing below it. A generated folder page used to replace it.
|
||||
- **Tag links under a base path**: inline `#tag` links from notes two or more folders deep stay on the site. On a site served under a sub-path, such as a GitHub Pages project site, they went to `/tags/…` and returned 404.
|
||||
- **Locales without a translation** (such as `sv-SE`) no longer crash the build: Quartz uses a translation of the same language, else English, and prints a warning. Dates still use your locale.
|
||||
- **`npx quartz plugin install --latest`** no longer fails because a _disabled_ plugin can't be updated (for example an old `quartz-themes` entry). It prints a warning with the command to remove the entry.
|
||||
|
||||
## 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 in 5.3, stable since 5.4) 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,9 +7,49 @@ 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.4
|
||||
|
||||
Upgrading from 5.3? See [[getting-started/upgrading#Upgrading from 5.3 to 5.4|Upgrading from 5.3 to 5.4]].
|
||||
|
||||
- **[[github-action|GitHub Action]]** — `quartz-community/action` builds and deploys a site from a repository that holds only your notes: no copy of Quartz, and an optional `quartz.config.yaml` and `quartz.lock.json`. The configuration can also be set in the workflow.
|
||||
- **Stable `extends`** — `extends: default` and local paths are stable: keep only your changes to the default configuration, and Quartz's updated defaults reach your site. See [[configuration#Extending the default configuration]].
|
||||
- **npm plugins in the lockfile** — npm plugins you add are pinned in `quartz.lock.json` (version and integrity) like Git plugins, instead of being written into Quartz's `package.json`, so upgrades don't conflict with them. See [[cli/plugin]].
|
||||
- **Config and lockfile together** — `quartz.lock.json` is read and written next to the config, and every `npx quartz plugin` command takes `--config` / `-C`, so a site's repository can hold its content, config and lockfile while Quartz is checked out elsewhere. See [[cli/build#Custom config file]].
|
||||
- **5.4.1** — links resolve as in Obsidian in more cases (`./` links, several notes with the same name), and popovers are placed correctly with Obsidian themes. See [[getting-started/upgrading#Upgrading from 5.4.0 to 5.4.1|Upgrading from 5.4.0 to 5.4.1]].
|
||||
|
||||
## New in 5.3
|
||||
|
||||
Upgrading from 5.2? See [[getting-started/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; stable since 5.4) — `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 [[getting-started/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.
|
||||
Upgrading from 5.0? See [[getting-started/upgrading#Upgrading from 5.0 to 5.1|Upgrading from 5.0 to 5.1]] for the steps and the changes you may notice.
|
||||
|
||||
- **[[prefetching|Prefetching]]** — pages are fetched before their links are followed, so they open at once (`configuration.prefetch`, default `viewport`). Works with and without SPA routing.
|
||||
- **[[built-in processing|Built-in processing]]** — frontmatter, link resolution, drafts and the content index are built into Quartz (`configuration.frontmatter`, `links`, `drafts`, `contentIndex`) instead of plugins that broke the site when disabled.
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
title: GitHub Action
|
||||
aliases:
|
||||
- action
|
||||
- quartz-community/action
|
||||
---
|
||||
|
||||
The [Quartz GitHub Action](https://github.com/quartz-community/action) builds a Quartz site from a repository that holds only your notes. You don't clone or fork Quartz: on every push, the action checks out a Quartz release, installs your plugins, builds the site and hands it to GitHub Pages.
|
||||
|
||||
> [!tip] Which setup do I need?
|
||||
>
|
||||
> - **Just notes** (an Obsidian vault, a `docs/` folder in a project, a notes repository): use the action. Your repository stays small, and new Quartz releases reach your site without `npx quartz upgrade`.
|
||||
> - **Changes to Quartz itself** (your own components, layouts or edits to Quartz's code): keep your own copy of Quartz, set up as in [[installation]], and deploy it as in [[hosting]].
|
||||
>
|
||||
> Both build the same site from the same `quartz.config.yaml`. The action needs Quartz 5.4.0 or later.
|
||||
|
||||
## Set it up
|
||||
|
||||
Your repository needs only your notes:
|
||||
|
||||
```
|
||||
content/ your notes (or docs/)
|
||||
quartz.config.yaml your configuration (optional)
|
||||
quartz.lock.json your pinned plugins (optional)
|
||||
```
|
||||
|
||||
1. Create `.github/workflows/deploy.yml`:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
name: Deploy Quartz site to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0 # the full history, for created and modified dates
|
||||
- uses: quartz-community/action@v1
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v5
|
||||
```
|
||||
|
||||
Change `main` if your notes live on another branch.
|
||||
|
||||
2. In your repository's **Settings**, under **Pages**, set **Source** to **GitHub Actions**.
|
||||
3. Push. The site is published at `<github-username>.github.io/<repository-name>`.
|
||||
|
||||
With only `content/`, the site uses Quartz's [[configuration#Extending the default configuration|default configuration]], titled with your repository's name, at its GitHub Pages address.
|
||||
|
||||
### Where your notes are
|
||||
|
||||
The action reads your notes from `content/`, or from `docs/` when there is no `content/`. For notes elsewhere, set `directory`, such as `.` for an Obsidian vault at the repository root:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
directory: .
|
||||
```
|
||||
|
||||
By default Quartz skips the `.obsidian`, `private` and `templates` folders, and files your `.gitignore` ignores. See [[private pages]] for keeping other notes off the site.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set your configuration in the workflow, in a `quartz.config.yaml` file, or both. Both take the same YAML as described in [[configuration]].
|
||||
|
||||
### In `quartz.config.yaml`
|
||||
|
||||
Start from Quartz's defaults with `extends: default` and write down only what you change:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
extends: default
|
||||
configuration:
|
||||
pageTitle: My notes
|
||||
baseUrl: me.github.io/notes
|
||||
plugins:
|
||||
- source: "@quartz-community/graph"
|
||||
enabled: false # turn off a default plugin
|
||||
- source: github:me/my-plugin # add one
|
||||
enabled: true
|
||||
```
|
||||
|
||||
A full config without `extends` works too, but then changes to Quartz's defaults in later releases don't reach your site. Put the file elsewhere with the `config` input (for example `config: docs/quartz.config.yaml`).
|
||||
|
||||
### In the workflow
|
||||
|
||||
`configuration` takes the same YAML, applied on top of your `quartz.config.yaml`, or on top of Quartz's defaults when there is none:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
configuration: |
|
||||
configuration:
|
||||
pageTitle: My notes
|
||||
plugins:
|
||||
- source: "@quartz-community/graph"
|
||||
enabled: false
|
||||
```
|
||||
|
||||
This way a repository needs no Quartz files at all. With a config file, it's handy to change one setting for one workflow, such as the `baseUrl` of a preview build.
|
||||
|
||||
### The site's address
|
||||
|
||||
Without a config file, `baseUrl` is your repository's GitHub Pages address (`owner.github.io/repository`). For a custom domain, set `base-url` (or `baseUrl` in your configuration), and add the domain in your repository's Pages settings as described in [[hosting#Custom Domain|Custom Domain]]:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
base-url: notes.example.com
|
||||
```
|
||||
|
||||
## Plugins and `quartz.lock.json`
|
||||
|
||||
The default plugins ship with Quartz. Other plugins, from GitHub or npm, are installed on every build. `quartz.lock.json` is optional: it pins each of them to an exact commit or version, so every build uses the same plugins. Without it, the action installs each one at its latest release.
|
||||
|
||||
To create or update the lockfile, run the [[cli/plugin|plugin commands]] with `--config` pointing at your site, from any Quartz 5.4.0 or later checkout:
|
||||
|
||||
```shell
|
||||
npx quartz plugin install --config ../my-notes/quartz.config.yaml # pin what the config lists
|
||||
npx quartz plugin install --config ../my-notes/quartz.config.yaml --latest # update the pins
|
||||
```
|
||||
|
||||
The lockfile is written next to `quartz.config.yaml`. Commit it.
|
||||
|
||||
## Favicon, images and custom styles
|
||||
|
||||
The action copies these from your repository over Quartz's own before building, if they exist:
|
||||
|
||||
- `quartz/static/`: the favicon (`icon.png`), the default social image (`og-image.png`) and other files served from `static/`
|
||||
- `quartz/styles/custom.scss`: your custom styles, such as overrides for an [[configuration#General Configuration|Obsidian theme's colours]]
|
||||
|
||||
## Choosing a Quartz version
|
||||
|
||||
The action builds with the newest Quartz 5 release by default, so fixes and new features reach your site on its next build. For a site that doesn't change when Quartz releases a new version, pin one:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
quartz-version: 5.4.1
|
||||
```
|
||||
|
||||
`quartz-version` also takes a tag, branch or commit of [jackyzha0/quartz](https://github.com/jackyzha0/quartz). Read [[upgrading]] before raising a pinned version.
|
||||
|
||||
## Inputs
|
||||
|
||||
| Input | Default | Description |
|
||||
| ----------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `quartz-version` | `latest` | Quartz release to build with: `latest` (the newest 5.x release), a version, or a tag, branch or commit |
|
||||
| `directory` | `content`, else `docs` | Content folder, relative to the repository root (`.` for the root itself) |
|
||||
| `config` | `quartz.config.yaml` | Config file, relative to the repository root (optional). `quartz.lock.json` is read from the same folder |
|
||||
| `configuration` | | Configuration as YAML: on top of the config file, or instead of one (then it extends `default` unless it says so) |
|
||||
| `base-url` | | The site's address, such as `notes.example.com`. Without a config file, the repository's GitHub Pages address |
|
||||
| `output` | outside the repository | Folder the site is built into, relative to the repository root. Keep it outside the content folder |
|
||||
| `node-version` | `24` | Node.js version (Quartz needs 22.22 or later) |
|
||||
| `cache` | `true` | Cache npm downloads and installed plugins between runs |
|
||||
| `upload-pages-artifact` | `true` | Upload the site as a GitHub Pages artifact for `actions/deploy-pages`. Set to `false` to deploy it some other way |
|
||||
|
||||
The action's outputs are `quartz-version` (the version the site was built with) and `output` (the absolute path of the built site). With `upload-pages-artifact: false`, deploy the folder from `output` to any host in a later step.
|
||||
|
||||
## Moving from your own copy of Quartz
|
||||
|
||||
If your site is a copy of Quartz (from the template or a fork), you can move it to the action:
|
||||
|
||||
1. Keep `content/`, `quartz.config.yaml`, `quartz.lock.json`, and any changes to `quartz/static/` and `quartz/styles/custom.scss`. Changes to other Quartz files aren't used by the action.
|
||||
2. Optionally, shrink `quartz.config.yaml` to `extends: default` and your changes (see [[configuration#Extending the default configuration]]). `npx quartz plugin list` and `npx quartz build --verbose` in your copy show what the site uses.
|
||||
3. Replace your deploy workflow with the one above.
|
||||
|
||||
Your notes and settings can stay in the same repository, or move to a new one that holds only them.
|
||||
+14
-8
@@ -6,6 +6,9 @@ Quartz effectively turns your Markdown files and other resources into a bundle o
|
||||
|
||||
However, if you'd like to publish your site to the world, you need a way to host it online. This guide will detail how to deploy with common hosting providers but any service that allows you to deploy static HTML should work as well.
|
||||
|
||||
> [!tip] Only publishing notes?
|
||||
> If your repository holds just your notes (an Obsidian vault, a project's `docs/` folder) and not a copy of Quartz, the [[github-action|Quartz GitHub Action]] builds and deploys it to GitHub Pages without cloning Quartz. The rest of this page is for sites that are a copy of Quartz.
|
||||
|
||||
> [!warning]
|
||||
> The rest of this guide assumes that you've already created your own GitHub repository for Quartz. If you haven't already, follow the [[installation#Setting Up Your GitHub Repository|GitHub repository setup]] section of the installation guide.
|
||||
|
||||
@@ -43,6 +46,9 @@ To add a custom domain, check out [Cloudflare's documentation](https://developer
|
||||
|
||||
## GitHub Pages
|
||||
|
||||
> [!tip]
|
||||
> A repository with only your notes doesn't need the workflow below: use the [[github-action|Quartz GitHub Action]].
|
||||
|
||||
In your local Quartz, create a new file `.github/workflows/deploy.yml` at the root of the repository.
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
@@ -66,21 +72,21 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git info
|
||||
- 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') }}
|
||||
restore-keys: |
|
||||
${{ 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') }}
|
||||
@@ -93,7 +99,7 @@ jobs:
|
||||
- name: Build Quartz
|
||||
run: npx quartz build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: public
|
||||
|
||||
@@ -106,7 +112,7 @@ jobs:
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
uses: actions/deploy-pages@v5
|
||||
```
|
||||
|
||||
Then:
|
||||
@@ -252,7 +258,7 @@ pages:
|
||||
- public
|
||||
```
|
||||
|
||||
When `.gitlab-ci.yaml` is committed, GitLab will build and deploy the website as a GitLab Page. You can find the url under `Deploy > Pages` in the sidebar.
|
||||
When `.gitlab-ci.yml` is committed, GitLab will build and deploy the website as a GitLab Page. You can find the url under `Deploy > Pages` in the sidebar.
|
||||
|
||||
By default, the page is private and only visible when logged in to a GitLab account with access to the repository but can be opened in the settings under `Deploy` -> `Pages`.
|
||||
|
||||
@@ -302,7 +308,7 @@ Don't forget to activate brotli / gzip compression.
|
||||
|
||||
### Using Caddy
|
||||
|
||||
Here's and example of how to do this with Caddy:
|
||||
Here's an example of how to do this with Caddy:
|
||||
|
||||
```caddy title="Caddyfile"
|
||||
example.com {
|
||||
|
||||
+4
-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.
|
||||
@@ -33,6 +33,9 @@ Your site is now running at `http://localhost:8080`. From here:
|
||||
- **[[installation|Push to GitHub]]** with `npx quartz sync`
|
||||
- **[[hosting|Deploy]]** to GitHub Pages, Cloudflare, Netlify, or Vercel
|
||||
|
||||
> [!tip] Notes on GitHub
|
||||
> If your notes are already in a GitHub repository, the [[github-action|Quartz GitHub Action]] publishes them to GitHub Pages without cloning Quartz.
|
||||
|
||||
For the full walkthrough, see the [[getting-started/index|Getting Started]] guide.
|
||||
|
||||
### Returning User?
|
||||
|
||||
@@ -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]].
|
||||
|
||||
@@ -24,15 +24,18 @@ configuration:
|
||||
|
||||
Options:
|
||||
|
||||
- `markdownLinkResolution`: Sets the strategy for resolving Markdown paths, can be `"absolute"`, `"relative"` or `"shortest"` (default; the `crawl-links` plugin defaulted to `"absolute"`). You should use the same setting here as in [[Obsidian compatibility|Obsidian]].
|
||||
- `absolute`: Path relative to the root of the content folder.
|
||||
- `relative`: Path relative to the file you are linking from.
|
||||
- `shortest`: Name of the file. If this isn't enough to identify the file, use the full absolute path.
|
||||
- `markdownLinkResolution`: how link targets (in wikilinks and Markdown links) are read: `"shortest"` (default; the `crawl-links` plugin defaulted to `"absolute"`), `"absolute"` or `"relative"`.
|
||||
- `shortest`: as Obsidian resolves links, whatever its "New link format" setting. A target (`note`, `folder/note`) matches every page whose path ends with it, case-insensitively. With one match, the link goes there. With several, it goes to the page whose path is exactly the target, else to a page in the linking note's folder or below it, else to any other; among those, the page with the shortest path wins (Quartz breaks a tie alphabetically; Obsidian by its own file order). A target starting with `./` or `../` is a path from the linking note's folder, and one starting with `/` a path from the root of the content folder.
|
||||
- `absolute`: a target is a path from the root of the content folder, as Obsidian writes links with "Absolute path in vault". A bare name only reaches a note at the root.
|
||||
- `relative`: a target is a path from the linking note's folder, as Obsidian writes links with "Relative path to file".
|
||||
|
||||
Obsidian's "New link format" setting only decides how Obsidian _writes_ new links; it reads every link the same way, as `shortest` does. Keep `shortest` unless all links in your notes are full paths (`absolute`) or relative paths (`relative`). Under every setting, a target starting with `./` or `../` is a path from the linking note's folder.
|
||||
|
||||
- `prettyLinks`: If `true` (default), simplifies links by removing folder paths, making them more user friendly (e.g. `folder/deeply/nested/note` becomes `note`).
|
||||
- `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.
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ enabled: true
|
||||
required: false
|
||||
---
|
||||
|
||||
This plugin determines the created, modified, and published dates for a document using three potential data sources: frontmatter metadata, Git history, and the filesystem. See [[authoring content#Syntax]] for more information.
|
||||
This plugin determines the created, modified, and published dates for a document using three potential data sources: frontmatter metadata, Git history, and the filesystem. See [[getting-started/authoring-content#Syntax|authoring content]] for more information.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
@@ -11,7 +11,7 @@ required: false
|
||||
|
||||
This plugin generates descriptions that are used as metadata for the HTML `head`, the [[RSS Feed]] and in [[folder and tag listings]] if there is no main body content, the description is used as the text between the title and the listing.
|
||||
|
||||
If the frontmatter contains a `description` property, it is used (see [[authoring content#Syntax]]). Otherwise, the plugin builds one from the first sentences of the content.
|
||||
If the frontmatter contains a `description` property, it is used (see [[getting-started/authoring-content#Syntax|authoring content]]). Otherwise, the plugin builds one from the first sentences of the content.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ enabled: true
|
||||
required: true
|
||||
---
|
||||
|
||||
Frontmatter parsing is [[built-in processing|built into Quartz]]: every page's frontmatter is parsed with [gray-matter](https://github.com/jonschlinkert/gray-matter) and normalised (see [[#Supported frontmatter]]). Displaying properties on the page is done by the optional `note-properties` plugin ([[#Properties panel]]). See [[authoring content#Syntax]], [[Obsidian compatibility]] and [[OxHugo compatibility]] for more information.
|
||||
Frontmatter parsing is [[built-in processing|built into Quartz]]: every page's frontmatter is parsed with [gray-matter](https://github.com/jonschlinkert/gray-matter) and normalised (see [[#Supported frontmatter]]). Displaying properties on the page is done by the optional `note-properties` plugin ([[#Properties panel]]). See [[getting-started/authoring-content#Syntax|authoring content]], [[Obsidian compatibility]] and [[OxHugo compatibility]] for more information.
|
||||
|
||||
## Parsing (built-in)
|
||||
|
||||
|
||||
@@ -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
+994
-1080
File diff suppressed because it is too large.
Load diff
+38
-39
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@jackyzha0/quartz",
|
||||
"description": "\ud83c\udf31 publish your digital garden and notes as a website",
|
||||
"description": "🌱 publish your digital garden and notes as a website",
|
||||
"private": true,
|
||||
"version": "5.1.0",
|
||||
"version": "5.4.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",
|
||||
@@ -42,60 +42,60 @@
|
||||
"@clack/prompts": "^1.8.0",
|
||||
"@floating-ui/dom": "^1.7.4",
|
||||
"@myriaddreamin/rehype-typst": "^0.7.0",
|
||||
"@napi-rs/simple-git": "1.1.0",
|
||||
"@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.7",
|
||||
"@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.5",
|
||||
"@quartz-community/footer": "^1.1.2",
|
||||
"@quartz-community/github-flavored-markdown": "^2.2.2",
|
||||
"@quartz-community/graph": "^1.0.10",
|
||||
"@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.2.0",
|
||||
"@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.5",
|
||||
"@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.5",
|
||||
"@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": "^2.0.1",
|
||||
"@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.5",
|
||||
"@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"
|
||||
@@ -99,7 +99,7 @@ plugins:
|
||||
- source: "@quartz-themes/core"
|
||||
enabled: false
|
||||
options:
|
||||
theme: tokyo-night
|
||||
theme: Tokyo Night
|
||||
mode: both
|
||||
- source: "@quartz-community/explicit-publish"
|
||||
enabled: false
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
#!/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)
|
||||
}
|
||||
import { existsSync } from "fs"
|
||||
import { resolve } from "path"
|
||||
import yargs from "yargs"
|
||||
import { hideBin } from "yargs/helpers"
|
||||
import {
|
||||
@@ -121,6 +123,24 @@ yargs(hideBin(process.argv))
|
||||
(yargs) => {
|
||||
return (
|
||||
yargs
|
||||
// like `build --config`: plugin commands read and write that config, and the
|
||||
// quartz.lock.json next to it (cli/lockfile-path.js)
|
||||
.option("config", {
|
||||
string: true,
|
||||
alias: ["C"],
|
||||
global: true,
|
||||
describe:
|
||||
"path to the config file (default: ./quartz.config.yaml); quartz.lock.json is next to it",
|
||||
})
|
||||
.middleware((argv) => {
|
||||
if (!argv.config) return
|
||||
const resolved = resolve(argv.config)
|
||||
if (!existsSync(resolved)) {
|
||||
console.error(`Config file not found: ${resolved}`)
|
||||
process.exit(1)
|
||||
}
|
||||
process.env.QUARTZ_CONFIG_PATH = resolved
|
||||
})
|
||||
.command(
|
||||
"install [names..]",
|
||||
"Install plugins from lockfile or config",
|
||||
@@ -335,6 +355,17 @@ yargs(hideBin(process.argv))
|
||||
},
|
||||
)
|
||||
.showHelpOnFail(true)
|
||||
.fail((msg, err, y) => {
|
||||
// A mistake in quartz.config.yaml (an `extends` error names the file and the key): the
|
||||
// message says what to fix, so print it without the usage text, which is about arguments.
|
||||
if (err?.name === "ConfigExtendsError") {
|
||||
console.error(`✗ ${err.message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
y.showHelp()
|
||||
console.error(err ?? msg)
|
||||
process.exit(1)
|
||||
})
|
||||
.help()
|
||||
.strict()
|
||||
.demandCommand().argv
|
||||
+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
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,11 @@ export const SyncArgv = {
|
||||
|
||||
export const BuildArgv = {
|
||||
...CommonArgv,
|
||||
config: {
|
||||
string: true,
|
||||
alias: ["C"],
|
||||
describe: "path to the config file (default: ./quartz.config.yaml)",
|
||||
},
|
||||
output: {
|
||||
string: true,
|
||||
alias: ["o"],
|
||||
|
||||
+24
-5
@@ -39,6 +39,7 @@ import {
|
||||
readPluginsJson,
|
||||
writePluginsJson,
|
||||
updateGlobalConfig,
|
||||
extendedConfigFiles,
|
||||
LOCKFILE_PATH,
|
||||
} from "./plugin-data.js"
|
||||
import {
|
||||
@@ -334,6 +335,17 @@ export async function handleBuild(argv) {
|
||||
argv.watch = true
|
||||
}
|
||||
|
||||
// Let `--config <path>` override the default ./quartz.config.yaml. Passed down
|
||||
// via env so it reaches the esbuild-bundled build code and worker threads.
|
||||
if (argv.config) {
|
||||
const resolved = path.resolve(argv.config)
|
||||
if (!fs.existsSync(resolved)) {
|
||||
console.error(`Config file not found: ${resolved}`)
|
||||
process.exit(1)
|
||||
}
|
||||
process.env.QUARTZ_CONFIG_PATH = resolved
|
||||
}
|
||||
|
||||
// " Quartz v5.1.0 " for a release checkout, plus `git describe` (e.g. v5.1.0-3-g1a2b3c4-dirty) otherwise
|
||||
const checkout = describeQuartzCheckout()
|
||||
const describe = checkout.describe && checkout.describe !== `v${version}` ? checkout.describe : ""
|
||||
@@ -607,11 +619,18 @@ export async function handleBuild(argv) {
|
||||
"quartz.config.yaml",
|
||||
"quartz.config.default.yaml",
|
||||
])
|
||||
chokidar
|
||||
.watch(paths, { ignoreInitial: true })
|
||||
.on("add", () => build(clientRefresh))
|
||||
.on("change", () => build(clientRefresh))
|
||||
.on("unlink", () => build(clientRefresh))
|
||||
const extraWatch = process.env.QUARTZ_CONFIG_PATH ? [process.env.QUARTZ_CONFIG_PATH] : []
|
||||
// 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
|
||||
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export const LOCKFILE_NAME: string
|
||||
export function resolveLockfilePath(configPath: string, cwd?: string): string
|
||||
export function currentLockfilePath(cwd?: string): string
|
||||
@@ -0,0 +1,29 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
|
||||
export const LOCKFILE_NAME = "quartz.lock.json"
|
||||
|
||||
/**
|
||||
* Where quartz.lock.json is: next to the config file Quartz uses (`--config` / `-C`, or
|
||||
* QUARTZ_CONFIG_PATH), so a repository that holds only a site's content, config and lockfile
|
||||
* (such as one the GitHub Action builds) keeps its pins with its config.
|
||||
*
|
||||
* With the config in Quartz's own folder (the usual setup) that is Quartz's folder, as before.
|
||||
* A config elsewhere whose folder has no lockfile yet keeps using an existing one in Quartz's
|
||||
* folder (`cwd`), so setups from before this change still find their pins.
|
||||
*/
|
||||
export function resolveLockfilePath(configPath, cwd = process.cwd()) {
|
||||
const besideConfig = path.join(path.dirname(path.resolve(configPath)), LOCKFILE_NAME)
|
||||
const inQuartz = path.join(cwd, LOCKFILE_NAME)
|
||||
if (besideConfig !== inQuartz && !fs.existsSync(besideConfig) && fs.existsSync(inQuartz)) {
|
||||
return inQuartz
|
||||
}
|
||||
return besideConfig
|
||||
}
|
||||
|
||||
/** The lockfile for the config this process uses: QUARTZ_CONFIG_PATH's, else Quartz's folder. */
|
||||
export function currentLockfilePath(cwd = process.cwd()) {
|
||||
return process.env.QUARTZ_CONFIG_PATH
|
||||
? resolveLockfilePath(process.env.QUARTZ_CONFIG_PATH, cwd)
|
||||
: path.join(cwd, LOCKFILE_NAME)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import test, { describe, afterEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { currentLockfilePath, resolveLockfilePath } from "./lockfile-path.js"
|
||||
|
||||
describe("resolveLockfilePath", () => {
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-lockfile-path-"))
|
||||
|
||||
test("the lockfile is next to the config", () => {
|
||||
const quartz = tmp()
|
||||
const site = tmp()
|
||||
assert.strictEqual(
|
||||
resolveLockfilePath(path.join(site, "quartz.config.yaml"), quartz),
|
||||
path.join(site, "quartz.lock.json"),
|
||||
)
|
||||
// the usual setup: the config in Quartz's folder
|
||||
assert.strictEqual(
|
||||
resolveLockfilePath(path.join(quartz, "quartz.config.yaml"), quartz),
|
||||
path.join(quartz, "quartz.lock.json"),
|
||||
)
|
||||
})
|
||||
|
||||
test("an existing lockfile in Quartz's folder is kept until the config's folder has one", () => {
|
||||
const quartz = tmp()
|
||||
const site = tmp()
|
||||
fs.writeFileSync(path.join(quartz, "quartz.lock.json"), "{}")
|
||||
const config = path.join(site, "quartz.config.yaml")
|
||||
assert.strictEqual(resolveLockfilePath(config, quartz), path.join(quartz, "quartz.lock.json"))
|
||||
fs.writeFileSync(path.join(site, "quartz.lock.json"), "{}")
|
||||
assert.strictEqual(resolveLockfilePath(config, quartz), path.join(site, "quartz.lock.json"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("currentLockfilePath", () => {
|
||||
const saved = process.env.QUARTZ_CONFIG_PATH
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.QUARTZ_CONFIG_PATH
|
||||
else process.env.QUARTZ_CONFIG_PATH = saved
|
||||
})
|
||||
|
||||
test("follows QUARTZ_CONFIG_PATH, else Quartz's folder", () => {
|
||||
const site = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-lockfile-current-"))
|
||||
delete process.env.QUARTZ_CONFIG_PATH
|
||||
assert.strictEqual(currentLockfilePath("/q"), path.join("/q", "quartz.lock.json"))
|
||||
process.env.QUARTZ_CONFIG_PATH = path.join(site, "quartz.config.yaml")
|
||||
assert.strictEqual(currentLockfilePath("/q"), path.join(site, "quartz.lock.json"))
|
||||
})
|
||||
})
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
/** A quartz.lock.json entry pinning an npm plugin (see npm-plugins.js). */
|
||||
export interface NpmLockEntry {
|
||||
source: unknown
|
||||
version: string
|
||||
integrity?: string
|
||||
resolved?: string
|
||||
installedAt?: string
|
||||
}
|
||||
/** What installing an npm plugin returns: the fields its lock entry pins. */
|
||||
export interface NpmInstallResult {
|
||||
version: string
|
||||
integrity?: string
|
||||
resolved?: string
|
||||
}
|
||||
export function npmPackageName(spec: string): string
|
||||
export function isNpmLockEntry(entry: unknown): entry is NpmLockEntry
|
||||
export function readNpmLockEntry(name: string, lockfilePath: string): NpmLockEntry | undefined
|
||||
export function isHostDependency(name: string, root?: string): boolean
|
||||
export function npmPluginDir(name: string, pluginsDir?: string): string
|
||||
export function installedNpmPluginVersion(name: string, pluginsDir: string): string | null
|
||||
export function isPinnedNpmPluginInstalled(name: string, pluginsDir: string, root?: string): boolean
|
||||
export function latestNpmVersion(name: string): string
|
||||
export function latestNpmVersionAsync(name: string): Promise<string>
|
||||
export function listPluginDirNames(pluginsDir: string): string[]
|
||||
export function installNpmPlugin(
|
||||
name: string,
|
||||
options: {
|
||||
version?: string
|
||||
integrity?: string
|
||||
pluginsDir: string
|
||||
verbose?: boolean
|
||||
/** Runs npm (tests pass a fake). */
|
||||
run?: (args: string[], options: { cwd: string; stdio?: string; timeout?: number }) => unknown
|
||||
},
|
||||
): NpmInstallResult
|
||||
export function removeNpmPlugin(name: string, pluginsDir: string): void
|
||||
export function nextNpmLockEntry(
|
||||
lockEntry: unknown,
|
||||
source: unknown,
|
||||
result: NpmInstallResult,
|
||||
): NpmLockEntry
|
||||
export function ensureNpmPlugin(
|
||||
name: string,
|
||||
options: {
|
||||
lockEntry?: NpmLockEntry
|
||||
fallbackVersion?: string
|
||||
pluginsDir: string
|
||||
verbose?: boolean
|
||||
},
|
||||
): NpmInstallResult | null
|
||||
@@ -0,0 +1,289 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { assertNpmSpec, npm, npmAsync } from "./subprocess.js"
|
||||
|
||||
/**
|
||||
* npm plugins that Quartz's package.json doesn't list are pinned in quartz.lock.json and
|
||||
* installed into .quartz/plugins/<@scope>/<name>, like Git plugins, instead of node_modules:
|
||||
*
|
||||
* - `npm install` / `npm ci` remove packages package.json doesn't list, so a plugin installed
|
||||
* into node_modules without saving would disappear; saving it to Quartz's package.json made
|
||||
* `npx quartz upgrade` conflict on the user's additions.
|
||||
* - A site whose repository holds only its content, config and lockfile (the GitHub Action)
|
||||
* pins its npm plugins in a file it owns.
|
||||
*
|
||||
* A plugin in package.json (Quartz's own default plugins, or one the user `npm install`ed) is
|
||||
* versioned there and loaded from node_modules, as before: package.json wins.
|
||||
*
|
||||
* Lock entry: `{ source, version, integrity, resolved, installedAt }` (no `commit`, which every
|
||||
* Git or local entry has).
|
||||
*/
|
||||
|
||||
const NPM_INSTALL_TIMEOUT_MS = 300_000
|
||||
const NPM_VIEW_TIMEOUT_MS = 60_000
|
||||
|
||||
/** `@scope/name` of an npm plugin source (a version suffix, `@scope/name@1.2`, is dropped). */
|
||||
export function npmPackageName(spec) {
|
||||
const at = spec.lastIndexOf("@")
|
||||
return at > 0 ? spec.slice(0, at) : spec
|
||||
}
|
||||
|
||||
/** Whether a lock entry pins an npm plugin. */
|
||||
export function isNpmLockEntry(entry) {
|
||||
return (
|
||||
!!entry &&
|
||||
typeof entry === "object" &&
|
||||
entry.commit === undefined &&
|
||||
typeof entry.version === "string"
|
||||
)
|
||||
}
|
||||
|
||||
/** The npm lock entry for `name` in the lockfile at `lockfilePath`, if there is one. */
|
||||
export function readNpmLockEntry(name, lockfilePath) {
|
||||
try {
|
||||
const entry = JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))?.plugins?.[name]
|
||||
return isNpmLockEntry(entry) ? entry : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether `name` is a dependency in package.json at `root` (Quartz's directory). */
|
||||
export function isHostDependency(name, root = process.cwd()) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8"))
|
||||
return [
|
||||
pkg.dependencies,
|
||||
pkg.devDependencies,
|
||||
pkg.optionalDependencies,
|
||||
pkg.peerDependencies,
|
||||
].some((deps) => deps && Object.hasOwn(deps, name))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a pinned npm plugin is installed: `<pluginsDir>/@scope/name`. */
|
||||
export function npmPluginDir(name, pluginsDir = path.join(process.cwd(), ".quartz", "plugins")) {
|
||||
return path.join(pluginsDir, ...name.split("/"))
|
||||
}
|
||||
|
||||
/** The version of the pinned npm plugin installed in `pluginsDir`, or null. */
|
||||
export function installedNpmPluginVersion(name, pluginsDir) {
|
||||
try {
|
||||
const pkg = JSON.parse(
|
||||
fs.readFileSync(path.join(npmPluginDir(name, pluginsDir), "package.json"), "utf-8"),
|
||||
)
|
||||
return pkg.name === name && typeof pkg.version === "string" ? pkg.version : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the npm plugin `name` is pinned in quartz.lock.json and loaded from
|
||||
* `<pluginsDir>/@scope/name` (rather than from node_modules): it is not in package.json, and it
|
||||
* is installed there.
|
||||
*/
|
||||
export function isPinnedNpmPluginInstalled(name, pluginsDir, root = process.cwd()) {
|
||||
return !isHostDependency(name, root) && installedNpmPluginVersion(name, pluginsDir) !== null
|
||||
}
|
||||
|
||||
/** The version npm's `latest` tag points at. */
|
||||
export function latestNpmVersion(name) {
|
||||
const out = npm(["view", assertNpmSpec(name), "version", "--json"], {
|
||||
timeout: NPM_VIEW_TIMEOUT_MS,
|
||||
})
|
||||
const version = JSON.parse(out)
|
||||
if (typeof version !== "string") throw new Error(`npm view ${name} returned no version`)
|
||||
return version
|
||||
}
|
||||
|
||||
/** The version npm's `latest` tag points at, without blocking (for status checks in parallel). */
|
||||
export async function latestNpmVersionAsync(name) {
|
||||
const { stdout } = await npmAsync(["view", assertNpmSpec(name), "version", "--json"], {
|
||||
timeout: NPM_VIEW_TIMEOUT_MS,
|
||||
})
|
||||
const version = JSON.parse(stdout)
|
||||
if (typeof version !== "string") throw new Error(`npm view ${name} returned no version`)
|
||||
return version
|
||||
}
|
||||
|
||||
/**
|
||||
* The directories `pluginsDir` holds plugins in: `name` for Git and local plugins,
|
||||
* `@scope/name` for pinned npm plugins.
|
||||
*/
|
||||
export function listPluginDirNames(pluginsDir) {
|
||||
if (!fs.existsSync(pluginsDir)) return []
|
||||
const isDir = (p) => {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const names = []
|
||||
for (const entry of fs.readdirSync(pluginsDir)) {
|
||||
const full = path.join(pluginsDir, entry)
|
||||
if (!isDir(full)) continue
|
||||
if (entry.startsWith("@")) {
|
||||
for (const child of fs.readdirSync(full)) {
|
||||
if (isDir(path.join(full, child))) names.push(`${entry}/${child}`)
|
||||
}
|
||||
} else if (!entry.startsWith(".")) {
|
||||
names.push(entry)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// Packages plugins share with Quartz (gitLoader's getSharedExternals): one copy at runtime.
|
||||
const SINGLETONS = ["preact", "@jackyzha0/quartz", "vfile", "unified"]
|
||||
const SHARED_SCOPES = ["@quartz-community/", "@quartz-themes/"]
|
||||
|
||||
/**
|
||||
* Whether a dependency of a pinned plugin should come from Quartz's node_modules rather than
|
||||
* the plugin's own: a shared package (singletons, @quartz-community/*, Quartz's dependencies)
|
||||
* that Quartz has installed. Git plugins with a pre-built dist/ install no dependencies at
|
||||
* all, and resolve these from Quartz the same way.
|
||||
*/
|
||||
function sharedWithHost(dep, hostRoot) {
|
||||
let quartzDeps = []
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(hostRoot, "package.json"), "utf-8"))
|
||||
quartzDeps = Object.keys(pkg.dependencies ?? {})
|
||||
} catch {}
|
||||
const shared =
|
||||
SINGLETONS.includes(dep) ||
|
||||
SHARED_SCOPES.some((scope) => dep.startsWith(scope)) ||
|
||||
quartzDeps.includes(dep)
|
||||
return shared && fs.existsSync(path.join(hostRoot, "node_modules", ...dep.split("/")))
|
||||
}
|
||||
|
||||
function moveInto(from, to) {
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true })
|
||||
fs.rmSync(to, { recursive: true, force: true })
|
||||
fs.renameSync(from, to)
|
||||
}
|
||||
|
||||
/**
|
||||
* Install `name` at `version` (exact, a range or a tag; default `latest`) into
|
||||
* `<pluginsDir>/@scope/name`, with its production dependencies in its own node_modules and
|
||||
* without its peer dependencies (they resolve to Quartz's copies). With `integrity`, the
|
||||
* package npm downloads must match it. Returns the lock entry fields.
|
||||
*/
|
||||
export function installNpmPlugin(
|
||||
name,
|
||||
{ version = "latest", integrity, pluginsDir, verbose = false, run = npm } = {},
|
||||
) {
|
||||
const spec = assertNpmSpec(`${name}@${version}`)
|
||||
const quartzDir = path.dirname(pluginsDir)
|
||||
fs.mkdirSync(quartzDir, { recursive: true })
|
||||
const tmp = fs.mkdtempSync(path.join(quartzDir, ".npm-install-"))
|
||||
try {
|
||||
fs.writeFileSync(
|
||||
path.join(tmp, "package.json"),
|
||||
JSON.stringify({ name: "quartz-npm-plugin-install", private: true }) + "\n",
|
||||
)
|
||||
run(
|
||||
[
|
||||
"install",
|
||||
spec,
|
||||
"--save-exact",
|
||||
"--omit=dev",
|
||||
"--ignore-scripts",
|
||||
"--legacy-peer-deps",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
],
|
||||
{ cwd: tmp, stdio: verbose ? "inherit" : "pipe", timeout: NPM_INSTALL_TIMEOUT_MS },
|
||||
)
|
||||
|
||||
const lock = JSON.parse(fs.readFileSync(path.join(tmp, "package-lock.json"), "utf-8"))
|
||||
const locked = lock.packages?.[`node_modules/${name}`]
|
||||
if (!locked?.version) throw new Error(`npm did not install ${name}`)
|
||||
if (integrity && locked.integrity && locked.integrity !== integrity) {
|
||||
throw new Error(
|
||||
`${name}@${locked.version} from the registry does not match the integrity in quartz.lock.json ` +
|
||||
`(${locked.integrity} instead of ${integrity})`,
|
||||
)
|
||||
}
|
||||
|
||||
const modules = path.join(tmp, "node_modules")
|
||||
const target = npmPluginDir(name, pluginsDir)
|
||||
moveInto(path.join(modules, ...name.split("/")), target)
|
||||
|
||||
// what's left in node_modules are the plugin's dependencies: they go into its own
|
||||
// node_modules, except the ones it shares with Quartz (see sharedWithHost)
|
||||
const hostRoot = path.dirname(quartzDir)
|
||||
const deps = path.join(target, "node_modules")
|
||||
const keep = (dep, from, to) => {
|
||||
if (!sharedWithHost(dep, hostRoot)) moveInto(from, to)
|
||||
}
|
||||
for (const entry of fs.readdirSync(modules)) {
|
||||
if (entry === ".bin" || entry.startsWith(".") || entry === "@types") continue
|
||||
const from = path.join(modules, entry)
|
||||
if (entry.startsWith("@")) {
|
||||
for (const child of fs.readdirSync(from)) {
|
||||
keep(`${entry}/${child}`, path.join(from, child), path.join(deps, entry, child))
|
||||
}
|
||||
} else {
|
||||
keep(entry, from, path.join(deps, entry))
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: locked.version,
|
||||
...(locked.integrity && { integrity: locked.integrity }),
|
||||
...(locked.resolved && { resolved: locked.resolved }),
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a pinned npm plugin's directory (and its `@scope` directory when that is empty). */
|
||||
export function removeNpmPlugin(name, pluginsDir) {
|
||||
const dir = npmPluginDir(name, pluginsDir)
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
const scope = path.dirname(dir)
|
||||
if (scope !== pluginsDir) {
|
||||
try {
|
||||
if (fs.readdirSync(scope).length === 0) fs.rmdirSync(scope)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock entry for an npm plugin just installed from `source`. Reinstalling the pinned version
|
||||
* (a fresh clone, `npm ci`, a CI runner) keeps `lockEntry` as it is, `installedAt` included, so
|
||||
* restoring plugins leaves quartz.lock.json unchanged, as it does for Git plugins.
|
||||
*/
|
||||
export function nextNpmLockEntry(lockEntry, source, result) {
|
||||
if (
|
||||
isNpmLockEntry(lockEntry) &&
|
||||
lockEntry.source === source &&
|
||||
lockEntry.version === result.version &&
|
||||
(!lockEntry.integrity || !result.integrity || lockEntry.integrity === result.integrity)
|
||||
) {
|
||||
return lockEntry
|
||||
}
|
||||
return { source, ...result, installedAt: new Date().toISOString() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure the pinned npm plugin `name` is installed as `lockEntry` pins it (installed at the
|
||||
* locked version, else at `fallbackVersion`). Returns the lock entry fields when it installed
|
||||
* something, null when the right version was already there.
|
||||
*/
|
||||
export function ensureNpmPlugin(name, { lockEntry, fallbackVersion, pluginsDir, verbose } = {}) {
|
||||
const wanted = lockEntry?.version ?? fallbackVersion
|
||||
const installed = installedNpmPluginVersion(name, pluginsDir)
|
||||
if (installed && (!wanted || wanted === "latest" || installed === wanted)) return null
|
||||
return installNpmPlugin(name, {
|
||||
version: wanted ?? "latest",
|
||||
integrity: lockEntry?.version === wanted ? lockEntry?.integrity : undefined,
|
||||
pluginsDir,
|
||||
verbose,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import test, { describe, beforeEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import {
|
||||
ensureNpmPlugin,
|
||||
installedNpmPluginVersion,
|
||||
installNpmPlugin,
|
||||
isHostDependency,
|
||||
isNpmLockEntry,
|
||||
isPinnedNpmPluginInstalled,
|
||||
listPluginDirNames,
|
||||
nextNpmLockEntry,
|
||||
npmPackageName,
|
||||
npmPluginDir,
|
||||
readNpmLockEntry,
|
||||
removeNpmPlugin,
|
||||
} from "./npm-plugins.js"
|
||||
|
||||
const write = (file, content) => {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||||
fs.writeFileSync(file, typeof content === "string" ? content : JSON.stringify(content))
|
||||
}
|
||||
|
||||
let root
|
||||
let pluginsDir
|
||||
beforeEach(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-npm-plugins-"))
|
||||
pluginsDir = path.join(root, ".quartz", "plugins")
|
||||
write(path.join(root, "package.json"), {
|
||||
name: "@jackyzha0/quartz",
|
||||
dependencies: { "@quartz-community/explorer": "^1", unified: "^11", "shared-dep": "^1" },
|
||||
devDependencies: { "@quartz-community/dev-only": "^1" },
|
||||
})
|
||||
// what Quartz has installed
|
||||
for (const dep of ["unified", "shared-dep", "@quartz-community/utils"]) {
|
||||
write(path.join(root, "node_modules", ...dep.split("/"), "package.json"), { name: dep })
|
||||
}
|
||||
})
|
||||
|
||||
describe("names and lock entries", () => {
|
||||
test("npmPackageName drops a version", () => {
|
||||
assert.strictEqual(npmPackageName("@me/plugin"), "@me/plugin")
|
||||
assert.strictEqual(npmPackageName("@me/plugin@1.2.3"), "@me/plugin")
|
||||
assert.strictEqual(npmPackageName("@me/plugin@^1"), "@me/plugin")
|
||||
})
|
||||
|
||||
test("an npm lock entry has a version and no commit", () => {
|
||||
assert.ok(isNpmLockEntry({ source: "@me/p", version: "1.0.0" }))
|
||||
assert.ok(!isNpmLockEntry({ source: "github:me/p", commit: "abc", version: "1.0.0" }))
|
||||
assert.ok(!isNpmLockEntry({ source: "./p", commit: "local" }))
|
||||
assert.ok(!isNpmLockEntry(undefined))
|
||||
})
|
||||
|
||||
test("readNpmLockEntry returns npm entries only", () => {
|
||||
const lockfile = path.join(root, "quartz.lock.json")
|
||||
write(lockfile, {
|
||||
version: "1.0.0",
|
||||
plugins: {
|
||||
"@me/p": { source: "@me/p", version: "2.0.0" },
|
||||
graph: { source: "github:me/graph", commit: "abc" },
|
||||
},
|
||||
})
|
||||
assert.strictEqual(readNpmLockEntry("@me/p", lockfile)?.version, "2.0.0")
|
||||
assert.strictEqual(readNpmLockEntry("graph", lockfile), undefined)
|
||||
assert.strictEqual(readNpmLockEntry("@me/p", path.join(root, "missing.json")), undefined)
|
||||
})
|
||||
|
||||
test("isHostDependency reads Quartz's package.json", () => {
|
||||
assert.ok(isHostDependency("@quartz-community/explorer", root))
|
||||
assert.ok(isHostDependency("@quartz-community/dev-only", root))
|
||||
assert.ok(!isHostDependency("@me/plugin", root))
|
||||
assert.ok(!isHostDependency("@me/plugin", path.join(root, "nowhere")))
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin directories", () => {
|
||||
test("pinned npm plugins live in @scope/name; listings include them", () => {
|
||||
write(path.join(pluginsDir, "graph", "package.json"), { name: "graph" })
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@me/plugin",
|
||||
version: "1.4.2",
|
||||
})
|
||||
fs.mkdirSync(path.join(pluginsDir, ".npm-install-x"), { recursive: true })
|
||||
write(path.join(pluginsDir, "index.ts"), "")
|
||||
assert.deepStrictEqual(listPluginDirNames(pluginsDir).sort(), ["@me/plugin", "graph"])
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), "1.4.2")
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/other", pluginsDir), null)
|
||||
})
|
||||
|
||||
test("a package with another name in the directory is not the plugin", () => {
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@someone/else",
|
||||
version: "1.0.0",
|
||||
})
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), null)
|
||||
})
|
||||
|
||||
test("package.json wins over a pinned copy", () => {
|
||||
write(path.join(npmPluginDir("@quartz-community/explorer", pluginsDir), "package.json"), {
|
||||
name: "@quartz-community/explorer",
|
||||
version: "1.0.0",
|
||||
})
|
||||
assert.ok(!isPinnedNpmPluginInstalled("@quartz-community/explorer", pluginsDir, root))
|
||||
})
|
||||
|
||||
test("removeNpmPlugin removes the scope directory once it is empty", () => {
|
||||
for (const name of ["@me/a", "@me/b"]) {
|
||||
write(path.join(npmPluginDir(name, pluginsDir), "package.json"), { name, version: "1.0.0" })
|
||||
}
|
||||
removeNpmPlugin("@me/a", pluginsDir)
|
||||
assert.ok(fs.existsSync(path.join(pluginsDir, "@me")))
|
||||
removeNpmPlugin("@me/b", pluginsDir)
|
||||
assert.ok(!fs.existsSync(path.join(pluginsDir, "@me")))
|
||||
removeNpmPlugin("@me/never-installed", pluginsDir)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* A stand-in for `npm install <spec>` in the temporary project: writes node_modules and
|
||||
* package-lock.json as npm would for @me/plugin with two dependencies, one of which Quartz has.
|
||||
*/
|
||||
function fakeNpm({ version = "1.4.2", integrity = "sha512-good" } = {}) {
|
||||
const calls = []
|
||||
const run = (args, { cwd }) => {
|
||||
calls.push({ args, cwd })
|
||||
const modules = path.join(cwd, "node_modules")
|
||||
write(path.join(modules, "@me", "plugin", "package.json"), { name: "@me/plugin", version })
|
||||
write(path.join(modules, "@me", "plugin", "dist", "index.js"), "export {}")
|
||||
write(path.join(modules, "own-dep", "package.json"), { name: "own-dep" })
|
||||
write(path.join(modules, "shared-dep", "package.json"), { name: "shared-dep" })
|
||||
write(path.join(modules, "@quartz-community", "utils", "package.json"), {
|
||||
name: "@quartz-community/utils",
|
||||
})
|
||||
write(path.join(modules, "@types", "node", "package.json"), { name: "@types/node" })
|
||||
write(path.join(modules, ".bin", "tool"), "")
|
||||
write(path.join(cwd, "package-lock.json"), {
|
||||
packages: {
|
||||
"node_modules/@me/plugin": {
|
||||
version,
|
||||
integrity,
|
||||
resolved: `https://registry.npmjs.org/@me/plugin/-/plugin-${version}.tgz`,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return { run, calls }
|
||||
}
|
||||
|
||||
describe("installNpmPlugin", () => {
|
||||
test("installs into .quartz/plugins/@scope/name with its own dependencies", () => {
|
||||
const npm = fakeNpm()
|
||||
const result = installNpmPlugin("@me/plugin", { version: "1.4.2", pluginsDir, run: npm.run })
|
||||
assert.deepStrictEqual(result, {
|
||||
version: "1.4.2",
|
||||
integrity: "sha512-good",
|
||||
resolved: "https://registry.npmjs.org/@me/plugin/-/plugin-1.4.2.tgz",
|
||||
})
|
||||
const dir = npmPluginDir("@me/plugin", pluginsDir)
|
||||
assert.ok(fs.existsSync(path.join(dir, "dist", "index.js")))
|
||||
assert.ok(fs.existsSync(path.join(dir, "node_modules", "own-dep", "package.json")))
|
||||
// shared with Quartz: resolved from Quartz's node_modules, not a second copy
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "shared-dep")))
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "@quartz-community", "utils")))
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "@types")))
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", ".bin")))
|
||||
// the temporary project is gone, and nothing touched Quartz's package.json
|
||||
assert.deepStrictEqual(
|
||||
fs.readdirSync(path.join(root, ".quartz")).filter((n) => n.startsWith(".npm-install-")),
|
||||
[],
|
||||
)
|
||||
assert.ok(
|
||||
!JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8")).dependencies[
|
||||
"@me/plugin"
|
||||
],
|
||||
)
|
||||
|
||||
const [{ args }] = npm.calls
|
||||
assert.strictEqual(args[0], "install")
|
||||
assert.strictEqual(args[1], "@me/plugin@1.4.2")
|
||||
for (const flag of ["--omit=dev", "--ignore-scripts", "--legacy-peer-deps", "--save-exact"]) {
|
||||
assert.ok(args.includes(flag), flag)
|
||||
}
|
||||
})
|
||||
|
||||
test("a package that doesn't match the pinned integrity is refused and not installed", () => {
|
||||
const npm = fakeNpm({ integrity: "sha512-other" })
|
||||
assert.throws(
|
||||
() =>
|
||||
installNpmPlugin("@me/plugin", {
|
||||
version: "1.4.2",
|
||||
integrity: "sha512-good",
|
||||
pluginsDir,
|
||||
run: npm.run,
|
||||
}),
|
||||
/does not match the integrity in quartz\.lock\.json/,
|
||||
)
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), null)
|
||||
})
|
||||
|
||||
test("reinstalling replaces the previous version", () => {
|
||||
installNpmPlugin("@me/plugin", { version: "1.4.2", pluginsDir, run: fakeNpm().run })
|
||||
installNpmPlugin("@me/plugin", {
|
||||
version: "2.0.0",
|
||||
pluginsDir,
|
||||
run: fakeNpm({ version: "2.0.0" }).run,
|
||||
})
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), "2.0.0")
|
||||
})
|
||||
|
||||
test("an invalid name or version never reaches npm", () => {
|
||||
const npm = fakeNpm()
|
||||
assert.throws(() =>
|
||||
installNpmPlugin("@me/plugin", { version: "1$(id)", pluginsDir, run: npm.run }),
|
||||
)
|
||||
assert.throws(() => installNpmPlugin("--global", { pluginsDir, run: npm.run }))
|
||||
assert.strictEqual(npm.calls.length, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("ensureNpmPlugin", () => {
|
||||
test("does nothing when the pinned version is installed", () => {
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@me/plugin",
|
||||
version: "1.4.2",
|
||||
})
|
||||
assert.strictEqual(
|
||||
ensureNpmPlugin("@me/plugin", {
|
||||
lockEntry: { source: "@me/plugin", version: "1.4.2" },
|
||||
pluginsDir,
|
||||
}),
|
||||
null,
|
||||
)
|
||||
})
|
||||
|
||||
test("an installed plugin without a pin is left as it is", () => {
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@me/plugin",
|
||||
version: "1.0.0",
|
||||
})
|
||||
assert.strictEqual(ensureNpmPlugin("@me/plugin", { pluginsDir }), null)
|
||||
})
|
||||
})
|
||||
|
||||
describe("nextNpmLockEntry", () => {
|
||||
const pinned = {
|
||||
source: "@me/plugin",
|
||||
version: "1.4.2",
|
||||
integrity: "sha512-good",
|
||||
resolved: "https://registry.npmjs.org/@me/plugin/-/plugin-1.4.2.tgz",
|
||||
installedAt: "2026-01-01T00:00:00.000Z",
|
||||
}
|
||||
const result = { version: "1.4.2", integrity: "sha512-good", resolved: pinned.resolved }
|
||||
|
||||
test("reinstalling the pinned version keeps the lock entry, installedAt included", () => {
|
||||
assert.strictEqual(nextNpmLockEntry(pinned, "@me/plugin", result), pinned)
|
||||
})
|
||||
|
||||
test("a new version, source or package is a new entry", () => {
|
||||
const updated = nextNpmLockEntry(pinned, "@me/plugin", { ...result, version: "2.0.0" })
|
||||
assert.strictEqual(updated.version, "2.0.0")
|
||||
assert.notStrictEqual(updated.installedAt, pinned.installedAt)
|
||||
assert.notStrictEqual(nextNpmLockEntry(pinned, "@me/plugin@^1", result), pinned)
|
||||
assert.notStrictEqual(
|
||||
nextNpmLockEntry(pinned, "@me/plugin", { ...result, integrity: "sha512-other" }),
|
||||
pinned,
|
||||
)
|
||||
const added = nextNpmLockEntry(undefined, "@me/plugin", result)
|
||||
assert.deepStrictEqual(
|
||||
{ ...added, installedAt: undefined },
|
||||
{
|
||||
source: "@me/plugin",
|
||||
...result,
|
||||
installedAt: undefined,
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,11 @@
|
||||
import { isHostDependency, npmPackageName, npmPluginDir } from "./npm-plugins.js"
|
||||
import { resolveLockfilePath } from "./lockfile-path.js"
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { execSync } from "child_process"
|
||||
import YAML, { isMap, isNode, isScalar, isSeq } from "yaml"
|
||||
|
||||
// Quartz's own folder; `quartz upgrade` merges this one. Plugin commands use getLockfilePath().
|
||||
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
|
||||
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
|
||||
const CONFIG_YAML_PATH = path.join(process.cwd(), "quartz.config.yaml")
|
||||
@@ -13,6 +16,7 @@ const LEGACY_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.json")
|
||||
const LEGACY_DEFAULT_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.default.json")
|
||||
|
||||
function resolveConfigPath() {
|
||||
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
|
||||
if (fs.existsSync(CONFIG_YAML_PATH)) return CONFIG_YAML_PATH
|
||||
if (fs.existsSync(LEGACY_PLUGINS_JSON_PATH)) return LEGACY_PLUGINS_JSON_PATH
|
||||
if (fs.existsSync(DEFAULT_CONFIG_YAML_PATH)) return DEFAULT_CONFIG_YAML_PATH
|
||||
@@ -157,6 +161,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()
|
||||
@@ -190,12 +253,16 @@ export function writePluginsJson(data) {
|
||||
// Edit the user's file in place; when it does not exist yet, start from the
|
||||
// file we read the config from (e.g. quartz.config.default.yaml) so its
|
||||
// comments carry over.
|
||||
// A config chosen with QUARTZ_CONFIG_PATH (`--config`) is the user's file: edited where it is
|
||||
// (it used to be read from there and written to ./quartz.config.yaml).
|
||||
const chosen = process.env.QUARTZ_CONFIG_PATH ? resolveConfigPath() : null
|
||||
const target = chosen && /\.ya?ml$/.test(chosen) ? chosen : CONFIG_YAML_PATH
|
||||
let baseRaw
|
||||
const basePath = fs.existsSync(CONFIG_YAML_PATH) ? CONFIG_YAML_PATH : resolveConfigPath()
|
||||
const basePath = fs.existsSync(target) ? target : resolveConfigPath()
|
||||
if (fs.existsSync(basePath) && (basePath.endsWith(".yaml") || basePath.endsWith(".yml"))) {
|
||||
baseRaw = fs.readFileSync(basePath, "utf-8")
|
||||
}
|
||||
writeDataToFile(CONFIG_YAML_PATH, rest, baseRaw)
|
||||
writeDataToFile(target, rest, baseRaw)
|
||||
}
|
||||
|
||||
function readDefaultPluginsJson() {
|
||||
@@ -203,10 +270,16 @@ function readDefaultPluginsJson() {
|
||||
return readFileAsData(defaultPath)
|
||||
}
|
||||
|
||||
/** quartz.lock.json of the config in use: next to it (see lockfile-path.js). */
|
||||
export function getLockfilePath() {
|
||||
return resolveLockfilePath(resolveConfigPath())
|
||||
}
|
||||
|
||||
export function readLockfile() {
|
||||
if (!fs.existsSync(LOCKFILE_PATH)) return null
|
||||
const lockfilePath = getLockfilePath()
|
||||
if (!fs.existsSync(lockfilePath)) return null
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(LOCKFILE_PATH, "utf-8"))
|
||||
return JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -220,7 +293,7 @@ export function writeLockfile(lockfile) {
|
||||
}
|
||||
lockfile = { ...lockfile, plugins: sorted }
|
||||
}
|
||||
fs.writeFileSync(LOCKFILE_PATH, JSON.stringify(lockfile, null, 2) + "\n")
|
||||
fs.writeFileSync(getLockfilePath(), JSON.stringify(lockfile, null, 2) + "\n")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -314,8 +387,9 @@ export const SOURCE_FORMATS_HELP = [
|
||||
]
|
||||
|
||||
/**
|
||||
* Directory a configured plugin lives in: node_modules for npm packages,
|
||||
* .quartz/plugins/<name> for everything else. Returns null when unparseable.
|
||||
* Directory a configured plugin lives in: node_modules for npm packages package.json lists,
|
||||
* .quartz/plugins/@scope/<name> for other npm packages (pinned in quartz.lock.json, see
|
||||
* npm-plugins.js), .quartz/plugins/<name> for everything else. Returns null when unparseable.
|
||||
*/
|
||||
export function resolvePluginDir(source) {
|
||||
let parsed
|
||||
@@ -325,7 +399,8 @@ export function resolvePluginDir(source) {
|
||||
return null
|
||||
}
|
||||
if (parsed.npmPackage) {
|
||||
const pkgName = getSourceUrl(source)
|
||||
const pkgName = npmPackageName(getSourceUrl(source))
|
||||
if (!isHostDependency(pkgName)) return npmPluginDir(pkgName, PLUGINS_DIR)
|
||||
return path.join(process.cwd(), "node_modules", ...pkgName.split("/"))
|
||||
}
|
||||
return path.join(PLUGINS_DIR, parsed.name)
|
||||
|
||||
@@ -4,6 +4,11 @@ import os from "os"
|
||||
import { styleText } from "util"
|
||||
import {
|
||||
readPluginsJson,
|
||||
readEffectivePluginsJson,
|
||||
resolveEffectiveConfig,
|
||||
configExtends,
|
||||
loadConfigExtendsModule,
|
||||
getConfigReadPath,
|
||||
writePluginsJson,
|
||||
readLockfile,
|
||||
writeLockfile,
|
||||
@@ -12,7 +17,7 @@ import {
|
||||
parseGitSource,
|
||||
getGitCommit,
|
||||
PLUGINS_DIR,
|
||||
LOCKFILE_PATH,
|
||||
getLockfilePath,
|
||||
isLocalSource,
|
||||
getSourceUrl,
|
||||
formatSource,
|
||||
@@ -51,6 +56,19 @@ import {
|
||||
npmAsync,
|
||||
} from "./subprocess.js"
|
||||
import { writePluginIndex } from "./plugin-index.js"
|
||||
import {
|
||||
installedNpmPluginVersion,
|
||||
installNpmPlugin,
|
||||
isHostDependency,
|
||||
isNpmLockEntry,
|
||||
nextNpmLockEntry,
|
||||
latestNpmVersion,
|
||||
latestNpmVersionAsync,
|
||||
listPluginDirNames,
|
||||
npmPackageName,
|
||||
npmPluginDir,
|
||||
removeNpmPlugin,
|
||||
} from "./npm-plugins.js"
|
||||
import {
|
||||
builtinKeyFor,
|
||||
builtinMessage,
|
||||
@@ -128,6 +146,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)
|
||||
@@ -176,11 +255,13 @@ async function cloneAtCommitAsync({ url, ref, commit, dir }) {
|
||||
/**
|
||||
* Move a shallow clone to a pinned commit. The commit is fetched by SHA (GitHub and most hosts
|
||||
* allow fetching reachable commits), so a pin that is no longer the branch tip works (#2559).
|
||||
* The checkout is forced: the plugin directory is Quartz's clone, and its build (npm install)
|
||||
* rewrites tracked files such as package-lock.json, which a restored CI cache keeps (#2639).
|
||||
*/
|
||||
async function checkoutPinnedCommitAsync(dir, commit) {
|
||||
export async function checkoutPinnedCommitAsync(dir, commit) {
|
||||
assertCommit(commit)
|
||||
await gitAsync(["fetch", "--depth", "1", "origin", commit], { cwd: dir })
|
||||
await gitAsync(["checkout", "--quiet", commit], { cwd: dir })
|
||||
await gitAsync(["checkout", "--quiet", "--force", commit], { cwd: dir })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -318,7 +399,12 @@ export function linkPeerPlugins(pluginDir) {
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
|
||||
const peers = pkg.peerDependencies ?? {}
|
||||
|
||||
const quartzRoot = path.resolve(pluginDir, "..", "..", "..")
|
||||
// .quartz/plugins/<name>, or .quartz/plugins/@scope/<name> for a pinned npm plugin
|
||||
const scoped = path.basename(path.dirname(pluginDir)).startsWith("@")
|
||||
const quartzRoot = path.resolve(
|
||||
pluginDir,
|
||||
...(scoped ? ["..", "..", "..", ".."] : ["..", "..", ".."]),
|
||||
)
|
||||
const hostNodeModules = path.join(quartzRoot, "node_modules")
|
||||
// a local plugin is a symlink; relative links made through it would dangle
|
||||
const realDir = fs.realpathSync(pluginDir)
|
||||
@@ -403,12 +489,8 @@ function canonicalSource(source) {
|
||||
function findPluginByPackageName(packageName) {
|
||||
if (!fs.existsSync(PLUGINS_DIR)) return null
|
||||
|
||||
const plugins = fs.readdirSync(PLUGINS_DIR).filter((entry) => {
|
||||
const entryPath = path.join(PLUGINS_DIR, entry)
|
||||
return fs.statSync(entryPath).isDirectory()
|
||||
})
|
||||
|
||||
for (const pluginDirName of plugins) {
|
||||
// `name` for Git and local plugins, `@scope/name` for pinned npm plugins
|
||||
for (const pluginDirName of listPluginDirNames(PLUGINS_DIR)) {
|
||||
const pkgPath = path.join(PLUGINS_DIR, pluginDirName, "package.json")
|
||||
if (!fs.existsSync(pkgPath)) continue
|
||||
try {
|
||||
@@ -425,16 +507,157 @@ 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)
|
||||
if (parsed.npmPackage) npmPackages.push(parsed.name)
|
||||
// pinned npm plugins are directories in .quartz/plugins, which the index reads anyway
|
||||
if (parsed.npmPackage && isHostDependency(npmPackageName(parsed.name)))
|
||||
npmPackages.push(parsed.name)
|
||||
} catch {}
|
||||
}
|
||||
writePluginIndex({ pluginsDir: PLUGINS_DIR, npmPackages, verbose: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* The npm plugins `plugin install` takes care of: those package.json doesn't list are pinned in
|
||||
* quartz.lock.json and installed into .quartz/plugins/@scope/name (see npm-plugins.js); those it
|
||||
* lists stay with npm. Runs before the Git plugins and writes their lock entries itself; the Git
|
||||
* steps after it leave npm entries alone.
|
||||
*
|
||||
* - default: install each pinned plugin at its locked version (configured but unpinned ones get
|
||||
* a hint to run `install --from-config`)
|
||||
* - `fromConfig`: also pin and install configured ones without an entry (at the latest version),
|
||||
* and remove entries the config no longer has
|
||||
* - `latest`: move every pin to the version npm's `latest` tag points at
|
||||
*/
|
||||
async function syncNpmPlugins({ pluginsJson, names, fromConfig, latest, dryRun }) {
|
||||
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
|
||||
lockfile.plugins ??= {}
|
||||
|
||||
const configured = new Map()
|
||||
for (const entry of pluginsJson?.plugins ?? []) {
|
||||
try {
|
||||
if (!parseGitSource(entry.source).npmPackage) continue
|
||||
const pkg = npmPackageName(getSourceUrl(entry.source))
|
||||
if (NPM_NAME_PATTERN.test(pkg)) configured.set(pkg, entry)
|
||||
} catch {}
|
||||
}
|
||||
const lockedNames = Object.entries(lockfile.plugins)
|
||||
.filter(([, entry]) => isNpmLockEntry(entry))
|
||||
.map(([name]) => name)
|
||||
const wanted = (pkg) =>
|
||||
!names?.length || names.some((n) => n === pkg || n === shortPluginName(pkg))
|
||||
const all = [...new Set([...configured.keys(), ...lockedNames])].filter(wanted)
|
||||
|
||||
let changed = false
|
||||
let installedAny = false
|
||||
|
||||
// package.json wins: an entry left from when the plugin was pinned goes
|
||||
for (const pkg of all.filter((p) => isHostDependency(p))) {
|
||||
if (!isNpmLockEntry(lockfile.plugins[pkg])) continue
|
||||
console.log(styleText("gray", `${pkg} is in package.json, which versions it: removing its pin`))
|
||||
if (dryRun) continue
|
||||
delete lockfile.plugins[pkg]
|
||||
removeNpmPlugin(pkg, PLUGINS_DIR)
|
||||
changed = true
|
||||
}
|
||||
|
||||
const unpinned = []
|
||||
const rows = []
|
||||
for (const pkg of all.filter((p) => !isHostDependency(p))) {
|
||||
const entry = configured.get(pkg)
|
||||
const lockEntry = isNpmLockEntry(lockfile.plugins[pkg]) ? lockfile.plugins[pkg] : undefined
|
||||
|
||||
if (!entry) {
|
||||
// pinned, but no longer configured
|
||||
if (!fromConfig) continue
|
||||
console.log(styleText("yellow", `${pkg} — pinned but not in the config: removing it`))
|
||||
if (dryRun) continue
|
||||
delete lockfile.plugins[pkg]
|
||||
removeNpmPlugin(pkg, PLUGINS_DIR)
|
||||
changed = true
|
||||
installedAny = true
|
||||
continue
|
||||
}
|
||||
// like Git plugins: a disabled plugin isn't installed until it is pinned
|
||||
if (!lockEntry && !entry.enabled) continue
|
||||
if (!lockEntry && !fromConfig && !latest) {
|
||||
unpinned.push(pkg)
|
||||
continue
|
||||
}
|
||||
|
||||
const installedVersion = installedNpmPluginVersion(pkg, PLUGINS_DIR)
|
||||
let version = lockEntry?.version
|
||||
if (latest || !version) {
|
||||
try {
|
||||
version = latestNpmVersion(pkg)
|
||||
} catch (err) {
|
||||
console.log(styleText("red", `✗ ${pkg}: could not look up its latest version on npm`))
|
||||
console.log(styleText("gray", ` ${describeCommandError(err)}`))
|
||||
markFailed()
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
rows.push({ pkg, installed: installedVersion ?? "—", target: version })
|
||||
continue
|
||||
}
|
||||
// `restore` (clean) also leaves a plugin that is installed at its pinned version alone
|
||||
if (installedVersion === version && lockEntry?.version === version) continue
|
||||
|
||||
try {
|
||||
console.log(styleText("cyan", `→ Installing ${pkg}@${version} from npm...`))
|
||||
const result = installNpmPlugin(pkg, {
|
||||
version,
|
||||
integrity: lockEntry?.version === version ? lockEntry.integrity : undefined,
|
||||
pluginsDir: PLUGINS_DIR,
|
||||
})
|
||||
linkPeerPlugins(npmPluginDir(pkg, PLUGINS_DIR))
|
||||
const next = nextNpmLockEntry(lockEntry, entry.source, result)
|
||||
if (next !== lockEntry) {
|
||||
lockfile.plugins[pkg] = next
|
||||
changed = true
|
||||
}
|
||||
installedAny = true
|
||||
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
|
||||
} catch (err) {
|
||||
console.log(styleText("red", `✗ Failed to install ${pkg} from npm`))
|
||||
console.log(styleText("gray", ` ${describeCommandError(err)}`))
|
||||
markFailed()
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.length > 0) {
|
||||
console.log(styleText("bold", latest ? "npm plugins (latest):" : "npm plugins to install:"))
|
||||
const width = Math.max(...rows.map((row) => row.pkg.length)) + 2
|
||||
for (const { pkg, installed, target } of rows) {
|
||||
const status =
|
||||
installed === target
|
||||
? styleText("green", "up to date")
|
||||
: styleText("yellow", `${installed} → ${target}`)
|
||||
console.log(` ${pkg.padEnd(width)}${status}`)
|
||||
}
|
||||
console.log()
|
||||
}
|
||||
if (unpinned.length > 0) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`⚠ ${unpinned.length} npm plugin(s) in the config are not pinned in quartz.lock.json: ${unpinned.join(", ")}`,
|
||||
),
|
||||
)
|
||||
console.log(
|
||||
styleText("gray", " Run 'npx quartz plugin install --from-config' to install and pin them."),
|
||||
)
|
||||
}
|
||||
|
||||
if (changed && !dryRun) writeLockfile(lockfile)
|
||||
if (installedAny && !dryRun) await regeneratePluginIndex()
|
||||
return { installedAny }
|
||||
}
|
||||
|
||||
export async function handlePluginInstallUnified({
|
||||
names,
|
||||
fromConfig = false,
|
||||
@@ -453,19 +676,41 @@ 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)),
|
||||
}
|
||||
// npm plugins package.json doesn't list are pinned and installed first; without a lockfile
|
||||
// they are pinned from the config, as Git plugins are below
|
||||
const hadLockfile = readLockfile() !== null
|
||||
await syncNpmPlugins({
|
||||
pluginsJson,
|
||||
names,
|
||||
fromConfig: fromConfig || !hadLockfile,
|
||||
latest,
|
||||
dryRun,
|
||||
})
|
||||
|
||||
// the steps below handle Git and local plugins; npm entries are written back as they are
|
||||
let lockfile = readLockfile()
|
||||
const npmLockEntries = Object.fromEntries(
|
||||
Object.entries(lockfile?.plugins ?? {}).filter(([, entry]) => isNpmLockEntry(entry)),
|
||||
)
|
||||
const withNpmEntries = (lf) => ({ ...lf, plugins: { ...npmLockEntries, ...lf.plugins } })
|
||||
if (lockfile) {
|
||||
lockfile = {
|
||||
...lockfile,
|
||||
plugins: Object.fromEntries(
|
||||
Object.entries(lockfile.plugins ?? {}).filter(([name]) => !builtinMessage(name)),
|
||||
Object.entries(lockfile.plugins ?? {}).filter(
|
||||
([name, entry]) => !builtinMessage(name) && !isNpmLockEntry(entry),
|
||||
),
|
||||
),
|
||||
}
|
||||
// a lockfile the npm step just created holds no Git pins: install those from the config
|
||||
if (!hadLockfile && Object.keys(lockfile.plugins).length === 0) lockfile = null
|
||||
}
|
||||
|
||||
if (!fromConfig && !lockfile) {
|
||||
@@ -477,12 +722,7 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
})
|
||||
if (gitEntries.length === 0 && findMissingNpmPlugins(pluginsJson).length === 0) {
|
||||
console.log(
|
||||
styleText(
|
||||
"green",
|
||||
"✓ No Git or local plugins to install (plugins from npm are installed by 'npm install' / 'npm ci')",
|
||||
),
|
||||
)
|
||||
console.log(styleText("green", "✓ No Git or local plugins to install"))
|
||||
return
|
||||
}
|
||||
if (dryRun && latest) {
|
||||
@@ -922,7 +1162,7 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
|
||||
if (lockfileChanged) {
|
||||
writeLockfile(lockfile)
|
||||
writeLockfile(withNpmEntries(lockfile))
|
||||
console.log()
|
||||
if (failed === 0) {
|
||||
console.log(styleText("green", `✓ Resolved ${installed.length} plugin(s)`))
|
||||
@@ -1090,6 +1330,13 @@ export async function handlePluginInstallUnified({
|
||||
const pluginsToUpdate = nameFilter ? Array.from(nameFilter) : Object.keys(lockfile.plugins)
|
||||
const updatedPlugins = []
|
||||
let lockfileChanged = false
|
||||
// Disabled in the config: the build never loads them, so failing to update one is a warning,
|
||||
// not a failed update (an old entry whose repository changed layout failed every update).
|
||||
const disabledNames = new Set(
|
||||
(pluginsJson?.plugins ?? [])
|
||||
.filter((entry) => entry.enabled === false)
|
||||
.map((entry) => extractPluginName(entry.source)),
|
||||
)
|
||||
|
||||
// Phase 1: Validate and categorize plugins (fast, sequential)
|
||||
const validPlugins = []
|
||||
@@ -1174,6 +1421,16 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (disabledNames.has(name)) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`⚠ Could not update ${name} (disabled, so the build does not load it): ${describeCommandError(error)}\n` +
|
||||
` Remove it with \`npx quartz plugin remove ${name}\` or fix its source.`,
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
console.log(
|
||||
styleText("red", `✗ Failed to update ${name}: ${describeCommandError(error)}`),
|
||||
)
|
||||
@@ -1201,7 +1458,7 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
|
||||
if (lockfileChanged) {
|
||||
writeLockfile(lockfile)
|
||||
writeLockfile(withNpmEntries(lockfile))
|
||||
console.log()
|
||||
console.log(styleText("gray", "Updated quartz.lock.json"))
|
||||
}
|
||||
@@ -1413,7 +1670,11 @@ export async function handlePluginInstallUnified({
|
||||
|
||||
const NPM_NAME_PATTERN = /^@[a-z0-9-~][a-z0-9-._~]*\/[a-z0-9-~][a-z0-9-._~]*$/
|
||||
|
||||
/** Enabled npm-sourced plugins whose package is not present in node_modules. */
|
||||
/**
|
||||
* Enabled npm-sourced plugins in package.json whose package is not present in node_modules
|
||||
* (`npm install` installs them). Plugins package.json doesn't list are pinned in
|
||||
* quartz.lock.json instead, see syncNpmPlugins.
|
||||
*/
|
||||
function findMissingNpmPlugins(pluginsJson) {
|
||||
const missing = []
|
||||
for (const entry of pluginsJson?.plugins ?? []) {
|
||||
@@ -1422,6 +1683,7 @@ function findMissingNpmPlugins(pluginsJson) {
|
||||
if (!parseGitSource(entry.source).npmPackage) continue
|
||||
const pkg = getSourceUrl(entry.source)
|
||||
if (!NPM_NAME_PATTERN.test(pkg)) continue
|
||||
if (!isHostDependency(npmPackageName(pkg))) continue
|
||||
const dir = resolvePluginDir(entry.source)
|
||||
if (dir && !fs.existsSync(path.join(dir, "package.json"))) missing.push(pkg)
|
||||
} catch {}
|
||||
@@ -1474,8 +1736,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
|
||||
@@ -1513,11 +1779,46 @@ export async function handlePluginAdd(
|
||||
)
|
||||
continue
|
||||
}
|
||||
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
|
||||
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
|
||||
const configSource = nameOverride ? { repo: parsed.name, name: nameOverride } : parsed.name
|
||||
const pluginDir = path.join(process.cwd(), "node_modules", ...parsed.name.split("/"))
|
||||
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
|
||||
const pkg = npmPackageName(parsed.name)
|
||||
if (isHostDependency(pkg)) {
|
||||
// in package.json already (a default plugin, or one installed with npm): npm's
|
||||
console.log(styleText("cyan", `→ Installing ${name} from npm (package.json)...`))
|
||||
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
|
||||
const pluginDir = path.join(process.cwd(), "node_modules", ...pkg.split("/"))
|
||||
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
|
||||
continue
|
||||
}
|
||||
// pinned in quartz.lock.json and installed into .quartz/plugins/@scope/name, so Quartz's
|
||||
// package.json stays as Quartz ships it (see npm-plugins.js)
|
||||
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
|
||||
const requested = parsed.name.slice(pkg.length + 1) || "latest"
|
||||
let result
|
||||
try {
|
||||
result = installNpmPlugin(pkg, { version: requested, pluginsDir: PLUGINS_DIR })
|
||||
} catch (err) {
|
||||
console.log(styleText("red", `✗ Failed to install ${pkg} from npm`))
|
||||
console.log(styleText("gray", ` ${describeCommandError(err)}`))
|
||||
hadFailure = true
|
||||
continue
|
||||
}
|
||||
const pluginDir = npmPluginDir(pkg, PLUGINS_DIR)
|
||||
linkPeerPlugins(pluginDir)
|
||||
lockfile.plugins[pkg] = {
|
||||
source: configSource,
|
||||
...result,
|
||||
installedAt: new Date().toISOString(),
|
||||
}
|
||||
lockfileChanged = true
|
||||
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
|
||||
addedPlugins.push({
|
||||
name,
|
||||
pluginDir,
|
||||
source: parsed.name,
|
||||
configSource,
|
||||
npm: true,
|
||||
skipBuild: true,
|
||||
})
|
||||
continue
|
||||
}
|
||||
const name = nameOverride ?? parsed.name
|
||||
@@ -1694,7 +1995,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 = {
|
||||
@@ -1772,13 +2077,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
|
||||
@@ -1794,11 +2122,17 @@ export async function handlePluginRemove(names) {
|
||||
try {
|
||||
const parsed = parseGitSource(configEntry.source)
|
||||
isNpm = Boolean(parsed.npmPackage)
|
||||
if (!isNpm && !lockfile.plugins[lockKey]) lockKey = parsed.name
|
||||
if (isNpm) lockKey = npmPackageName(getSourceUrl(configEntry.source))
|
||||
else if (!lockfile.plugins[lockKey]) lockKey = parsed.name
|
||||
} catch {}
|
||||
} else if (isNpmLockEntry(lockfile.plugins[lockKey])) {
|
||||
isNpm = true
|
||||
}
|
||||
const pluginDir = path.join(PLUGINS_DIR, lockKey)
|
||||
const installed = !isNpm && (Boolean(lockfile.plugins[lockKey]) || fs.existsSync(pluginDir))
|
||||
// an npm plugin package.json doesn't list is pinned and installed like a Git plugin
|
||||
const pinnedNpm = isNpm && !isHostDependency(lockKey)
|
||||
const pluginDir = path.join(PLUGINS_DIR, ...lockKey.split("/"))
|
||||
const installed =
|
||||
(!isNpm || pinnedNpm) && (Boolean(lockfile.plugins[lockKey]) || fs.existsSync(pluginDir))
|
||||
|
||||
if (!configEntry && !installed) {
|
||||
const candidates = [
|
||||
@@ -1824,7 +2158,10 @@ export async function handlePluginRemove(names) {
|
||||
console.log(styleText("cyan", `→ Removing ${displayName}...`))
|
||||
|
||||
if (installed) {
|
||||
if (fs.existsSync(pluginDir) || fs.lstatSync(pluginDir, { throwIfNoEntry: false })) {
|
||||
if (pinnedNpm) {
|
||||
removeNpmPlugin(lockKey, PLUGINS_DIR)
|
||||
removedFiles = true
|
||||
} else if (fs.existsSync(pluginDir) || fs.lstatSync(pluginDir, { throwIfNoEntry: false })) {
|
||||
fs.rmSync(pluginDir, { recursive: true, force: true })
|
||||
removedFiles = true
|
||||
}
|
||||
@@ -1839,7 +2176,7 @@ export async function handlePluginRemove(names) {
|
||||
removedSources.push(configEntry.source)
|
||||
}
|
||||
console.log(styleText("green", `✓ Removed ${displayName}`))
|
||||
if (isNpm) {
|
||||
if (isNpm && !pinnedNpm && configEntry) {
|
||||
console.log(
|
||||
styleText(
|
||||
"gray",
|
||||
@@ -1890,7 +2227,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.`))
|
||||
@@ -1901,12 +2240,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)
|
||||
@@ -1915,7 +2255,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 (
|
||||
@@ -1960,14 +2301,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)
|
||||
@@ -1977,7 +2322,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("=")
|
||||
@@ -1994,7 +2340,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)}`),
|
||||
@@ -2008,7 +2354,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)`),
|
||||
@@ -2080,6 +2448,18 @@ function collectUntrackedEntries(pluginsJson, lockfile) {
|
||||
continue
|
||||
}
|
||||
if (parsed.npmPackage) {
|
||||
const pkgName = npmPackageName(getSourceUrl(entry.source))
|
||||
if (!isHostDependency(pkgName)) {
|
||||
// pinned in quartz.lock.json like Git plugins; missing when it has no entry yet
|
||||
if (!isNpmLockEntry(lockfile?.plugins?.[pkgName])) {
|
||||
missing.push({
|
||||
name: extractPluginName(entry.source),
|
||||
source: formatSource(entry.source),
|
||||
enabled: Boolean(entry.enabled),
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
const pkg = readEntryPackageJson(entry.source)
|
||||
npm.push({
|
||||
name: extractPluginName(entry.source),
|
||||
@@ -2100,7 +2480,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 ?? {})
|
||||
|
||||
@@ -2127,18 +2508,43 @@ export async function handlePluginList() {
|
||||
: styleText("gray", "disabled")
|
||||
|
||||
if (lockEntries.length > 0) {
|
||||
console.log(styleText("bold", "Git / local plugins (quartz.lock.json):"))
|
||||
console.log(styleText("bold", "Pinned plugins (quartz.lock.json):"))
|
||||
console.log()
|
||||
}
|
||||
|
||||
for (const [name, entry] of lockEntries) {
|
||||
const pluginDir = path.join(PLUGINS_DIR, name)
|
||||
const pluginDir = path.join(PLUGINS_DIR, ...name.split("/"))
|
||||
const exists = fs.existsSync(pluginDir)
|
||||
const overriddenName = nameOverrides.get(name)
|
||||
const displayLabel = overriddenName
|
||||
? `${overriddenName} ${styleText("gray", `(dir: ${name})`)}`
|
||||
: name
|
||||
|
||||
if (isNpmLockEntry(entry)) {
|
||||
const installedVersion = installedNpmPluginVersion(name, PLUGINS_DIR)
|
||||
const status = !installedVersion
|
||||
? styleText("red", "✗")
|
||||
: installedVersion === entry.version
|
||||
? styleText("green", "✓")
|
||||
: styleText("yellow", "⚡")
|
||||
console.log(
|
||||
` ${status} ${styleText("bold", displayLabel)} ${enabledLabel(overriddenName ?? name)}`,
|
||||
)
|
||||
console.log(` Source: ${formatSource(entry.source)} (npm)`)
|
||||
console.log(` Version: ${entry.version}`)
|
||||
if (installedVersion && installedVersion !== entry.version) {
|
||||
console.log(
|
||||
` Current: ${installedVersion} (differs from lockfile — run 'npx quartz plugin install ${name}')`,
|
||||
)
|
||||
}
|
||||
if (!installedVersion) console.log(` Not on disk — run 'npx quartz plugin install'`)
|
||||
if (entry.installedAt) {
|
||||
console.log(` Installed: ${new Date(entry.installedAt).toLocaleDateString()}`)
|
||||
}
|
||||
console.log()
|
||||
continue
|
||||
}
|
||||
|
||||
if (entry.commit === "local") {
|
||||
const isLinked = exists && fs.lstatSync(pluginDir).isSymbolicLink()
|
||||
const status = isLinked ? styleText("green", "✓") : styleText("red", "✗")
|
||||
@@ -2220,7 +2626,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"))
|
||||
@@ -2237,6 +2644,19 @@ export async function handlePluginStatus() {
|
||||
)
|
||||
|
||||
const rows = Object.entries(lockfile.plugins).map(([name, entry]) => {
|
||||
if (isNpmLockEntry(entry)) {
|
||||
const installedVersion = installedNpmPluginVersion(name, PLUGINS_DIR)
|
||||
return {
|
||||
name,
|
||||
entry,
|
||||
npmPinned: true,
|
||||
exists: installedVersion !== null,
|
||||
displayName: nameOverrides.get(name) ?? name,
|
||||
sourceLabel: `${formatSource(entry.source)} (npm)`,
|
||||
commitLabel: `v${entry.version}`,
|
||||
enabled: enabledByName.get(extractPluginName(entry.source)) ?? false,
|
||||
}
|
||||
}
|
||||
const pluginDir = path.join(PLUGINS_DIR, name)
|
||||
const exists = fs.existsSync(pluginDir)
|
||||
const displayName = nameOverrides.get(name) ?? name
|
||||
@@ -2331,6 +2751,21 @@ export async function handlePluginStatus() {
|
||||
})
|
||||
}
|
||||
|
||||
if (row.npmPinned) {
|
||||
return latestNpmVersionAsync(row.name)
|
||||
.then((latestVersion) => {
|
||||
const status = latestVersion === row.entry.version ? "up_to_date" : "update_available"
|
||||
const display = updateDisplay(status)
|
||||
updateLine(index, display.label, display.text)
|
||||
return { index, status, name: row.displayName }
|
||||
})
|
||||
.catch(() => {
|
||||
const display = updateDisplay("failed")
|
||||
updateLine(index, display.label, display.text)
|
||||
return { index, status: "failed", name: row.displayName }
|
||||
})
|
||||
}
|
||||
|
||||
return lsRemote(row.entry)
|
||||
.then(({ stdout }) => {
|
||||
const latestCommit = stdout.split("\t")[0].trim()
|
||||
@@ -2368,13 +2803,13 @@ export async function handlePluginStatus() {
|
||||
console.log(
|
||||
styleText(
|
||||
"gray",
|
||||
"\nnpm plugins are versioned by package.json — update them with 'npx quartz upgrade' or 'npm update'.",
|
||||
"\nnpm plugins in package.json are versioned there — update them with 'npx quartz upgrade' or 'npm update'.",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
if (updatesAvailable.length === 0 && failedChecks.length === 0) {
|
||||
console.log(styleText("green", "\n✓ All Git plugins up to date"))
|
||||
console.log(styleText("green", "\n✓ All pinned plugins up to date"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2457,7 +2892,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
|
||||
@@ -2472,6 +2923,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(
|
||||
@@ -2485,12 +2937,14 @@ 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) {
|
||||
if (fs.existsSync(getLockfilePath()) && !lockfile) {
|
||||
report(
|
||||
"error",
|
||||
"quartz.lock.json",
|
||||
@@ -2564,14 +3018,55 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
|
||||
const pluginDir = resolvePluginDir(entry.source)
|
||||
if (parsed.npmPackage) {
|
||||
if (!fs.existsSync(path.join(pluginDir, "package.json"))) {
|
||||
report(
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
"npm package is not installed",
|
||||
`Run 'npm install' (or 'npm install ${parsed.name}' if it is not in package.json).`,
|
||||
)
|
||||
return
|
||||
const pkgName = npmPackageName(getSourceUrl(entry.source))
|
||||
const pin = lockfile?.plugins?.[pkgName]
|
||||
if (isHostDependency(pkgName)) {
|
||||
if (isNpmLockEntry(pin)) {
|
||||
report(
|
||||
"warning",
|
||||
label,
|
||||
"is in package.json and also pinned in quartz.lock.json; package.json versions it",
|
||||
`Run 'npx quartz plugin install ${pkgName}' to remove the unused pin.`,
|
||||
)
|
||||
}
|
||||
if (!fs.existsSync(path.join(pluginDir, "package.json"))) {
|
||||
report(
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
"npm package is not installed",
|
||||
"Run 'npm install'.",
|
||||
)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// pinned in quartz.lock.json, installed into .quartz/plugins/@scope/name
|
||||
const installedVersion = installedNpmPluginVersion(pkgName, PLUGINS_DIR)
|
||||
if (!isNpmLockEntry(pin)) {
|
||||
if (enabled) {
|
||||
report(
|
||||
"warning",
|
||||
label,
|
||||
"not pinned in quartz.lock.json — the build installs the latest version",
|
||||
"Run 'npx quartz plugin install --from-config' and commit quartz.lock.json.",
|
||||
)
|
||||
}
|
||||
if (!installedVersion) return
|
||||
} else if (!installedVersion) {
|
||||
report(
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
`npm package is not installed (quartz.lock.json pins ${pin.version})`,
|
||||
"Run 'npx quartz plugin install'.",
|
||||
)
|
||||
return
|
||||
} else if (installedVersion !== pin.version) {
|
||||
report(
|
||||
"warning",
|
||||
label,
|
||||
`${installedVersion} is installed but quartz.lock.json pins ${pin.version}`,
|
||||
`Run 'npx quartz plugin install ${pkgName}' to install the pinned version.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
gitPluginCount++
|
||||
@@ -2637,7 +3132,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
"has no built entry point (dist/ missing)",
|
||||
parsed.npmPackage
|
||||
parsed.npmPackage && isHostDependency(npmPackageName(getSourceUrl(entry.source)))
|
||||
? "Reinstall it with 'npm install'."
|
||||
: `Run 'npx quartz plugin install ${parsed.name}' to build it.`,
|
||||
)
|
||||
@@ -2667,7 +3162,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) {
|
||||
@@ -2715,7 +3210,11 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
const configured = new Set(
|
||||
plugins.flatMap((e) => {
|
||||
try {
|
||||
return [parseGitSource(e.source).name]
|
||||
const parsed = parseGitSource(e.source)
|
||||
// npm pins are keyed by package name, also when the config renames the plugin
|
||||
return parsed.npmPackage
|
||||
? [parsed.name, npmPackageName(getSourceUrl(e.source))]
|
||||
: [parsed.name]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
@@ -2769,10 +3268,23 @@ 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)),
|
||||
)
|
||||
// npm pins are keyed by package name, also when the config gives the plugin another name
|
||||
for (const entry of pluginsJson?.plugins ?? []) {
|
||||
try {
|
||||
if (parseGitSource(entry.source).npmPackage)
|
||||
configuredNames.add(npmPackageName(getSourceUrl(entry.source)))
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const orphans = Object.keys(lockfile.plugins).filter((name) => !configuredNames.has(name))
|
||||
|
||||
@@ -2798,7 +3310,9 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
|
||||
|
||||
console.log(styleText("cyan", `→ Removing ${name}...`))
|
||||
|
||||
if (fs.existsSync(pluginDir)) {
|
||||
if (isNpmLockEntry(lockfile.plugins[name])) {
|
||||
removeNpmPlugin(name, PLUGINS_DIR)
|
||||
} else if (fs.existsSync(pluginDir)) {
|
||||
fs.rmSync(pluginDir, { recursive: true })
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
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 { buildPluginAsync, linkPeerPlugins, pluginSourceChanged } from "./plugin-git-handlers.js"
|
||||
import { pathToFileURL } from "url"
|
||||
import YAML from "yaml"
|
||||
import {
|
||||
buildPluginAsync,
|
||||
checkoutPinnedCommitAsync,
|
||||
linkPeerPlugins,
|
||||
pluginSourceChanged,
|
||||
} from "./plugin-git-handlers.js"
|
||||
|
||||
let root
|
||||
let hostPreact
|
||||
@@ -161,3 +168,256 @@ describe("pluginSourceChanged", () => {
|
||||
assert.strictEqual(pluginSourceChanged(priorEntry, "github:owner/new-repo"), true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("checkoutPinnedCommitAsync", () => {
|
||||
const git = (cwd, cmd) =>
|
||||
execSync(`git -c user.name=t -c user.email=t@t -c commit.gpgsign=false ${cmd}`, {
|
||||
cwd,
|
||||
stdio: "pipe",
|
||||
timeout: 30000,
|
||||
})
|
||||
.toString()
|
||||
.trim()
|
||||
|
||||
function makeRemote() {
|
||||
const remote = path.join(root, "remote")
|
||||
fs.mkdirSync(remote)
|
||||
git(remote, "init -q -b main")
|
||||
git(remote, "config uploadpack.allowAnySHA1InWant true")
|
||||
fs.writeFileSync(path.join(remote, "package-lock.json"), `{ "v": 1 }`)
|
||||
git(remote, "add -A")
|
||||
git(remote, "commit -q -m one")
|
||||
const first = git(remote, "rev-parse HEAD")
|
||||
fs.writeFileSync(path.join(remote, "package-lock.json"), `{ "v": 2 }`)
|
||||
git(remote, "commit -q -am two")
|
||||
return { remote, first }
|
||||
}
|
||||
|
||||
test("moves to a pinned commit that is not the branch tip", async () => {
|
||||
const { remote, first } = makeRemote()
|
||||
const dir = path.join(root, "plugin")
|
||||
git(root, `clone -q --depth 1 ${pathToFileURL(remote).href} "${dir}"`)
|
||||
await checkoutPinnedCommitAsync(dir, first)
|
||||
assert.strictEqual(git(dir, "rev-parse HEAD"), first)
|
||||
})
|
||||
|
||||
// a plugin's build (npm install) rewrites its tracked package-lock.json; a restored CI cache
|
||||
// keeps that change, and the checkout refused to move ("commit your changes or stash them")
|
||||
test("moves even when the plugin's build left tracked files changed (#2639)", async () => {
|
||||
const { remote, first } = makeRemote()
|
||||
const dir = path.join(root, "plugin")
|
||||
git(root, `clone -q --depth 1 ${pathToFileURL(remote).href} "${dir}"`)
|
||||
fs.writeFileSync(path.join(dir, "package-lock.json"), `{ "v": "rewritten by npm" }`)
|
||||
await checkoutPinnedCommitAsync(dir, first)
|
||||
assert.strictEqual(git(dir, "rev-parse HEAD"), first)
|
||||
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 })
|
||||
// the default plugins are Quartz's dependencies, as in Quartz's own package.json
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "site",
|
||||
version: "5.3.0",
|
||||
dependencies: { "@quartz-community/graph": "^1", "@quartz-community/comments": "^1" },
|
||||
}),
|
||||
)
|
||||
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/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin install --latest with a plugin that can't be updated", () => {
|
||||
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
|
||||
// A Git plugin whose repository no longer has the configured subdirectory (an old
|
||||
// quartz-themes entry: the repository moved its plugin out of `plugin/`).
|
||||
const site = (enabled) => {
|
||||
const repo = path.join(root, "repo")
|
||||
fs.mkdirSync(repo, { recursive: true })
|
||||
fs.writeFileSync(path.join(repo, "README.md"), "no plugin/ here\n")
|
||||
const git = (args) => execSync(`git ${args}`, { cwd: repo, stdio: "ignore", timeout: 30_000 })
|
||||
git("init -q -b main")
|
||||
git("-c user.name=t -c user.email=t@t add .")
|
||||
git("-c user.name=t -c user.email=t@t commit -q -m init")
|
||||
const url = pathToFileURL(repo).href
|
||||
const dir = path.join(root, "site")
|
||||
fs.mkdirSync(path.join(dir, ".quartz", "plugins", "old-theme"), { recursive: true })
|
||||
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.1" }`)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.yaml"),
|
||||
YAML.stringify({
|
||||
configuration: { pageTitle: "t" },
|
||||
plugins: [{ source: { name: "old-theme", repo: url, subdir: "plugin" }, enabled }],
|
||||
}),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.lock.json"),
|
||||
JSON.stringify({
|
||||
version: "1.0.0",
|
||||
plugins: {
|
||||
"old-theme": {
|
||||
source: url,
|
||||
resolved: url,
|
||||
subdir: "plugin",
|
||||
commit: "0000000000000000000000000000000000000000",
|
||||
installedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
return dir
|
||||
}
|
||||
const run = (dir) => {
|
||||
const result = spawnSync(process.execPath, [cli, "plugin", "install", "--latest"], {
|
||||
cwd: dir,
|
||||
encoding: "utf-8",
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
|
||||
})
|
||||
return { output: result.stdout + result.stderr, status: result.status }
|
||||
}
|
||||
|
||||
test("a disabled plugin only warns: the build doesn't load it", () => {
|
||||
const { output, status } = run(site(false))
|
||||
assert.match(output, /Could not update old-theme \(disabled/)
|
||||
assert.match(output, /npx quartz plugin remove old-theme/)
|
||||
assert.strictEqual(status, 0)
|
||||
})
|
||||
|
||||
test("an enabled plugin fails the update", () => {
|
||||
const { output, status } = run(site(true))
|
||||
assert.match(output, /Failed to update old-theme/)
|
||||
assert.strictEqual(status, 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin commands with --config elsewhere", () => {
|
||||
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
|
||||
const run = (cwd, args) =>
|
||||
spawnSync(process.execPath, [cli, ...args], {
|
||||
cwd,
|
||||
encoding: "utf-8",
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
|
||||
})
|
||||
|
||||
test("-C reads and writes that config and the quartz.lock.json next to it", () => {
|
||||
const quartz = path.join(root, "quartz")
|
||||
fs.mkdirSync(quartz, { recursive: true })
|
||||
fs.writeFileSync(path.join(quartz, "package.json"), `{ "name": "q", "version": "5.3.0" }`)
|
||||
fs.writeFileSync(path.join(quartz, "quartz.config.default.yaml"), "plugins: []\n")
|
||||
// a site repository outside Quartz: content, config and lockfile only
|
||||
const site = path.join(root, "site")
|
||||
fs.mkdirSync(site, { recursive: true })
|
||||
fs.writeFileSync(path.join(site, "quartz.config.yaml"), "extends: default\n")
|
||||
const plugin = path.join(root, "my-plugin")
|
||||
fs.mkdirSync(plugin, { recursive: true })
|
||||
fs.writeFileSync(
|
||||
path.join(plugin, "package.json"),
|
||||
`{ "name": "my-plugin", "version": "1.0.0" }`,
|
||||
)
|
||||
// pre-built, so `add` doesn't build it
|
||||
fs.mkdirSync(path.join(plugin, "dist"))
|
||||
fs.writeFileSync(path.join(plugin, "dist", "index.js"), "export {}\n")
|
||||
fs.writeFileSync(path.join(plugin, "dist", "index.d.ts"), "export {}\n")
|
||||
|
||||
const result = run(quartz, [
|
||||
"plugin",
|
||||
"add",
|
||||
plugin,
|
||||
"-C",
|
||||
path.join(site, "quartz.config.yaml"),
|
||||
])
|
||||
assert.strictEqual(result.status, 0, result.stdout + result.stderr)
|
||||
const lock = JSON.parse(fs.readFileSync(path.join(site, "quartz.lock.json"), "utf-8"))
|
||||
assert.strictEqual(lock.plugins["my-plugin"]?.commit, "local")
|
||||
assert.ok(!fs.existsSync(path.join(quartz, "quartz.lock.json")))
|
||||
assert.match(fs.readFileSync(path.join(site, "quartz.config.yaml"), "utf-8"), /my-plugin/)
|
||||
assert.ok(!fs.existsSync(path.join(quartz, "quartz.config.yaml")))
|
||||
// installed into Quartz's .quartz/plugins, where the build loads it
|
||||
assert.ok(fs.existsSync(path.join(quartz, ".quartz", "plugins", "my-plugin")))
|
||||
|
||||
const list = run(quartz, ["plugin", "list", "--config", path.join(site, "quartz.config.yaml")])
|
||||
assert.match(list.stdout, /my-plugin/)
|
||||
|
||||
const missing = run(quartz, ["plugin", "list", "-C", path.join(site, "nope.yaml")])
|
||||
assert.strictEqual(missing.status, 1)
|
||||
assert.match(missing.stderr, /Config file not found/)
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,7 @@
|
||||
* Overrides are registered under the key the config loader looks them up by: the npm package name
|
||||
* for npm plugins, the directory name for Git/local plugins (#2565).
|
||||
*/
|
||||
import { listPluginDirNames } from "./npm-plugins.js"
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
@@ -120,20 +121,23 @@ export function collectPluginExports({ pluginsDir, npmPackages = [], verbose = f
|
||||
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) entries.set(key, info)
|
||||
}
|
||||
|
||||
const dirs = fs.existsSync(pluginsDir)
|
||||
? fs.readdirSync(pluginsDir).filter((n) => fs.statSync(path.join(pluginsDir, n)).isDirectory())
|
||||
: []
|
||||
for (const name of dirs) {
|
||||
const distIndex = path.join(pluginsDir, name, "dist", "index.d.ts")
|
||||
// `name` for Git and local plugins, `@scope/name` for npm plugins pinned in quartz.lock.json
|
||||
const fromDirs = new Set()
|
||||
for (const name of listPluginDirNames(pluginsDir)) {
|
||||
const distIndex = path.join(pluginsDir, ...name.split("/"), "dist", "index.d.ts")
|
||||
if (!fs.existsSync(distIndex)) {
|
||||
if (verbose)
|
||||
console.log(styleText("yellow", `⚠`), `Skipping ${name}: no dist/index.d.ts found`)
|
||||
continue
|
||||
}
|
||||
add(name, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
|
||||
fromDirs.add(name)
|
||||
// a pinned npm plugin keeps its package name as the registry key, as from node_modules
|
||||
const key = name.startsWith("@") ? name.replace(/^@/, "").replace(/\//g, "__") : name
|
||||
add(key, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
|
||||
}
|
||||
|
||||
for (const pkg of npmPackages) {
|
||||
if (fromDirs.has(pkg)) continue
|
||||
let distIndex
|
||||
try {
|
||||
const pkgJson = fileURLToPath(import.meta.resolve(`${pkg}/package.json`))
|
||||
|
||||
@@ -105,6 +105,24 @@ describe("plugin index", () => {
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("npm plugins pinned in quartz.lock.json are read from .quartz/plugins/@scope/name", () => {
|
||||
const pluginsDir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-plugin-index-pinned-"))
|
||||
const dist = path.join(pluginsDir, "@me", "widget", "dist")
|
||||
fs.mkdirSync(dist, { recursive: true })
|
||||
fs.writeFileSync(
|
||||
path.join(dist, "index.d.ts"),
|
||||
`import { QuartzComponent } from '@quartz-community/types';\ndeclare const Widget: () => QuartzComponent;\nexport { Widget };\n`,
|
||||
)
|
||||
// also listed by the config as an npm package: read once, from the directory
|
||||
const entries = collectPluginExports({ pluginsDir, npmPackages: ["@me/widget"] })
|
||||
assert.deepStrictEqual([...entries.keys()], ["me__widget"])
|
||||
const entry = entries.get("me__widget")!
|
||||
assert.strictEqual(entry.importPath, "./@me/widget")
|
||||
assert.strictEqual(entry.registryKey, "@me/widget")
|
||||
assert.ok(entry.overridable.includes("Widget"))
|
||||
fs.rmSync(pluginsDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("npm plugins register under their package name", () => {
|
||||
const source = renderPluginIndex(
|
||||
new Map([
|
||||
|
||||
@@ -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")
|
||||
@@ -263,6 +293,32 @@ describe("shipped configs", () => {
|
||||
assert.deepStrictEqual([...schemaPositions].sort(), [...LAYOUT_POSITIONS].sort())
|
||||
})
|
||||
|
||||
test("schema has every built-in and font of the configuration", () => {
|
||||
const configuration = schema.properties.configuration.properties
|
||||
for (const key of ["frontmatter", "links", "drafts", "contentIndex", "fonts", "slugs"]) {
|
||||
assert.ok(configuration[key], key)
|
||||
}
|
||||
const typography = configuration.theme.properties.typography.properties
|
||||
assert.deepStrictEqual(Object.keys(typography).sort(), ["body", "code", "header", "title"])
|
||||
assert.strictEqual(typography.header.$ref, "#/$defs/font")
|
||||
const fontObject = schema.$defs.font.oneOf.find((s) => s.type === "object")
|
||||
assert.deepStrictEqual(Object.keys(fontObject.properties).sort(), [
|
||||
"includeItalic",
|
||||
"name",
|
||||
"weights",
|
||||
])
|
||||
})
|
||||
|
||||
test("schema requires a full theme only without extends", () => {
|
||||
// with `extends`, `theme: { colors: { lightMode: { secondary: … } } }` is a whole config
|
||||
const theme = schema.properties.configuration.properties.theme
|
||||
assert.strictEqual(theme.required, undefined)
|
||||
assert.strictEqual(theme.properties.colors.required, undefined)
|
||||
const full = schema.else.properties.configuration.properties.theme
|
||||
assert.deepStrictEqual(full.required, ["fontOrigin", "cdnCaching", "typography", "colors"])
|
||||
assert.deepStrictEqual(full.properties.colors.required, ["lightMode", "darkMode"])
|
||||
})
|
||||
|
||||
for (const file of files) {
|
||||
test(`${path.basename(file)} has no plugin entry problems`, () => {
|
||||
const data = YAML.parse(fs.readFileSync(file, "utf-8"))
|
||||
|
||||
@@ -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} />
|
||||
))}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import test, { describe } from "node:test"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import assert from "node:assert"
|
||||
import { renderTranscludes, pageResources } from "./renderPage"
|
||||
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"
|
||||
@@ -48,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",
|
||||
@@ -81,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",
|
||||
@@ -183,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",
|
||||
@@ -308,6 +426,62 @@ describe("renderTranscludes", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("transformPageContent (render-time transforms)", () => {
|
||||
const text = (root: Root) => toHtml(root)
|
||||
const target: Root = {
|
||||
type: "root",
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "p",
|
||||
properties: {},
|
||||
children: [{ type: "text", value: "Target content" }],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
test("runs before, then transclusions, then treeTransforms, then after, on a copy", () => {
|
||||
const page: Root = { type: "root", children: [makeTranscludeBlockquote("target")] }
|
||||
const data = makeComponentData([makePageData("target", target)]) as QuartzComponentProps
|
||||
data.tree = page
|
||||
const seen: string[] = []
|
||||
const root = transformPageContent(cfg, "current" as FullSlug, data, {
|
||||
before: [(r) => seen.push(`before:${text(r).includes("Target content")}`)],
|
||||
treeTransforms: [(r) => seen.push(`tree:${text(r).includes("Target content")}`)],
|
||||
after: [
|
||||
(r) => {
|
||||
seen.push(`after:${text(r).includes("Target content")}`)
|
||||
r.children = [{ type: "text", value: "replaced" }]
|
||||
},
|
||||
],
|
||||
})
|
||||
assert.deepStrictEqual(seen, ["before:false", "tree:true", "after:true"])
|
||||
assert.strictEqual(text(root), "replaced")
|
||||
// the page's own tree is untouched
|
||||
assert.ok(text(page).includes("transclude"))
|
||||
})
|
||||
|
||||
test("a before transform can swap in content that then gets transclusions inlined", () => {
|
||||
const data = makeComponentData([makePageData("target", target)]) as QuartzComponentProps
|
||||
data.tree = { type: "root", children: [{ type: "text", value: "placeholder" }] } as Root
|
||||
const root = transformPageContent(cfg, "current" as FullSlug, data, {
|
||||
before: [(r) => (r.children = [makeTranscludeBlockquote("target")])],
|
||||
treeTransforms: [],
|
||||
after: [],
|
||||
})
|
||||
assert.ok(text(root).includes("Target content"))
|
||||
})
|
||||
|
||||
test("a plain list is the page types' treeTransforms", () => {
|
||||
const data = makeComponentData([]) as QuartzComponentProps
|
||||
data.tree = { type: "root", children: [] } as Root
|
||||
const root = transformPageContent(cfg, "current" as FullSlug, data, [
|
||||
(r) => r.children.push({ type: "text", value: "x" }),
|
||||
])
|
||||
assert.strictEqual(text(root), "x")
|
||||
})
|
||||
})
|
||||
|
||||
describe("pageResources", () => {
|
||||
const emptyResources: StaticResources = {
|
||||
css: [],
|
||||
@@ -329,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,14 +7,21 @@ 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"
|
||||
import { i18n } from "../i18n"
|
||||
import { styleText } from "util"
|
||||
import { resolveFrame } from "./frames"
|
||||
import type { TreeTransform } from "../plugins/types"
|
||||
import type { PageTreeTransforms, TreeTransform } from "../plugins/types"
|
||||
import { blockOf, createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
import type { BuildCtx } from "../util/ctx"
|
||||
|
||||
interface RenderComponents {
|
||||
@@ -50,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,
|
||||
@@ -101,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: [
|
||||
@@ -138,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,
|
||||
@@ -146,6 +232,9 @@ export function renderTranscludes(
|
||||
componentData: QuartzComponentProps,
|
||||
visited: Set<FullSlug>,
|
||||
) {
|
||||
// a prefix per transclusion, unique on the page, for the ids inside it
|
||||
const scopeFor = createIdScopes()
|
||||
|
||||
// Walk the tree manually instead of using visit() so we can track the
|
||||
// ancestor chain for cycle detection. visit() runs the callback before
|
||||
// descending into replaced children, so a Set-based guard there falsely
|
||||
@@ -168,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(
|
||||
@@ -210,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") {
|
||||
@@ -223,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
|
||||
@@ -244,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))
|
||||
|
||||
@@ -264,60 +356,32 @@ export function renderTranscludes(
|
||||
continue
|
||||
}
|
||||
|
||||
el.children = [
|
||||
...(page.htmlAst.children.slice(startIdx, endIdx) 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 = [
|
||||
{
|
||||
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(
|
||||
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),
|
||||
),
|
||||
{
|
||||
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(),
|
||||
)
|
||||
}
|
||||
|
||||
// Recurse into the replaced children to resolve nested transclusions,
|
||||
// then remove from visited so sibling embeds of the same target work.
|
||||
walk(el)
|
||||
// its ids (headings, footnotes) are unique on the page, and links inside it go to them
|
||||
scopeTranscludedIds(el, scopeFor(transcludeTarget), inner.properties?.href as string)
|
||||
visited.delete(transcludeTarget)
|
||||
}
|
||||
}
|
||||
@@ -325,26 +389,48 @@ export function renderTranscludes(
|
||||
walk(root)
|
||||
}
|
||||
|
||||
/**
|
||||
* A page's content as it is rendered: a copy of its tree with the transformers' `before`
|
||||
* transforms applied, transclusions inlined, then the page types' `treeTransforms` and the
|
||||
* transformers' `after` transforms applied.
|
||||
*/
|
||||
export function transformPageContent(
|
||||
cfg: GlobalConfiguration,
|
||||
slug: FullSlug,
|
||||
componentData: QuartzComponentProps,
|
||||
transforms?: TreeTransform[] | PageTreeTransforms,
|
||||
): Root {
|
||||
const { before, treeTransforms, after } = Array.isArray(transforms)
|
||||
? { before: [], treeTransforms: transforms, after: [] }
|
||||
: (transforms ?? { before: [], treeTransforms: [], after: [] })
|
||||
|
||||
// make a deep copy of the tree so we don't remove the transclusion references
|
||||
// for the file cached in contentMap in build.ts
|
||||
const root = clone(componentData.tree) as Root
|
||||
|
||||
// transformers' render-time transforms that need the content before it is filled in
|
||||
for (const transform of before) transform(root, slug, componentData)
|
||||
|
||||
const visited = new Set<FullSlug>([slug])
|
||||
renderTranscludes(root, cfg, slug, componentData, visited)
|
||||
|
||||
// Run plugin-provided tree transforms (e.g. resolving inline bases codeblocks)
|
||||
for (const transform of treeTransforms) transform(root, slug, componentData)
|
||||
|
||||
// transformers' render-time transforms of the finished content (e.g. encrypting it)
|
||||
for (const transform of after) transform(root, slug, componentData)
|
||||
return root
|
||||
}
|
||||
|
||||
export function renderPage(
|
||||
cfg: GlobalConfiguration,
|
||||
slug: FullSlug,
|
||||
componentData: QuartzComponentProps,
|
||||
components: RenderComponents,
|
||||
pageResources: StaticResources,
|
||||
treeTransforms?: TreeTransform[],
|
||||
transforms?: TreeTransform[] | PageTreeTransforms,
|
||||
): string {
|
||||
// make a deep copy of the tree so we don't remove the transclusion references
|
||||
// for the file cached in contentMap in build.ts
|
||||
const root = clone(componentData.tree) as Root
|
||||
const visited = new Set<FullSlug>([slug])
|
||||
renderTranscludes(root, cfg, slug, componentData, visited)
|
||||
|
||||
// Run plugin-provided tree transforms (e.g. resolving inline bases codeblocks)
|
||||
if (treeTransforms) {
|
||||
for (const transform of treeTransforms) {
|
||||
transform(root, slug, componentData)
|
||||
}
|
||||
}
|
||||
const root = transformPageContent(cfg, slug, componentData, transforms)
|
||||
|
||||
// set componentData.tree to the edited html that has transclusions rendered
|
||||
componentData.tree = root
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Where a popover goes, and how far its content scrolls to show a heading. Kept out of
|
||||
* popover.inline.ts so tests can import them.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The popover's inline style for a position from floating-ui's `fixed` strategy. The
|
||||
* position is set here, not left to stylesheets: Obsidian's app.css, which quartz-themes-core
|
||||
* bundles for Obsidian themes, makes `.popover` `position: absolute`, and the viewport
|
||||
* coordinates then landed the popover a page's scroll above its link.
|
||||
*/
|
||||
export function popoverPlacement(x: number, y: number) {
|
||||
return {
|
||||
position: "fixed",
|
||||
top: "0",
|
||||
left: "0",
|
||||
transform: `translate(${x.toFixed()}px, ${y.toFixed()}px)`,
|
||||
}
|
||||
}
|
||||
|
||||
interface Box {
|
||||
getBoundingClientRect(): { top: number }
|
||||
}
|
||||
|
||||
/**
|
||||
* The scrollTop that shows `target` `buffer` px below the top of `inner`, measured on screen:
|
||||
* `offsetTop` is relative to the nearest positioned ancestor, which a theme can put inside the
|
||||
* popover (Obsidian themes position `.markdown-preview-view`).
|
||||
*/
|
||||
export function scrollTopFor(inner: Box & { scrollTop: number }, target: Box, buffer = 12) {
|
||||
return (
|
||||
target.getBoundingClientRect().top -
|
||||
inner.getBoundingClientRect().top +
|
||||
inner.scrollTop -
|
||||
buffer
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
|
||||
import { normalizeRelativeURLs } from "../../util/path"
|
||||
import { fetchCanonical } from "./util"
|
||||
import { popoverPlacement, scrollTopFor } from "./popover-layout"
|
||||
|
||||
const p = new DOMParser()
|
||||
let activeAnchor: HTMLAnchorElement | null = null
|
||||
@@ -19,9 +20,7 @@ async function mouseEnterHandler(
|
||||
strategy: "fixed",
|
||||
middleware: [inline({ x: clientX, y: clientY }), shift(), flip()],
|
||||
})
|
||||
Object.assign(popoverElement.style, {
|
||||
transform: `translate(${x.toFixed()}px, ${y.toFixed()}px)`,
|
||||
})
|
||||
Object.assign(popoverElement.style, popoverPlacement(x, y))
|
||||
}
|
||||
|
||||
function showPopover(popoverElement: HTMLElement) {
|
||||
@@ -32,11 +31,12 @@ 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
|
||||
inner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
|
||||
inner.scroll({ top: scrollTopFor(inner, heading), behavior: "instant" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { popoverPlacement, scrollTopFor } from "./popover-layout"
|
||||
|
||||
type ScrollArg = { top: number; behavior?: ScrollBehavior }
|
||||
// a heading `offsetTop` px from the top of the popover's content (not scrolled)
|
||||
type FakeHeading = { offsetTop: number }
|
||||
const box = (top: number) => ({ getBoundingClientRect: () => ({ top }) })
|
||||
|
||||
interface FakePopoverInner {
|
||||
scrollTop: number
|
||||
getBoundingClientRect: () => { top: number }
|
||||
scroll: (arg: ScrollArg) => void
|
||||
querySelector: (sel: string) => FakeHeading | null
|
||||
_scrolled: ScrollArg | null
|
||||
@@ -25,6 +30,8 @@ interface FakePopoverElement {
|
||||
|
||||
function makeInner(heading: FakeHeading | null = null): FakePopoverInner {
|
||||
const inner: FakePopoverInner = {
|
||||
scrollTop: 0,
|
||||
getBoundingClientRect: () => ({ top: 0 }),
|
||||
scroll(arg) {
|
||||
this._scrolled = arg
|
||||
},
|
||||
@@ -84,7 +91,7 @@ function fixedShowPopover(
|
||||
const targetAnchor = `#popover-internal-${hash.slice(1)}`
|
||||
const heading = inner.querySelector(targetAnchor)
|
||||
if (heading) {
|
||||
inner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
|
||||
inner.scroll({ top: scrollTopFor(inner, box(heading.offsetTop)), behavior: "instant" })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,7 +114,7 @@ describe("showPopover on cache-hit with hash", () => {
|
||||
assert.deepStrictEqual(
|
||||
inner._scrolled,
|
||||
{ top: 200 - 12, behavior: "instant" },
|
||||
"scroll must target heading.offsetTop - 12",
|
||||
"scroll must show the heading 12px below the top",
|
||||
)
|
||||
assert.deepStrictEqual(inner._selectorsQueried, ["#popover-internal-plugins"])
|
||||
})
|
||||
@@ -221,3 +228,25 @@ describe("bfcache popover cleanup", () => {
|
||||
assert.strictEqual(queried, false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("popover layout", () => {
|
||||
test("the popover is placed with position: fixed, which its coordinates are for", () => {
|
||||
// Obsidian's app.css (quartz-themes-core) sets .popover { position: absolute }
|
||||
assert.deepStrictEqual(popoverPlacement(764.4, -4.6), {
|
||||
position: "fixed",
|
||||
top: "0",
|
||||
left: "0",
|
||||
transform: "translate(764px, -5px)",
|
||||
})
|
||||
})
|
||||
|
||||
test("scrolls to a heading by its position on screen, not its offsetTop", () => {
|
||||
// the content box starts 100px into the popover (an Obsidian theme positions
|
||||
// .markdown-preview-view, so the heading's offsetTop counts from there)
|
||||
const inner = { scrollTop: 0, ...box(200) }
|
||||
assert.strictEqual(scrollTopFor(inner, box(200 + 100 + 5944)), 100 + 5944 - 12)
|
||||
// already scrolled: the same target
|
||||
const scrolled = { scrollTop: 3000, ...box(200) }
|
||||
assert.strictEqual(scrollTopFor(scrolled, box(200 + 100 + 5944 - 3000)), 100 + 5944 - 12)
|
||||
})
|
||||
})
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import type { Element, ElementContent } from "hast"
|
||||
import { blockOf, createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
|
||||
const h = (
|
||||
tagName: string,
|
||||
properties: Element["properties"] = {},
|
||||
children: ElementContent[] = [],
|
||||
): Element => ({ type: "element", tagName, properties, children })
|
||||
const text = (value: string): ElementContent => ({ type: "text", value })
|
||||
|
||||
describe("createIdScopes", () => {
|
||||
test("a prefix per transclusion, unique on the page", () => {
|
||||
const scope = createIdScopes()
|
||||
assert.strictEqual(scope("notes/Source"), "source--")
|
||||
assert.strictEqual(scope("notes/source"), "source-2--")
|
||||
assert.strictEqual(scope("other"), "other--")
|
||||
})
|
||||
})
|
||||
|
||||
describe("scopeTranscludedIds", () => {
|
||||
test("prefixes ids and the references to them inside the transclusion", () => {
|
||||
const el = h("div", { className: ["transclude"] }, [
|
||||
h("h2", { id: "details" }, [text("Details")]),
|
||||
h("p", {}, [
|
||||
h("a", { href: "#details" }, [text("jump")]),
|
||||
h("sup", {}, [
|
||||
h(
|
||||
"a",
|
||||
{
|
||||
href: "#user-content-fn-1",
|
||||
id: "user-content-fnref-1",
|
||||
dataFootnoteRef: "",
|
||||
ariaDescribedBy: ["footnote-label"],
|
||||
},
|
||||
[text("1")],
|
||||
),
|
||||
]),
|
||||
]),
|
||||
h("section", { dataFootnotes: "" }, [
|
||||
h("h2", { id: "footnote-label" }, [text("Footnotes")]),
|
||||
h("ol", {}, [
|
||||
h("li", { id: "user-content-fn-1" }, [
|
||||
h("a", { href: "#user-content-fnref-1" }, [text("↩")]),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
scopeTranscludedIds(el, "source--", "./source")
|
||||
const [heading, para, section] = el.children as Element[]
|
||||
assert.strictEqual(heading!.properties.id, "source--details")
|
||||
const [jump, sup] = para!.children as Element[]
|
||||
assert.strictEqual(jump!.properties.href, "#source--details")
|
||||
const ref = (sup!.children[0] as Element).properties
|
||||
assert.strictEqual(ref.href, "#source--user-content-fn-1")
|
||||
assert.strictEqual(ref.id, "source--user-content-fnref-1")
|
||||
assert.deepStrictEqual(ref.ariaDescribedBy, ["source--footnote-label"])
|
||||
const li = (section!.children[1] as Element).children[0] as Element
|
||||
assert.strictEqual(li.properties.id, "source--user-content-fn-1")
|
||||
assert.strictEqual((li.children[0] as Element).properties.href, "#source--user-content-fnref-1")
|
||||
})
|
||||
|
||||
test("a same-page link whose target isn't in the transclusion goes to the transcluded page", () => {
|
||||
const el = h("div", {}, [h("a", { href: "#elsewhere" }, [text("x")])])
|
||||
scopeTranscludedIds(el, "source--", "./source#overview")
|
||||
assert.strictEqual((el.children[0] as Element).properties.href, "./source#elsewhere")
|
||||
})
|
||||
|
||||
test("leaves inline svg and math alone, and other links", () => {
|
||||
const el = h("div", {}, [
|
||||
h("svg", {}, [h("linearGradient", { id: "grad" }), h("rect", { fill: "url(#grad)" })]),
|
||||
h("a", { href: "./other#x" }, [text("x")]),
|
||||
])
|
||||
scopeTranscludedIds(el, "source--", "./source")
|
||||
const svg = el.children[0] as Element
|
||||
assert.strictEqual((svg.children[0] as Element).properties.id, "grad")
|
||||
assert.strictEqual((el.children[1] as Element).properties.href, "./other#x")
|
||||
})
|
||||
})
|
||||
|
||||
describe("sliceWithFootnotes", () => {
|
||||
const page: ElementContent[] = [
|
||||
h("h2", { id: "a" }, [text("A")]),
|
||||
h("p", {}, [h("a", { href: "#user-content-fn-2", dataFootnoteRef: "" }, [text("2")])]),
|
||||
h("h2", { id: "b" }, [text("B")]),
|
||||
h("p", {}, [h("a", { href: "#user-content-fn-1", dataFootnoteRef: "" }, [text("1")])]),
|
||||
h("section", { dataFootnotes: "", className: ["footnotes"] }, [
|
||||
h("ol", {}, [h("li", { id: "user-content-fn-1" }), h("li", { id: "user-content-fn-2" })]),
|
||||
]),
|
||||
]
|
||||
const footnoteIds = (nodes: ElementContent[]) =>
|
||||
nodes
|
||||
.filter((n): n is Element => n.type === "element" && n.tagName === "section")
|
||||
.flatMap((s) =>
|
||||
((s.children[0] as Element).children as Element[]).map((li) => li.properties.id),
|
||||
)
|
||||
|
||||
test("the last section gets only its own footnotes, not the whole footnotes section", () => {
|
||||
assert.deepStrictEqual(footnoteIds(sliceWithFootnotes(page, 2, undefined)), [
|
||||
"user-content-fn-1",
|
||||
])
|
||||
})
|
||||
|
||||
test("an earlier section gets its footnotes too", () => {
|
||||
const slice = sliceWithFootnotes(page, 0, 2)
|
||||
assert.strictEqual(slice.length, 3)
|
||||
assert.deepStrictEqual(footnoteIds(slice), ["user-content-fn-2"])
|
||||
})
|
||||
|
||||
test("a section without footnote references gets no footnotes section", () => {
|
||||
const plain = [h("h2", { id: "c" }), h("p"), page[4]!]
|
||||
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"])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { Element, ElementContent, Root } from "hast"
|
||||
|
||||
/**
|
||||
* Transcluded content is a copy of another page's HTML, ids included: two transclusions (or a
|
||||
* transclusion and its host) share heading ids and footnote ids (`user-content-fn-1`), so a
|
||||
* footnote reference or a `[[#Heading]]` link jumps to whichever element comes first on the page.
|
||||
* Obsidian resolves each embed on its own.
|
||||
*
|
||||
* {@link scopeTranscludedIds} gives the ids inside one transclusion a prefix, unique on the page,
|
||||
* and rewrites the references inside it to match. The host's ids stay as they are. A same-page
|
||||
* link (`#id`) whose target isn't in the transclusion (a heading slice that doesn't hold it) links
|
||||
* to the id on the transcluded page instead.
|
||||
*/
|
||||
|
||||
/** Space-separated id references (hast property names). */
|
||||
const ID_LIST_PROPERTIES = [
|
||||
"ariaDescribedBy",
|
||||
"ariaLabelledBy",
|
||||
"ariaControls",
|
||||
"ariaOwns",
|
||||
"ariaDetails",
|
||||
"ariaFlowTo",
|
||||
"htmlFor",
|
||||
"headers",
|
||||
] as const
|
||||
|
||||
/** Subtrees whose ids are referenced from inside them in ways we don't rewrite (`url(#id)`). */
|
||||
const OPAQUE = new Set(["svg", "math"])
|
||||
|
||||
function forEachElement(node: Element | Root, fn: (el: Element) => void) {
|
||||
for (const child of node.children) {
|
||||
if (child.type !== "element") continue
|
||||
fn(child)
|
||||
if (!OPAQUE.has(child.tagName)) forEachElement(child, fn)
|
||||
}
|
||||
}
|
||||
|
||||
/** Per page render: a prefix for each transclusion, unique on the page. */
|
||||
export function createIdScopes(): (target: string) => string {
|
||||
const used = new Map<string, number>()
|
||||
return (target) => {
|
||||
const base =
|
||||
(target.split("/").pop() ?? target)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "") || "transclude"
|
||||
const count = (used.get(base) ?? 0) + 1
|
||||
used.set(base, count)
|
||||
return count === 1 ? `${base}--` : `${base}-${count}--`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefixes the ids inside the transclusion `el` with `prefix` and rewrites references to them
|
||||
* inside it. `sourceHref` is the link to the transcluded page (relative to the host), for
|
||||
* same-page links whose target isn't in the transclusion.
|
||||
*/
|
||||
export function scopeTranscludedIds(el: Element, prefix: string, sourceHref?: string) {
|
||||
const ids = new Set<string>()
|
||||
forEachElement(el, (node) => {
|
||||
const id = node.properties?.id
|
||||
if (typeof id === "string" && id) ids.add(id)
|
||||
})
|
||||
|
||||
const pageHref = typeof sourceHref === "string" ? sourceHref.split("#")[0] : undefined
|
||||
const scoped = (id: string) => (ids.has(id) ? `${prefix}${id}` : id)
|
||||
|
||||
forEachElement(el, (node) => {
|
||||
const props = node.properties
|
||||
if (!props) return
|
||||
if (typeof props.id === "string" && ids.has(props.id)) props.id = `${prefix}${props.id}`
|
||||
|
||||
const href = props.href
|
||||
if (typeof href === "string" && href.startsWith("#") && href.length > 1) {
|
||||
let target = href.slice(1)
|
||||
try {
|
||||
target = decodeURIComponent(target)
|
||||
} catch {
|
||||
// keep as written
|
||||
}
|
||||
if (ids.has(target)) props.href = `#${prefix}${target}`
|
||||
else if (pageHref) props.href = `${pageHref}${href}`
|
||||
}
|
||||
|
||||
const record = props as Record<string, unknown>
|
||||
for (const name of ID_LIST_PROPERTIES) {
|
||||
const value = record[name]
|
||||
if (Array.isArray(value)) record[name] = value.map((token) => scoped(String(token)))
|
||||
else if (typeof value === "string") record[name] = value.split(/\s+/).map(scoped).join(" ")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[]
|
||||
return props.dataFootnotes !== undefined || classes.includes("footnotes")
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, in its block
|
||||
* wrapper if it has one).
|
||||
*/
|
||||
export function sliceWithFootnotes(
|
||||
pageChildren: ElementContent[],
|
||||
start: number,
|
||||
end: number | undefined,
|
||||
): ElementContent[] {
|
||||
const slice = pageChildren.slice(start, end).filter((node): boolean => !isFootnotesSection(node))
|
||||
const section = pageChildren.find(isFootnotesSection)
|
||||
if (!section) return slice
|
||||
|
||||
const referenced = new Set<string>()
|
||||
const collect = (node: Element | Root) =>
|
||||
forEachElement(node, (child) => {
|
||||
const href = child.properties?.href
|
||||
if (child.properties?.dataFootnoteRef !== undefined && typeof href === "string")
|
||||
referenced.add(href.replace(/^#/, ""))
|
||||
})
|
||||
for (const node of slice) if (node.type === "element") collect(node as Element)
|
||||
if (referenced.size === 0) return slice
|
||||
|
||||
const copy = structuredClone(section) as Element
|
||||
const keep = (list: Element) => {
|
||||
list.children = list.children.filter(
|
||||
(item) =>
|
||||
item.type !== "element" ||
|
||||
item.tagName !== "li" ||
|
||||
referenced.has(String(item.properties?.id ?? "")),
|
||||
)
|
||||
}
|
||||
forEachElement(copy, (node) => {
|
||||
if (node.tagName === "ol") keep(node)
|
||||
})
|
||||
return [...slice, copy]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { i18n, resolveTranslationLocale } from "./index"
|
||||
|
||||
describe("i18n locale fallback", () => {
|
||||
test("a locale with a translation uses it, whatever its case", (t) => {
|
||||
t.mock.method(console, "warn", () => {})
|
||||
assert.strictEqual(resolveTranslationLocale("de-DE"), "de-DE")
|
||||
assert.strictEqual(resolveTranslationLocale("de-de"), "de-DE")
|
||||
assert.strictEqual(resolveTranslationLocale(undefined), "en-US")
|
||||
})
|
||||
|
||||
test("a locale without one uses the same language, else English, and warns once", (t) => {
|
||||
const warn = t.mock.method(console, "warn", () => {})
|
||||
assert.strictEqual(resolveTranslationLocale("es-MX"), "es-ES")
|
||||
assert.strictEqual(resolveTranslationLocale("es-MX"), "es-ES")
|
||||
assert.strictEqual(resolveTranslationLocale("sv-SE"), "en-US")
|
||||
assert.strictEqual(resolveTranslationLocale("nb"), "nb-NO")
|
||||
assert.strictEqual(warn.mock.callCount(), 3)
|
||||
assert.match(String(warn.mock.calls[0]!.arguments[0]), /no translation for locale "es-MX"/)
|
||||
})
|
||||
|
||||
// used to throw: TRANSLATIONS["sv-SE"] was undefined
|
||||
test("i18n() of a locale without a translation returns one", (t) => {
|
||||
t.mock.method(console, "warn", () => {})
|
||||
assert.strictEqual(i18n("da-DK").pages.error.title, i18n("en-US").pages.error.title)
|
||||
})
|
||||
})
|
||||
+28
-1
@@ -85,6 +85,33 @@ export const TRANSLATIONS = {
|
||||
} as const
|
||||
|
||||
export const defaultTranslation = "en-US"
|
||||
export const i18n = (locale: ValidLocale): Translation => TRANSLATIONS[locale ?? defaultTranslation]
|
||||
|
||||
const warnedLocales = new Set<string>()
|
||||
|
||||
/**
|
||||
* The translation to use for `locale`: its own, else one of the same language (`es-MX` uses
|
||||
* `es-ES`), else English. A locale without a translation used to crash the build
|
||||
* (`TRANSLATIONS[locale]` is undefined); dates and numbers still use the configured locale.
|
||||
*/
|
||||
export function resolveTranslationLocale(locale: string | undefined): ValidLocale {
|
||||
if (!locale) return defaultTranslation
|
||||
const keys = Object.keys(TRANSLATIONS) as ValidLocale[]
|
||||
const exact = keys.find((key) => key.toLowerCase() === locale.toLowerCase())
|
||||
if (exact) return exact
|
||||
const language = locale.split("-")[0]!.toLowerCase()
|
||||
const chosen =
|
||||
keys.find((key) => key.split("-")[0]!.toLowerCase() === language) ?? defaultTranslation
|
||||
if (!warnedLocales.has(locale)) {
|
||||
warnedLocales.add(locale)
|
||||
console.warn(
|
||||
`Quartz has no translation for locale "${locale}"; its text uses ${chosen}. ` +
|
||||
`Dates still use ${locale}. Translations: https://quartz.jzhao.xyz/features/i18n`,
|
||||
)
|
||||
}
|
||||
return chosen
|
||||
}
|
||||
|
||||
export const i18n = (locale: ValidLocale | string | undefined): Translation =>
|
||||
TRANSLATIONS[resolveTranslationLocale(locale)]
|
||||
export type ValidLocale = keyof typeof TRANSLATIONS
|
||||
export type ValidCallout = keyof CalloutTranslation
|
||||
@@ -7,14 +7,27 @@ 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 { buildLayeredCSS, buildUnlayeredCSS, resolveFonts } from "./fonts"
|
||||
import {
|
||||
Links,
|
||||
LinksInstance,
|
||||
markLinksToRemovedPages,
|
||||
markUnpublishedLinks,
|
||||
removedPages,
|
||||
} from "./links"
|
||||
import {
|
||||
buildLayeredCSS,
|
||||
buildUnlayeredCSS,
|
||||
googleFontHref,
|
||||
resolveFontSpecs,
|
||||
resolveFonts,
|
||||
} from "./fonts"
|
||||
import { isContentError } from "../../util/pluginErrors"
|
||||
import { Drafts, isDraft } from "./drafts"
|
||||
import {
|
||||
@@ -28,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 => ({
|
||||
@@ -174,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
|
||||
|
||||
@@ -217,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
|
||||
@@ -331,11 +435,120 @@ describe("links built-in", () => {
|
||||
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
|
||||
})
|
||||
|
||||
// #2725: resolved as Obsidian does (utils 1.3.5)
|
||||
test("a ./ link is in the page's folder, under every strategy", () => {
|
||||
for (const markdownLinkResolution of ["shortest", "absolute", "relative"]) {
|
||||
const { els, file } = run(
|
||||
[a("./index", "index"), a("./sibling")],
|
||||
"folder/special",
|
||||
{ markdownLinkResolution },
|
||||
["index", "folder/index", "folder/special", "folder/sibling", "sibling"],
|
||||
)
|
||||
const [index, sibling] = els.filter((e) => e.tagName === "a")
|
||||
assert.strictEqual(index.properties.href, "./", markdownLinkResolution)
|
||||
assert.strictEqual(index.properties["data-slug"], "folder/index", markdownLinkResolution)
|
||||
assert.strictEqual(sibling.properties["data-slug"], "folder/sibling", markdownLinkResolution)
|
||||
// the folder page, not the home page
|
||||
assert.ok(file.data.links?.includes("folder/" as SimpleSlug), markdownLinkResolution)
|
||||
}
|
||||
})
|
||||
|
||||
test("of several pages with a name, the one under the page's folder, else the shortest path", () => {
|
||||
const allSlugs = [
|
||||
"index",
|
||||
"projects/alpha/index",
|
||||
"projects/alpha/current",
|
||||
"projects/beta/index",
|
||||
"projects/beta/current",
|
||||
]
|
||||
const opts = { markdownLinkResolution: "shortest" }
|
||||
const slugOf = (src: string, target: string) =>
|
||||
run([a(target)], src, opts, allSlugs).els[0]!.properties["data-slug"]
|
||||
// relative-mode vaults write a note in the same folder as a bare name
|
||||
assert.strictEqual(slugOf("projects/alpha/index", "current.md"), "projects/alpha/current")
|
||||
assert.strictEqual(slugOf("projects/beta/index", "current"), "projects/beta/current")
|
||||
// from elsewhere, the shortest path (Obsidian sorts by path length)
|
||||
assert.strictEqual(slugOf("index", "current"), "projects/beta/current")
|
||||
})
|
||||
|
||||
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")
|
||||
// ./ is relative to ceske/page (utils 1.3.5): the same page as ../ceske/cestina
|
||||
assert.strictEqual(cestina.properties.href, "./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")
|
||||
@@ -408,6 +621,83 @@ describe("links built-in", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("pretty links shorten a link whose text is its percent-decoded href (#2643)", () => {
|
||||
const { els } = run(
|
||||
[
|
||||
a("Folder/Name%20With%20Space", "Folder/Name With Space"),
|
||||
a("Ordner/%C3%9Cbersicht", "Ordner/Übersicht"),
|
||||
a("Folder/Name%20With%20Space", "own text"),
|
||||
],
|
||||
"page",
|
||||
{ prettyLinks: true },
|
||||
)
|
||||
const links = els.filter((e) => e.tagName === "a")
|
||||
assert.deepStrictEqual(
|
||||
links.map((e) => (e.children[0] as Text).value),
|
||||
["Name With Space", "Übersicht", "own text"],
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
links.map((e) => (e.properties.className as string[]).includes("alias")),
|
||||
[false, false, true],
|
||||
)
|
||||
})
|
||||
|
||||
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"))
|
||||
@@ -463,6 +753,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([
|
||||
{
|
||||
@@ -621,4 +1004,455 @@ describe("fonts built-in", () => {
|
||||
delete (globalThis as Record<string, unknown>).__quartzFonts
|
||||
}
|
||||
})
|
||||
|
||||
test("the interface and per-heading fonts are loaded from Google Fonts", () => {
|
||||
const href = decodeURIComponent(
|
||||
googleFontHref(
|
||||
resolveFontSpecs(
|
||||
{ interface: "Inter", h1: { name: "Playfair Display", weights: [700] } },
|
||||
{},
|
||||
),
|
||||
),
|
||||
)
|
||||
assert.match(href, /family=Inter:wght@400;600/)
|
||||
assert.match(href, /family=Playfair Display:wght@700/)
|
||||
assert.doesNotMatch(decodeURIComponent(googleFontHref(resolveFontSpecs({}, {}))), /Inter/)
|
||||
const single = (spec: object) =>
|
||||
decodeURIComponent(googleFontHref(resolveFontSpecs({ title: spec as never }, {})))
|
||||
assert.match(single({ name: "Lora", weights: [400] }), /family=Lora&/)
|
||||
assert.match(
|
||||
single({ name: "Lora", weights: [400], includeItalic: true }),
|
||||
/family=Lora:ital@0;1&/,
|
||||
)
|
||||
assert.match(
|
||||
single({ name: "Lora", weights: [700], includeItalic: true }),
|
||||
/family=Lora:ital,wght@0,700;1,700&/,
|
||||
)
|
||||
})
|
||||
|
||||
test("explicit body/interface/code fonts set Obsidian's overrides on body", () => {
|
||||
;(globalThis as Record<string, unknown>).__quartzFonts = {
|
||||
themeName: "Things",
|
||||
fonts: { "--font-text": "Inter", "--font-monospace": "JetBrains Mono" },
|
||||
}
|
||||
try {
|
||||
const opts = { body: "Lora", code: "Fira Code" }
|
||||
const css = buildUnlayeredCSS(resolveFonts(opts, {}), opts, true)
|
||||
assert.match(css, /html body \{[^}]*--font-text-override: Lora;/)
|
||||
assert.match(css, /html body \{[^}]*--font-monospace-override: Fira Code;/)
|
||||
assert.doesNotMatch(css, /--font-interface-override/)
|
||||
// a theme with themeFonts: false registers no fonts, but still reads the overrides
|
||||
assert.match(
|
||||
buildUnlayeredCSS(resolveFonts({ interface: "Inter" }, {}), { interface: "Inter" }, false),
|
||||
/html body \{\n --font-interface-override: Inter;\n\}/,
|
||||
)
|
||||
assert.doesNotMatch(buildUnlayeredCSS(resolveFonts({}, {}), {}, true), /override/)
|
||||
} finally {
|
||||
delete (globalThis as Record<string, unknown>).__quartzFonts
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ import { QuartzEmitterPlugin } from "../types"
|
||||
|
||||
const HEADING_LEVELS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const
|
||||
type HeadingLevel = (typeof HEADING_LEVELS)[number]
|
||||
type FontRole = "title" | "header" | "body" | "code"
|
||||
type FontRole = "title" | "header" | "body" | "code" | "interface"
|
||||
|
||||
export const SELF_HOSTED_STYLESHEET = "static/fonts/quartz-fonts.css"
|
||||
export const QUARTZ_DEFAULT_HEADER = "Schibsted Grotesk"
|
||||
@@ -40,12 +40,14 @@ const DEFAULT_WEIGHTS: Record<FontRole, number[]> = {
|
||||
header: [400, 700],
|
||||
body: [400, 600],
|
||||
code: [400, 600],
|
||||
interface: [400, 600],
|
||||
}
|
||||
const DEFAULT_ITALIC: Record<FontRole, boolean> = {
|
||||
title: false,
|
||||
header: false,
|
||||
body: true,
|
||||
code: false,
|
||||
interface: false,
|
||||
}
|
||||
|
||||
/** Option defaults; every key is listed so unknown options can be reported. */
|
||||
@@ -107,13 +109,20 @@ export function readConfiguredTypography(ctx: BuildCtx | undefined): ConfiguredT
|
||||
return result
|
||||
}
|
||||
|
||||
/** Options first, then `configuration.theme.typography`, then Quartz's defaults. */
|
||||
/**
|
||||
* Options first, then `configuration.theme.typography`, then Quartz's defaults. The interface
|
||||
* and per-heading fonts exist only as options.
|
||||
*/
|
||||
export function resolveFontSpecs(options: FontsConfig, typography: ConfiguredTypography) {
|
||||
return {
|
||||
title: options.title ?? typography.title,
|
||||
header: options.header ?? typography.header ?? QUARTZ_DEFAULT_HEADER,
|
||||
body: options.body ?? typography.body ?? QUARTZ_DEFAULT_BODY,
|
||||
code: options.code ?? typography.code ?? QUARTZ_DEFAULT_CODE,
|
||||
interface: options.interface,
|
||||
headings: HEADING_LEVELS.map((l) => options[l]).filter(
|
||||
(spec): spec is FontSpecification => spec !== undefined,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,20 +149,16 @@ function mergeInto(map: Map<string, MergedFont>, role: FontRole, spec: FontSpeci
|
||||
}
|
||||
}
|
||||
|
||||
/** Google Fonts css2 `family` value; a single weight still names its axis unless it's 400. */
|
||||
function formatMerged(entry: MergedFont): string {
|
||||
const weights = [...entry.weights].sort((a, b) => a - b)
|
||||
const features: string[] = []
|
||||
if (entry.italic) features.push("ital")
|
||||
if (weights.length > 1) {
|
||||
const spec = entry.italic
|
||||
? weights
|
||||
.flatMap((w) => [`0,${w}`, `1,${w}`])
|
||||
.sort()
|
||||
.join(";")
|
||||
: weights.join(";")
|
||||
features.push(`wght@${spec}`)
|
||||
const defaultWeight = weights.length === 1 && weights[0] === 400
|
||||
if (entry.italic) {
|
||||
if (defaultWeight) return `${entry.name}:ital@0;1`
|
||||
const tuples = [...weights.map((w) => `0,${w}`), ...weights.map((w) => `1,${w}`)]
|
||||
return `${entry.name}:ital,wght@${tuples.join(";")}`
|
||||
}
|
||||
return features.length > 0 ? `${entry.name}:${features.join(",")}` : entry.name
|
||||
return defaultWeight ? entry.name : `${entry.name}:wght@${weights.join(";")}`
|
||||
}
|
||||
|
||||
export function googleFontHref(fonts: ReturnType<typeof resolveFontSpecs>): string {
|
||||
@@ -162,6 +167,8 @@ export function googleFontHref(fonts: ReturnType<typeof resolveFontSpecs>): stri
|
||||
mergeInto(merged, "body", fonts.body)
|
||||
mergeInto(merged, "code", fonts.code)
|
||||
if (fonts.title) mergeInto(merged, "title", fonts.title)
|
||||
if (fonts.interface) mergeInto(merged, "interface", fonts.interface)
|
||||
for (const spec of fonts.headings) mergeInto(merged, "header", spec)
|
||||
const params = [...merged.values()]
|
||||
.map(formatMerged)
|
||||
.map((f) => `family=${encodeURIComponent(f)}`)
|
||||
@@ -218,6 +225,7 @@ function validate(options: FontsConfig) {
|
||||
check("header", options.header, "header")
|
||||
check("body", options.body, "body")
|
||||
check("code", options.code, "code")
|
||||
check("interface", options.interface, "interface")
|
||||
for (const level of HEADING_LEVELS) check(level, options[level], "header")
|
||||
}
|
||||
|
||||
@@ -310,15 +318,37 @@ export function buildLayeredCSS(fonts: ResolvedFonts, options: FontsConfig, them
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
/** Unlayered heading fonts beat every layer; with a theme, only explicitly configured ones. */
|
||||
/** Obsidian's override variables for the body, interface and code roles. */
|
||||
const OBSIDIAN_OVERRIDES: [string, "body" | "interface" | "code"][] = [
|
||||
["--font-text-override", "body"],
|
||||
["--font-interface-override", "interface"],
|
||||
["--font-monospace-override", "code"],
|
||||
]
|
||||
|
||||
/**
|
||||
* Unlayered heading fonts beat every layer; with a theme, only explicitly configured ones.
|
||||
*
|
||||
* Explicitly configured body/interface/code fonts also go to Obsidian's `--font-*-override`
|
||||
* variables on `body`: an Obsidian theme's app.css sets `--font-text` and friends on `body`
|
||||
* itself, so the `:root` values from {@link buildLayeredCSS} never reach the page. This holds
|
||||
* whether or not the theme registers its fonts (with `themeFonts: false` it maps the overrides
|
||||
* to Quartz's font variables on `body`), so the selector is `html body`, which wins over a
|
||||
* theme's `body` rule regardless of stylesheet order. Without an Obsidian theme nothing reads
|
||||
* the overrides.
|
||||
*/
|
||||
export function buildUnlayeredCSS(
|
||||
fonts: ResolvedFonts,
|
||||
options: FontsConfig,
|
||||
themeActive: boolean,
|
||||
) {
|
||||
return HEADING_LEVELS.filter((l) => !themeActive || isExplicit(options, l))
|
||||
.map((l) => `${l} { font-family: ${fonts[l]}; }`)
|
||||
.join("\n")
|
||||
const rules = HEADING_LEVELS.filter((l) => !themeActive || isExplicit(options, l)).map(
|
||||
(l) => `${l} { font-family: ${fonts[l]}; }`,
|
||||
)
|
||||
const overrides = OBSIDIAN_OVERRIDES.filter(([, key]) => options[key] !== undefined).map(
|
||||
([name, key]) => ` ${name}: ${fonts[key]};`,
|
||||
)
|
||||
if (overrides.length > 0) rules.push(["html body {", ...overrides, "}"].join("\n"))
|
||||
return rules.join("\n")
|
||||
}
|
||||
|
||||
// ---- plugin ------------------------------------------------------------------------
|
||||
@@ -345,9 +375,9 @@ export const Fonts: QuartzEmitterPlugin<FontsConfig> = (userOpts) => {
|
||||
const theme = ctx?.cfg?.configuration?.theme as
|
||||
{ cdnCaching?: boolean; fontOrigin?: string } | undefined
|
||||
const headLinksTypography = theme?.cdnCaching === true && theme?.fontOrigin === "googleFonts"
|
||||
const overridesTypography = (["title", "header", "body", "code"] as const).some(
|
||||
(k) => options[k] !== undefined,
|
||||
)
|
||||
const overridesTypography = (
|
||||
["title", "header", "body", "code", "interface", ...HEADING_LEVELS] as const
|
||||
).some((k) => options[k] !== undefined)
|
||||
if (options.fontOrigin === "googleFonts" && (!headLinksTypography || overridesTypography)) {
|
||||
const href = googleFontHref(resolveFontSpecs(options, typography))
|
||||
additionalHead = [
|
||||
|
||||
@@ -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,18 @@ 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 {
|
||||
return decodeURI(href)
|
||||
} catch {
|
||||
return href
|
||||
}
|
||||
}
|
||||
|
||||
const EXTERNAL_ICON_PATH =
|
||||
"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"
|
||||
@@ -63,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 [
|
||||
() => {
|
||||
@@ -106,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) {
|
||||
@@ -131,12 +311,14 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
})
|
||||
}
|
||||
|
||||
// link text differs from the href → it's an alias ("[[note|text]]")
|
||||
// link text differs from the href → it's an alias ("[[note|text]]"). The href is
|
||||
// percent-encoded by now ("a%20b" for "a b"), so it is compared decoded too (#2643)
|
||||
const firstChild = node.children[0]
|
||||
if (
|
||||
node.children.length === 1 &&
|
||||
firstChild?.type === "text" &&
|
||||
firstChild.value !== dest
|
||||
firstChild.value !== dest &&
|
||||
firstChild.value !== decodedHref(dest)
|
||||
) {
|
||||
classes.push("alias")
|
||||
}
|
||||
@@ -153,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
|
||||
}
|
||||
@@ -228,4 +410,5 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
]
|
||||
},
|
||||
}
|
||||
return instance
|
||||
}
|
||||
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user