Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
23 changes: 21 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand All @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
156 changes: 156 additions & 0 deletions src/appearance.cjs
Original file line number Diff line number Diff line change
@@ -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 };
78 changes: 53 additions & 25 deletions src/cache.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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,
Expand Down
Loading
Loading