Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

fix(obsidian): problems with updating lint config (#1278)

Elijah Potter91d915c5cc6d
diff --git a/Cargo.toml b/Cargo.toml
index 03a4b76ad..73ce47416 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,4 +10,6 @@ opt-level = 1
codegen-units = 1
lto = true
opt-level = 3
-strip = true
+# Stripping binaries triggers a bug in `wasm-opt`.
+# Disable it for now.
+# strip = true
diff --git a/harper-core/src/linting/of_course.rs b/harper-core/src/linting/of_course.rs
index 9f69b07e4..3828b2f50 100644
--- a/harper-core/src/linting/of_course.rs
+++ b/harper-core/src/linting/of_course.rs
@@ -30,7 +30,7 @@ impl PatternLinter for OfCourse {
fn match_to_lint(&self, matched: &[Token], source: &[char]) -> Option<Lint> {
// Skip if the word before “of” is “kind” or “sort” → “kind of curse” is valid.
if let Some(of_idx) = matched.first().map(|t| t.span.start) {
- match source.get(..of_idx).map(|src| {
+ if let Some(prev) = source.get(..of_idx).map(|src| {
// Walk backwards over whitespace to find the preceding word token.
let mut i = of_idx.saturating_sub(1);
while i > 0 && src[i].is_whitespace() {
@@ -44,13 +44,10 @@ impl PatternLinter for OfCourse {
.unwrap_or(0);
src[start..=i].iter().collect::<String>()
}) {
- Some(prev) => {
- let lower = prev.to_ascii_lowercase();
- if lower == "kind" || lower == "sort" {
- return None;
- }
+ let lower = prev.to_ascii_lowercase();
+ if lower == "kind" || lower == "sort" {
+ return None;
}
- _ => (),
}
}
diff --git a/harper-core/src/patterns/word.rs b/harper-core/src/patterns/word.rs
index 989b4d71c..03a18c5d5 100644
--- a/harper-core/src/patterns/word.rs
+++ b/harper-core/src/patterns/word.rs
@@ -46,16 +46,14 @@ impl SingleTokenPattern for Word {
}
let chars = token.span.get_content(source);
- let eq = if self.exact {
+ if self.exact {
chars == self.word.as_slice()
} else {
chars
.iter()
.zip(&self.word)
.all(|(a, b)| a.eq_ignore_ascii_case(b))
- };
-
- eq
+ }
}
}
diff --git a/justfile b/justfile
index 1c8be014a..3488907f7 100644
--- a/justfile
+++ b/justfile
@@ -37,6 +37,14 @@ test-harperjs: build-harperjs
cd "{{justfile_directory()}}/packages/harper.js/examples/commonjs-simple"
pnpm start
+test-obsidian: build-obsidian
+ #!/bin/bash
+ set -eo pipefail
+
+ pnpm install
+ cd "{{justfile_directory()}}/packages/obsidian-plugin"
+ pnpm test
+
dev-wp: build-harperjs
#! /bin/bash
@@ -232,7 +240,7 @@ dogfood:
done
# Test everything.
-test: test-vscode test-harperjs
+test: test-vscode test-harperjs test-obsidian
cargo test
# Use `harper-cli` to parse a provided file and print out the resulting tokens.
diff --git a/packages/harper.js/vite.config.ts b/packages/harper.js/vite.config.ts
index f8cf71d0d..268b7ee0c 100644
--- a/packages/harper.js/vite.config.ts
+++ b/packages/harper.js/vite.config.ts
@@ -68,10 +68,7 @@ export default defineConfig({
enabled: true,
headless: true,
screenshotFailures: false,
- instances: [
- { browser: 'chromium' },
- // { browser: 'firefox' },
- ],
+ instances: [{ browser: 'chromium' }],
},
},
assetsInclude: ['**/*.wasm'],
diff --git a/packages/obsidian-plugin/package.json b/packages/obsidian-plugin/package.json
index 480c51874..14ceb5c4b 100644
--- a/packages/obsidian-plugin/package.json
+++ b/packages/obsidian-plugin/package.json
@@ -4,18 +4,19 @@
"version": "0.35.0",
"main": "main.js",
"devDependencies": {
- "@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.0",
- "@rollup/plugin-typescript": "^12.1.2",
- "@rollup/plugin-wasm": "^6.2.2",
+ "@types/lodash-es": "^4.17.12",
+ "@vitest/browser": "^3.0.6",
"obsidian": "^1.7.2",
- "rollup": "^4.34.9",
"rollup-plugin-peer-deps-external": "^2.2.4",
- "rollup-plugin-svg-import": "^3.0.0"
+ "rollup-plugin-svg-import": "^3.0.0",
+ "vite": "^6.3.5",
+ "vitest": "^3.0.8"
},
"scripts": {
- "build": "rollup -c",
- "dev": "rollup -c --watch"
+ "build": "vite build",
+ "dev": "vite build --watch",
+ "test": "vitest run"
},
"peerDependencies": {
"@codemirror/autocomplete": "^6.16.3",
diff --git a/packages/obsidian-plugin/rollup.config.mjs b/packages/obsidian-plugin/rollup.config.mjs
deleted file mode 100644
index a4c00be36..000000000
--- a/packages/obsidian-plugin/rollup.config.mjs
+++ /dev/null
@@ -1,25 +0,0 @@
-import json from '@rollup/plugin-json';
-import { nodeResolve } from '@rollup/plugin-node-resolve';
-import typescript from '@rollup/plugin-typescript';
-import { wasm } from '@rollup/plugin-wasm';
-import external from 'rollup-plugin-peer-deps-external';
-import svg from 'rollup-plugin-svg-import';
-
-export default {
- input: 'src/index.ts',
- output: {
- file: 'main.js',
- format: 'cjs',
- },
- external: ['obsidian', 'electron'],
- plugins: [
- json(),
- svg({
- stringify: true,
- }),
- external(),
- wasm({ maxFileSize: 2 ** 32, publicPath: './' }),
- nodeResolve(),
- typescript({ compilerOptions: { lib: ['es5', 'es6', 'dom'], target: 'es5' } }),
- ],
-};
diff --git a/packages/obsidian-plugin/src/HarperSettingTab.ts b/packages/obsidian-plugin/src/HarperSettingTab.ts
index 36f9b23f8..5e90c0b41 100644
--- a/packages/obsidian-plugin/src/HarperSettingTab.ts
+++ b/packages/obsidian-plugin/src/HarperSettingTab.ts
@@ -2,16 +2,19 @@ import './index.js';
import { Dialect } from 'harper.js';
import { startCase } from 'lodash-es';
import { type App, PluginSettingTab, Setting } from 'obsidian';
+import type State from './State.js';
+import type { Settings } from './State.js';
import type HarperPlugin from './index.js';
-import type { Settings } from './index.js';
export class HarperSettingTab extends PluginSettingTab {
- private plugin: HarperPlugin;
+ private state: State;
private settings: Settings;
private descriptions: Record<string, string>;
+ private plugin: HarperPlugin;
- constructor(app: App, plugin: HarperPlugin) {
+ constructor(app: App, plugin: HarperPlugin, state: State) {
super(app, plugin);
+ this.state = state;
this.plugin = plugin;
this.updateDescriptions();
@@ -19,13 +22,13 @@ export class HarperSettingTab extends PluginSettingTab {
}
updateSettings() {
- this.plugin.getSettings().then((v) => {
+ this.state.getSettings().then((v) => {
this.settings = v;
});
}
updateDescriptions() {
- this.plugin.getDescriptions().then((v) => {
+ this.state.getDescriptions().then((v) => {
this.descriptions = v;
});
}
@@ -37,7 +40,7 @@ export class HarperSettingTab extends PluginSettingTab {
new Setting(containerEl).setName('Use Web Worker').addToggle((toggle) =>
toggle.setValue(this.settings.useWebWorker).onChange(async (value) => {
this.settings.useWebWorker = value;
- await this.plugin.initializeFromSettings(this.settings);
+ await this.state.initializeFromSettings(this.settings);
}),
);
@@ -51,7 +54,7 @@ export class HarperSettingTab extends PluginSettingTab {
.onChange(async (value) => {
const dialect = Number.parseInt(value);
this.settings.dialect = dialect;
- await this.plugin.initializeFromSettings(this.settings);
+ await this.state.initializeFromSettings(this.settings);
this.plugin.updateStatusBar(dialect);
});
});
@@ -68,7 +71,7 @@ export class HarperSettingTab extends PluginSettingTab {
.setValue(this.settings.delay ?? -1)
.onChange(async (value) => {
this.settings.delay = value;
- await this.plugin.initializeFromSettings(this.settings);
+ await this.state.initializeFromSettings(this.settings);
});
});
@@ -77,7 +80,7 @@ export class HarperSettingTab extends PluginSettingTab {
.setButtonText('Forget Ignored Suggestions')
.onClick(() => {
this.settings.ignoredLints = undefined;
- this.plugin.initializeFromSettings(this.settings);
+ this.state.initializeFromSettings(this.settings);
})
.setWarning();
});
@@ -128,14 +131,14 @@ export class HarperSettingTab extends PluginSettingTab {
.setValue(valueToString(value))
.onChange(async (value) => {
this.settings.lintSettings[setting] = stringToValue(value);
- await this.plugin.initializeFromSettings(this.settings);
+ await this.state.initializeFromSettings(this.settings);
}),
);
}
}
}
-function valueToString(value: boolean | undefined): string {
+function valueToString(value: boolean | null): string {
switch (value) {
case true:
return 'enable';
@@ -144,18 +147,16 @@ function valueToString(value: boolean | undefined): string {
case null:
return 'default';
}
-
- throw 'Fell through case';
}
-function stringToValue(str: string): boolean | undefined {
+function stringToValue(str: string): boolean | null {
switch (str) {
case 'enable':
return true;
case 'disable':
return false;
case 'default':
- return undefined;
+ return null;
}
throw 'Fell through case';
diff --git a/packages/obsidian-plugin/src/State.test.ts b/packages/obsidian-plugin/src/State.test.ts
new file mode 100644
index 000000000..10a4c5ce1
--- /dev/null
+++ b/packages/obsidian-plugin/src/State.test.ts
@@ -0,0 +1,101 @@
+import { shuffle } from 'lodash-es';
+import { expect, test } from 'vitest';
+import State from './State';
+
+/** Create an instance of the test class that doesn't use external persistence. */
+function createEphemeralState(): State {
+ return new State(
+ (_) => Promise.resolve(),
+ () => {},
+ );
+}
+
+test('Toggling linting should change extension array.', () => {
+ const state = createEphemeralState();
+
+ const editorExtensions = state.getCMEditorExtensions();
+ state.enableEditorLinter();
+
+ expect(editorExtensions.length).toBe(1);
+
+ state.disableEditorLinter();
+
+ expect(editorExtensions.length).toBe(0);
+});
+
+test('Passing default settings back in should have a null net change.', async () => {
+ const state = createEphemeralState();
+
+ const initialSettings = await state.getSettings();
+ await state.initializeFromSettings(initialSettings);
+ const reinitSettings = await state.getSettings();
+
+ expect(reinitSettings).toStrictEqual(initialSettings);
+});
+
+test('Default settings should have null linter configs', async () => {
+ const state = createEphemeralState();
+
+ const defaultSettings = await state.getSettings();
+
+ const linterKeys = Object.keys(defaultSettings.lintSettings);
+
+ expect(linterKeys.length).toBeGreaterThan(0);
+
+ for (const key of linterKeys) {
+ const setting = defaultSettings.lintSettings[key];
+ expect(setting).toBeNull();
+ }
+});
+
+test('Lint keys are not undefined', async () => {
+ const state = createEphemeralState();
+
+ const defaultSettings = await state.getSettings();
+
+ expect(defaultSettings.lintSettings.ThisKeyDoesNotExist).toBeUndefined();
+ expect(defaultSettings.lintSettings.RepeatedWords).toBeNull();
+});
+
+test('Lint keys can be enabled, then set to default.', async () => {
+ const state = createEphemeralState();
+
+ let settings = await state.getSettings();
+
+ settings.lintSettings.RepeatedWords = true;
+ await state.initializeFromSettings(settings);
+ settings = await state.getSettings();
+ expect(settings.lintSettings.RepeatedWords).toBe(true);
+
+ settings.lintSettings.RepeatedWords = null;
+ await state.initializeFromSettings(settings);
+ settings = await state.getSettings();
+ expect(settings.lintSettings.RepeatedWords).toBe(null);
+});
+
+test('Lint settings and descriptions have the same keys', async () => {
+ const state = createEphemeralState();
+
+ const settings = await state.getSettings();
+ const descriptions = await state.getDescriptions();
+
+ expect(Object.keys(descriptions).sort()).toStrictEqual(Object.keys(settings.lintSettings).sort());
+});
+
+test('Can be initialized with incomplete lint settings and retain default state.', async () => {
+ const state = createEphemeralState();
+
+ // Get the default settings
+ const defaultSettings = await state.getSettings();
+
+ // Pick just a few lint settings to keep.
+ const numberToKeep = 5;
+ const reducedLintSettings = Object.fromEntries(
+ shuffle(Object.entries(defaultSettings.lintSettings)).slice(0, numberToKeep),
+ );
+ expect(Object.keys(reducedLintSettings).length).toBe(numberToKeep);
+
+ await state.initializeFromSettings({ ...defaultSettings, lintSettings: reducedLintSettings });
+
+ expect(await state.getSettings()).toStrictEqual(defaultSettings);
+});
diff --git a/packages/obsidian-plugin/src/State.ts b/packages/obsidian-plugin/src/State.ts
new file mode 100644
index 000000000..9bb41d4df
--- /dev/null
+++ b/packages/obsidian-plugin/src/State.ts
@@ -0,0 +1,255 @@
+import type { Extension } from '@codemirror/state';
+import type { LintConfig, Linter, Suggestion } from 'harper.js';
+import { type Dialect, LocalLinter, SuggestionKind, WorkerLinter, binaryInlined } from 'harper.js';
+import { toArray } from 'lodash-es';
+import type { Workspace } from 'obsidian';
+import { linter } from './lint';
+
+export type Settings = {
+ ignoredLints?: string;
+ useWebWorker: boolean;
+ dialect?: Dialect;
+ lintSettings: LintConfig;
+ userDictionary?: string[];
+ delay?: number;
+};
+
+const DEFAULT_DELAY = -1;
+
+/** The centralized state for the entire Obsidian plugin.
+ * Since it also contains most business logic, for testing purpose it should not interact with Obsidian directly.*/
+export default class State {
+ private harper: Linter;
+ private saveData: (data: any) => Promise<void>;
+ private delay: number;
+ private workspace: Workspace;
+ private onExtensionChange: () => void;
+
+ /** The CodeMirror extension objects that should be inserted by the host. */
+ private editorExtensions: Extension[];
+
+ /** @param saveDataCallback A callback which will be used to save data on disk.
+ * @param onExtensionChange A callback this class will run when the extension array is modified. */
+ constructor(saveDataCallback: (data: any) => Promise<void>, onExtensionChange: () => void) {
+ this.harper = new WorkerLinter({ binary: binaryInlined });
+ this.delay = DEFAULT_DELAY;
+ this.saveData = saveDataCallback;
+ this.onExtensionChange = onExtensionChange;
+ this.editorExtensions = [];
+ }
+
+ public async initializeFromSettings(settings: Settings | null) {
+ if (settings == null) {
+ settings = { useWebWorker: true, lintSettings: {} };
+ }
+
+ const defaultConfig = await this.harper.getDefaultLintConfig();
+ for (const [key, value] of Object.entries(defaultConfig)) {
+ if (settings.lintSettings[key] == undefined) {
+ settings.lintSettings[key] = null;
+ }
+ }
+
+ const oldSettings = await this.getSettings();
+
+ if (
+ settings.useWebWorker !== oldSettings.useWebWorker ||
+ settings.dialect !== oldSettings.dialect
+ ) {
+ if (settings.useWebWorker) {
+ this.harper = new WorkerLinter({ binary: binaryInlined, dialect: settings.dialect });
+ } else {
+ this.harper = new LocalLinter({ binary: binaryInlined, dialect: settings.dialect });
+ }
+ } else {
+ await this.harper.clearIgnoredLints();
+ }
+
+ if (settings.ignoredLints !== undefined) {
+ await this.harper.importIgnoredLints(settings.ignoredLints);
+ }
+
+ if (settings.userDictionary != null && settings.userDictionary.length > 0) {
+ await this.harper.importWords(settings.userDictionary);
+ }
+
+ await this.harper.setLintConfig(settings.lintSettings);
+ this.harper.setup();
+
+ this.delay = settings.delay ?? DEFAULT_DELAY;
+
+ // Reinitialize it.
+ if (this.hasEditorLinter()) {
+ this.disableEditorLinter();
+ this.enableEditorLinter();
+ }
+
+ await this.saveData(settings);
+ }
+
+ /** Construct the linter plugin that actually shows the errors. */
+ private constructEditorLinter(): Extension {
+ return linter(
+ async (view) => {
+ const text = view.state.doc.sliceString(-1);
+ const chars = toArray(text);
+
+ const lints = await this.harper.lint(text);
+
+ return lints.map((lint) => {
+ const span = lint.span();
+
+ span.start = charIndexToCodePointIndex(span.start, chars);
+ span.end = charIndexToCodePointIndex(span.end, chars);
+
+ const actions = lint.suggestions().map((sug) => {
+ return {
+ name: suggestionToLabel(sug),
+ apply: (view) => {
+ if (sug.kind() === SuggestionKind.Remove) {
+ view.dispatch({
+ changes: {
+ from: span.start,
+ to: span.end,
+ insert: '',
+ },
+ });
+ } else if (sug.kind() === SuggestionKind.Replace) {
+ view.dispatch({
+ changes: {
+ from: span.start,
+ to: span.end,
+ insert: sug.get_replacement_text(),
+ },
+ });
+ } else if (sug.kind() === SuggestionKind.InsertAfter) {
+ view.dispatch({
+ changes: {
+ from: span.end,
+ to: span.end,
+ insert: sug.get_replacement_text(),
+ },
+ });
+ }
+ },
+ };
+ });
+
+ if (lint.lint_kind() === 'Spelling') {
+ const word = lint.get_problem_text();
+
+ actions.push({
+ name: `Add “${word}” to your dictionary`,
+ apply: (view) => {
+ this.harper.importWords([word]);
+ this.reinitialize();
+ },
+ });
+ }
+
+ return {
+ from: span.start,
+ to: span.end,
+ severity: 'error',
+ title: lint.lint_kind_pretty(),
+ renderMessage: (view) => {
+ const node = document.createElement('template');
+ node.innerHTML = lint.message_html();
+ return node.content;
+ },
+ ignore: async () => {
+ await this.harper.ignoreLint(text, lint);
+ await this.reinitialize();
+ },
+ actions,
+ };
+ });
+ },
+ {
+ delay: this.delay,
+ },
+ );
+ }
+
+ public async reinitialize() {
+ const settings = await this.getSettings();
+ await this.initializeFromSettings(settings);
+ }
+
+ public async getSettings(): Promise<Settings> {
+ const usingWebWorker = this.harper instanceof WorkerLinter;
+
+ return {
+ ignoredLints: await this.harper.exportIgnoredLints(),
+ useWebWorker: usingWebWorker,
+ lintSettings: await this.harper.getLintConfig(),
+ userDictionary: await this.harper.exportWords(),
+ dialect: await this.harper.getDialect(),
+ delay: this.delay,
+ };
+ }
+
+ public async getDescriptions(): Promise<Record<string, string>> {
+ return await this.harper.getLintDescriptions();
+ }
+
+ /** Get a reference to the CM editor extensions.
+ * Do not mutate the returned value, except via methods on this class. */
+ public getCMEditorExtensions(): Extension[] {
+ return this.editorExtensions;
+ }
+
+ /** Enables the editor linter by adding an extension to the editor extensions array. */
+ public enableEditorLinter() {
+ if (!this.hasEditorLinter()) {
+ this.editorExtensions.push(this.constructEditorLinter());
+ this.onExtensionChange();
+ console.log('Enabled');
+ }
+ }
+
+ /** Disables the editor linter by removing the extension from the editor extensions array. */
+ public disableEditorLinter() {
+ while (this.hasEditorLinter()) {
+ this.editorExtensions.pop();
+ }
+ this.onExtensionChange();
+ }
+
+ public hasEditorLinter(): boolean {
+ return this.editorExtensions.length !== 0;
+ }
+
+ public toggleAutoLint() {
+ if (this.hasEditorLinter()) {
+ this.disableEditorLinter();
+ } else {
+ this.enableEditorLinter();
+ }
+ }
+}
+
+/** Harper returns positions based on char indexes,
+ * but Obsidian identifies locations in documents based on Unicode code points.
+ * This converts between from the former to the latter.*/
+function charIndexToCodePointIndex(index: number, sourceChars: string[]): number {
+ let traversed = 0;
+
+ for (let i = 0; i < index; i++) {
+ const delta = sourceChars[i].length;
+
+ traversed += delta;
+ }
+
+ return traversed;
+}
+
+function suggestionToLabel(sug: Suggestion) {
+ if (sug.kind() === SuggestionKind.Remove) {
+ return 'Remove';
+ } else if (sug.kind() === SuggestionKind.Replace) {
+ return `Replace with “${sug.get_replacement_text()}”`;
+ } else if (sug.kind() === SuggestionKind.InsertAfter) {
+ return `Insert “${sug.get_replacement_text()}” after this.`;
+ }
+}
diff --git a/packages/obsidian-plugin/src/index.ts b/packages/obsidian-plugin/src/index.ts
index bf239b238..cc97b9771 100644
--- a/packages/obsidian-plugin/src/index.ts
+++ b/packages/obsidian-plugin/src/index.ts
@@ -1,19 +1,9 @@
-import type { Extension } from '@codemirror/state';
-import type { LintConfig, Linter, Suggestion } from 'harper.js';
-import {
- Dialect,
- LocalLinter,
- SuggestionKind,
- WorkerLinter,
- binary,
- binaryInlined,
-} from 'harper.js';
-import { toArray } from 'lodash-es';
+import { Dialect } from 'harper.js';
import { type App, Menu, Notice, Plugin, type PluginManifest } from 'obsidian';
-import logoSvg from '../logo.svg';
+import logoSvg from '../logo.svg?raw';
import packageJson from '../package.json';
import { HarperSettingTab } from './HarperSettingTab';
-import { linter } from './lint';
+import State from './State';
async function getLatestVersion(): Promise<string> {
const response = await fetch('https://writewithharper.com/latestversion', {
@@ -42,105 +32,16 @@ export async function logVersionInfo(): Promise<void> {
logVersionInfo();
-function suggestionToLabel(sug: Suggestion) {
- if (sug.kind() === SuggestionKind.Remove) {
- return 'Remove';
- } else if (sug.kind() === SuggestionKind.Replace) {
- return `Replace with “${sug.get_replacement_text()}”`;
- } else if (sug.kind() === SuggestionKind.InsertAfter) {
- return `Insert “${sug.get_replacement_text()}” after this.`;
- }
-}
-
-const DEFAULT_DELAY = -1;
-
-export type Settings = {
- ignoredLints?: string;
- useWebWorker: boolean;
- dialect?: Dialect;
- lintSettings: LintConfig;
- userDictionary?: string[];
- delay?: number;
-};
-
export default class HarperPlugin extends Plugin {
- private harper: Linter;
- private editorExtensions: Extension[];
- private delay: number;
+ private state: State;
private dialectSpan: HTMLSpanElement | null = null;
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
- this.harper = new WorkerLinter({ binary: binaryInlined });
- this.editorExtensions = [];
- this.delay = DEFAULT_DELAY;
- }
-
- public async initializeFromSettings(settings: Settings | null) {
- if (settings == null) {
- settings = { useWebWorker: true, lintSettings: {} };
- }
-
- if (Object.keys(settings.lintSettings).length == 0) {
- settings.lintSettings = await this.harper.getDefaultLintConfig();
- Object.keys(settings.lintSettings).forEach((key) => {
- settings.lintSettings[key] = null;
- });
- }
-
- const oldSettings = await this.getSettings();
-
- if (
- settings.useWebWorker !== oldSettings.useWebWorker ||
- settings.dialect !== oldSettings.dialect
- ) {
- if (settings.useWebWorker) {
- this.harper = new WorkerLinter({ binary: binaryInlined, dialect: settings.dialect });
- } else {
- this.harper = new LocalLinter({ binary: binaryInlined, dialect: settings.dialect });
- }
- } else {
- await this.harper.clearIgnoredLints();
- }
-
- if (settings.ignoredLints !== undefined) {
- await this.harper.importIgnoredLints(settings.ignoredLints);
- }
-
- if (settings.userDictionary != null && settings.userDictionary.length > 0) {
- await this.harper.importWords(settings.userDictionary);
- }
-
- await this.harper.setLintConfig(settings.lintSettings);
- this.harper.setup();
-
- this.delay = settings.delay ?? DEFAULT_DELAY;
-
- // Reinitialize it.
- if (this.hasEditorLinter()) {
- this.disableEditorLinter();
- this.enableEditorLinter();
- }
-
- await this.saveData(settings);
- }
-
- public async reinitialize() {
- const settings = await this.getSettings();
- await this.initializeFromSettings(settings);
- }
-
- public async getSettings(): Promise<Settings> {
- const usingWebWorker = this.harper instanceof WorkerLinter;
-
- return {
- ignoredLints: await this.harper.exportIgnoredLints(),
- useWebWorker: usingWebWorker,
- lintSettings: await this.harper.getLintConfig(),
- userDictionary: await this.harper.exportWords(),
- dialect: await this.harper.getDialect(),
- delay: this.delay,
- };
+ this.state = new State(
+ (n) => this.saveData(n),
+ () => this.app.workspace.updateOptions(),
+ );
}
async onload() {
@@ -150,17 +51,13 @@ export default class HarperPlugin extends Plugin {
}
const data = await this.loadData();
- await this.initializeFromSettings(data);
- this.registerEditorExtension(this.editorExtensions);
+ await this.state.initializeFromSettings(data);
+ this.registerEditorExtension(this.state.getCMEditorExtensions());
this.setupCommands();
this.setupStatusBar();
- this.enableEditorLinter();
+ this.state.enableEditorLinter();
- this.addSettingTab(new HarperSettingTab(this.app, this));
- }
-
- public async getDescriptions(): Promise<Record<string, string>> {
- return await this.harper.getLintDescriptions();
+ this.addSettingTab(new HarperSettingTab(this.app, this, this.state));
}
private getDialectStatus(dialectNum: Dialect): string {
@@ -180,8 +77,7 @@ export default class HarperPlugin extends Plugin {
}
private setupStatusBar() {
- /** @type HTMLElement */
- const statusBarItem = this.addStatusBarItem();
+ const statusBarItem: HTMLElement = this.addStatusBarItem();
statusBarItem.className += ' mod-clickable';
const button = document.createElement('span');
@@ -196,7 +92,8 @@ export default class HarperPlugin extends Plugin {
const dialect = document.createElement('span');
this.dialectSpan = dialect;
- this.harper.getDialect().then((dialectNum) => {
+ this.state.getSettings().then((settings) => {
+ const dialectNum = settings.dialect ?? Dialect.American;
this.updateStatusBar(dialectNum);
button.appendChild(dialect);
});
@@ -206,10 +103,10 @@ export default class HarperPlugin extends Plugin {
menu.addItem((item) =>
item
- .setTitle(`${this.hasEditorLinter() ? 'Disable' : 'Enable'} automatic checking`)
+ .setTitle(`${this.state.hasEditorLinter() ? 'Disable' : 'Enable'} automatic checking`)
.setIcon('documents')
.onClick(() => {
- this.toggleAutoLint();
+ this.state.toggleAutoLint();
}),
);
@@ -223,139 +120,13 @@ export default class HarperPlugin extends Plugin {
this.addCommand({
id: 'harper-toggle-auto-lint',
name: 'Toggle automatic grammar checking',
- callback: () => this.toggleAutoLint(),
+ callback: () => this.state.toggleAutoLint(),
});
}
- enableEditorLinter() {
- if (!this.hasEditorLinter()) {
- this.editorExtensions.push(this.constructEditorLinter());
- this.app.workspace.updateOptions();
- console.log('Enabled');
- }
- }
-
- disableEditorLinter() {
- while (this.hasEditorLinter()) {
- this.editorExtensions.pop();
- }
- this.app.workspace.updateOptions();
- }
-
- hasEditorLinter(): boolean {
- return this.editorExtensions.length !== 0;
- }
-
- private toggleAutoLint() {
- if (this.hasEditorLinter()) {
- this.disableEditorLinter();
- } else {
- this.enableEditorLinter();
- }
- }
-
- /** Construct the linter plugin that actually shows the errors. */
- private constructEditorLinter(): Extension {
- return linter(
- async (view) => {
- const text = view.state.doc.sliceString(-1);
- const chars = toArray(text);
-
- const lints = await this.harper.lint(text);
-
- return lints.map((lint) => {
- const span = lint.span();
-
- span.start = charIndexToCodePointIndex(span.start, chars);
- span.end = charIndexToCodePointIndex(span.end, chars);
-
- const actions = lint.suggestions().map((sug) => {
- return {
- name: suggestionToLabel(sug),
- apply: (view) => {
- if (sug.kind() === SuggestionKind.Remove) {
- view.dispatch({
- changes: {
- from: span.start,
- to: span.end,
- insert: '',
- },
- });
- } else if (sug.kind() === SuggestionKind.Replace) {
- view.dispatch({
- changes: {
- from: span.start,
- to: span.end,
- insert: sug.get_replacement_text(),
- },
- });
- } else if (sug.kind() === SuggestionKind.InsertAfter) {
- view.dispatch({
- changes: {
- from: span.end,
- to: span.end,
- insert: sug.get_replacement_text(),
- },
- });
- }
- },
- };
- });
-
- if (lint.lint_kind() === 'Spelling') {
- const word = lint.get_problem_text();
-
- actions.push({
- name: `Add “${word}” to your dictionary`,
- apply: (view) => {
- this.harper.importWords([word]);
- this.reinitialize();
- },
- });
- }
-
- return {
- from: span.start,
- to: span.end,
- severity: 'error',
- title: lint.lint_kind_pretty(),
- renderMessage: (view) => {
- const node = document.createElement('template');
- node.innerHTML = lint.message_html();
- return node.content;
- },
- ignore: async () => {
- await this.harper.ignoreLint(text, lint);
- await this.reinitialize();
- },
- actions,
- };
- });
- },
- {
- delay: this.delay,
- },
- );
- }
-
- updateStatusBar(dialect: Dialect) {
+ public updateStatusBar(dialect: Dialect) {
if (this.dialectSpan != null) {
this.dialectSpan.innerHTML = this.getDialectStatus(dialect);
}
}
}
-
-/** Harper returns positions based on char indexes,
- * but Obsidian identifies locations in documents based on Unicode code points.
- * This converts between from the former to the latter.*/
-function charIndexToCodePointIndex(index: number, sourceChars: string[]): number {
- let traversed = 0;
-
- for (let i = 0; i < index; i++) {
- const delta = sourceChars[i].length;
-
- traversed += delta;
- }
-
- return traversed;
-}
diff --git a/packages/obsidian-plugin/vite.config.ts b/packages/obsidian-plugin/vite.config.ts
new file mode 100644
index 000000000..d99b47abb
--- /dev/null
+++ b/packages/obsidian-plugin/vite.config.ts
@@ -0,0 +1,32 @@
+import external from 'rollup-plugin-peer-deps-external';
+import svg from 'rollup-plugin-svg-import';
+import { defineConfig } from 'vite';
+
+export default defineConfig({
+ plugins: [svg({ stringify: true }), external()],
+ build: {
+ outDir: '.',
+ target: 'es6',
+ lib: {
+ entry: 'src/index.ts',
+ formats: ['cjs'],
+ fileName: 'main',
+ },
+ rollupOptions: {
+ external: ['obsidian', 'electron'],
+ output: {
+ inlineDynamicImports: true,
+ },
+ },
+ },
+ test: {
+ retry: process.env.CI ? 5 : 0,
+ browser: {
+ provider: 'playwright',
+ enabled: true,
+ headless: true,
+ screenshotFailures: false,
+ instances: [{ browser: 'chromium' }],
+ },
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ee3d6b0c8..701782dac 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -133,7 +133,7 @@ importers:
version: 7.52.1(@types/[email protected])
'@vitest/browser':
specifier: ^3.0.6
harper-wasm:
specifier: workspace:*
version: link:../../harper-wasm/pkg
@@ -154,13 +154,13 @@ importers:
version: 5.8.2
vite:
specifier: ^6.1.0
vite-plugin-dts:
specifier: ^4.5.0
vite-plugin-virtual:
specifier: ^0.3.0
vitest:
specifier: ^3.0.5
@@ -219,30 +219,30 @@ importers:
specifier: 'catalog:'
version: 2.8.1
devDependencies:
- '@rollup/plugin-json':
- specifier: ^6.1.0
- version: 6.1.0([email protected])
'@rollup/plugin-node-resolve':
specifier: ^16.0.0
version: 16.0.1([email protected])
- '@rollup/plugin-typescript':
- specifier: ^12.1.2
- '@rollup/plugin-wasm':
- specifier: ^6.2.2
- version: 6.2.2([email protected])
+ '@types/lodash-es':
+ specifier: ^4.17.12
+ version: 4.17.12
+ '@vitest/browser':
+ specifier: ^3.0.6
obsidian:
specifier: ^1.7.2
version: 1.8.7(@codemirror/[email protected])(@codemirror/[email protected])
- rollup:
- specifier: ^4.34.9
- version: 4.35.0
rollup-plugin-peer-deps-external:
specifier: ^2.2.4
version: 2.2.4([email protected])
rollup-plugin-svg-import:
specifier: ^3.0.0
version: 3.0.0([email protected])
+ vite:
+ specifier: ^6.3.5
+ vitest:
+ specifier: ^3.0.8
packages/vscode-plugin:
dependencies:
@@ -279,10 +279,10 @@ importers:
dependencies:
'@sveltepress/theme-default':
specifier: ^5.0.7
- version: 5.0.8(119b2392b87513309a4baf63f09633e5)
+ version: 5.0.8(ec98b668707205b36fd417e3c66836ba)
'@sveltepress/vite':
specifier: ^1.1.5
chart.js:
specifier: ^4.4.8
version: 4.4.8
@@ -304,13 +304,13 @@ importers:
devDependencies:
'@sveltejs/adapter-node':
specifier: ^5.2.12
'@sveltejs/kit':
specifier: ^2.17.1
'@sveltejs/vite-plugin-svelte':
specifier: ^5.0.3
'@types/reveal.js':
specifier: ^5.0.3
version: 5.0.5
@@ -343,16 +343,16 @@ importers:
version: 5.8.2
vite:
specifier: ^6.1.0
vite-plugin-pwa:
specifier: ^0.21.1
vite-plugin-top-level-await:
specifier: ^1.5.0
vite-plugin-wasm:
specifier: ^3.4.1
packages/wordpress-plugin:
dependencies:
@@ -2559,19 +2559,6 @@ packages:
rollup:
optional: true
- '@rollup/[email protected]':
- resolution: {integrity: sha512-cdtSp154H5sv637uMr1a8OTWB0L1SWDSm1rDGiyfcGcvQ6cuTs4MDk2BVEBGysUWago4OJN4EQZqOTl/QY3Jgg==}
- engines: {node: '>=14.0.0'}
- peerDependencies:
- rollup: ^2.14.0||^3.0.0||^4.0.0
- tslib: '*'
- typescript: '>=3.7.0'
- peerDependenciesMeta:
- rollup:
- optional: true
- tslib:
- optional: true
-
'@rollup/[email protected]':
resolution: {integrity: sha512-10monEYsBp3scM4/ND4LNH5Rxvh3e/cVeL3jWTgZ2SrQ+BmUoQcopVQvnaMcOnykb1VkxUFuDAN+0FnpTFRy2A==}
engines: {node: '>=14.0.0'}
@@ -2581,15 +2568,6 @@ packages:
rollup:
optional: true
- '@rollup/[email protected]':
- resolution: {integrity: sha512-gpC4R1G9Ni92ZIRTexqbhX7U+9estZrbhP+9SRb0DW9xpB9g7j34r+J2hqrcW/lRI7dJaU84MxZM0Rt82tqYPQ==}
- engines: {node: '>=14.0.0'}
- peerDependencies:
- rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0
- peerDependenciesMeta:
- rollup:
- optional: true
-
'@rollup/[email protected]':
resolution: {integrity: sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==}
engines: {node: '>= 8.0.0'}
@@ -6060,6 +6038,14 @@ packages:
picomatch:
optional: true
+ resolution: {integrity: sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
resolution: {integrity: sha512-txsf5fu3anp2ff3+gOJJzRImtrtm/oa9tYLN0iTuINZ++EyVR/nRrg2fKYwvG/pXDofcrvvb0scEbX3NyW/COw==}
@@ -10235,6 +10221,10 @@ packages:
resolution: {integrity: sha512-qkf4trmKSIiMTs/E63cxH+ojC2unam7rJ0WrauAzpT3ECNTxGRMlaXxVbfxMUC/w0LaYk6jQ4y/nGR9uBO3tww==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-al6n+QEANGFOMf/dmUMsuS5/r9B06uwlyNjZZql/zv8J7ybHCgoihBNORZCY2mzUuAnomQa2JdhyHKzZxPCrFA==}
engines: {node: ^18.0.0 || >=20.0.0}
@@ -10765,8 +10755,8 @@ packages:
terser:
optional: true
- resolution: {integrity: sha512-yW7PeMM+LkDzc7CgJuRLMW2Jz0FxMOsVJ8Lv3gpgW9WLcb9cTW+121UEr1hvmfR7w3SegR5ItvYyzVz1vxNJgQ==}
+ resolution: {integrity: sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
hasBin: true
peerDependencies:
@@ -14308,25 +14298,10 @@ snapshots:
optionalDependencies:
rollup: 2.79.2
- dependencies:
- '@rollup/pluginutils': 5.1.4([email protected])
- resolve: 1.22.10
- typescript: 5.8.2
- optionalDependencies:
- rollup: 4.35.0
- tslib: 2.8.1
-
optionalDependencies:
rollup: 4.35.0
- dependencies:
- '@rollup/pluginutils': 5.1.4([email protected])
- optionalDependencies:
- rollup: 4.35.0
-
dependencies:
'@types/estree': 0.0.39
@@ -14573,17 +14548,17 @@ snapshots:
magic-string: 0.25.9
string.prototype.matchall: 4.0.12
dependencies:
'@rollup/plugin-commonjs': 28.0.3([email protected])
'@rollup/plugin-json': 6.1.0([email protected])
'@rollup/plugin-node-resolve': 16.0.1([email protected])
rollup: 4.35.0
dependencies:
'@types/cookie': 0.6.0
cookie: 0.6.0
devalue: 5.1.1
@@ -14596,7 +14571,7 @@ snapshots:
set-cookie-parser: 2.7.1
sirv: 3.0.1
svelte: 5.21.0
dependencies:
@@ -14607,12 +14582,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 4.4.0
svelte: 5.21.0
transitivePeerDependencies:
- supports-color
@@ -14629,30 +14604,30 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 4.4.0
deepmerge: 4.3.1
kleur: 4.1.5
magic-string: 0.30.17
svelte: 5.21.0
transitivePeerDependencies:
- supports-color
- '@sveltepress/[email protected](119b2392b87513309a4baf63f09633e5)':
+ '@sveltepress/[email protected](ec98b668707205b36fd417e3c66836ba)':
dependencies:
'@docsearch/css': 3.9.0
'@shikijs/twoslash': 1.29.2([email protected])
'@sveltepress/twoslash': 1.1.6([email protected])([email protected])
'@unocss/extractor-svelte': 0.61.9
lru-cache: 10.4.3
mdast-util-from-markdown: 2.0.2
mdast-util-gfm: 3.1.0
@@ -14660,8 +14635,8 @@ snapshots:
svelte: 5.21.0
uid: 2.0.2
unist-util-visit: 5.0.0
workbox-precaching: 7.3.0
workbox-routing: 7.3.0
transitivePeerDependencies:
@@ -14695,10 +14670,10 @@ snapshots:
- supports-color
- typescript
dependencies:
cross-spawn: 7.0.6
fs-extra: 11.3.0
lru-cache: 10.4.3
@@ -14717,8 +14692,8 @@ snapshots:
unified: 11.0.5
unist-util-visit: 5.0.0
vfile: 6.0.3
yaml: 2.7.0
transitivePeerDependencies:
- '@nuxt/kit'
@@ -15406,13 +15381,13 @@ snapshots:
'@ungap/[email protected]': {}
dependencies:
'@unocss/core': 0.61.9
'@unocss/reset': 0.61.9
optionalDependencies:
transitivePeerDependencies:
- rollup
- supports-color
@@ -15551,7 +15526,7 @@ snapshots:
dependencies:
'@unocss/core': 0.61.9
dependencies:
'@ampproject/remapping': 2.3.0
'@rollup/pluginutils': 5.1.4([email protected])
@@ -15563,7 +15538,7 @@ snapshots:
chokidar: 3.6.0
fast-glob: 3.3.3
magic-string: 0.30.17
transitivePeerDependencies:
- rollup
- supports-color
@@ -15575,17 +15550,17 @@ snapshots:
'@use-gesture/core': 10.3.1
react: 18.3.1
dependencies:
kolorist: 1.8.0
tinyglobby: 0.2.12
dependencies:
'@testing-library/user-event': 14.6.1(@testing-library/[email protected])
'@vitest/utils': 3.0.8
magic-string: 0.30.17
@@ -15610,14 +15585,14 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
dependencies:
'@vitest/spy': 3.0.8
estree-walker: 3.0.3
magic-string: 0.30.17
optionalDependencies:
'@vitest/[email protected]':
dependencies:
@@ -19197,6 +19172,10 @@ snapshots:
optionalDependencies:
picomatch: 4.0.2
+ optionalDependencies:
+ picomatch: 4.0.2
+
dependencies:
flat-cache: 6.1.7
@@ -24128,6 +24107,11 @@ snapshots:
fdir: 6.4.3([email protected])
picomatch: 4.0.2
+ dependencies:
+ fdir: 6.4.4([email protected])
+ picomatch: 4.0.2
+
@@ -24412,9 +24396,9 @@ snapshots:
dependencies:
'@unocss/cli': 0.61.9([email protected])
'@unocss/core': 0.61.9
'@unocss/extractor-arbitrary-variants': 0.61.9
@@ -24433,9 +24417,9 @@ snapshots:
'@unocss/transformer-compile-class': 0.61.9
'@unocss/transformer-directives': 0.61.9
'@unocss/transformer-variant-group': 0.61.9
optionalDependencies:
transitivePeerDependencies:
- postcss
- rollup
@@ -24608,7 +24592,7 @@ snapshots:
debug: 4.4.0
es-module-lexer: 1.6.0
pathe: 2.0.3
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -24623,7 +24607,7 @@ snapshots:
- tsx
- yaml
dependencies:
'@microsoft/api-extractor': 7.52.1(@types/[email protected])
'@rollup/pluginutils': 5.1.4([email protected])
@@ -24636,13 +24620,13 @@ snapshots:
magic-string: 0.30.17
typescript: 5.8.2
optionalDependencies:
transitivePeerDependencies:
- '@types/node'
- rollup
- supports-color
dependencies:
'@antfu/utils': 0.7.10
'@rollup/pluginutils': 5.1.4([email protected])
@@ -24653,39 +24637,39 @@ snapshots:
perfect-debounce: 1.0.0
picocolors: 1.1.1
sirv: 3.0.1
transitivePeerDependencies:
- rollup
- supports-color
dependencies:
debug: 4.4.0
pretty-bytes: 6.1.1
tinyglobby: 0.2.12
workbox-build: 7.3.0(@types/[email protected])
workbox-window: 7.3.0
transitivePeerDependencies:
- supports-color
dependencies:
'@rollup/plugin-virtual': 3.0.2([email protected])
'@swc/core': 1.11.9
uuid: 10.0.0
transitivePeerDependencies:
- '@swc/helpers'
- rollup
dependencies:
dependencies:
dependencies:
@@ -24699,11 +24683,14 @@ snapshots:
sass: 1.85.1
terser: 5.39.0
dependencies:
esbuild: 0.25.1
+ fdir: 6.4.4([email protected])
+ picomatch: 4.0.2
postcss: 8.5.3
rollup: 4.35.0
+ tinyglobby: 0.2.13
optionalDependencies:
'@types/node': 22.13.10
fsevents: 2.3.3
@@ -24718,14 +24705,14 @@ snapshots:
optionalDependencies:
optionalDependencies:
dependencies:
'@vitest/expect': 3.0.8
'@vitest/pretty-format': 3.0.8
'@vitest/runner': 3.0.8
'@vitest/snapshot': 3.0.8
@@ -24741,13 +24728,13 @@ snapshots:
tinyexec: 0.3.2
tinypool: 1.0.2
tinyrainbow: 2.0.0
why-is-node-running: 2.3.0
optionalDependencies:
'@types/debug': 4.1.12
'@types/node': 22.13.10
jsdom: 20.0.3
transitivePeerDependencies:
- jiti