Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(#364): refactored to reduce duplication of state
Elijah Potter8697a0046ac7
diff --git a/packages/harper.js/src/main.ts b/packages/harper.js/src/main.tsindex 983925321..d967c5a6e 100644--- a/packages/harper.js/src/main.ts+++ b/packages/harper.js/src/main.ts@@ -8,7 +8,8 @@ export type { Linter, Lint, Span, Suggestion };export enum SuggestionKind {Replace = 0,- Remove = 1+ Remove = 1,+ InsertAfter = 2}export type LintConfig = Record<string, boolean | undefined>;diff --git a/packages/obsidian-plugin/.gitignore b/packages/obsidian-plugin/.gitignoreindex 7abf2a8c6..88acc764a 100644--- a/packages/obsidian-plugin/.gitignore+++ b/packages/obsidian-plugin/.gitignore@@ -2,3 +2,4 @@main.jsnode_modulesharper-obsidian-plugin.zip+manifest.jsondiff --git a/packages/obsidian-plugin/package.json b/packages/obsidian-plugin/package.jsonindex 0ed5826ba..9c8f8ee3b 100644--- a/packages/obsidian-plugin/package.json+++ b/packages/obsidian-plugin/package.json@@ -1,36 +1,37 @@{- "name": "obsidian-plugin",- "private": true,- "version": "0.0.1",- "main": "main.js",- "devDependencies": {- "@rollup/plugin-node-resolve": "^15.2.3",- "@rollup/plugin-typescript": "^11.1.6",- "@rollup/plugin-wasm": "^6.2.2",- "rollup": "^4.22.4",- "rollup-plugin-peer-deps-external": "^2.2.4",- "rollup-plugin-svg-import": "^3.0.0"- },- "scripts": {- "build": "rollup -c",- "dev": "rollup -c --watch"- },- "peerDependencies": {- "@codemirror/autocomplete": "^6.16.3",- "@codemirror/collab": "^6.1.1",- "@codemirror/commands": "^6.6.0",- "@codemirror/language": "^6.10.2",- "@codemirror/lint": "^6.8.1",- "@codemirror/search": "^6.5.6",- "@codemirror/state": "^6.4.1",- "@codemirror/view": "^6.28.3",- "@lezer/common": "^1.2.1",- "@lezer/highlight": "^1.2.0",- "@lezer/lr": "^1.4.1"- },- "dependencies": {- "crelt": "^1.0.5",- "lodash-es": "^4.17.21",- "harper.js": "link:../harper.js"- }+ "name": "obsidian-plugin",+ "private": true,+ "version": "0.0.1",+ "main": "main.js",+ "devDependencies": {+ "@rollup/plugin-node-resolve": "^15.2.3",+ "@rollup/plugin-typescript": "^11.1.6",+ "@rollup/plugin-wasm": "^6.2.2",+ "obsidian": "^1.7.2",+ "rollup": "^4.22.4",+ "rollup-plugin-peer-deps-external": "^2.2.4",+ "rollup-plugin-svg-import": "^3.0.0"+ },+ "scripts": {+ "build": "rollup -c",+ "dev": "rollup -c --watch"+ },+ "peerDependencies": {+ "@codemirror/autocomplete": "^6.16.3",+ "@codemirror/collab": "^6.1.1",+ "@codemirror/commands": "^6.6.0",+ "@codemirror/language": "^6.10.2",+ "@codemirror/lint": "^6.8.1",+ "@codemirror/search": "^6.5.6",+ "@codemirror/state": "^6.4.1",+ "@codemirror/view": "^6.28.3",+ "@lezer/common": "^1.2.1",+ "@lezer/highlight": "^1.2.0",+ "@lezer/lr": "^1.4.1"+ },+ "dependencies": {+ "crelt": "^1.0.5",+ "harper.js": "link:../harper.js",+ "lodash-es": "^4.17.21"+ }}diff --git a/packages/obsidian-plugin/rollup.config.mjs b/packages/obsidian-plugin/rollup.config.mjsindex 66b6e012f..ab7345270 100644--- a/packages/obsidian-plugin/rollup.config.mjs+++ b/packages/obsidian-plugin/rollup.config.mjs@@ -5,7 +5,7 @@ import { nodeResolve } from '@rollup/plugin-node-resolve';import svg from 'rollup-plugin-svg-import';export default {- input: 'src/index.js',+ input: 'src/index.ts',output: {file: 'main.js',format: 'cjs'diff --git a/packages/obsidian-plugin/src/HarperSettingTab.js b/packages/obsidian-plugin/src/HarperSettingTab.tssimilarity index 65%rename from packages/obsidian-plugin/src/HarperSettingTab.jsrename to packages/obsidian-plugin/src/HarperSettingTab.tsindex e75b08452..482d4f3fe 100644--- a/packages/obsidian-plugin/src/HarperSettingTab.js+++ b/packages/obsidian-plugin/src/HarperSettingTab.ts@@ -1,21 +1,14 @@import './index.js';import { startCase } from 'lodash-es';-import { PluginSettingTab, Setting } from 'obsidian';+import { App, PluginSettingTab, Setting } from 'obsidian';+import HarperPlugin, { Settings } from './index.js';export class HarperSettingTab extends PluginSettingTab {- /** @type HarperPlugin- * @private */- plugin;+ private plugin: HarperPlugin;+ private settings: Settings;+ private descriptions: Record<string, string>;- /** @type Record<string, any> */- settings;-- /** @type Record<string, string> */- descriptions;-- /** @param {App} app- * @param {HarperPlugin} plugin */- constructor(app, plugin) {+ constructor(app: App, plugin: HarperPlugin) {super(app, plugin);this.plugin = plugin;@@ -40,13 +33,13 @@ 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.setSettings(this.settings);+ await this.plugin.initializeFromSettings(this.settings);}));- for (let setting of Object.keys(this.settings.lintSettings)) {- let value = this.settings.lintSettings[setting];- let description = this.descriptions[setting];+ for (const setting of Object.keys(this.settings.lintSettings)) {+ const value = this.settings.lintSettings[setting];+ const description = this.descriptions[setting];new Setting(containerEl).setName(startCase(setting))@@ -59,16 +52,14 @@ export class HarperSettingTab extends PluginSettingTab {.setValue(valueToString(value)).onChange(async (value) => {this.settings.lintSettings[setting] = stringToValue(value);- await this.plugin.setSettings(this.settings);+ await this.plugin.initializeFromSettings(this.settings);}));}}}-/** @param {boolean | undefined} value- * @returns {string} */-function valueToString(value) {+function valueToString(value: boolean | undefined): string {switch (value) {case true:return 'enable';@@ -81,16 +72,14 @@ function valueToString(value) {throw 'Fell through case';}-/** @param {str} value- * @returns {boolean | undefined} */-function stringToValue(str) {+function stringToValue(str): boolean | undefined {switch (str) {case 'enable':return true;case 'disable':return false;case 'default':- return null;+ return undefined;}throw 'Fell through case';diff --git a/packages/obsidian-plugin/src/index.js b/packages/obsidian-plugin/src/index.jsdeleted file mode 100644index 68cf5111f..000000000--- a/packages/obsidian-plugin/src/index.js+++ /dev/null@@ -1,209 +0,0 @@-import logoSvg from '../logo.svg';-import { linter } from './lint';-import { Plugin, addIcon, Menu } from 'obsidian';-import { LocalLinter, WorkerLinter } from 'harper.js';-import { HarperSettingTab } from './HarperSettingTab';--function suggestionToLabel(sug) {- if (sug.kind() == 'Remove') {- return 'Remove';- } else {- return `Replace with "${sug.get_replacement_text()}"`;- }-}--function initHarperInstance(useWebWorker) {- if (useWebWorker) {- console.log('Switching to `WorkerLinter`');- harper = new WorkerLinter();- } else {- console.log('Switching to `LocalLinter`');- harper = new LocalLinter();- }- harper.setup();-}--let harper;--initHarperInstance(true);--const harperLinter = (plugin) =>- linter(- async (view) => {- if (!plugin.shouldLint()) {- return [];- }-- const text = view.state.doc.sliceString(-1);-- const lints = await harper.lint(text);-- return lints.map((lint) => {- let span = lint.span();-- return {- from: span.start,- to: span.end,- severity: 'error',- title: lint.lint_kind(),- message: lint.message(),- actions: lint.suggestions().map((sug) => {- return {- name: suggestionToLabel(sug),- apply: (view) => {- if (sug === 'Remove') {- view.dispatch({- changes: {- from: span.start,- to: span.end,- insert: ''- }- });- } else {- view.dispatch({- changes: {- from: span.start,- to: span.end,- insert: sug.get_replacement_text()- }- });- }- }- };- })- };- });- },- {- delay: -1,- needsRefresh: () => {- let temp = plugin.lintSettingModified;- plugin.lintSettingModified = false;- return temp;- }- }- );--export default class HarperPlugin extends Plugin {- /** @private */- shouldAutoLint = true;- /** @public */- lintSettingModified = false;-- /** @public- * @returns {Promise<Record<string, string>>} */- async getDescriptions() {- return await harper.getLintDescriptions();- }-- /** @public- * @returns {Promise<Record<string, any>>} */- async getSettings() {- this.lintSettingChanged();-- let lintSettings = await harper.getLintConfig();-- return { ...this.settings, lintSettings };- }-- /** @public- * @param {Record<string, any>} settings- * @returns {Promise<void>} */- async setSettings(settings) {- if (settings == null) {- settings = {};- }-- if (settings.useWebWorker == undefined) {- settings.useWebWorker = true;- }-- if (settings.lintSettings == undefined) {- settings.lintSettings = {};- }-- if (settings.lintSettings.spell_check == undefined) {- settings.lintSettings.spell_check = false;- }-- await harper.setLintConfig(settings.lintSettings);- this.lintSettingChanged();- this.saveData(settings);-- if (this.settings?.useWebWorker != settings.useWebWorker) {- initHarperInstance(settings.useWebWorker);- }-- this.settings = settings;- }-- async onload() {- console.log(harperLinter(this));-- this.registerEditorExtension([harperLinter(this)]);- this.app.workspace.updateOptions();-- addIcon('harper-logo', logoSvg);-- this.setupCommands();- this.setupStatusBar();-- await this.setSettings(await this.loadData());- this.addSettingTab(new HarperSettingTab(this.app, this));- }-- setupCommands() {- this.addCommand({- id: 'harper-toggle-auto-lint',- name: 'Toggle automatic grammar checking',- callback: () => this.toggleAutoLint()- });- }-- setupStatusBar() {- /** @type HTMLElement */- let statusBarItem = this.addStatusBarItem();- statusBarItem.className += ' mod-clickable';-- let button = document.createElement('span');- button.style = 'width:24px';- button.innerHTML = logoSvg;-- button.addEventListener('click', (event) => {- const menu = new Menu();-- menu.addItem((item) =>- item- .setTitle(`${this.shouldAutoLint ? 'Disable' : 'Enable'} automatic checking`)- .setIcon('documents')- .onClick(() => {- this.toggleAutoLint();- })- );-- menu.showAtMouseEvent(event);- });-- statusBarItem.appendChild(button);- }-- shouldLint() {- return this.shouldAutoLint;- }-- /** @param {boolean} shouldAutoLint */- setAutoLint(shouldAutoLint) {- this.shouldAutoLint = shouldAutoLint;- this.lintSettingChanged();- }-- toggleAutoLint() {- this.shouldAutoLint = !this.shouldAutoLint;- this.lintSettingChanged();- }-- lintSettingChanged() {- this.lintSettingModified = true;- this.app.workspace.updateOptions();- }-}diff --git a/packages/obsidian-plugin/src/index.ts b/packages/obsidian-plugin/src/index.tsnew file mode 100644index 000000000..ccc954e70--- /dev/null+++ b/packages/obsidian-plugin/src/index.ts@@ -0,0 +1,200 @@+import logoSvg from '../logo.svg';+import { Plugin, addIcon, Menu, PluginManifest, App } from 'obsidian';+import { LintConfig, Linter, Suggestion } from 'harper.js';+import { LocalLinter, SuggestionKind, WorkerLinter } from 'harper.js';+import { linter } from './lint';+import { Extension } from '@codemirror/state';+import { HarperSettingTab } from './HarperSettingTab';++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.`;+ }+}++export type Settings = {+ useWebWorker: boolean;+ lintSettings: LintConfig;+};++export default class HarperPlugin extends Plugin {+ private harper: Linter;+ private editorExtensions: Extension[];++ constructor(app: App, manifest: PluginManifest) {+ super(app, manifest);+ this.harper = new WorkerLinter();+ this.editorExtensions = [];+ }++ public async initializeFromSettings(settings: Settings | null) {+ if (settings == null) {+ settings = { useWebWorker: true, lintSettings: {} };+ }++ if (settings.useWebWorker) {+ this.harper = new WorkerLinter();+ } else {+ this.harper = new LocalLinter();+ }++ await this.harper.setLintConfig(settings.lintSettings);+ this.harper.setup();++ // Reinitialize it.+ if (this.hasEditorLinter()) {+ this.disableEditorLinter();+ this.enableEditorLinter();+ }++ await this.saveData(settings);+ }++ public async getSettings(): Promise<Settings> {+ const usingWebWorker = this.harper instanceof WorkerLinter;++ return {+ useWebWorker: usingWebWorker,+ lintSettings: await this.harper.getLintConfig()+ };+ }++ async onload() {+ const data = await this.loadData();+ await this.initializeFromSettings(data);+ this.registerEditorExtension(this.editorExtensions);+ this.setupCommands();+ this.setupStatusBar();+ this.enableEditorLinter();++ this.addSettingTab(new HarperSettingTab(this.app, this));+ }++ public async getDescriptions(): Promise<Record<string, string>> {+ return await this.harper.getLintDescriptions();+ }++ private setupStatusBar() {+ /** @type HTMLElement */+ const statusBarItem = this.addStatusBarItem();+ statusBarItem.className += ' mod-clickable';++ const button = document.createElement('span');+ button.style = 'width:24px';+ button.innerHTML = logoSvg;++ button.addEventListener('click', (event) => {+ const menu = new Menu();++ menu.addItem((item) =>+ item+ .setTitle(`${this.hasEditorLinter() ? 'Disable' : 'Enable'} automatic checking`)+ .setIcon('documents')+ .onClick(() => {+ this.toggleAutoLint();+ })+ );++ menu.showAtMouseEvent(event);+ });++ statusBarItem.appendChild(button);+ }++ private setupCommands() {+ this.addCommand({+ id: 'harper-toggle-auto-lint',+ name: 'Toggle automatic grammar checking',+ callback: () => this.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 lints = await this.harper.lint(text);++ return lints.map((lint) => {+ const span = lint.span();++ return {+ from: span.start,+ to: span.end,+ severity: 'error',+ title: lint.lint_kind(),+ message: lint.message(),+ 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()+ }+ });+ }+ }+ };+ })+ };+ });+ },+ {+ delay: -1+ }+ );+ }+}diff --git a/packages/yarn.lock b/packages/yarn.lockindex b31d249b2..9b42cc273 100644--- a/packages/yarn.lock+++ b/packages/yarn.lock@@ -2552,6 +2552,13 @@resolved "https://registry.yarnpkg.com/@types/aria-query/-/aria-query-5.0.4.tgz#1a31c3d378850d2778dabb6374d036dcba4ba708"integrity sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==+"@types/[email protected]":+ version "5.60.8"+ resolved "https://registry.yarnpkg.com/@types/codemirror/-/codemirror-5.60.8.tgz#b647d04b470e8e1836dd84b2879988fc55c9de68"+ integrity sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==+ dependencies:+ "@types/tern" "*"+"@types/cookie@^0.6.0":version "0.6.0"resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.6.0.tgz#eac397f28bf1d6ae0ae081363eca2f425bedf0d5"@@ -2625,6 +2632,13 @@resolved "https://registry.yarnpkg.com/@types/statuses/-/statuses-2.0.5.tgz#f61ab46d5352fd73c863a1ea4e1cef3b0b51ae63"integrity sha512-jmIUGWrAiwu3dZpxntxieC+1n/5c3mjrImkmOSQ2NC5uP6cYO4aAZDdSmRcI5C1oiTmqlZGHC+/NmJrKogbP5A==+"@types/tern@*":+ version "0.23.9"+ resolved "https://registry.yarnpkg.com/@types/tern/-/tern-0.23.9.tgz#6f6093a4a9af3e6bb8dde528e024924d196b367c"+ integrity sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw==+ dependencies:+ "@types/estree" "*"+"@types/tough-cookie@^4.0.5":version "4.0.5"resolved "https://registry.yarnpkg.com/@types/tough-cookie/-/tough-cookie-4.0.5.tgz#cb6e2a691b70cb177c6e3ae9c1d2e8b2ea8cd304"@@ -5340,9 +5354,7 @@ gzip-size@^6.0.0:duplexer "^0.1.2""harper.js@link:harper.js":- version "0.0.0"- dependencies:- wasm "link:../harper-wasm/pkg"+ version "0.15.0"has-bigints@^1.0.2:version "1.1.0"@@ -6934,6 +6946,11 @@ mlly@^1.7.2, mlly@^1.7.3:pkg-types "^1.2.1"ufo "^1.5.4"+ version "2.29.4"+ resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.4.tgz#3dbe052889fe7c1b2ed966fcb3a77328964ef108"+ integrity sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==+mri@^1.1.0:version "1.2.0"resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b"@@ -7116,6 +7133,14 @@ object.assign@^4.1.5:has-symbols "^1.1.0"object-keys "^1.1.1"+obsidian@^1.7.2:+ version "1.7.2"+ resolved "https://registry.yarnpkg.com/obsidian/-/obsidian-1.7.2.tgz#2d989288742ae7a65760fd87a953d1ff2a402808"+ integrity sha512-k9hN9brdknJC+afKr5FQzDRuEFGDKbDjfCazJwpgibwCAoZNYHYV8p/s3mM8I6AsnKrPKNXf8xGuMZ4enWelZQ==+ dependencies:+ "@types/codemirror" "5.60.8"+ moment "2.29.4"+ofetch@^1.3.4:version "1.4.1"resolved "https://registry.yarnpkg.com/ofetch/-/ofetch-1.4.1.tgz#b6bf6b0d75ba616cef6519dd8b6385a8bae480ec"