Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(harper.js): can now append to the dictionary
Elijah Potter631b3d20be5d
diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dictindex 3dcca9986..f8cd072d4 100644--- a/harper-core/dictionary.dict+++ b/harper-core/dictionary.dict@@ -34027,7 +34027,6 @@ notional/51Ynotoriety/1Mnotorious/5Ynotwithstanding/7+-notwork/1Snougat/1MSnoun/14KMSnourish/14DSLGdiff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex 55ca43d0c..993c06d7c 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -1,8 +1,6 @@use paste::paste;use serde::{Deserialize, Serialize};-//-use super::an_a::AnA;use super::avoid_curses::AvoidCurses;use super::boring_words::BoringWords;diff --git a/harper-core/src/spell/mutable_dictionary.rs b/harper-core/src/spell/mutable_dictionary.rsindex a88fed755..5c58b77cd 100644--- a/harper-core/src/spell/mutable_dictionary.rs+++ b/harper-core/src/spell/mutable_dictionary.rs@@ -92,7 +92,9 @@ impl MutableDictionary {) {let pairs: Vec<_> = words.into_iter()- .map(|(v, m)| (v.as_ref().to_smallvec(), m))+ .filter_map(|(v, m)| {+ (!self.contains_word(v.as_ref())).then(|| (v.as_ref().to_smallvec(), m))+ }).collect();self.words.extend(pairs.iter().map(|(v, _)| v.clone()));diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rsindex c4cfb22da..8a49a0b2c 100644--- a/harper-wasm/src/lib.rs+++ b/harper-wasm/src/lib.rs@@ -6,7 +6,10 @@ use std::sync::Arc;use harper_core::language_detection::is_doc_likely_english;use harper_core::linting::{LintGroup, LintGroupConfig, Linter as _};use harper_core::parsers::{IsolateEnglish, Markdown, Parser, PlainEnglish};-use harper_core::{remove_overlaps, Document, FstDictionary, IgnoredLints, Lrc, MutableDictionary};+use harper_core::{+ remove_overlaps, CharString, Dictionary, Document, FstDictionary, IgnoredLints, Lrc,+ MergedDictionary, MutableDictionary, WordMetadata,+};use serde::{Deserialize, Serialize};use wasm_bindgen::prelude::wasm_bindgen;use wasm_bindgen::JsValue;@@ -61,8 +64,12 @@ impl Language {#[wasm_bindgen]pub struct Linter {- lint_group: LintGroup<Arc<FstDictionary>>,- dictionary: Arc<FstDictionary>,+ lint_group: LintGroup<Arc<MergedDictionary>>,+ /// The user-supplied dictionary.+ ///+ /// To make changes affect linting, run [`Self::synchronize_lint_dict`].+ user_dictionary: MutableDictionary,+ dictionary: Arc<MergedDictionary>,ignored_lints: IgnoredLints,}@@ -72,15 +79,35 @@ impl Linter {/// Note that this can mean constructing the curated dictionary, which is the most expensive operation/// in Harper.pub fn new() -> Self {- let dictionary = FstDictionary::curated();+ let dictionary = Self::construct_merged_dict(MutableDictionary::default());Self {lint_group: LintGroup::new(LintGroupConfig::default(), dictionary.clone()),+ user_dictionary: MutableDictionary::new(),dictionary,ignored_lints: IgnoredLints::default(),}}+ /// Update the dictionary inside [`Self::lint_group`] to include [`Self::user_dictionary`].+ /// This clears any linter caches, so use it sparingly.+ fn synchronize_lint_dict(&mut self) {+ let lint_config = self.lint_group.config;+ self.dictionary = Self::construct_merged_dict(self.user_dictionary.clone());+ self.lint_group = LintGroup::new(lint_config, self.dictionary.clone());+ }++ /// Construct the actual dictionary to be used for linting and parsing from the curated dictionary+ /// and [`Self::user_dictionary`].+ fn construct_merged_dict(user_dictionary: MutableDictionary) -> Arc<MergedDictionary> {+ let mut lint_dict = MergedDictionary::new();++ lint_dict.add_dictionary(FstDictionary::curated());+ lint_dict.add_dictionary(Arc::new(user_dictionary.clone()));++ Arc::new(lint_dict)+ }+/// Helper method to quickly check if a plain string is likely intended to be Englishpub fn is_likely_english(&self, text: String) -> bool {let document = Document::new_plain_english(&text, &self.dictionary);@@ -179,6 +206,27 @@ impl Linter {pub fn clear_ignored_lints(&mut self) {self.ignored_lints = IgnoredLints::new();}++ /// Import words into the dictionary.+ pub fn import_words(&mut self, additional_words: Vec<String>) {+ self.user_dictionary+ .extend_words(additional_words.iter().map(|word| {+ (+ word.chars().collect::<CharString>(),+ WordMetadata::default(),+ )+ }));+ self.synchronize_lint_dict();+ }++ /// Export words from the dictionary.+ /// Note: this will only return words previously added by [`Self::import_words`].+ pub fn export_words(&mut self) -> Vec<String> {+ self.user_dictionary+ .words_iter()+ .map(|v| v.iter().collect())+ .collect()+ }}impl Default for Linter {diff --git a/packages/harper.js/package.json b/packages/harper.js/package.jsonindex 04ddde11b..f910c3aed 100644--- a/packages/harper.js/package.json+++ b/packages/harper.js/package.json@@ -1,36 +1,36 @@{- "name": "harper.js",- "version": "0.21.1",- "license": "Apache-2.0",- "author": "Elijah Potter",- "description": "The grammar checker for developers.",- "repository": {- "type": "git",- "url": "git+https://github.com/automattic/harper.git",- "directory": "packages/harper.js"- },- "bugs": {- "url": "https://github.com/automattic/harper/issues"- },- "homepage": "https://writewithharper.com",- "type": "module",- "scripts": {- "dev": "vite",- "build": "tsc && vite build",- "test": "vitest run --browser chromium && vitest run --browser firefox"- },- "devDependencies": {- "@microsoft/api-documenter": "^7.26.5",- "@microsoft/api-extractor": "^7.49.1",- "@vitest/browser": "^3.0.5",- "playwright": "^1.49.1",- "typescript": "~5.7.3",- "vite": "^6.1.0",- "vite-plugin-dts": "^4.5.0",- "vite-plugin-virtual": "^0.3.0",- "vitest": "^3.0.5",- "wasm": "link:../../harper-wasm/pkg"- },- "main": "dist/harper.js",- "types": "dist/harper.d.ts"+ "name": "harper.js",+ "version": "0.21.1",+ "license": "Apache-2.0",+ "author": "Elijah Potter",+ "description": "The grammar checker for developers.",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/automattic/harper.git",+ "directory": "packages/harper.js"+ },+ "bugs": {+ "url": "https://github.com/automattic/harper/issues"+ },+ "homepage": "https://writewithharper.com",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "tsc && vite build",+ "test": "vitest run --browser chromium"+ },+ "devDependencies": {+ "@microsoft/api-documenter": "^7.26.5",+ "@microsoft/api-extractor": "^7.49.1",+ "@vitest/browser": "^3.0.5",+ "playwright": "^1.49.1",+ "typescript": "~5.7.3",+ "vite": "^6.1.0",+ "vite-plugin-dts": "^4.5.0",+ "vite-plugin-virtual": "^0.3.0",+ "vitest": "^3.0.5",+ "wasm": "link:../../harper-wasm/pkg"+ },+ "main": "dist/harper.js",+ "types": "dist/harper.d.ts"}diff --git a/packages/harper.js/src/Linter.test.ts b/packages/harper.js/src/Linter.test.tsindex 84fd96bde..bca9a9093 100644--- a/packages/harper.js/src/Linter.test.ts+++ b/packages/harper.js/src/Linter.test.ts@@ -169,6 +169,20 @@ for (const [linterName, Linter] of Object.entries(linters)) {expect(firstLints.length).toBeGreaterThan(secondLints.length);expect(secondLints.length).toBe(0);});++ test(`${linterName} can add words to the dictionary`, async () => {+ const source = 'asdf is not a word';++ const linter = new Linter();+ let lints = await linter.lint(source);++ expect(lints).toHaveLength(1);++ await linter.importWords(['asdf']);+ lints = await linter.lint(source);++ expect(lints).toHaveLength(0);+ });}test('Linters have the same config format', async () => {diff --git a/packages/harper.js/src/Linter.ts b/packages/harper.js/src/Linter.tsindex 90630da7c..609a621c0 100644--- a/packages/harper.js/src/Linter.ts+++ b/packages/harper.js/src/Linter.ts@@ -63,4 +63,11 @@ export default interface Linter {/** Clear records of all previously ignored lints. */clearIgnoredLints(): Promise<void>;++ /** Import words into the dictionary. This is a significant operation, so try to batch words. */+ importWords(words: string[]): Promise<void>;++ /** Export all added words from the dictionary. Note that this will NOT export anything from the curated dictionary,+ * only words from previous calls to `this.importWords`. */+ exportWords(): Promise<string[]>;}diff --git a/packages/harper.js/src/LocalLinter.ts b/packages/harper.js/src/LocalLinter.tsindex 45e06dbe1..fd98d23fb 100644--- a/packages/harper.js/src/LocalLinter.ts+++ b/packages/harper.js/src/LocalLinter.ts@@ -124,4 +124,16 @@ export default class LocalLinter implements Linter {return this.inner!.clear_ignored_lints();}++ async importWords(words: string[]): Promise<void> {+ await this.initialize();++ return this.inner!.import_words(words);+ }++ async exportWords(): Promise<string[]> {+ await this.initialize();++ return this.inner!.export_words();+ }}diff --git a/packages/harper.js/src/WorkerLinter/index.ts b/packages/harper.js/src/WorkerLinter/index.tsindex e2dfdfe10..56fe5979a 100644--- a/packages/harper.js/src/WorkerLinter/index.ts+++ b/packages/harper.js/src/WorkerLinter/index.ts@@ -129,6 +129,14 @@ export default class WorkerLinter implements Linter {return this.rpc('clearIgnoredLints', []);}+ async importWords(words: string[]): Promise<void> {+ return this.rpc('importWords', [words]);+ }++ async exportWords(): Promise<string[]> {+ return this.rpc('exportWords', []);+ }+/** Run a procedure on the remote worker. */private async rpc(procName: string, args: any[]): Promise<any> {const promise = new Promise((resolve, reject) => {