Skip to content

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

feat: setup `justfile` + made WASM interface cleaner

Elijah Potter66da0b27beaf
diff --git a/.github/workflows/build_harper_ls.yml b/.github/workflows/build_harper_ls.yml
index 25dfb9915..0a46bc7cd 100644
--- a/.github/workflows/build_harper_ls.yml
+++ b/.github/workflows/build_harper_ls.yml
@@ -82,6 +82,5 @@ jobs:
uses: softprops/action-gh-release@v1
with:
draft: true
- name:
files: "harper-ls-*"
if: startsWith(github.ref, 'refs/tags/')
diff --git a/.github/workflows/precommit.yml b/.github/workflows/precommit.yml
index f43a2e545..2e931a7aa 100644
--- a/.github/workflows/precommit.yml
+++ b/.github/workflows/precommit.yml
@@ -18,7 +18,8 @@ jobs:
- uses: actions/setup-node@v4
- name: Install Rust Nightly
run: rustup toolchain install nightly && rustup component add rustfmt --toolchain nightly
+ - uses: extractions/setup-just@v1
- name: Install `wasm-pack`
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
- name: Precommit
- run: ./precommit.sh
+ run: just precommit
diff --git a/Cargo.lock b/Cargo.lock
index 86925ac3e..a7cbd947c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -143,55 +143,6 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
-[[package]]
-name = "axum"
-version = "0.6.20"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
-dependencies = [
- "async-trait",
- "axum-core",
- "bitflags 1.3.2",
- "bytes",
- "futures-util",
- "http",
- "http-body",
- "hyper",
- "itoa",
- "matchit",
- "memchr",
- "mime",
- "percent-encoding",
- "pin-project-lite",
- "rustversion",
- "serde",
- "serde_json",
- "serde_path_to_error",
- "serde_urlencoded",
- "sync_wrapper",
- "tokio",
- "tower",
- "tower-layer",
- "tower-service",
-]
-
-[[package]]
-name = "axum-core"
-version = "0.3.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c"
-dependencies = [
- "async-trait",
- "bytes",
- "futures-util",
- "http",
- "http-body",
- "mime",
- "rustversion",
- "tower-layer",
- "tower-service",
-]
-
[[package]]
name = "backtrace"
version = "0.3.71"
@@ -412,12 +363,6 @@ dependencies = [
"windows-sys 0.52.0",
]
-[[package]]
-name = "fnv"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
-
[[package]]
name = "form_urlencoded"
version = "1.2.1"
@@ -617,19 +562,6 @@ dependencies = [
"tracing-subscriber",
]
-[[package]]
-name = "harper-serve"
-version = "0.1.0"
-dependencies = [
- "axum",
- "harper-core",
- "serde",
- "serde_json",
- "tokio",
- "tracing",
- "tracing-subscriber",
-]
-
[[package]]
name = "harper-wasm"
version = "0.1.0"
@@ -637,8 +569,6 @@ dependencies = [
"console_error_panic_hook",
"harper-core",
"once_cell",
- "serde",
- "serde-wasm-bindgen",
"tracing",
"tracing-wasm",
"wasm-bindgen",
@@ -667,63 +597,12 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
-[[package]]
-name = "http"
-version = "0.2.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
-dependencies = [
- "bytes",
- "fnv",
- "itoa",
-]
-
-[[package]]
-name = "http-body"
-version = "0.4.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
-dependencies = [
- "bytes",
- "http",
- "pin-project-lite",
-]
-
[[package]]
name = "httparse"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
-[[package]]
-name = "httpdate"
-version = "1.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
-
-[[package]]
-name = "hyper"
-version = "0.14.28"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80"
-dependencies = [
- "bytes",
- "futures-channel",
- "futures-core",
- "futures-util",
- "http",
- "http-body",
- "httparse",
- "httpdate",
- "itoa",
- "pin-project-lite",
- "socket2",
- "tokio",
- "tower-service",
- "tracing",
- "want",
-]
-
[[package]]
name = "idna"
version = "0.5.0"
@@ -795,15 +674,6 @@ version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
-[[package]]
-name = "js-sys"
-version = "0.3.69"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d"
-dependencies = [
- "wasm-bindgen",
-]
-
[[package]]
name = "lazy_static"
version = "1.4.0"
@@ -861,24 +731,12 @@ dependencies = [
"url",
]
-[[package]]
-name = "matchit"
-version = "0.7.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
-
[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
-[[package]]
-name = "mime"
-version = "0.3.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
-
[[package]]
name = "miniz_oxide"
version = "0.7.2"
@@ -1176,12 +1034,6 @@ dependencies = [
"windows-sys 0.52.0",
]
-[[package]]
-name = "rustversion"
-version = "1.0.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6"
-
[[package]]
name = "ryu"
version = "1.0.18"
@@ -1203,17 +1055,6 @@ dependencies = [
"serde_derive",
]
-[[package]]
-name = "serde-wasm-bindgen"
-version = "0.6.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"
-dependencies = [
- "js-sys",
- "serde",
- "wasm-bindgen",
-]
-
[[package]]
name = "serde_derive"
version = "1.0.203"
@@ -1236,16 +1077,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "serde_path_to_error"
-version = "0.1.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6"
-dependencies = [
- "itoa",
- "serde",
-]
-
[[package]]
name = "serde_repr"
version = "0.1.19"
@@ -1257,18 +1088,6 @@ dependencies = [
"syn",
]
-[[package]]
-name = "serde_urlencoded"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
-dependencies = [
- "form_urlencoded",
- "itoa",
- "ryu",
- "serde",
-]
-
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -1323,12 +1142,6 @@ dependencies = [
"unicode-ident",
]
-[[package]]
-name = "sync_wrapper"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
-
[[package]]
name = "terminal_size"
version = "0.3.0"
@@ -1435,10 +1248,8 @@ dependencies = [
"futures-util",
"pin-project",
"pin-project-lite",
- "tokio",
"tower-layer",
"tower-service",
- "tracing",
]
[[package]]
@@ -1493,7 +1304,6 @@ version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"
dependencies = [
- "log",
"pin-project-lite",
"tracing-attributes",
"tracing-core",
@@ -1686,12 +1496,6 @@ dependencies = [
"tree-sitter",
]
-[[package]]
-name = "try-lock"
-version = "0.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
-
[[package]]
name = "unicase"
version = "2.7.0"
@@ -1764,15 +1568,6 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
-[[package]]
-name = "want"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
-dependencies = [
- "try-lock",
-]
-
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
diff --git a/Cargo.toml b/Cargo.toml
index 60580af34..5cd96d9ab 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = [ "harper-cli", "harper-core", "harper-ls", "harper-serve", "harper-comments", "harper-wasm"]
+members = [ "harper-cli", "harper-core", "harper-ls", "harper-comments", "harper-wasm"]
resolver = "2"
[profile.release]
diff --git a/format.sh b/format.sh
deleted file mode 100755
index 20dd2a783..000000000
--- a/format.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#! /bin/bash
-
-set -eo pipefail
-
-cargo +nightly fmt
-
-R=$(pwd)
-
-cd $R/packages
-yarn prettier -w .
diff --git a/harper-core/src/linting/lint.rs b/harper-core/src/linting/lint.rs
index e557e45ac..0434ed6a2 100644
--- a/harper-core/src/linting/lint.rs
+++ b/harper-core/src/linting/lint.rs
@@ -39,6 +39,21 @@ pub enum LintKind {
Miscellaneous
}
+impl Display for LintKind {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let s = match self {
+ LintKind::Spelling => "Spelling",
+ LintKind::Capitalization => "Capitalization",
+ LintKind::Formatting => "Formatting",
+ LintKind::Repetition => "Repetition",
+ LintKind::Readability => "Readability",
+ LintKind::Miscellaneous => "Miscellaneous"
+ };
+
+ write!(f, "{}", s)
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Is)]
pub enum Suggestion {
ReplaceWith(Vec<char>),
diff --git a/harper-serve/Cargo.toml b/harper-serve/Cargo.toml
deleted file mode 100644
index 8a74d2d0b..000000000
--- a/harper-serve/Cargo.toml
+++ /dev/null
@@ -1,16 +0,0 @@
-[package]
-name = "harper-serve"
-version = "0.1.0"
-edition = "2021"
-private = true
-publish = false
-repository = "https://github.com/elijah-potter/harper"
-
-[dependencies]
-axum = "0.6.20"
-serde = { version = "1.0.197", features = ["derive"] }
-tokio = { version = "1.36.0", features = ["fs", "rt", "rt-multi-thread", "macros"] }
-tracing = "0.1.40"
-tracing-subscriber = "0.3.17"
-harper-core = { path = "../harper-core" }
-serde_json = "1.0.110"
diff --git a/harper-serve/README.md b/harper-serve/README.md
deleted file mode 100644
index 93383e9ea..000000000
--- a/harper-serve/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# `harper-serve`
-
-This crates exists as a way to debug both the web interface and the underlying engine at the same time.
-To set the web interface to use a server as the backend, edit the first line of `analysis.ts`.
-
-When I'm debugging, I then start the `harper-serve` binary with [`bacon`](https://github.com/Canop/bacon).
diff --git a/harper-serve/src/main.rs b/harper-serve/src/main.rs
deleted file mode 100644
index 96cc21a99..000000000
--- a/harper-serve/src/main.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-#![allow(dead_code)]
-
-use std::net::SocketAddr;
-
-use axum::body::Body;
-use axum::http::{Request, StatusCode};
-use axum::middleware::{self, Next};
-use axum::response::Response;
-use axum::routing::post;
-use axum::{Json, Router};
-use harper_core::{Document, FatToken, FullDictionary, Lint, LintGroup, Linter, Span, Suggestion};
-use serde::{Deserialize, Serialize};
-use tokio::time::Instant;
-use tracing::{info, Level};
-use tracing_subscriber::FmtSubscriber;
-
-#[tokio::main]
-async fn main() {
- let subscriber = FmtSubscriber::builder()
- .with_max_level(Level::DEBUG)
- .finish();
-
- tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
-
- let app = Router::new()
- .route("/", post(root))
- .route("/parse", post(parse_text))
- .route("/lint", post(lint))
- .route("/apply", post(apply_suggestion))
- .layer(middleware::from_fn(timing_middleware));
-
- let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
- info!("listening on {}", addr);
- axum::Server::bind(&addr)
- .serve(app.into_make_service())
- .await
- .unwrap();
-}
-
-async fn timing_middleware(request: Request<Body>, next: Next<Body>) -> Response {
- info!("Handling request at endpoint: {}", request.uri().path());
-
- let uri = request.uri().clone();
-
- let start = Instant::now();
-
- let res = next.run(request).await;
-
- let end = Instant::now();
-
- let diff = end - start;
-
- info!(
- "Took {} ms to process request at endpoint: {}",
- diff.as_millis(),
- uri.path(),
- );
-
- res
-}
-
-async fn root() -> &'static str {
- info!("Hello world");
-
- "Hello, World!"
-}
-
-async fn parse_text(Json(payload): Json<ParseRequest>) -> (StatusCode, Json<ParseResponse>) {
- let text = payload.text;
-
- let document = Document::new_markdown(&text);
- let tokens: Vec<_> = document.fat_tokens().collect();
-
- (StatusCode::ACCEPTED, Json(ParseResponse { tokens }))
-}
-
-#[derive(Deserialize)]
-struct ParseRequest {
- pub text: String
-}
-
-#[derive(Serialize)]
-struct ParseResponse {
- pub tokens: Vec<FatToken>
-}
-
-async fn lint(Json(payload): Json<LintRequest>) -> (StatusCode, Json<LintResponse>) {
- let text = payload.text;
-
- let document = Document::new_markdown(&text);
-
- let dictionary = FullDictionary::create_from_curated();
- let mut linter = LintGroup::new(Default::default(), dictionary);
-
- let lints = linter.lint(&document);
-
- (StatusCode::ACCEPTED, Json(LintResponse { lints }))
-}
-
-#[derive(Deserialize)]
-struct LintRequest {
- pub text: String
-}
-
-#[derive(Serialize)]
-struct LintResponse {
- pub lints: Vec<Lint>
-}
-
-async fn apply_suggestion(
- Json(payload): Json<ApplySuggestionRequest>
-) -> (StatusCode, Json<ApplySuggestionResponse>) {
- let text = payload.text;
- let mut document = Document::new_markdown(&text);
- document.apply_suggestion(&payload.suggestion, payload.span);
-
- (
- StatusCode::ACCEPTED,
- Json(ApplySuggestionResponse {
- text: document.get_full_string()
- })
- )
-}
-
-#[derive(Deserialize)]
-struct ApplySuggestionRequest {
- pub text: String,
- pub suggestion: Suggestion,
- pub span: Span
-}
-
-#[derive(Serialize)]
-struct ApplySuggestionResponse {
- pub text: String
-}
diff --git a/harper-wasm/Cargo.toml b/harper-wasm/Cargo.toml
index 812228e3f..ae2f04133 100644
--- a/harper-wasm/Cargo.toml
+++ b/harper-wasm/Cargo.toml
@@ -15,6 +15,4 @@ tracing = "0.1.40"
tracing-wasm = "0.2.1"
wasm-bindgen = "0.2.91"
harper-core = { path = "../harper-core" }
-serde = "1.0.197"
-serde-wasm-bindgen = "0.6.3"
once_cell = "1.19.0"
diff --git a/harper-wasm/README.md b/harper-wasm/README.md
new file mode 100644
index 000000000..d62f9b86a
--- /dev/null
+++ b/harper-wasm/README.md
@@ -0,0 +1,5 @@
+# `harper-wasm`
+
+`harper-wasm` is the WebAssembly-compiled version of the [Harper](https://github.com/elijah-potter/harper) grammar checker.
+
+Currently, the API exists to meet the needs of both the [web demo](https://writewithharper.com) and the Obsidian plugin.
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index 70389e33e..68ea5f71c 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -1,10 +1,12 @@
+#![doc = include_str!("../README.md")]
+
+use std::rc::Rc;
use std::sync::Mutex;
+use harper_core::parsers::Markdown;
use harper_core::{remove_overlaps, Document, FullDictionary, LintGroup, Linter};
use once_cell::sync::Lazy;
-use serde::Serialize;
use wasm_bindgen::prelude::wasm_bindgen;
-use wasm_bindgen::JsValue;
static LINTER: Lazy<Mutex<LintGroup<FullDictionary>>> = Lazy::new(|| {
Mutex::new(LintGroup::new(
@@ -13,11 +15,6 @@ static LINTER: Lazy<Mutex<LintGroup<FullDictionary>>> = Lazy::new(|| {
))
});
-/// Create the serializer that preserves types across the JavaScript barrier
-fn glue_serializer() -> serde_wasm_bindgen::Serializer {
- serde_wasm_bindgen::Serializer::new().serialize_missing_as_null(true)
-}
-
/// Setup the WebAssembly module's logging.
///
/// Not strictly necessary for anything to function, but makes bug-hunting less
@@ -29,47 +26,144 @@ pub fn setup() {
tracing_wasm::set_as_global_default();
}
+/// Configure Harper whether to include spell checking in the linting provided
+/// by the [`lint`] function.
#[wasm_bindgen]
pub fn use_spell_check(set: bool) {
let mut linter = LINTER.lock().unwrap();
linter.config.spell_check = Some(set);
}
+/// Perform the configured linting on the provided text.
#[wasm_bindgen]
-pub fn lint(text: String) -> Vec<JsValue> {
- let document = Document::new_markdown(&text);
+pub fn lint(text: String) -> Vec<Lint> {
+ let source: Vec<_> = text.chars().collect();
+
+ let document = Document::new_from_vec(source.clone(), Box::new(Markdown));
let mut lints = LINTER.lock().unwrap().lint(&document);
remove_overlaps(&mut lints);
+ let text = Rc::new(source);
+
lints
.into_iter()
- .map(|lint| lint.serialize(&glue_serializer()).unwrap())
- .collect()
-}
-
-#[wasm_bindgen]
-pub fn parse(text: String) -> Vec<JsValue> {
- let document = Document::new_markdown(&text);
-
- document
- .fat_tokens()
- .map(|lint| lint.serialize(&glue_serializer()).unwrap())
+ .map(|l| Lint::new(l, text.clone()))
.collect()
}
#[wasm_bindgen]
pub fn apply_suggestion(
text: String,
- span: JsValue,
- suggestion: JsValue
+ span: Span,
+ suggestion: &Suggestion
) -> Result<String, String> {
- let span = serde_wasm_bindgen::from_value(span).map_err(|e| e.to_string())?;
- let suggestion = serde_wasm_bindgen::from_value(suggestion).map_err(|e| e.to_string())?;
-
let mut document = Document::new_markdown(&text);
- document.apply_suggestion(&suggestion, span);
+ document.apply_suggestion(&suggestion.inner, span.into());
Ok(document.get_full_string())
}
+
+#[wasm_bindgen]
+pub struct Suggestion {
+ inner: harper_core::Suggestion
+}
+
+#[wasm_bindgen]
+pub enum SuggestionKind {
+ Replace,
+ Remove
+}
+
+#[wasm_bindgen]
+impl Suggestion {
+ pub(crate) fn new(inner: harper_core::Suggestion) -> Self {
+ Self { inner }
+ }
+
+ /// Get the text that is going to replace error.
+ /// If [`Self::kind`] is `SuggestionKind::Remove`, this will return an empty
+ /// string.
+ pub fn get_replacement_text(&self) -> String {
+ match &self.inner {
+ harper_core::Suggestion::Remove => "".to_string(),
+ harper_core::Suggestion::ReplaceWith(chars) => chars.iter().collect()
+ }
+ }
+
+ pub fn kind(&self) -> SuggestionKind {
+ match &self.inner {
+ harper_core::Suggestion::Remove => SuggestionKind::Remove,
+ harper_core::Suggestion::ReplaceWith(_) => SuggestionKind::Replace
+ }
+ }
+}
+
+#[wasm_bindgen]
+pub struct Lint {
+ inner: harper_core::Lint,
+ source: Rc<Vec<char>>
+}
+
+#[wasm_bindgen]
+impl Lint {
+ pub(crate) fn new(inner: harper_core::Lint, source: Rc<Vec<char>>) -> Self {
+ Self { inner, source }
+ }
+
+ /// Get the content of the source material pointed to by [`Self::span`]
+ pub fn get_problem_text(&self) -> String {
+ self.inner.span.get_content_string(&self.source)
+ }
+
+ /// Get a string representing the general category of the lint.
+ pub fn lint_kind(&self) -> String {
+ self.inner.lint_kind.to_string()
+ }
+
+ pub fn suggestion_count(&self) -> usize {
+ self.inner.suggestions.len()
+ }
+
+ pub fn suggestions(&self) -> Vec<Suggestion> {
+ self.inner
+ .suggestions
+ .iter()
+ .map(|s| Suggestion::new(s.clone()))
+ .collect()
+ }
+
+ pub fn span(&self) -> Span {
+ self.inner.span.into()
+ }
+
+ pub fn message(&self) -> String {
+ self.inner.message.clone()
+ }
+}
+
+#[wasm_bindgen]
+pub struct Span {
+ pub start: usize,
+ pub end: usize
+}
+
+#[wasm_bindgen]
+impl Span {
+ pub fn new(start: usize, end: usize) -> Self {
+ Self { start, end }
+ }
+}
+
+impl From<Span> for harper_core::Span {
+ fn from(value: Span) -> Self {
+ harper_core::Span::new(value.start, value.end)
+ }
+}
+
+impl From<harper_core::Span> for Span {
+ fn from(value: harper_core::Span) -> Self {
+ Span::new(value.start, value.end)
+ }
+}
diff --git a/justfile b/justfile
new file mode 100644
index 000000000..f929ca89d
--- /dev/null
+++ b/justfile
@@ -0,0 +1,60 @@
+format:
+ cargo +nightly fmt
+ cd {{justfile_directory()}}/packages; yarn prettier -w .
+
+# Build the WebAssembly for a specific target (usually either `web` or `bundler`)
+build-wasm target:
+ cd {{justfile_directory()}}/harper-wasm && wasm-pack build --target {{target}}
+
+dev-web:
+ #! /bin/bash
+ set -eo pipefail
+
+ just build-wasm bundler
+
+ cd {{justfile_directory()}}/packages/web
+ yarn install -f
+ yarn dev
+
+build-web:
+ #! /bin/bash
+ set -eo pipefail
+ just build-wasm bundler
+
+ cd {{justfile_directory()}}/packages/web
+ yarn install -f
+ yarn run check
+ yarn run build
+
+build-obsidian:
+ #! /bin/bash
+ set -eo pipefail
+
+ just build-wasm web
+ cd {{justfile_directory()}}/packages/obsidian-plugin
+
+ yarn install -f
+ yarn build
+
+ zip harper-obsidian-plugin.zip manifest.json main.js
+
+precommit:
+ #! /bin/bash
+ set -eo pipefail
+
+ cargo +nightly fmt --check
+ cargo clippy -- -Dwarnings
+ cargo test
+ cargo test --release
+ cargo doc
+ cargo build
+ cargo build --release
+ cargo bench
+
+ cd {{justfile_directory()}}/packages
+ yarn install
+ yarn prettier --check .
+ yarn eslint .
+
+ just build-obsidian
+ just build-web
diff --git a/packages/obsidian-plugin/build.sh b/packages/obsidian-plugin/build.sh
deleted file mode 100755
index 2dee9c077..000000000
--- a/packages/obsidian-plugin/build.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#! /bin/bash
-
-set -eo pipefail
-
-R=`pwd`
-cd ../../harper-wasm
-wasm-pack build --target web
-cd $R
-
-yarn install
-yarn build
-
-zip harper-obsidian-plugin.zip manifest.json main.js
diff --git a/packages/obsidian-plugin/harper-obsidian-plugin.zip b/packages/obsidian-plugin/harper-obsidian-plugin.zip
index 9e31d7fb1..ebf9239e6 100644
Binary files a/packages/obsidian-plugin/harper-obsidian-plugin.zip and b/packages/obsidian-plugin/harper-obsidian-plugin.zip differ
diff --git a/packages/obsidian-plugin/src/index.js b/packages/obsidian-plugin/src/index.js
index 4dc249189..dd1def73b 100644
--- a/packages/obsidian-plugin/src/index.js
+++ b/packages/obsidian-plugin/src/index.js
@@ -3,53 +3,50 @@ import { Plugin } from 'obsidian';
import wasm from 'wasm/harper_wasm_bg.wasm';
import init, { lint, use_spell_check } from 'wasm';
-function contentToString(content) {
- return content.reduce((p, c) => p + c, '');
-}
-
function suggestionToLabel(sug) {
- if (sug === 'Remove') {
+ if (sug.kind() == 'Remove') {
return 'Remove';
} else {
- return `Replace with "${contentToString(sug.ReplaceWith)}"`;
+ return `Replace with "${sug.get_replacement_text()}"`;
}
}
const harperLinter = linter(
async (view) => {
- let text = view.state.doc.sliceString(-1);
+ const text = view.state.doc.sliceString(-1);
await init(await wasm());
+
use_spell_check(false);
- let lints = lint(text);
+ const lints = lint(text);
return lints.map((lint) => {
- console.log('Rendering lints...');
+ let span = lint.span();
return {
- from: lint.span.start,
- to: lint.span.end,
+ from: span.start,
+ to: span.end,
severity: 'error',
- title: lint.lint_kind,
- message: lint.message,
- actions: lint.suggestions.map((sug) => {
+ 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: lint.span.start,
- to: lint.span.end,
+ from: span.start,
+ to: span.end,
insert: ''
}
});
} else {
view.dispatch({
changes: {
- from: lint.span.start,
- to: lint.span.end,
- insert: contentToString(sug.ReplaceWith)
+ from: span.start,
+ to: span.end,
+ insert: sug.get_replacement_text()
}
});
}
diff --git a/packages/web/src/lib/Editor.svelte b/packages/web/src/lib/Editor.svelte
index 83dcf9b69..08c820ff0 100644
--- a/packages/web/src/lib/Editor.svelte
+++ b/packages/web/src/lib/Editor.svelte
@@ -3,8 +3,8 @@
import demo from '../../../../demo.md?raw';
import Underlines from '$lib/Underlines.svelte';
import { Button } from 'flowbite-svelte';
- import { lintText, applySuggestion, spanContent } from '$lib/analysis';
- import type { Lint } from '$lib/analysis';
+ import { lintText, applySuggestion } from '$lib/analysis';
+ import { Lint, SuggestionKind } from 'wasm';
let content = demo;
@@ -16,12 +16,12 @@
$: lintText(content).then((newLints) => (lints = newLints));
$: boxHeight = calcHeight(content);
$: if (focused != null && lintCards[focused])
- lintCards[focused].scrollIntoView({ behavior: 'smooth', block: 'center' });
+ lintCards[focused].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
$: if (editor != null && focused != null) {
let lint = lints[focused % lints.length];
if (lint != null) {
- let p = lint.span.end;
+ let p = lint.span().end;
editor.selectionStart = p;
editor.selectionEnd = p;
}
@@ -63,33 +63,30 @@
<div class="pl-2 border-l-[3px] border-l-primary-500">
<div class="flex flex-row">
<h3 class="font-bold">
- {lint.lint_kind} - “<span class="italic">
- {spanContent(lint.span, content)}
+ {lint.lint_kind()} - “<span class="italic">
+ {lint.get_problem_text()}
</span> ”
</h3>
</div>
<div
class="transition-all overflow-hidden flex flex-col justify-evenly"
- style={`height: ${focused === i ? `calc(55px * ${lint.suggestions.length + 1})` : '0px'}`}
+ style={`height: ${focused === i ? `calc(55px * ${lint.suggestion_count() + 1})` : '0px'}`}
>
- <p style="height: 50px" class="text-left">{lint.message}</p>
- {#each lint.suggestions as suggestion}
+ <p style="height: 50px" class="text-left">{lint.message()}</p>
+ {#each lint.suggestions() as suggestion}
<div class="w-full p-[4px]">
<Button
class="w-full"
style="height: 40px; margin: 5px 0px;"
on:click={() =>
- applySuggestion(content, suggestion, lint.span).then(
+ applySuggestion(content, suggestion, lint.span()).then(
(edited) => (content = edited)
)}
>
- {#if suggestion == 'Remove'}
- Remove "{content.substring(lint.span.start, lint.span.end)}"
+ {#if suggestion.kind() == SuggestionKind.Remove}
+ Remove "{lint.get_problem_text()}"
{:else}
- Replace "{content.substring(lint.span.start, lint.span.end)}" with "{suggestion.ReplaceWith.reduce(
- (p, c) => p + c,
- ''
- )}"
+ Replace "{lint.get_problem_text()}" with "{suggestion.get_replacement_text()}"
{/if}
</Button>
</div>
diff --git a/packages/web/src/lib/Underlines.svelte b/packages/web/src/lib/Underlines.svelte
index 5233d9be8..e929665a0 100644
--- a/packages/web/src/lib/Underlines.svelte
+++ b/packages/web/src/lib/Underlines.svelte
@@ -4,8 +4,8 @@
// Someday, I'll return to it and spruce it up.
// For now, it works.
- import type { Lint } from '$lib/analysis';
- import { lintText, spanContent } from '$lib/analysis';
+ import { lintText } from '$lib/analysis';
+ import { Lint } from 'wasm';
export let content: string;
export let focusLintIndex: number | undefined;
@@ -17,10 +17,14 @@
(newLints) =>
(lints = newLints
.map<[Lint, number]>((lint, index) => [lint, index])
- .toSorted(([a], [b]) => a.span.start - b.span.end))
+ .toSorted(([a], [b]) => a.span().start - b.span().end))
);
$: if (focusLintIndex != null && lintHighlights[focusLintIndex] != null)
- lintHighlights[focusLintIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
+ lintHighlights[focusLintIndex].scrollIntoView({
+ behavior: 'smooth',
+ block: 'center',
+ inline: 'center'
+ });
function reOrgString(text: string): (string | undefined)[] {
if (text.trim().length == 0) {
@@ -54,10 +58,10 @@
let prev = arr[index - 1];
if (prev != null) {
- prevStart = prev[0].span.end;
+ prevStart = prev[0].span().end;
}
- let prevEnd = lint.span.start;
+ let prevEnd = lint.span().start;
let prevContent = [];
@@ -68,7 +72,7 @@
let lintContent: UnderlineDetails = {
focused: lintIndex === focusLintIndex,
index: lintIndex,
- content: spanContent(lint.span, content).replaceAll(' ', '\u00A0')
+ content: lint.get_problem_text().replaceAll(' ', '\u00A0')
};
return [...prevContent, lintContent];
@@ -80,7 +84,7 @@
let finalChunk;
if (lastLint != null) {
- finalChunk = content.substring(lastLint[0].span.end);
+ finalChunk = content.substring(lastLint[0].span().end);
} else {
finalChunk = content;
}
diff --git a/packages/web/src/lib/analysis.ts b/packages/web/src/lib/analysis.ts
index 182d70f30..f95b6860c 100644
--- a/packages/web/src/lib/analysis.ts
+++ b/packages/web/src/lib/analysis.ts
@@ -1,111 +1,14 @@
-const defaultUseWasm = true;
+import type { Lint, Span, Suggestion } from 'wasm';
-export interface ParseResponse {
- tokens: Token[];
-}
-
-export interface Token {
- content: string[];
- kind: TokenKind;
-}
-
-export type TokenKind =
- | { kind: 'Word' }
- | { kind: 'Punctuation'; value: Punctuation }
- | { kind: 'Number'; value: number }
- | { kind: 'Space'; value: number }
- | { kind: 'Newline'; value: number };
-
-export type Punctuation =
- | 'Period'
- | 'Bang'
- | 'Question'
- | 'Colon'
- | 'Semicolon'
- | 'Quote'
- | 'Comma'
- | 'Hyphen'
- | 'Apostrophe'
- | 'OpenSquare'
- | 'CloseSquare'
- | 'OpenRound'
- | 'CloseRound'
- | 'Hash';
-
-export async function parseText(text: string, useWasm = defaultUseWasm): Promise<Token[]> {
- if (useWasm) {
- const wasm = await import('wasm');
-
- const tokens = wasm.parse(text);
- return tokens;
- } else {
- const req = await fetch('/parse', {
- method: 'POST',
- body: JSON.stringify({ text }),
- headers: {
- 'CONTENT-TYPE': 'application/json'
- }
- });
-
- const res: ParseResponse = await req.json();
- return res.tokens;
- }
-}
-
-export function contentToString(content: string[]): string {
- return content.reduce((p, c) => p + c, '');
-}
-
-export interface LintResponse {
- lints: Lint[];
-}
-
-export interface Lint {
- span: Span;
- lint_kind: 'Capitalization' | 'Spelling';
- suggestions: Suggestion[];
- message: string;
-}
-
-export type Suggestion =
- | {
- ReplaceWith: string[];
- }
- | 'Remove';
-
-export interface Span {
- start: number;
- end: number;
-}
-
-export function spanContent(span: Span, source: string): string {
- return source.substring(span.start, span.end);
-}
-
-export async function lintText(text: string, useWasm = defaultUseWasm): Promise<Lint[]> {
+export async function lintText(text: string): Promise<Lint[]> {
console.time('lintText');
- let lints;
- if (useWasm) {
- const wasm = await import('wasm');
+ const wasm = await import('wasm');
- lints = wasm.lint(text);
- } else {
- const req = await fetch(`/lint`, {
- method: 'POST',
- body: JSON.stringify({ text }),
- headers: {
- 'CONTENT-TYPE': 'application/json'
- }
- });
-
- const res: LintResponse = await req.json();
-
- lints = res.lints;
- }
+ let lints = wasm.lint(text);
// We only want to show fixable errors.
- lints = lints.filter((lint) => lint.suggestions.length > 0);
+ lints = lints.filter((lint) => lint.suggestion_count() > 0);
console.timeEnd('lintText');
@@ -115,24 +18,10 @@ export async function lintText(text: string, useWasm = defaultUseWasm): Promise<
export async function applySuggestion(
text: string,
suggestion: Suggestion,
- span: Span,
- useWasm = defaultUseWasm
+ span: Span
): Promise<string> {
- if (useWasm) {
- const wasm = await import('wasm');
-
- const applied = wasm.apply_suggestion(text, span, suggestion);
- return applied;
- } else {
- const req = await fetch(`/apply`, {
- method: 'POST',
- body: JSON.stringify({ text, suggestion, span }),
- headers: {
- 'CONTENT-TYPE': 'application/json'
- }
- });
+ const wasm = await import('wasm');
- const res = await req.json();
- return res.text;
- }
+ const applied = wasm.apply_suggestion(text, span, suggestion);
+ return applied;
}
diff --git a/precommit.sh b/precommit.sh
deleted file mode 100755
index 4f56aa29e..000000000
--- a/precommit.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#! /bin/bash
-
-# Run the tools necessary to make sure the code is ready for commit.
-
-set -eo pipefail
-
-R=$(pwd)
-RUSTDOCFLAGS="-D warnings"
-
-cargo +nightly fmt --check
-cargo clippy -- -Dwarnings
-cargo test
-cargo test --release
-cargo doc
-cargo build
-cargo build --release
-cargo bench
-
-cd $R/packages
-yarn install
-yarn prettier --check .
-yarn eslint .
-
-cd $R/harper-wasm
-wasm-pack build --target web
-
-cd $R/packages/obsidian-plugin
-yarn install
-yarn run build
-
-cd $R/harper-wasm
-wasm-pack build --target bundler
-
-cd $R/packages/web
-yarn install -f
-yarn run check
-yarn run build