Compare commits

..
Author SHA1 Message Date
saberzero1 c92fed97c0 fix(popover): place popovers with position: fixed, and scroll to headings by their position on screen 2026-11-30 14:14:04 +01:00
Emile Bangma 79d3ea9875 fix(cli): reinstalling a pinned npm plugin keeps its quartz.lock.json entry 2026-11-30 13:38:13 +01:00
saberzero1 f2015a4c76 fix(cli): reinstalling a pinned npm plugin keeps its quartz.lock.json entry 2026-11-30 12:10:57 +01:00
Emile Bangma 2e69d52f76 Merge pull request #2728 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-30 12:03:53 +01:00
github-actions[bot] 8c81436188 chore: release Quartz 2026-11-30 10:40:15 +00:00
Emile Bangma fe47fb1239 Merge pull request #2733 from jackyzha0/dev-mode/lockfile-next-to-config
feat(plugins): quartz.lock.json next to the config; --config on plugin commands
2026-11-30 11:39:54 +01:00
Emile Bangma fb4dbab487 Merge pull request #2732 from jackyzha0/dev-mode/npm-plugin-pins
feat(plugins): pin npm plugins outside package.json in quartz.lock.json
2026-11-30 11:37:45 +01:00
Emile Bangma 9ca6f4ee69 Merge pull request #2731 from jackyzha0/dev-mode/extends-stable
feat(config): extends is stable for default and local paths; reserve $ keys
2026-11-30 11:37:30 +01:00
saberzero1 cc8d104cc7 feat(plugins): quartz.lock.json next to the config; --config on plugin commands
The lockfile is read and written next to the config file in use, and
every plugin command takes --config/-C like build. A config elsewhere
keeps using an existing lockfile in Quartz's folder until its own
folder has one. Plugin commands also edit the config chosen with
QUARTZ_CONFIG_PATH instead of ./quartz.config.yaml.
2026-11-30 02:51:45 +01:00
saberzero1 9ebfc67c1b feat(config): extends is stable for default and local paths; reserve $ keys
Keys starting with $ are an error in every file of an extends chain (the
top-level $schema aside), so merge operators can be added later without
changing existing configs. https:// URLs stay experimental.

A ConfigExtendsError from a command now prints just its message instead of
the CLI usage text.
2026-11-30 01:49:44 +01:00
29 changed files with 459 additions and 40 deletions

No files matched your search

@@ -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.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
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.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
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
View File
@@ -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.
+12
View File
@@ -1,5 +1,17 @@
# @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
+7
View File
@@ -65,6 +65,13 @@ By default Quartz loads `quartz.config.yaml` from the current working directory.
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.)
```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.
+2
View File
@@ -11,6 +11,8 @@ Quartz plugins come from two kinds of sources:
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
+6 -3
View File
@@ -44,17 +44,20 @@ plugins:
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. An empty file (or one with only comments) is an empty config, and `extends: []` extends nothing.
- A list stacks presets: each file in it adds its own changes. Quartz puts every file of the `extends` chain in one line and applies each once, its bases before it: the list's entries in order, each after the bases it extends, and your file last. A base that several entries share (usually `default`) is applied once, at its first appearance. So with `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, the order is `default` → `a.yaml` → `b.yaml` → your file: what `a.yaml` changes stays unless `b.yaml` changes the same thing (later entries win), and your file wins over both. An entry that doesn't extend the shared base is applied before it if it comes first, so the base's settings win over it; make such a preset extend `default` too, or list it after the others.
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
- **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.
- 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.
- `npx quartz build --serve` also rebuilds when a local file your config extends changes.
- `npx quartz plugin` commands and `npx quartz info` read the merged configuration, as the build does: `plugin list`, `status`, `doctor`, `install` and `prune` see the plugins your bases configure. Commands that change plugins only ever write your own file, never the merged result: `enable`, `disable` and `config --set` add or change your entry for the plugin (`- source: …` with just that change), `config --unset` removes your value and, when a base sets the option, sets it to `null` so the plugin's default applies, and `add` appends a full entry. `remove` refuses a plugin that a base configures (it can't be removed from your file); disable it instead.
> [!warning] Experimental
> `extends` is experimental: the merge rules may still change.
> [!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
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@jackyzha0/quartz",
"version": "5.3.1",
"version": "5.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@jackyzha0/quartz",
"version": "5.3.1",
"version": "5.4.0",
"license": "MIT",
"dependencies": {
"@clack/prompts": "^1.8.0",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "@jackyzha0/quartz",
"description": "🌱 publish your digital garden and notes as a website",
"private": true,
"version": "5.3.1",
"version": "5.4.0",
"type": "module",
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
"license": "MIT",
+31
View File
@@ -7,6 +7,8 @@ if (major < 22 || (major === 22 && minor < 22)) {
)
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
+3
View File
@@ -0,0 +1,3 @@
export const LOCKFILE_NAME: string
export function resolveLockfilePath(configPath: string, cwd?: string): string
export function currentLockfilePath(cwd?: string): string
+29
View File
@@ -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)
}
+50
View File
@@ -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"))
})
})
+5
View File
@@ -34,6 +34,11 @@ export function installNpmPlugin(
},
): 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: {
+17
View File
@@ -254,6 +254,23 @@ export function removeNpmPlugin(name, pluginsDir) {
}
}
/**
* 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
+36
View File
@@ -11,6 +11,7 @@ import {
isNpmLockEntry,
isPinnedNpmPluginInstalled,
listPluginDirNames,
nextNpmLockEntry,
npmPackageName,
npmPluginDir,
readNpmLockEntry,
@@ -241,3 +242,38 @@ describe("ensureNpmPlugin", () => {
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,
},
)
})
})
+17 -5
View File
@@ -1,9 +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")
@@ -251,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() {
@@ -264,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
}
@@ -281,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")
}
/**
+7 -7
View File
@@ -17,7 +17,7 @@ import {
parseGitSource,
getGitCommit,
PLUGINS_DIR,
LOCKFILE_PATH,
getLockfilePath,
isLocalSource,
getSourceUrl,
formatSource,
@@ -61,6 +61,7 @@ import {
installNpmPlugin,
isHostDependency,
isNpmLockEntry,
nextNpmLockEntry,
latestNpmVersion,
latestNpmVersionAsync,
listPluginDirNames,
@@ -614,12 +615,11 @@ async function syncNpmPlugins({ pluginsJson, names, fromConfig, latest, dryRun }
pluginsDir: PLUGINS_DIR,
})
linkPeerPlugins(npmPluginDir(pkg, PLUGINS_DIR))
lockfile.plugins[pkg] = {
source: entry.source,
...result,
installedAt: new Date().toISOString(),
const next = nextNpmLockEntry(lockEntry, entry.source, result)
if (next !== lockEntry) {
lockfile.plugins[pkg] = next
changed = true
}
changed = true
installedAny = true
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
} catch (err) {
@@ -2944,7 +2944,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
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",
+55
View File
@@ -366,3 +366,58 @@ describe("plugin install --latest with a plugin that can't be updated", () => {
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/)
})
})
@@ -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
)
}
+3 -4
View File
@@ -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) {
@@ -37,7 +36,7 @@ async function mouseEnterHandler(
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" })
}
}
}
+31 -2
View File
@@ -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)
})
})
@@ -379,6 +379,70 @@ describe("resolveExtends", () => {
)
})
describe("keys starting with $ are reserved", () => {
const own = path.join(root, "quartz.config.yaml")
const opts = { quartzRoot: root, readFile }
test("in the extending file, at any depth", async () => {
for (const [data, where] of [
[
{ configuration: { ignorePatterns: { $append: ["drafts"] } } },
"configuration.ignorePatterns.$append",
],
[{ configuration: { $pageTitle: "x" } }, "configuration.$pageTitle"],
[
{ layout: { byPageType: { folder: { $exclude: [] } } } },
"layout.byPageType.folder.$exclude",
],
[
{ plugins: [{ source: "@quartz-community/explorer", options: { $merge: {} } }] },
"plugins.0.options.$merge",
],
[
{ plugins: [{ source: "@quartz-community/explorer", $remove: true }] },
"plugins.0.$remove",
],
[{ $plugins: [] }, "$plugins"],
] as const) {
await assert.rejects(
() => resolveExtends({ extends: "default", ...data }, own, opts),
{
name: "ConfigExtendsError",
message: `${own}: "${where}" — keys starting with "$" are reserved in configs that use "extends"`,
},
where,
)
}
})
test("in a base the config extends", async () => {
put("preset.yaml", { extends: "default", configuration: { $x: 1 } })
await assert.rejects(
() => resolveExtends({ extends: "./preset.yaml" }, own, opts),
/preset\.yaml: "configuration\.\$x" — keys starting with "\$" are reserved/,
)
})
test("the top-level $schema is allowed, and $ inside values is fine", async () => {
const merged = await resolveExtends(
{
$schema: "./quartz/plugins/quartz-plugins.schema.json",
extends: "default",
configuration: { pageTitle: "$5 tips", ignorePatterns: ["$tmp"] },
},
own,
opts,
)
assert.strictEqual(merged.configuration.pageTitle, "$5 tips")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["$tmp"])
})
test("a config without extends is not checked", async () => {
const data = { configuration: { pageTitle: "x", $custom: 1 }, plugins: [] }
assert.strictEqual(await resolveExtends(data, own, opts), data as never)
})
})
test("a base that is not a configuration object is an error", async () => {
files[path.join(root, "list.yaml")] = "- source: explorer\n- source: graph\n"
const file = path.join(root, "list.yaml")
+27
View File
@@ -342,6 +342,32 @@ export function resolveTarget(target: string, from: string, quartzRoot: string):
return resolved
}
/**
* Keys starting with `$` are reserved in every file of an `extends` chain (the top-level
* `$schema` aside), at any depth: they are kept free for merge operators, such as appending
* to a list instead of replacing it, so adding those later changes no existing config.
*/
export const RESERVED_KEY_PREFIX = "$"
function assertNoReservedKeys(data: PlainObject, file: string) {
const visit = (value: unknown, at: string[]) => {
if (Array.isArray(value)) {
value.forEach((item, i) => visit(item, [...at, String(i)]))
return
}
if (!isPlainObject(value)) return
for (const [key, child] of Object.entries(value)) {
if (key.startsWith(RESERVED_KEY_PREFIX) && !(at.length === 0 && key === "$schema")) {
throw new ConfigExtendsError(
`${file}: "${[...at, key].join(".")}" — keys starting with "${RESERVED_KEY_PREFIX}" are reserved in configs that use "extends"`,
)
}
visit(child, [...at, key])
}
}
visit(data, [])
}
interface ConfigLayer {
/** Resolved path or URL ("" for the config being resolved). */
file: string
@@ -443,6 +469,7 @@ async function extendsLayers(
await visit(parsed, targetFile, here)
}
const { extends: _drop, ...own } = node
assertNoReservedKeys(own, nodeFile)
layers.push({ file: chain.length === 0 ? "" : self, data: own })
applied.add(self)
}
+2 -2
View File
@@ -51,6 +51,7 @@ import {
} from "../builtins"
import { registerPluginOrigin, reportError, warn } from "../../util/diagnostics"
import { firstPluginFrame } from "../../util/trace"
import { currentLockfilePath } from "../../cli/lockfile-path.js"
import {
ensureNpmPlugin,
isHostDependency,
@@ -319,7 +320,6 @@ async function importPluginModule(spec: ReturnType<typeof parsePluginSource>) {
}
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
const LOCKFILE = path.join(process.cwd(), "quartz.lock.json")
/**
* An npm plugin pinned in quartz.lock.json and installed in .quartz/plugins/@scope/name, because
@@ -469,7 +469,7 @@ export async function loadQuartzConfig(
continue
}
const installed = ensureNpmPlugin(name, {
lockEntry: readNpmLockEntry(name, LOCKFILE),
lockEntry: readNpmLockEntry(name, currentLockfilePath()),
pluginsDir: PLUGINS_DIR,
})
if (installed) linkPeerDependencies(npmPluginDir(name, PLUGINS_DIR))
+2 -2
View File
@@ -10,6 +10,7 @@ import {
} from "../../cli/subprocess.js"
import { writePluginIndex } from "../../cli/plugin-index.js"
import { listPluginDirNames } from "../../cli/npm-plugins.js"
import { currentLockfilePath } from "../../cli/lockfile-path.js"
import git from "isomorphic-git"
import http from "isomorphic-git/http/node"
import { styleText } from "util"
@@ -47,7 +48,6 @@ export interface GitPluginSpec {
export type PluginInstallSource = string | GitPluginSpec
const PLUGINS_CACHE_DIR = path.join(process.cwd(), ".quartz", "plugins")
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
const GIT_TIMEOUT_MS = 300_000
/**
@@ -56,7 +56,7 @@ const GIT_TIMEOUT_MS = 300_000
*/
export function readLockedCommit(
spec: Pick<GitPluginSpec, "name" | "repo" | "subdir">,
lockfilePath: string = LOCKFILE_PATH,
lockfilePath: string = currentLockfilePath(),
): string | undefined {
try {
const lock = JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))
+2 -1
View File
@@ -16,6 +16,7 @@ import {
readNpmLockEntry,
removeNpmPlugin,
} from "../../cli/npm-plugins.js"
import { currentLockfilePath } from "../../cli/lockfile-path.js"
import type { PluginSource, QuartzPluginsJson } from "./types.js"
import { absorbingBuiltin } from "../builtins/index.js"
import { resolveExtends } from "./config-extends.js"
@@ -105,7 +106,7 @@ async function main() {
// npm plugins package.json doesn't list are pinned in quartz.lock.json and installed into
// .quartz/plugins/@scope/name (see cli/npm-plugins.js); the others come from node_modules
const pluginsDir = path.join(process.cwd(), ".quartz", "plugins")
const lockfile = path.join(process.cwd(), "quartz.lock.json")
const lockfile = currentLockfilePath()
const hostPackages: string[] = []
for (const spec of npmSpecs) {
const name = npmPackageName(spec.name)
+1 -1
View File
@@ -35,7 +35,7 @@
"description": "JSON Schema reference"
},
"extends": {
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml) or a path relative to this file, or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Without extends, this file is the whole configuration.",
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml), a path relative to this file, an https:// URL (experimental), or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Keys starting with $ are reserved (except $schema). Without extends, this file is the whole configuration.",
"oneOf": [
{
"type": "string"