From 8f0bdba3a61dc126910ae46a2a5171c3ef2f7282 Mon Sep 17 00:00:00 2001 From: PZTHH Date: Wed, 7 Oct 2026 02:52:40 +0400 Subject: [PATCH] Add fixed Quick Look themes and snippet selection --- CONTRIBUTING.md | 10 +++ README.md | 23 +++++- package.json | 3 +- src/appearance.cjs | 156 +++++++++++++++++++++++++++++++++++++++ src/cache.cjs | 78 +++++++++++++------- src/capture.cjs | 62 +++++++++++++--- src/main.js | 154 ++++++++++++++++++++++++++++++++++++-- src/watch.cjs | 34 +++++++++ test/appearance.test.cjs | 143 +++++++++++++++++++++++++++++++++++ test/cache.test.cjs | 70 ++++++++++++++++++ test/capture.test.cjs | 28 +++++++ test/lifecycle.test.cjs | 35 +++++++++ test/render.cjs | 105 ++++++++++++++++++++++++++ test/sync.test.cjs | 7 +- test/watch.test.cjs | 17 +++++ 15 files changed, 881 insertions(+), 44 deletions(-) create mode 100644 src/appearance.cjs create mode 100644 test/appearance.test.cjs create mode 100644 test/render.cjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bd24e11..f47483e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,3 +5,13 @@ Bug reports and small improvements are welcome. For styling bugs, share a synthe Run `npm ci`, `npm test`, and `npm run build` before submitting a pull request. Test against a new vault and temporary Quick Look resources; don't modify an existing user's cache while running tests. For releases, the version in the tag must match `manifest.json`. The release workflow builds, tests, attests, and uploads the plugin files. + +For capture changes, also run the optional real-browser regression check: + +```sh +npm install --no-save --package-lock=false playwright +npx playwright install chromium webkit +npm run test:render +``` + +It verifies light/dark computed-style round trips for nested lists and contextual emphasis, plus isolation from active vault styles. The normal test suite needs no browser downloads. diff --git a/README.md b/README.md index 95fb32a..1091773 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,12 @@ Style Settings is optional. If you use it, QuickCss follows its choices along wi ## Install +Open **Settings → Community plugins → Browse**, search for **QuickCss**, then choose **Install** and **Enable**. + +### Manual installation + +If QuickCss isn't available in the community directory yet, or you need a specific release: + 1. Download `main.js`, `manifest.json`, and `styles.css` from the [latest release](https://github.com/Mars-den/quickcss/releases/latest). 2. Create a `quickcss` folder in your vault's `.obsidian/plugins` folder. 3. Put the three files inside it. @@ -56,7 +62,7 @@ If your vault uses a custom configuration folder, use its `plugins` folder inste ## Try it out -Once enabled, QuickCss captures your reading appearance and keeps it in sync. Select a Markdown file in Finder, press **Space**, and take a look. +Once enabled, QuickCss follows this vault’s reading appearance and keeps it in sync. Existing users keep this behavior. Select a Markdown file in Finder, press **Space**, and take a look. Open **Settings → QuickCss** for sample light and dark previews. They use your **text font**; the **interface font** is a separate setting for Obsidian's menus and settings. @@ -66,10 +72,23 @@ Already have a Quick Look window open? Close it and open it again after changing | Control | When to use it | | --- | --- | -| Automatic sync | Leave this on to follow theme, snippet, and Style Settings changes. Turning it off keeps the last applied appearance. | +| Automatic sync | Leave this on to keep the selected source and snippet files up to date. Turning it off keeps the last applied appearance. | | Sync now / use this vault | Refresh immediately, or switch which vault supplies the appearance. | | Restore and pause | Go back to the native preview and stop syncing. | +### Choose an appearance + +**Appearance source → Follow this vault** captures the active theme, enabled snippets, and Style Settings as before. **Fixed theme** chooses Default or a theme installed in this vault’s configuration folder. It leaves Obsidian’s own theme untouched and evaluates both light and dark modes using native Quick Look reading defaults. Changes to Obsidian’s active theme, body classes, fonts, or Style Settings do not change that fixed appearance. Theme features that require plugin classes or Style Settings may therefore differ from their appearance in Obsidian. + +The compact **Quick Look snippets** list reads existing `.css` files from your configuration folder’s `snippets` directory. Create or edit those files with your usual editor, then refresh the installed-file list if necessary. QuickCss does not change Obsidian’s snippet toggles. + +- **Follow this vault:** selected snippets are additions to the vault’s enabled snippets. Turning a toggle off here removes only that addition; it cannot disable a snippet enabled in Obsidian. An already-enabled file is not added twice. +- **Fixed theme:** only snippets selected here are included, after the chosen theme, in alphabetical filename order. + +Selected files are evaluated against synthetic Markdown and exported through the same safe computed-style capture as the vault source. Raw CSS is not copied to Finder. With automatic sync on, source-file changes trigger capture; while paused, selections are saved for the next **Sync now**. Missing selected files block capture and preserve the last applied appearance until you remove the selection or restore the file. + +A saved appearance and a successful cache write are tracked separately. Failed writes remain retryable by the owning vault and are not shown as a successfully applied selection. **Sync now** retries; cache monitoring also retries when relevant resources change. + ### A note about multiple vaults Quick Look belongs to your Mac, so all your vaults share one preview appearance. One vault supplies the styling at a time. Choose **Sync now / use this vault** when you want another vault's look instead. diff --git a/package.json b/package.json index fda0c45..130d2dd 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "build": "node esbuild.config.mjs", "test": "node --test test/*.test.cjs", "format": "prettier --write src test esbuild.config.mjs", - "format:check": "prettier --check src test esbuild.config.mjs" + "format:check": "prettier --check src test esbuild.config.mjs", + "test:render": "node test/render.cjs" }, "devDependencies": { "esbuild": "^0.25.0", diff --git a/src/appearance.cjs b/src/appearance.cjs new file mode 100644 index 0000000..e6753d2 --- /dev/null +++ b/src/appearance.cjs @@ -0,0 +1,156 @@ +const path = require("node:path"); +const fs = require("node:fs"); +const { strip } = require("./cache.cjs"); + +function settings(saved = {}) { + saved ??= {}; + return { + source: saved.source === "fixed" ? "fixed" : "vault", + theme: typeof saved.theme === "string" ? saved.theme : "", + snippets: Array.isArray(saved.snippets) + ? [ + ...new Set(saved.snippets.filter((name) => typeof name === "string")), + ].sort() + : [], + }; +} +function segment(name) { + if (!name || name === "." || name === ".." || /[\\/\0]/.test(name)) + throw Error("Invalid appearance file name"); + return name; +} +async function installed(adapter, configDir) { + const list = async (directory) => { + try { + return await adapter.list(directory); + } catch (error) { + if (await adapter.exists(directory)) throw error; + return { files: [], folders: [] }; + } + }; + const themes = await list(`${configDir}/themes`); + const snippets = await list(`${configDir}/snippets`); + return { + themes: themes.folders.map((folder) => folder.split("/").pop()).sort(), + snippets: snippets.files + .filter((file) => file.endsWith(".css")) + .map((file) => file.split("/").pop().slice(0, -4)) + .sort(), + }; +} +async function evaluation(app, cache, selection, appearance) { + const adapter = app.vault.adapter, + config = app.vault.configDir; + const fixed = selection.source === "fixed"; + const enabled = fixed ? [] : appearance.enabledCssSnippets || []; + const extras = selection.snippets.filter((name) => !enabled.includes(name)); + const readSnippet = (name) => + adapter.read(`${config}/snippets/${segment(name)}.css`); + let styles; + if (fixed) { + // The native renderer provides a stable reading baseline, independent of + // Obsidian's current theme, plugin styles, body classes and inline settings. + styles = strip(cache.current().source); + if (selection.theme) + styles += + "\n" + + (await adapter.read( + `${config}/themes/${segment(selection.theme)}/theme.css`, + )); + } + const snippets = await Promise.all(extras.map(readSnippet)); + return { + appearance: { + ...appearance, + cssTheme: fixed ? selection.theme || "Default" : appearance.cssTheme, + enabledCssSnippets: [ + ...new Set([...enabled, ...selection.snippets]), + ].sort(), + }, + options: fixed + ? { + styles: styles + "\n" + snippets.join("\n"), + classes: [], + inline: false, + } + : { extraStyles: snippets.join("\n") }, + }; +} +// Watch only appearance directories, plus their parent for creation/replacement. +// Plugin data and note files do not acquire recursive watches. +function watchFiles(app, changed, error = () => {}) { + const root = app.vault.adapter.getBasePath?.(); + if (!root) return () => {}; + const directory = path.join(root, app.vault.configDir); + const watchers = new Map(); + let closed = false, + settleTimer; + const refresh = () => { + if (closed) return; + let attached = false; + for (const folder of [ + directory, + path.join(directory, "themes"), + path.join(directory, "snippets"), + ]) { + let stat; + try { + stat = fs.statSync(folder); + } catch (failure) { + if (failure.code !== "ENOENT") error(failure); + } + const previous = watchers.get(folder); + if ( + previous && + (!stat || stat.ino !== previous.ino || stat.dev !== previous.dev) + ) { + previous.watcher.close(); + watchers.delete(folder); + } + if (!stat || watchers.has(folder)) continue; + try { + const watcher = fs.watch( + folder, + { recursive: folder !== directory, persistent: false }, + (_event, file) => { + if (closed) return; + if ( + folder === directory && + file && + !["themes", "snippets"].includes(file.toString()) + ) + return; + refresh(); + changed(); + }, + ); + watcher.on("error", (failure) => { + watcher.close(); + watchers.delete(folder); + error(failure); + }); + watchers.set(folder, { watcher, ino: stat.ino, dev: stat.dev }); + attached = true; + } catch (failure) { + error(failure); + } + } + // Native recursive watch registration can miss a write immediately after + // attachment. One deferred capture covers that gap without idle polling. + if (attached) { + clearTimeout(settleTimer); + settleTimer = setTimeout(() => { + if (!closed) changed(); + }, 100); + settleTimer.unref?.(); + } + }; + refresh(); + return () => { + closed = true; + clearTimeout(settleTimer); + for (const { watcher } of watchers.values()) watcher.close(); + watchers.clear(); + }; +} +module.exports = { settings, installed, evaluation, watchFiles }; diff --git a/src/cache.cjs b/src/cache.cjs index dd27eba..0f21bf1 100644 --- a/src/cache.cjs +++ b/src/cache.cjs @@ -235,27 +235,49 @@ class Cache { previousState.label === label && previousState.version === version ) - return this.writeCurrent(snapshot.css); - atomic( - this.stateFile, - JSON.stringify( - { - schema: 2, - owner: ownerId || previousState.owner, - enabled: true, - snapshot, - css: snapshot.css, - label, - version, - appliedAt: new Date().toISOString(), - }, - null, - 2, - ), - ); - return this.writeCurrent(snapshot.css); + return this.commitCurrent(previousState); + const requested = { + schema: 2, + owner: ownerId || previousState.owner, + enabled: true, + snapshot, + css: snapshot.css, + label, + version, + application: "pending", + requestedAt: new Date().toISOString(), + }; + atomic(this.stateFile, JSON.stringify(requested, null, 2)); + return this.commitCurrent(requested); }); } + commitCurrent(state) { + // Persist intent first so a crash or partial write can be retried by the owner. + // appliedAt describes this request only after the resource write succeeds. + try { + const result = this.writeCurrent(state.css); + const applied = { + ...state, + application: "applied", + appliedAt: new Date().toISOString(), + appliedCache: result.cache, + }; + delete applied.applicationError; + atomic(this.stateFile, JSON.stringify(applied, null, 2)); + return result; + } catch (error) { + const failed = { + ...state, + application: "failed", + applicationError: error.message, + }; + delete failed.appliedAt; + delete failed.appliedCache; + if (JSON.stringify(this.state()) !== JSON.stringify(failed)) + atomic(this.stateFile, JSON.stringify(failed, null, 2)); + throw error; + } + } claim(ownerId, label, force = false) { return this.locked(() => { const sharedState = this.state(); @@ -276,17 +298,23 @@ class Cache { const previousState = this.state(); if (!previousState.enabled) return { enabled: false }; if (ownerId && previousState.owner !== ownerId) return { skipped: true }; - const current = this.current(); - // Our own writes trigger filesystem notifications too. Checking before - // locking avoids both lock churn and an event/write feedback loop. - if (patch(current.source, previousState.css) === current.source) - return { changed: false, enabled: true }; + // Our own writes trigger filesystem notifications too. Check before + // locking to avoid churn; failed validation is retried under the lock so + // commitCurrent records failure for followers as well as the owner. + try { + const current = this.current(); + if ( + patch(current.source, previousState.css) === current.source && + (!previousState.application || previousState.application === "applied") + ) + return { changed: false, enabled: true }; + } catch {} return this.locked(() => { const sharedState = this.state(); if (!sharedState.enabled) return { enabled: false }; if (ownerId && sharedState.owner !== ownerId) return { skipped: true }; return { - ...this.writeCurrent(sharedState.css), + ...this.commitCurrent(sharedState), enabled: true, label: sharedState.label, version: sharedState.version, diff --git a/src/capture.cjs b/src/capture.cjs index 16a7eb9..f90f21c 100644 --- a/src/capture.cjs +++ b/src/capture.cjs @@ -55,7 +55,7 @@ const PROPERTIES = [ ]; const VARIABLES = /^--(?:font-|line-height-|file-line-width$|file-margins$|p-spacing$|heading-|h[1-6]-|text-|background-|color-|code-|blockquote-|list-|table-|callout-|link-|hr-|tag-|checkbox-|highlight-|bold-|italic-|embed-|accent-|interactive-accent)/; -const SAMPLE = `

Reading with your theme

A synthetic paragraph with bold words, italic words, a link and a highlight.

Headings and emphasis

Heading three

Heading four

Heading five
Heading six

A quotation wraps across lines so you can compare spacing and its vertical rule. Theme colors should remain readable on this canvas.

Some inline code.

const appearance = "captured"; // syntheticcapture1true

Lists and tasks

  • A list item
  • A second item
    • A nested item
  1. A numbered item
  • An open task
  • A completed task

Tables

ColumnValueDetail
ThemeCurrentFirst
ContentSyntheticMiddle
StateCapturedLast

Callouts

${["note", "info", "tip", "warning", "danger", "success"].map((type) => `
${type}

A ${type} callout.

`).join("")}

Links and tags

#sample · An internal link · An external link

End of preview — both canvases scroll with the settings page.

`; +const SAMPLE = `

Reading with your theme bold italic

A synthetic paragraph with bold words, italic words, a link and a highlight.

Headings and emphasis bold italic

Heading three bold italic

Heading four bold italic

Heading five bold italic
Heading six bold italic

A quotation wraps across lines so you can compare spacing and its vertical rule. Theme colors should remain readable on this canvas.

Some inline code.

const appearance = "captured"; // syntheticcapture1true

Lists and tasks bold italic

  • A list item
  • A second item
    • A nested item
      • A deeper item
  1. A numbered item
    1. A nested number
      1. A deeper number
  • An open task
  • A completed task

Tables bold italic

ColumnValueDetail
ThemeCurrentFirst
ContentSyntheticMiddle
StateCapturedLast

Callouts bold italic

${["note", "info", "tip", "warning", "danger", "success"].map((type) => `
${type} bold italic

A ${type} callout with bold and italic.

`).join("")}

Links and tags bold italic

#sample · An internal link · An external link

End of preview — both canvases scroll with the settings page.

`; const TARGETS = [ [".markdown-preview-view", ".markdown-preview-view"], ...[ @@ -87,7 +87,10 @@ const TARGETS = [ "a.tag", ].map((selectorSuffix) => [ ".markdown-rendered " + selectorSuffix, - ".markdown-rendered " + selectorSuffix, + ".markdown-rendered " + + (["strong", "em"].includes(selectorSuffix) + ? `p ${selectorSuffix}` + : selectorSuffix), ]), ...[ "keyword", @@ -115,6 +118,33 @@ const TARGETS = [ }), ), ]; +// Context rules follow the general rules so inherited heading/callout styles +// and list-depth differences survive scalar export. +const CONTEXT_TARGETS = [ + ...[1, 2, 3, 4, 5, 6].flatMap((level) => + ["strong", "em"].map((tag) => `.markdown-rendered h${level} ${tag}`), + ), + ...["ul", "ol"].flatMap((tag) => [ + `.markdown-rendered ${tag} > li`, + `.markdown-rendered ${tag} ${tag}`, + `.markdown-rendered ${tag} ${tag} > li`, + `.markdown-rendered ${tag} ${tag} ${tag}`, + `.markdown-rendered ${tag} ${tag} ${tag} > li`, + ]), + ...["note", "info", "tip", "warning", "danger", "success"].flatMap((type) => + [".callout-title-inner", ".callout-content"].flatMap((context) => + ["strong", "em"].map( + (tag) => + `.markdown-rendered .callout[data-callout="${type}"] ${context} ${tag}`, + ), + ), + ), +].map((selector) => { + const contextual = selector + .replace(/\bul\b/g, "ul:not(.contains-task-list)") + .replace(/\bli\b/g, "li:not(.task-list-item)"); + return [contextual, contextual]; +}); const TABLE_LAYOUT = [ "border-collapse", "border-spacing", @@ -589,9 +619,12 @@ function frame( } async function capture(sourceDocument, appearance = {}, options = {}) { checkAbort(options.signal); - const loaded = loadedCSS(sourceDocument); + const loaded = + options.styles === undefined + ? loadedCSS(sourceDocument) + : { css: options.styles, skipped: 0 }; if (!loaded.css) throw Error("No readable loaded stylesheets"); - const classes = Array.from(sourceDocument.body.classList), + const classes = options.classes ?? Array.from(sourceDocument.body.classList), parts = []; for (const mode of ["light", "dark"]) { checkAbort(options.signal); @@ -599,7 +632,7 @@ async function capture(sourceDocument, appearance = {}, options = {}) { sourceDocument, mode, classes, - loaded.css, + loaded.css + "\n" + (options.extraStyles || ""), sourceDocument.body, options, ); @@ -607,9 +640,11 @@ async function capture(sourceDocument, appearance = {}, options = {}) { checkAbort(options.signal); const previewDocument = iframe.contentDocument, previewWindow = iframe.contentWindow; - previewDocument.documentElement.style.cssText = - sourceDocument.documentElement.style.cssText; - previewDocument.body.style.cssText = sourceDocument.body.style.cssText; + if (options.inline !== false) { + previewDocument.documentElement.style.cssText = + sourceDocument.documentElement.style.cssText; + previewDocument.body.style.cssText = sourceDocument.body.style.cssText; + } const view = previewDocument.querySelector(".markdown-preview-view"), colors = colorResolver(previewWindow, previewDocument); try { @@ -625,6 +660,12 @@ async function capture(sourceDocument, appearance = {}, options = {}) { previewDocument.querySelector(query), ), ]), + ...CONTEXT_TARGETS.map(([selector, query]) => [ + selector, + previewWindow.getComputedStyle( + previewDocument.querySelector(query), + ), + ]), ...TABLE_TARGETS.map(([selector, query, properties]) => [ selector, previewWindow.getComputedStyle( @@ -663,7 +704,9 @@ async function capture(sourceDocument, appearance = {}, options = {}) { css: style, theme: appearance.cssTheme || "Default", snippets: appearance.enabledCssSnippets || [], - styleSettings: !!sourceDocument.getElementById("css-settings-manager"), + styleSettings: + options.inline !== false && + !!sourceDocument.getElementById("css-settings-manager"), capturedAt: new Date().toISOString(), skippedStylesheets: loaded.skipped, warning: @@ -682,6 +725,7 @@ module.exports = { loadedCSS, schemeCSS, preparePreview, + CONTEXT_TARGETS, TABLE_TARGETS, TABLE_LAYOUT, quoteDecoration, diff --git a/src/main.js b/src/main.js index d306556..b3ce02a 100644 --- a/src/main.js +++ b/src/main.js @@ -11,6 +11,12 @@ const { Cache, strip } = require("./cache.cjs"); const { capture, frame, preparePreview } = require("./capture.cjs"); const { AutomaticSync } = require("./sync.cjs"); const { CacheWatcher } = require("./watch.cjs"); +const { + settings, + installed, + evaluation, + watchFiles, +} = require("./appearance.cjs"); module.exports = class QuickCss extends Plugin { async onload() { if (!Platform.isMacOS) { @@ -23,6 +29,7 @@ module.exports = class QuickCss extends Plugin { const saved = await this.loadData(); this.snapshot = saved?.snapshot?.schema === 2 ? saved.snapshot : null; this.autoSync = saved?.autoSync !== false; + this.selection = settings(saved?.appearance); const vaultPath = this.app.vault.adapter.getBasePath?.(); this.owner = vaultPath ? crypto @@ -35,7 +42,11 @@ module.exports = class QuickCss extends Plugin { this.snapshot = shared.snapshot; this.pendingSettingsWrites = 0; if (saved?.snapshot) - await this.saveData({ autoSync: this.autoSync, owner: this.owner }); + await this.saveData({ + autoSync: this.autoSync, + owner: this.owner, + appearance: this.selection, + }); this.status = "Waiting for appearance to load."; this.disposed = false; this.busy = false; @@ -113,7 +124,16 @@ module.exports = class QuickCss extends Plugin { this.changed(); }, }); + const stopFiles = watchFiles( + this.app, + () => this.scheduleAppearance(), + (error) => + new Notice( + `Appearance file monitoring unavailable: ${error.message}. Use Sync now to refresh selected files.`, + ), + ); this.stopBackground = () => { + stopFiles(); headObserver.disconnect(); appearanceObserver.disconnect(); this.cacheWatcher.close(); @@ -184,7 +204,11 @@ module.exports = class QuickCss extends Plugin { if (this.disposed || this.shuttingDown) return; this.pendingSettingsWrites = (this.pendingSettingsWrites || 0) + 1; try { - await this.saveData({ autoSync: this.autoSync, owner: this.owner }); + await this.saveData({ + autoSync: this.autoSync, + owner: this.owner, + appearance: this.selection, + }); } finally { this.pendingSettingsWrites--; } @@ -207,7 +231,11 @@ module.exports = class QuickCss extends Plugin { const cacheResult = ownsAppearance ? this.cache.reconcile(this.owner) : {}; - this.status = `Active: ${sharedState.label} · ${ownsAppearance ? (this.autoSync ? "automatic sync on" : "sync paused") : "following another vault"}${cacheResult.changed ? " · cache repaired" : ""}.`; + if (ownsAppearance) Object.assign(sharedState, this.cache.state()); + this.status = + sharedState.application && sharedState.application !== "applied" + ? `Appearance saved; Quick Look application ${sharedState.application}: ${sharedState.applicationError || "waiting for owner to retry"}.` + : `Active: ${sharedState.label} · ${ownsAppearance ? (this.autoSync ? "automatic sync on" : "sync paused") : "following another vault"}${cacheResult.changed ? " · cache repaired" : ""}.`; } if (this.cacheWatcher?.error) this.status += " Cache monitoring unavailable; use Sync now to retry."; @@ -221,6 +249,7 @@ module.exports = class QuickCss extends Plugin { throw Object.assign(new Error("QuickCss stopped"), { name: "AbortError", }); + const selection = settings(this.selection); const epoch = this.captureEpoch || 0, controller = new AbortController(); (this.captureControllers ??= new Set()).add(controller); @@ -233,7 +262,14 @@ module.exports = class QuickCss extends Plugin { ), ); } catch {} - const snapshot = await capture(document, appearance, { + const source = await evaluation( + this.app, + this.cache, + selection, + appearance, + ); + const snapshot = await capture(document, source.appearance, { + ...source.options, signal: controller.signal, }); if ( @@ -299,6 +335,22 @@ module.exports = class QuickCss extends Plugin { this.sync.schedule(); } } + async setAppearance(changes) { + if (this.disposed || this.shuttingDown) return; + this.selection = settings({ ...this.selection, ...changes }); + this.sync.cancel(); + this.cancelCaptures(); + const epoch = this.captureEpoch; + await this.save(); + if (this.disposed || this.shuttingDown || epoch !== this.captureEpoch) + return; + if (this.autoSync && this.owns()) this.sync.schedule(); + this.status = + this.autoSync && this.owns() + ? "Waiting to sync selected appearance." + : "Selection saved. Sync now to apply, or enable automatic sync."; + this.changed(); + } async setAutomatic(value) { if (this.disposed || this.shuttingDown) return; this.autoSync = value; @@ -364,7 +416,7 @@ class QuickCssSettingsTab extends PluginSettingTab { container = this.containerEl; container.empty(); container.createEl("p", { - text: "Your theme, CSS snippets and Style Settings selections automatically style native macOS Quick Look.", + text: "Choose a vault appearance or a fixed theme for native macOS Quick Look.", }); this.status = container.createEl("p", { cls: "quickcss-status", @@ -373,7 +425,7 @@ class QuickCssSettingsTab extends PluginSettingTab { new Setting(container) .setName("Automatic sync") .setDesc( - "Keep Quick Look up to date with appearance changes in this vault.", + "Keep Quick Look up to date with the selected source and snippet files.", ) .addToggle((toggle) => toggle @@ -412,11 +464,100 @@ class QuickCssSettingsTab extends PluginSettingTab { container.createEl("p", { text: "One vault owns automatic sync across macOS. Other vaults follow it until you choose “use this vault”. Existing Quick Look panels may need reopening to refresh. Appearance is retained when Obsidian closes normally.", }); + this.sources = container.createDiv(); + this.showSources(); this.details = container.createEl("p"); this.previews = container.createDiv({ cls: "quickcss-previews" }); this.rendered = null; this.update(); } + async showSources() { + const generation = (this.sourceGeneration = + (this.sourceGeneration || 0) + 1), + container = this.sources, + plugin = this.plugin; + container.empty(); + const change = (values) => + plugin + .setAppearance(values) + .catch( + (error) => + new Notice(`Appearance selection failed: ${error.message}`), + ); + new Setting(container) + .setName("Appearance source") + .setDesc( + "Fixed theme uses native reading defaults and ignores this vault’s active theme and Style Settings.", + ) + .addDropdown((dropdown) => + dropdown + .addOption("vault", "Follow this vault") + .addOption("fixed", "Fixed theme") + .setValue(plugin.selection.source) + .onChange(async (source) => { + await change({ source }); + this.showSources(); + }), + ); + try { + const choices = await installed( + this.app.vault.adapter, + this.app.vault.configDir, + ); + if (generation !== this.sourceGeneration || !container.isConnected) + return; + if (plugin.selection.source === "fixed") { + new Setting(container).setName("Theme").addDropdown((dropdown) => { + dropdown.addOption("", "Default"); + for (const theme of choices.themes) dropdown.addOption(theme, theme); + if ( + plugin.selection.theme && + !choices.themes.includes(plugin.selection.theme) + ) + dropdown.addOption( + plugin.selection.theme, + `${plugin.selection.theme} (missing)`, + ); + dropdown + .setValue(plugin.selection.theme) + .onChange((theme) => change({ theme })); + }); + } + const snippetSection = container.createEl("details"); + snippetSection.createEl("summary", { + text: "Quick Look snippets", + }); + snippetSection.createEl("p", { + text: "Selected CSS files are added in name order after the source styles. Follow this vault also keeps its enabled snippets; these toggles do not disable them. Fixed theme uses only snippets selected here. Changes apply on the next sync.", + }); + for (const name of [ + ...new Set([...choices.snippets, ...plugin.selection.snippets]), + ].sort()) { + new Setting(snippetSection) + .setName(name + (choices.snippets.includes(name) ? "" : " (missing)")) + .addToggle((toggle) => + toggle + .setValue(plugin.selection.snippets.includes(name)) + .onChange((enabled) => + change({ + snippets: enabled + ? [...plugin.selection.snippets, name] + : plugin.selection.snippets.filter((item) => item !== name), + }), + ), + ); + } + new Setting(container).addButton((button) => + button + .setButtonText("Refresh installed files") + .onClick(() => this.showSources()), + ); + } catch (error) { + container.createEl("p", { + text: `Appearance files unavailable: ${error.message}`, + }); + } + } update() { if (!this.previews?.isConnected) return; this.status.setText(this.plugin.status); @@ -478,6 +619,7 @@ class QuickCssSettingsTab extends PluginSettingTab { } } hide() { + this.sourceGeneration = (this.sourceGeneration || 0) + 1; this.previewController?.abort(); this.generation++; for (const cleanup of this.cleanups) cleanup(); diff --git a/src/watch.cjs b/src/watch.cjs index fac2985..f0321c7 100644 --- a/src/watch.cjs +++ b/src/watch.cjs @@ -128,6 +128,37 @@ class CacheWatcher { this.options.error?.(error); } + fingerprint() { + // macOS may deliver duplicate or directory-only notifications long after + // registration. Compare relevant resource identity, not directory mtime. + const identify = (file) => { + try { + const stat = fs.statSync(file); + return [ + stat.dev, + stat.ino, + stat.isDirectory() ? null : stat.mtimeMs, + stat.isDirectory() ? null : stat.ctimeMs, + stat.isDirectory() ? null : stat.size, + ]; + } catch (error) { + return error.code; + } + }; + const current = path.join(this.cache.root, "current"); + return JSON.stringify([ + ...[ + this.cache.root, + this.cache.stateRoot, + current, + this.cache.stateFile, + ].map(identify), + ...["quicklook.css", "quicklook.js", "index.html"].map((file) => + identify(path.join(current, file)), + ), + ]); + } + schedule() { if (this.closed) return; clearTimeout(this.timer); @@ -135,6 +166,9 @@ class CacheWatcher { this.timer = null; if (this.closed) return; this.refresh(); + const fingerprint = this.fingerprint(); + if (fingerprint === this.lastFingerprint) return; + this.lastFingerprint = fingerprint; this.options.change(); }, this.options.delay ?? 100); this.timer.unref?.(); diff --git a/test/appearance.test.cjs b/test/appearance.test.cjs new file mode 100644 index 0000000..9781f55 --- /dev/null +++ b/test/appearance.test.cjs @@ -0,0 +1,143 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { settings, evaluation, installed } = require("../src/appearance.cjs"); +const { patch } = require("../src/cache.cjs"); +function fixture() { + const files = { + "custom/themes/Test/theme.css": + ".theme-light{color:blue}.theme-dark{color:cyan}", + "custom/snippets/a.css": "p{color:red}", + "custom/snippets/z.css": "p{color:green}", + }; + const reads = []; + const app = { + vault: { + configDir: "custom", + adapter: { + read: async (file) => { + reads.push(file); + if (!(file in files)) throw Error("missing: " + file); + return files[file]; + }, + }, + }, + }; + const cache = { + current: () => ({ source: patch("native{}", "old-capture{}") }), + }; + return { app, cache, reads, files }; +} +test("old settings migrate to follow vault, and snippet selections are stable and unique", () => { + assert.deepEqual(settings(), { source: "vault", theme: "", snippets: [] }); + assert.deepEqual( + settings({ + source: "fixed", + theme: "Test", + snippets: ["z", "a", "a", null], + }).snippets, + ["a", "z"], + ); +}); +test("fixed source excludes current theme, classes, inline settings and previous capture", async () => { + const { app, cache, reads } = fixture(); + const selection = settings({ + source: "fixed", + theme: "Test", + snippets: ["z", "a"], + }); + const first = await evaluation(app, cache, selection, { + cssTheme: "Active", + enabledCssSnippets: ["missing"], + }); + const next = await evaluation(app, cache, selection, { + cssTheme: "Changed", + enabledCssSnippets: [], + }); + assert.deepEqual(first, next); + assert.equal(first.appearance.cssTheme, "Test"); + assert.deepEqual(first.options.classes, []); + assert.equal(first.options.inline, false); + assert.equal( + first.options.styles, + "native{}\n.theme-light{color:blue}.theme-dark{color:cyan}\np{color:red}\np{color:green}", + ); + assert.ok(reads.every((file) => !file.includes("missing"))); +}); +test("follow adds only snippets not already enabled; missing selection blocks instead of silently dropping", async () => { + const { app, cache, reads } = fixture(); + const result = await evaluation( + app, + cache, + settings({ snippets: ["z", "a"] }), + { cssTheme: "Active", enabledCssSnippets: ["a"] }, + ); + assert.deepEqual(reads, ["custom/snippets/z.css"]); + assert.deepEqual(result.appearance.enabledCssSnippets, ["a", "z"]); + assert.deepEqual(result.options, { extraStyles: "p{color:green}" }); + await assert.rejects( + evaluation(app, cache, settings({ snippets: ["missing"] }), {}), + /missing/, + ); + await assert.rejects( + evaluation( + app, + cache, + settings({ source: "fixed", theme: "../escape" }), + {}, + ), + /Invalid/, + ); +}); +test("installed files respect custom config directory and filter CSS files", async () => { + const adapter = { + list: async (dir) => + dir.endsWith("themes") + ? { folders: ["custom/themes/Test"], files: [] } + : { + folders: [], + files: [ + "custom/snippets/z.css", + "custom/snippets/a.css", + "custom/snippets/ignored.txt", + ], + }, + }; + assert.deepEqual(await installed(adapter, "custom"), { + themes: ["Test"], + snippets: ["a", "z"], + }); +}); + +test("selected snippet disk changes notify without watching plugin directories; close stops monitoring", async (t) => { + const fs = require("node:fs"), + os = require("node:os"), + path = require("node:path"); + const { watchFiles } = require("../src/appearance.cjs"); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "quickcss-appearance-")); + const config = path.join(root, "custom"); + fs.mkdirSync(path.join(config, "snippets"), { recursive: true }); + fs.mkdirSync(path.join(config, "plugins")); + let changes = 0; + const errors = []; + const stop = watchFiles( + { vault: { configDir: "custom", adapter: { getBasePath: () => root } } }, + () => changes++, + (error) => errors.push(error), + ); + t.after(() => { + stop(); + fs.rmSync(root, { recursive: true, force: true }); + }); + fs.writeFileSync(path.join(config, "snippets", "extra.css"), "p{color:red}"); + const deadline = Date.now() + 3000; + while (!changes) { + assert.ok(Date.now() < deadline, "snippet event did not arrive"); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + stop(); + const count = changes; + fs.writeFileSync(path.join(config, "snippets", "extra.css"), "p{color:blue}"); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(changes, count); + assert.deepEqual(errors, []); +}); diff --git a/test/cache.test.cjs b/test/cache.test.cjs index 8118000..6ff1a77 100644 --- a/test/cache.test.cjs +++ b/test/cache.test.cjs @@ -284,3 +284,73 @@ test("ownership changes between reconciliation and lock acquisition prevent stal assert.equal(cache.reconcile("A").skipped, true); assert.equal(fs.readFileSync(file, "utf8"), bytes); }); + +test("failed resource writes retain requested appearance without claiming success and owner retries", (t) => { + const { cache, base, generation } = fixture(t); + const file = generation("a"); + cache.claim("A", "A"); + cache.applySnapshot(snapshot, "old", "1", "A"); + const write = cache.writeCurrent.bind(cache); + cache.writeCurrent = () => { + throw Error("synthetic resource failure"); + }; + const next = { ...snapshot, css: "body{color:purple}" }; + assert.throws(() => cache.applySnapshot(next, "new", "1", "A"), /synthetic/); + assert.equal(cache.state().application, "failed"); + assert.equal(cache.state().snapshot.css, next.css); + assert.equal(cache.state().appliedAt, undefined); + assert.match(cache.state().applicationError, /synthetic/); + assert.match(fs.readFileSync(file, "utf8"), /font-size:16px/); + assert.equal(cache.reconcile("B").skipped, true); + cache.writeCurrent = write; + assert.equal(cache.reconcile("A").changed, true); + assert.equal(cache.state().application, "applied"); + assert.ok(cache.state().appliedAt); + assert.equal(cache.state().applicationError, undefined); + assert.equal(cache.restore("A"), 1); + assert.equal(fs.readFileSync(file, "utf8"), base); +}); + +test("resource success followed by profile commit failure remains retryable without rewriting CSS", (t) => { + const { cache, generation } = fixture(t); + const file = generation("a"); + const write = cache.writeCurrent.bind(cache); + let renames = 0; + const rename = fs.renameSync; + t.after(() => { + fs.renameSync = rename; + }); + fs.renameSync = (from, to) => { + if (to === cache.stateFile && ++renames === 2) + throw Error("profile commit failure"); + return rename(from, to); + }; + assert.throws( + () => cache.applySnapshot(snapshot, "A", "1"), + /profile commit/, + ); + assert.equal(cache.state().application, "failed"); + assert.equal(cache.state().appliedAt, undefined); + assert.match(fs.readFileSync(file, "utf8"), /quickcss:begin/); + const mtime = fs.statSync(file).mtimeMs; + cache.writeCurrent = write; + assert.equal(cache.reconcile().changed, false); + assert.equal(cache.state().application, "applied"); + assert.equal(fs.statSync(file).mtimeMs, mtime); +}); + +test("invalid replacement resources report failure to followers without repeated profile-write churn", (t) => { + const { cache, generation } = fixture(t); + generation("a"); + cache.claim("A", "A"); + cache.applySnapshot(snapshot, "A", "1", "A"); + const file = generation("b"); + fs.writeFileSync(file, "unsupported renderer"); + assert.throws(() => cache.reconcile("A"), /Unsupported/); + assert.equal(cache.state().application, "failed"); + assert.equal(cache.state().appliedAt, undefined); + const mtime = fs.statSync(cache.stateFile).mtimeMs; + assert.throws(() => cache.reconcile("A"), /Unsupported/); + assert.equal(fs.statSync(cache.stateFile).mtimeMs, mtime); + assert.equal(cache.reconcile("B").skipped, true); +}); diff --git a/test/capture.test.cjs b/test/capture.test.cjs index fad3bb2..cd1e57e 100644 --- a/test/capture.test.cjs +++ b/test/capture.test.cjs @@ -251,3 +251,31 @@ test("cancelling an iframe evaluation removes it immediately and rejects before ); assert.equal(appended, 1); }); + +test("context capture separates heading and callout emphasis and gives nested lists sufficient specificity", () => { + const { CONTEXT_TARGETS, SAMPLE } = require("../src/capture.cjs"); + assert.match(SAMPLE, /

[^<]+/); + assert.match(SAMPLE, /A deeper item/); + for (const level of [1, 2, 3, 4, 5, 6]) + for (const tag of ["strong", "em"]) + assert.ok( + CONTEXT_TARGETS.some( + ([selector]) => selector === `.markdown-rendered h${level} ${tag}`, + ), + ); + for (const tag of ["strong", "em"]) + assert.ok( + CONTEXT_TARGETS.some( + ([selector]) => + selector === + `.markdown-rendered .callout[data-callout="note"] .callout-content ${tag}`, + ), + ); + assert.ok( + CONTEXT_TARGETS.some( + ([selector]) => + selector === + ".markdown-rendered ul:not(.contains-task-list) ul:not(.contains-task-list) ul:not(.contains-task-list)", + ), + ); +}); diff --git a/test/lifecycle.test.cjs b/test/lifecycle.test.cjs index c1781ad..bcfbb79 100644 --- a/test/lifecycle.test.cjs +++ b/test/lifecycle.test.cjs @@ -410,3 +410,38 @@ test("cache notifications repair styling in the owner while followers never reco assert.equal(captures, 0, "cache changes must not recapture the theme"); assert.match(follower.status, /following another vault/); }); + +test("fixed selection persists through pause, quit and restart without taking over another vault", async (t) => { + const { instance, file } = setup(t); + const owner = instance("A"); + await owner.onload(); + owner.layout(); + owner.sync.cancel(); + owner.captureCurrent = async () => snapshot; + await owner.syncNow(); + const follower = instance("B"); + await follower.onload(); + follower.layout(); + await follower.setAppearance({ + source: "fixed", + theme: "Test", + snippets: ["extra"], + }); + assert.equal(follower.owns(), false); + assert.equal(follower.sync.timer, null); + await follower.setAutomatic(false); + const bytes = fs.readFileSync(file, "utf8"); + follower.beginShutdown(); + follower.onunload(); + const restarted = instance("B", follower.saved); + await restarted.onload(); + restarted.layout(); + assert.deepEqual(restarted.selection, { + source: "fixed", + theme: "Test", + snippets: ["extra"], + }); + assert.equal(restarted.autoSync, false); + assert.equal(restarted.owns(), false); + assert.equal(fs.readFileSync(file, "utf8"), bytes); +}); diff --git a/test/render.cjs b/test/render.cjs new file mode 100644 index 0000000..fb8ea06 --- /dev/null +++ b/test/render.cjs @@ -0,0 +1,105 @@ +const path = require("node:path"); +const { buildSync } = require("esbuild"); +const captureBundle = buildSync({ + entryPoints: [path.join(__dirname, "../src/capture.cjs")], + bundle: true, + platform: "browser", + format: "iife", + globalName: "QuickCapture", + write: false, +}).outputFiles[0].text; +const assert = require("node:assert/strict"); +const { chromium, webkit } = require( + process.env.QUICKCSS_PLAYWRIGHT || "playwright", +); +(async () => { + for (const [name, engine] of [ + ["chromium", chromium], + ["webkit", webkit], + ]) { + const browser = await engine.launch({ headless: true }); + try { + const page = await browser.newPage(); + await page.setContent( + "", + ); + await page.addScriptTag({ content: captureBundle }); + const result = await page.evaluate(async () => { + const css = `body{--font-text-size:16px;font-size:16px;color:black}.markdown-rendered{color:black} + body.theme-dark{color:white;background:#222}body.theme-light{background:#fff} + h1{font-size:32px}h1 strong{color:blue;font-weight:900}h1 em{color:purple} + ul{list-style-type:disc}ul ul{list-style-type:circle}ul ul ul{list-style-type:square} + ol{list-style-type:decimal}ol ol{list-style-type:lower-alpha}ol ol ol{list-style-type:lower-roman} + .callout[data-callout=note] .callout-content strong{color:green} + .callout[data-callout=warning] .callout-content strong{color:orange}`; + const snapshot = await QuickCapture.capture( + document, + { cssTheme: "Test" }, + { styles: css, classes: [], inline: false }, + ); + const check = async (mode, styles) => { + const iframe = await QuickCapture.frame(document, mode, [], styles); + try { + const d = iframe.contentDocument; + const prop = (s, p) => + iframe.contentWindow + .getComputedStyle(d.querySelector(s)) + .getPropertyValue(p); + return { + color: prop("body", "color"), + paragraphBold: prop("p strong", "color"), + rootNumber: prop("ol > li", "list-style-type"), + heading: prop("h1 strong", "color"), + italic: prop("h1 em", "color"), + nested: prop("ul ul", "list-style-type"), + deep: prop("ul ul ul", "list-style-type"), + number: prop("ol ol", "list-style-type"), + deepNumber: prop("ol ol ol", "list-style-type"), + note: prop( + "[data-callout=note] .callout-content strong", + "color", + ), + warning: prop( + "[data-callout=warning] .callout-content strong", + "color", + ), + }; + } finally { + iframe.remove(); + } + }; + const results = []; + for (const mode of ["light", "dark"]) + results.push({ + mode, + before: await check(mode, css), + after: await check(mode, snapshot.css), + }); + document.body.className = "active"; + document.body.style.color = "pink"; + document.querySelector("style").textContent = + "body{color:magenta}h1{color:orange}"; + const stable = await QuickCapture.capture( + document, + { cssTheme: "Test" }, + { styles: css, classes: [], inline: false }, + ); + return { + results, + stable: stable.css === snapshot.css, + css: snapshot.css, + }; + }); + assert.equal(result.stable, true); + for (const row of result.results) assert.deepEqual(row.after, row.before); + console.log( + `${name}: light/dark contextual round trips and fixed-source isolation passed`, + ); + } finally { + await browser.close(); + } + } +})().catch((e) => { + console.error(e); + process.exitCode = 1; +}); diff --git a/test/sync.test.cjs b/test/sync.test.cjs index f2a7ac4..de36a2b 100644 --- a/test/sync.test.cjs +++ b/test/sync.test.cjs @@ -257,12 +257,17 @@ test("settings saves exclude captured CSS, track pending writes, and stop on shu const p = new QuickCss(); p.autoSync = true; p.owner = "A"; + p.selection = { source: "fixed", theme: "Test", snippets: ["extra"] }; p.snapshot = { css: "large captured theme" }; let resolve, calls = 0; p.saveData = (data) => { calls++; - assert.deepEqual(data, { autoSync: true, owner: "A" }); + assert.deepEqual(data, { + autoSync: true, + owner: "A", + appearance: p.selection, + }); return new Promise((r) => (resolve = r)); }; const saving = p.save(); diff --git a/test/watch.test.cjs b/test/watch.test.cjs index e3421be..5707778 100644 --- a/test/watch.test.cjs +++ b/test/watch.test.cjs @@ -166,3 +166,20 @@ test("idle monitoring and unrelated files do not schedule cache checks", async ( assert.equal(changes(), before); assert.equal(watcher.timer, null); }); + +test("late duplicate directory notifications do not repeat settled checks, but resource edits still notify", async (t) => { + const { cache, watcher, changes } = fixture(t); + await waitFor(() => changes() > 0 && watcher.timer === null); + const before = changes(); + // Reproduce a native event delivered after the registration debounce has + // already fired, including platforms that cannot identify the changed name. + watcher.schedule(); + await new Promise((resolve) => setTimeout(resolve, 40)); + assert.equal(changes(), before); + atomic( + cache.stateFile, + JSON.stringify({ ...cache.state(), ownerLabel: "renamed" }), + ); + await waitFor(() => changes() > before); + assert.equal(cache.state().ownerLabel, "renamed"); +});