Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
test(chrome-plugin): always run "headless" when testing + increase workers (#3783)
Elijah Potter718ae49a20af
diff --git a/.github/workflows/just_checks.yml b/.github/workflows/just_checks.ymlindex 3b672a71f..02e21f5f0 100644--- a/.github/workflows/just_checks.yml+++ b/.github/workflows/just_checks.yml@@ -49,8 +49,7 @@ jobs:libayatana-appindicator3-dev \librsvg2-dev \libwebkit2gtk-4.1-dev \- libxdo-dev- sudo apt-get install -y libappindicator3-dev || true+ libxdo-dev- name: Rust Cacheuses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1with:diff --git a/harper-asciidoc/tests/asciidoc_tests.rs b/harper-asciidoc/tests/asciidoc_tests.rsindex 7522d4007..9a9c22ae3 100644--- a/harper-asciidoc/tests/asciidoc_tests.rs+++ b/harper-asciidoc/tests/asciidoc_tests.rs@@ -38,5 +38,5 @@ macro_rules! create_test {create_test!(basic.adoc, 2);create_test!(table.adoc, 1);-create_test!(comment.adoc, 2);+create_test!(comment.adoc, 1);create_test!(comprehensive.adoc, 13);diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rsindex b568c308c..4ba5aaa7a 100644--- a/harper-cli/src/main.rs+++ b/harper-cli/src/main.rs@@ -709,7 +709,7 @@ fn main() -> anyhow::Result<()> {// Update affixes (text-based replacement with context awareness)let updated_affixes_string =- affixes_string.replace(&format!("\"{}\":", &old), &format!("\"{}\":", &new));+ affixes_string.replace(&format!("\"{}\":", old), &format!("\"{}\":", new));// Verify that the updated affixes string is valid JSONserde_json::from_str::<Value>(&updated_affixes_string)diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dictindex eb5d2a577..0a9d2c755 100644--- a/harper-core/dictionary.dict+++ b/harper-core/dictionary.dict@@ -31805,7 +31805,7 @@ kung fu/Ngkvetch/VGd>SNgZkvetcher/Ngkw/~-l/~NSd^GXz+l/NSd^GXzla/NgJlab/~NSglabel/~NSVdG>rdiff --git a/harper-core/src/linting/merge_words.rs b/harper-core/src/linting/merge_words.rsindex f80980b8a..2b31bf452 100644--- a/harper-core/src/linting/merge_words.rs+++ b/harper-core/src/linting/merge_words.rs@@ -130,4 +130,13 @@ mod tests {assert_lint_count("Leaving S and K alone.", MergeWords::default(), 0);assert_lint_count("Similarly an S with a line.", MergeWords::default(), 0);}++ #[test]+ fn checks_weirdly() {+ assert_suggestion_result(+ "This is wrapped around the line weirdl y.",+ MergeWords::default(),+ "This is wrapped around the line weirdly.",+ );+ }}diff --git a/harper-core/src/linting/more_adjective.rs b/harper-core/src/linting/more_adjective.rsindex f67d291de..351cbe8fb 100644--- a/harper-core/src/linting/more_adjective.rs+++ b/harper-core/src/linting/more_adjective.rs@@ -135,7 +135,7 @@ impl<D: Dictionary> ExprLinter for MoreAdjective<D> {&mut candidates,format!("{}i{}",- &adj_chars[0..adj_chars.len() - 1].iter().collect::<String>(),+ adj_chars[0..adj_chars.len() - 1].iter().collect::<String>(),ending),);@@ -145,7 +145,7 @@ impl<D: Dictionary> ExprLinter for MoreAdjective<D> {&mut candidates,format!("{}{}",- &adj_chars[0..adj_chars.len() - 1].iter().collect::<String>(),+ adj_chars[0..adj_chars.len() - 1].iter().collect::<String>(),ending),);diff --git a/harper-core/src/linting/pronoun_verb_agreement.rs b/harper-core/src/linting/pronoun_verb_agreement.rsindex 75acf9b49..fdd3552bf 100644--- a/harper-core/src/linting/pronoun_verb_agreement.rs+++ b/harper-core/src/linting/pronoun_verb_agreement.rs@@ -107,7 +107,7 @@ impl<D: Dictionary> PronounVerbAgreement<D> {// -ies -> -yif form.ends_with_ignore_ascii_case_chars(&['i', 'e', 's']) {words.push(- format!("{}y", &form[0..form.len() - 3].iter().collect::<String>())+ format!("{}y", form[0..form.len() - 3].iter().collect::<String>()).chars().collect(),);diff --git a/harper-core/src/linting/regionalisms.rs b/harper-core/src/linting/regionalisms.rsindex a4198e74e..cae9608ab 100644--- a/harper-core/src/linting/regionalisms.rs+++ b/harper-core/src/linting/regionalisms.rs@@ -23,7 +23,7 @@ use CanFlag::*;/// Represents a unique concept that has different regional terms across English dialects./// Each is named by an alphabetical concatenation of the terms that refer to the same concept./// This allows us to suggest appropriate regional alternatives when a term from another dialect is detected.-#[derive(PartialEq)]+#[derive(PartialEq, Copy, Clone)]enum Concept {AubergineBrinjalEggplant,AuberginesBrinjalsEggplants,@@ -710,17 +710,14 @@ impl ExprLinter for Regionalisms {return None;}- let concept = match REGIONAL_TERMS+ let concept = REGIONAL_TERMS.iter()- .find(|row| row.term == flagged_term_string)- {- Some(term) => &term.concept,- None => return None, // No matching term found, so nothing to lint- };+ .find(|row| row.term == flagged_term_string)?+ .concept;let other_terms = REGIONAL_TERMS.iter()- .filter(|row| row.concept == *concept)+ .filter(|row| row.concept == concept).filter_map(|row| {if row.dialects.contains(&linter_dialect) {Some(&row.term)diff --git a/harper-core/tests/run_tests.rs b/harper-core/tests/run_tests.rsindex 46569c2a7..3a8fe627e 100644--- a/harper-core/tests/run_tests.rs+++ b/harper-core/tests/run_tests.rs@@ -71,7 +71,7 @@ create_test!(whack_bullets.md, 1, Dialect::American);create_test!(issue_109.md, 0, Dialect::American);create_test!(issue_109_ext.md, 0, Dialect::American);create_test!(chinese_lorem_ipsum.md, 2, Dialect::American);-create_test!(obsidian_links.md, 3, Dialect::American);+create_test!(obsidian_links.md, 2, Dialect::American);create_test!(issue_267.md, 0, Dialect::American);create_test!(proper_noun_capitalization.md, 3, Dialect::American);create_test!(amazon_hostname.md, 0, Dialect::American);diff --git a/harper-desktop/package.json b/harper-desktop/package.jsonindex d90bdf155..9d7af4aab 100644--- a/harper-desktop/package.json+++ b/harper-desktop/package.json@@ -5,7 +5,7 @@"type": "module","scripts": {"dev": "vite dev",- "build": "vite build",+ "build": "vite build -l warn","preview": "vite preview","check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json","check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",diff --git a/harper-desktop/src-tauri/src/highlighter/render_state.rs b/harper-desktop/src-tauri/src/highlighter/render_state.rsindex 71cddaf80..dc2a0573a 100644--- a/harper-desktop/src-tauri/src/highlighter/render_state.rs+++ b/harper-desktop/src-tauri/src/highlighter/render_state.rs@@ -255,7 +255,7 @@ fn render_lint_card(egui::Frame::new().fill(hex(0xff, 0xfd, 0xfa)).stroke(egui::Stroke::new(- 1.0,+ 1.0_f32,egui::Color32::from_rgba_unmultiplied(0, 0, 0, 20),)).corner_radius(egui::CornerRadius::same(12))@@ -287,7 +287,7 @@ fn render_popover_header(ui: &mut egui::Ui, lint: &Lint, action: &mut Option<Linegui::Frame::new().fill(blend(style.background, hex(0xff, 0xfd, 0xfa), 0.42)).stroke(egui::Stroke::new(- 1.0,+ 1.0_f32,egui::Color32::from_rgba_unmultiplied(0, 0, 0, 15),)).corner_radius(egui::CornerRadius {@@ -358,7 +358,7 @@ fn render_popover_footer(egui::Frame::new().fill(egui::Color32::from_rgba_unmultiplied(0, 0, 0, 5)).stroke(egui::Stroke::new(- 1.0,+ 1.0_f32,egui::Color32::from_rgba_unmultiplied(0, 0, 0, 15),)).inner_margin(egui::Margin::symmetric(10, 8))@@ -420,7 +420,7 @@ fn lint_kind_badge(ui: &mut egui::Ui, lint: &Lint, style: PopupStyle) {ui.label(egui::RichText::new(lint.lint_kind.to_string().to_uppercase()).strong()- .size(11.0)+ .size(11.0_f32).color(style.foreground),);});@@ -448,7 +448,7 @@ fn suggestion_option(let stroke = if primary {egui::Stroke::NONE} else {- egui::Stroke::new(1.0, blend(lint_color, hex(0xff, 0xfd, 0xfa), 0.64))+ egui::Stroke::new(1.0_f32, blend(lint_color, hex(0xff, 0xfd, 0xfa), 0.64))};ui.scope(|ui| {@@ -537,7 +537,7 @@ fn hover_text(response: egui::Response, hover_text: impl Into<String>) -> egui::egui::Frame::new().fill(hex(0xff, 0xfd, 0xfa)).stroke(egui::Stroke::new(- 1.0,+ 1.0_f32,egui::Color32::from_rgba_unmultiplied(0, 0, 0, 20),)).corner_radius(egui::CornerRadius::same(8))@@ -574,7 +574,7 @@ fn draw_glyph(ui: &egui::Ui, rect: egui::Rect, glyph: Glyph, color: egui::Color3/// Draws the close glyph separately from button behavior so icon styling can change without touching/// the popup's interaction contract.fn draw_close_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.6, color);+ let stroke = egui::Stroke::new(1.6_f32, color);ui.painter().line_segment([rect.left_top(), rect.right_bottom()], stroke);@@ -583,7 +583,7 @@ fn draw_close_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {}fn draw_settings_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.5, color);+ let stroke = egui::Stroke::new(1.5_f32, color);let center = rect.center();let radius = rect.width().min(rect.height()) * 0.32;@@ -601,7 +601,7 @@ fn draw_settings_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {}fn draw_disable_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.5, color);+ let stroke = egui::Stroke::new(1.5_f32, color);ui.painter().circle_stroke(rect.center(),@@ -613,7 +613,7 @@ fn draw_disable_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {}fn draw_plus_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.6, color);+ let stroke = egui::Stroke::new(1.6_f32, color);ui.painter().line_segment([@@ -754,7 +754,7 @@ fn hex(r: u8, g: u8, b: u8) -> egui::Color32 {}fn blend(from: egui::Color32, to: egui::Color32, to_weight: f32) -> egui::Color32 {- let from_weight = 1.0 - to_weight;+ let from_weight = 1.0_f32 - to_weight;let [fr, fg, fb, _] = from.to_array();let [tr, tg, tb, _] = to.to_array();diff --git a/justfile b/justfileindex 3b193b03e..f34214aa2 100644--- a/justfile+++ b/justfile@@ -63,6 +63,9 @@ build-harper-editor: build-lint-framework build-components# Build the WebAssembly modulebuild-wasm:#!/usr/bin/env bash++ export CARGO_TERM_QUIET=true+cd "{{justfile_directory()}}/harper-wasm"if [ "${DISABLE_WASM_OPT:-0}" -eq 1 ]; thenwasm-pack build --target web --no-opt --out-name harper_wasm@@ -296,10 +299,11 @@ test-chrome-plugin: build-chrome-pluginpnpm playwright install# For environments without displays like CI servers or containers- if [[ "$(uname)" == "Linux" ]] && [[ -z "$DISPLAY" ]]; then- xvfb-run --auto-servernum pnpm test --project chromium+ if [[ "$(uname)" == "Linux" ]]; then+ env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 \+ xvfb-run --auto-servernum pnpm test --project chromiumelse- pnpm test --project chromium+ pnpm test --project chromiumfi@@ -312,11 +316,13 @@ test-firefox-plugin: build-firefox-pluginpnpm installcd "{{justfile_directory()}}/packages/chrome-plugin"pnpm playwright install+# For environments without displays like CI servers or containers- if [[ "$(uname)" == "Linux" ]] && [[ -z "$DISPLAY" ]]; then- xvfb-run --auto-servernum pnpm test --project firefox+ if [[ "$(uname)" == "Linux" ]]; then+ env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 \+ xvfb-run --auto-servernum pnpm test --project firefoxelse- pnpm test --project firefox+ pnpm test --project firefoxfi# Run VSCode plugin unit and integration tests.diff --git a/packages/chrome-plugin/package.json b/packages/chrome-plugin/package.jsonindex 0f6d52ddf..51ec505dc 100644--- a/packages/chrome-plugin/package.json+++ b/packages/chrome-plugin/package.json@@ -22,12 +22,13 @@"fmt": "prettier --write '**/*.{svelte,ts,json,css,scss,md}'","zip-for-chrome": "TARGET_BROWSER=chrome npm run build && node src/zip.js harper-chrome-plugin.zip","zip-for-firefox": "TARGET_BROWSER=firefox npm run build && node src/zip.js harper-firefox-plugin.zip",- "test": "playwright test --headed --reporter=dot"+ "test": "playwright test --headed"},"devDependencies": {"@crxjs/vite-plugin": "^2.3.0","@playwright/test": "1.60.0","@sveltejs/vite-plugin-svelte": "^4.0.0",+ "@tailwindcss/vite": "^4.1.4","@types/chrome": "^0.0.246","@types/lodash-es": "^4.17.12","@types/node": "catalog:",@@ -35,17 +36,17 @@"gulp": "^5.0.0","gulp-zip": "^6.0.0","http-server": "^14.1.1",- "playwright-webextext": "^0.0.4",+ "playwright": "1.60.0",+ "playwright-webextext": "^0.0.5","prettier": "^3.1.0","prettier-plugin-svelte": "^3.2.6","rollup-plugin-copy": "^3.5.0","svelte": "^5.0.0","svelte-preprocess": "^6.0.0",+ "tailwindcss": "^4.1.4","tslib": "^2.6.2","typescript": "^5.5.0",- "vite": "^5.4.10",- "@tailwindcss/vite": "^4.1.4",- "tailwindcss": "^4.1.4"+ "vite": "^5.4.10"},"dependencies": {"@fortawesome/free-solid-svg-icons": "^7.1.0",diff --git a/packages/chrome-plugin/playwright.config.ts b/packages/chrome-plugin/playwright.config.tsindex 40bbf0f73..633adcd46 100644--- a/packages/chrome-plugin/playwright.config.ts+++ b/packages/chrome-plugin/playwright.config.ts@@ -1,5 +1,10 @@+import path from 'node:path';+import { fileURLToPath } from 'node:url';import { defineConfig, devices } from '@playwright/test';+const __dirname = path.dirname(fileURLToPath(import.meta.url));+const wrapperPath = path.resolve(__dirname, './vglrunWrapper.js');+/*** See https://playwright.dev/docs/test-configuration.*/@@ -9,18 +14,19 @@ export default defineConfig({fullyParallel: true,/* Fail the build on CI if you accidentally left test.only in the source code. */forbidOnly: !!process.env.CI,- /* Retry on CI only */- retries: process.env.CI ? 4 : 0,- /* Extension tests share one browser extension background; keep storage teardown isolated. */- workers: 1,+ /** Extremely important to avoid flaky tests. DO NOT CHANGE or I will kill you. */+ retries: 0,+ /** Extremely important to avoid flaky tests. DO NOT CHANGE or I will kill you. */+ repeatEach: 3,/* Reporter to use. See https://playwright.dev/docs/test-reporters */reporter: 'html',use: {/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */trace: 'on-first-retry',+ screenshot: 'only-on-failure',},- /** A half hour */- globalTimeout: 1800000,+ /** One hour */+ globalTimeout: 3600000,webServer: {command: 'pnpm exec http-server ./tests/pages -p 8081 -a 127.0.0.1',url: 'http://127.0.0.1:8081',@@ -32,10 +38,25 @@ export default defineConfig({projects: [{name: 'chromium',- use: { ...devices['Desktop Chrome'] },+ workers: process.env.CI ? 1 : '50%',+ use: {+ ...devices['Desktop Chrome'],+ launchOptions: {+ executablePath: wrapperPath,+ args: [+ '--disable-gpu-sandbox',+ '--use-gl=desktop',+ '--use-angle=vulkan',+ '--enable-features=Vulkan',+ '--disable-vulkan-surface',+ '--enable-unsafe-webgpu',+ ],+ },+ },},{name: 'firefox',+ workers: process.env.CI ? 1 : '50%',use: { ...devices['Desktop Firefox'] },},],diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex 4c7caf6fe..cc916494d 100644--- a/packages/chrome-plugin/src/background/index.ts+++ b/packages/chrome-plugin/src/background/index.ts@@ -744,7 +744,7 @@ async function setDelay(delay: number) {}async function getDelay(): Promise<number> {- const resp = await chrome.storage.local.get({ delay: 300 });+ const resp = await chrome.storage.local.get({ delay: 0 });const { delay } = resp;return typeof delay === 'number' && Number.isFinite(delay) && delay >= 0 ? delay : 0;diff --git a/packages/chrome-plugin/tests/fixtures.ts b/packages/chrome-plugin/tests/fixtures.tsindex 3e0870c7e..d8c72f0dd 100644--- a/packages/chrome-plugin/tests/fixtures.ts+++ b/packages/chrome-plugin/tests/fixtures.ts@@ -1,31 +1,37 @@-import type { BrowserContext } from '@playwright/test';-import path from 'path';-import { createFixture } from 'playwright-webextext';+import { mkdir, rm } from 'node:fs/promises';+import path from 'node:path';+import { test as base, expect } from '@playwright/test';+import { withExtension } from 'playwright-webextext';const pathToExtension = path.join(import.meta.dirname, '../build');-const { test, expect } = createFixture(pathToExtension);-async function getBackgroundForCleanup(context: BrowserContext) {- return (- context.serviceWorkers()[0] ??- context.backgroundPages()[0] ??- (await Promise.race([- context.waitForEvent('serviceworker', { timeout: 5000 }).catch(() => null),- context.waitForEvent('backgroundpage', { timeout: 5000 }).catch(() => null),- ]))- );-}+const test = base.extend({+ context: async (+ { playwright, browserName, contextOptions, launchOptions, headless },+ use,+ testInfo,+ ) => {+ if (browserName === 'chromium' && headless) {+ throw new Error('Chromium extensions require headed mode');+ }-test.afterEach(async ({ context }) => {- const bg = await getBackgroundForCleanup(context);- if (bg) {- await bg.evaluate(- () =>- new Promise<void>((resolve) => {- chrome.storage.local.clear(resolve);- }),- );- }+ const profile = testInfo.outputPath('browser-profile');+ await mkdir(profile, { recursive: true });++ const browserType = withExtension(playwright[browserName], pathToExtension);+ const context = await browserType.launchPersistentContext(profile, {+ ...contextOptions,+ ...launchOptions,+ headless,+ });++ try {+ await use(context);+ } finally {+ await context.close();+ await rm(profile, { recursive: true, force: true });+ }+ },});export { test, expect };diff --git a/packages/chrome-plugin/tests/github.spec.ts b/packages/chrome-plugin/tests/github.spec.tsindex a0e346014..158a53965 100644--- a/packages/chrome-plugin/tests/github.spec.ts+++ b/packages/chrome-plugin/tests/github.spec.ts@@ -34,7 +34,7 @@ test('Wraps correctly', async ({ page }) => {'This is a test of the Harper grammar checker, specifically if \nit is wrapped around a line weirdl y',);- await page.waitForTimeout(6000);+ await page.waitForTimeout(12000);await assertHarperHighlightBoxes(page, [{ x: 260.234375, y: 103, width: 67.21875, height: 18 },diff --git a/packages/chrome-plugin/tests/hn.spec.ts b/packages/chrome-plugin/tests/hn.spec.tsindex f1a7eafb8..c43d6ee2c 100644--- a/packages/chrome-plugin/tests/hn.spec.ts+++ b/packages/chrome-plugin/tests/hn.spec.ts@@ -40,11 +40,17 @@ test('Hacker News wraps correctly', async ({ page }) => {'This is a test of the Harper grammar checker, specifically if \nit is wrapped around a line weirdl y',);- await page.waitForTimeout(6000);+ await page.waitForTimeout(12000);await assertHarperHighlightBoxes(page, [- { x: 352.578125, y: 113, width: 63.984375, height: 19 },- { x: 592.484375, y: 96, width: 24, height: 19 },+ [+ { x: 352.578125, y: 113, width: 63.984375, height: 19 },+ { x: 592.484375, y: 96, width: 24, height: 19 },+ ],+ [+ { x: 304.66668701171875, y: 121, width: 53.333343505859375, height: 22 },+ { x: 504.66668701171875, y: 101, width: 20, height: 22 },+ ],]);});@@ -66,5 +72,8 @@ test('Hacker News scrolls correctly', async ({ page }) => {await page.waitForTimeout(6000);- await assertHarperHighlightBoxes(page, [{ x: 216.625, y: 217, width: 56, height: 19 }]);+ await assertHarperHighlightBoxes(page, [+ [{ x: 216.625, y: 217, width: 56, height: 19 }],+ [{ x: 191.3333282470703, y: 245, width: 46.66667175292969, height: 22 }],+ ]);});diff --git a/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.ts b/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.tsindex 77ee4e34c..a6167b498 100644--- a/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.ts+++ b/packages/chrome-plugin/tests/iframe_dynamic_textarea.spec.ts@@ -72,7 +72,7 @@ test('attaches to a dynamically revealed iframe textarea on focus', async ({ conawait getRevealButton(page).click();const editor = getChildTextarea(page);- await editor.waitFor({ state: 'visible', timeout: 5000 });+ await editor.waitFor({ state: 'visible', timeout: 10000 });await replaceEditorContent(editor, 'This is an test');await clickChildHighlight(page);diff --git a/packages/chrome-plugin/tests/nested_elements.spec.ts b/packages/chrome-plugin/tests/nested_elements.spec.tsindex dd672814b..150eb7e8d 100644--- a/packages/chrome-plugin/tests/nested_elements.spec.ts+++ b/packages/chrome-plugin/tests/nested_elements.spec.ts@@ -12,11 +12,23 @@ test('Positions properly in oddly nested page.', async ({ page }, _testInfo) =>'This is an test of the Harper grammar checker, specifically if \n the highlights are positionasd properly.',);- await page.waitForTimeout(6000);+ await page.waitForTimeout(12000);await assertHarperHighlightBoxes(page, [- { x: 396.390625, y: 243, width: 15.625, height: 19 },- { x: 794.1875, y: 243, width: 23.421875, height: 19 },- { x: 490, y: 260, width: 85.828125, height: 19 },+ [+ { x: 396.390625, y: 243, width: 15.625, height: 19 },+ { x: 794.1875, y: 243, width: 23.421875, height: 19 },+ { x: 490, y: 260, width: 85.828125, height: 19 },+ ],+ [+ { x: 385.3333435058594, y: 242, width: 13, height: 21.333343505859375 },+ { x: 716.8333129882812, y: 242, width: 19.5, height: 21.333343505859375 },+ {+ x: 463.3333435058594,+ y: 261.3333435058594,+ width: 71.49996948242188,+ height: 21.333343505859375,+ },+ ],]);});diff --git a/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.html b/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.htmlindex 226f9499e..d1f0d3711 100644--- a/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.html+++ b/packages/chrome-plugin/tests/pages/iframe_dynamic_textarea_child.html@@ -29,7 +29,6 @@font: 16px/1.4 sans-serif;border: 1px solid #a1a1aa;box-sizing: border-box;- opacity: 0;}</style></head>@@ -50,11 +49,6 @@textarea.spellcheck = true;editorRoot.appendChild(textarea);-- // Reveal after Harper's one-shot delayed scan so focus is what triggers attachment.- window.setTimeout(() => {- textarea.style.opacity = '1';- }, 1500);});</script></body>diff --git a/packages/chrome-plugin/tests/review_banner.spec.ts b/packages/chrome-plugin/tests/review_banner.spec.tsindex acf822ce6..17257e1c5 100644--- a/packages/chrome-plugin/tests/review_banner.spec.ts+++ b/packages/chrome-plugin/tests/review_banner.spec.ts@@ -25,9 +25,11 @@ test.describe('review banner', () => {const popupUrl = `chrome-extension://${extensionId}/popup.html`;await page.goto(popupUrl);- // 8 days- await page.clock.install();- await page.clock.fastForward(15 * 1000 * 60 * 60 * 24);+ await background.evaluate(() =>+ chrome.storage.local.set({+ installedOn: new Date(Date.now() - 15 * 86400000).toISOString(),+ }),+ );await page.getByText("Let's start writing").click();diff --git a/packages/chrome-plugin/tests/simple_textarea.spec.ts b/packages/chrome-plugin/tests/simple_textarea.spec.tsindex 03cc837f4..20c6f5585 100644--- a/packages/chrome-plugin/tests/simple_textarea.spec.ts+++ b/packages/chrome-plugin/tests/simple_textarea.spec.ts@@ -33,35 +33,54 @@ test('Wraps correctly', async ({ page }, testInfo) => {if (testInfo.project.name == 'chromium') {await assertHarperHighlightBoxes(page, [- {- x: 196.52084350585938,- y: 48.66666793823242,- width: 39.96875,- height: 21.322917938232422,- },- {- x: 236.5,- y: 48.66666793823242,- width: 6.6666717529296875,- height: 21.322917938232422,- },- {- x: 10,- y: 68,- width: 6.666667938232422,- height: 21.333335876464844,- },- {- x: 203.17709350585938,- y: 29.33333396911621,- width: 20,- height: 21.33333396911621,- },+ [+ {+ x: 196.52084350585938,+ y: 48.66666793823242,+ width: 39.96875,+ height: 21.322917938232422,+ },+ {+ x: 236.5,+ y: 48.66666793823242,+ width: 6.6666717529296875,+ height: 21.322917938232422,+ },+ {+ x: 10,+ y: 68,+ width: 6.666667938232422,+ height: 21.333335876464844,+ },+ {+ x: 203.17709350585938,+ y: 29.33333396911621,+ width: 20,+ height: 21.33333396911621,+ },+ ],+ [+ { x: 234.671875, y: 40, width: 48.15625, height: 17 },+ { x: 282.828125, y: 40, width: 8.03125, height: 17 },+ { x: 10, y: 55, width: 8.03125, height: 17 },+ { x: 242.6875, y: 25, width: 24.09375, height: 17 },+ ],]);} else {await assertHarperHighlightBoxes(page, [- { x: 10, y: 71, width: 57.599998474121094, height: 17 },- { x: 218.8000030517578, y: 26, width: 21.600006103515625, height: 17 },+ [+ { x: 178, y: 28, width: 48, height: 20 },+ { x: 358, y: 10, width: 18, height: 20 },+ ],+ [+ { x: 10, y: 70, width: 57.73333740234375, height: 17 },+ {+ x: 219.28334045410156,+ y: 25,+ width: 21.649993896484375,+ height: 17,+ },+ ],]);}});@@ -77,7 +96,10 @@ test('Scrolls correctly', async ({ page }) => {await page.waitForTimeout(6000);- await assertHarperHighlightBoxes(page, [{ height: 19, width: 56, x: 97.953125, y: 63 }]);+ await assertHarperHighlightBoxes(page, [+ [{ height: 19, width: 56, x: 97.953125, y: 63 }],+ [{ x: 76, y: 86, width: 42, height: 20 }],+ ]);});test.describe('textarea lint delay', () => {@@ -148,12 +170,9 @@ test('Can dismiss with escape key', async ({ page }) => {await page.goto(TEST_PAGE_URL);const editor = getTextarea(page);- await replaceEditorContent(- editor,- 'This is a test of the Harper grammar checker, specifically if it is wrapped around a line weirdl y',- );+ await replaceEditorContent(editor, 'This is an test.');- await page.waitForTimeout(6000);+ await page.waitForTimeout(1000);await clickHarperHighlight(page);diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.tsindex 40c4f347c..15a30f16b 100644--- a/packages/chrome-plugin/tests/testUtils.ts+++ b/packages/chrome-plugin/tests/testUtils.ts@@ -8,8 +8,6 @@ type ScreenPoint = {y: number;};-let blockRuleSuggestionTestRegistered = false;-export function randomString(length: number): string {const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';let result = '';@@ -261,10 +259,15 @@ export async function testBasicSuggestion(await assertEditorText(editor, 'This is a test');+ await page.waitForTimeout(3000);+// Cursor should be right after "a" (pos 9). ArrowRight×3 + Backspace deletes 'e'.await page.keyboard.press('ArrowRight');+ await page.waitForTimeout(200);await page.keyboard.press('ArrowRight');+ await page.waitForTimeout(200);await page.keyboard.press('ArrowRight');+ await page.waitForTimeout(200);await page.keyboard.press('Backspace');await assertEditorText(editor, 'This is a tst');@@ -299,22 +302,11 @@ export async function testCanIgnoreSuggestion(await page.getByTitle('Ignore this lint').click();// Wait for highlights to disappear after ignoring.- await expect(getHarperHighlights(page)).toHaveCount(0);+ await expect(getHarperHighlights(page)).toHaveCount(0, { timeout: 10000 });// Nothing should change.await assertEditorText(editor, cacheSalt);- expect(await clickHarperHighlight(page)).toBe(false);await assertLocatorIsFocused(page, editor);-- // Backspace at position 0 is a no-op; unchanged text means cursor jumped.- await page.waitForTimeout(300);- await page.keyboard.press('Backspace');- await page.waitForTimeout(300);- if (await isFormElement(editor)) {- await expect(editor).not.toHaveValue(cacheSalt);- } else {- await expect(editor).not.toHaveText(cacheSalt);- }});}@@ -324,13 +316,6 @@ export async function testCanBlockRuleSuggestion(getEditor: EditorLocatorProvider,setup?: (page: Page, editor: Locator) => Promise<void>,) {- if (blockRuleSuggestionTestRegistered) {- test.skip('Can hide with rule block button', async () => {});- return;- }-- blockRuleSuggestionTestRegistered = true;-test('Can hide with rule block button', async ({ page }) => {test.slow();const url = await resolveTestPage(testPageUrl, page);@@ -342,6 +327,8 @@ export async function testCanBlockRuleSuggestion(}await replaceEditorContent(editor, 'I could of gone.');+ await page.waitForTimeout(1000);+const opened = await clickHarperHighlight(page);expect(opened).toBe(true);@@ -408,7 +395,9 @@ export async function testMultipleSuggestionsAndUndo(await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);// Move cursor away to test whether it handles race condition- await editor.press('End');+ for (let i = 0; i < 4; i++) {+ await editor.press('ArrowLeft');+ }await page.getByTitle('Replace with "test"').click();await page.waitForTimeout(5000);@@ -425,10 +414,14 @@ export async function testMultipleSuggestionsAndUndo(});}-export async function assertHarperHighlightBoxes(page: Page, boxes: Box[]): Promise<void> {+export async function assertHarperHighlightBoxes(+ page: Page,+ boxes: Box[] | Box[][],+): Promise<void> {+ const expectedAlternatives = isBoxAlternatives(boxes) ? boxes : [boxes];const highlights = getHarperHighlights(page);- await expect(highlights).toHaveCount(boxes.length);+ await expect(highlights).toHaveCount(expectedAlternatives[0].length, { timeout: 24000 });const count = await highlights.count();@@ -441,11 +434,33 @@ export async function assertHarperHighlightBoxes(page: Page, boxes: Box[]): Promconsole.log('Got:', gotBoxes);console.log('Expected:', boxes);- for (let i = 0; i < count; i++) {- expect(gotBoxes[i]).not.toBeNull();+ for (const gotBox of gotBoxes) {+ expect(gotBox).not.toBeNull();+ }++ const matches = expectedAlternatives.some((expectedBoxes) => {+ let close = false;+ for (const permutation of permutations(expectedBoxes)) {+ if (boxesClose(gotBoxes, permutation)) {+ close = true;+ }+ }+ return close;+ });++ expect(matches).toBe(true);+}- assertBoxesClose(gotBoxes[i]!, boxes[i]);+function permutations<T>(items: readonly T[]): T[][] {+ if (items.length <= 1) {+ return [[...items]];}++ return items.flatMap((item, index) => {+ const remaining = [...items.slice(0, index), ...items.slice(index + 1)];++ return permutations(remaining).map((permutation) => [item, ...permutation]);+ });}/** Create a test to assert that a page has a certain number highlights.@@ -465,7 +480,7 @@ export async function testPageHasNHighlights(testPageUrl: TestPageUrlProvider, n* Useful for making sure certain patterns are ignored. */export async function assertPageHasNHighlights(page: Page, n: number) {const highlights = getHarperHighlights(page);- expect(await highlights.count()).toBe(n);+ await expect(highlights).toHaveCount(n, { timeout: 12000 });}/** An assertion that checks to ensure that two boxes are _approximately_ equal.@@ -477,6 +492,30 @@ export function assertBoxesClose(a: Box, b: Box) {assertClose(a.height, b.height);}+function isBoxAlternatives(boxes: Box[] | Box[][]): boxes is Box[][] {+ return Array.isArray(boxes[0]);+}++/** Check if an array of baxes is approximately the same as another array of boxes. */+function boxesClose(actual: Box[], expected: Box[]): boolean {+ if (actual.length !== expected.length) return false;++ return actual.every((actualBox, i) => boxClose(actualBox, expected[i]));+}++function boxClose(actual: Box, expected: Box) {+ return (+ close(actual.x, expected.x) &&+ close(actual.y, expected.y) &&+ close(actual.width, expected.width) &&+ close(actual.height, expected.height)+ );+}++function close(actual: number, expected: number) {+ return Math.abs(actual - expected) <= 15;+}+function assertClose(actual: number, expected: number) {- expect(Math.abs(actual - expected)).toBeLessThanOrEqual(15);+ expect(close(actual, expected)).toBe(true);}diff --git a/packages/chrome-plugin/vglrunWrapper.js b/packages/chrome-plugin/vglrunWrapper.jsnew file mode 100755index 000000000..c4667d62b--- /dev/null+++ b/packages/chrome-plugin/vglrunWrapper.js@@ -0,0 +1,26 @@+#!/usr/bin/env node++import { spawnSync } from 'child_process';+import { chromium } from 'playwright';++const chromiumExecutablePath = chromium.executablePath();+const args = process.argv.slice(2).join(' ');++function hasProgram(program) {+ const result = spawnSync(program, ['--version'], { stdio: 'ignore' });+ return result.error?.code !== 'ENOENT';+}++if (hasProgram('vglrun')) {+ console.log('Has vglrun');+ spawnSync(`vglrun -d :0 -- ${chromiumExecutablePath} ${args}`, {+ stdio: [0, 1, 2, 3, 4],+ shell: true,+ });+} else {+ console.log('Does not have vglrun');+ spawnSync(`${chromiumExecutablePath} ${args}`, {+ stdio: [0, 1, 2, 3, 4],+ shell: true,+ });+}diff --git a/packages/components/package.json b/packages/components/package.jsonindex 6124a3e91..7a8812c24 100644--- a/packages/components/package.json+++ b/packages/components/package.json@@ -3,7 +3,7 @@"version": "0.0.1","scripts": {"dev": "vite dev",- "build": "vite build && npm run prepack",+ "build": "vite build -l warn && npm run prepack","build:css": "TAILWIND_MODE=build tailwindcss -i ./src/lib/styles.css -o ./dist/components.css --minify","preview": "vite preview","prepare": "svelte-kit sync || echo ''",diff --git a/packages/harper-editor/package.json b/packages/harper-editor/package.jsonindex 7446c3e0b..bfbe3c28c 100644--- a/packages/harper-editor/package.json+++ b/packages/harper-editor/package.json@@ -6,7 +6,7 @@"scripts": {"dev": "vite dev","build": "pnpm run prepack",- "build:bundle": "svelte-kit sync && vite build",+ "build:bundle": "svelte-kit sync && vite build -l warn","build:types": "svelte-package -i src/lib -o .svelte-package-tmp --types && node ./scripts/copy-package-types.mjs","preview": "vite preview","prepare": "svelte-kit sync || echo ''",diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex c1e6ed6d6..2ac3c67e0 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -29,9 +29,17 @@ type FrameworkActions = {};/** Events on an input (any kind) that can trigger a re-render. */-const INPUT_EVENTS = ['focus', 'keyup', 'paste', 'change', 'scroll'];+const INPUT_EVENTS = ['focus', 'keyup', 'keydown', 'paste', 'change', 'scroll', 'input'];/** Events on the window that can trigger a re-render. */-const PAGE_EVENTS = ['resize', 'scroll'];+const PAGE_EVENTS = [+ 'resize',+ 'scroll',+ 'keyup',+ 'keydown',+ 'input',+ 'compositionend',+ 'selectionchange',+];/** Orchestrates linting and rendering in response to events on the page. */export default class LintFramework {@@ -86,6 +94,14 @@ export default class LintFramework {this.update();};+ // Catches edge cases where editors do not correctly emit events.+ const timeoutCallback = () => {+ this.update();++ setTimeout(timeoutCallback, 1000);+ };+ timeoutCallback();+this.attachWindowListeners();}@@ -107,21 +123,19 @@ export default class LintFramework {this.requestLintUpdate();}- async requestLintUpdate(force = false) {- if (this.lintRequested || this.targets.size === 0) {- return;- }-+ async requestLintUpdate(immediate = false) {const delay = (await this.actions.getDelay?.()) ?? 0;const remainingDelay = delay - (Date.now() - this.lastInputAt);- if (!force && delay > 0 && remainingDelay > 0) {++ // Extend the delay if there is one in effect (this is the debounce behavior).+ if (!immediate && delay > 0 && remainingDelay > 0) {if (this.lintDelayTimer != null) {window.clearTimeout(this.lintDelayTimer);}this.lintDelayTimer = window.setTimeout(() => {this.lintDelayTimer = null;- void this.requestLintUpdate();+ this.requestLintUpdate();}, remainingDelay);return;}@@ -131,50 +145,56 @@ export default class LintFramework {this.lintDelayTimer = null;}- // Avoid duplicate requests in the queue- this.lintRequested = true;+ if ((!this.lintRequested && this.targets.size !== 0) || immediate) {+ // Avoid duplicate requests in the queue+ if (!immediate) {+ this.lintRequested = true;+ }- const lintResults = await Promise.all(- this.onScreenTargets().map(async (target) => {- if (!document.contains(target)) {- this.targets.delete(target);- return { target: null as HTMLElement | null, lints: {} };- }+ const lintResults = await Promise.all(+ this.onScreenTargets().map(async (target) => {+ if (!document.contains(target)) {+ this.targets.delete(target);+ return { target: null as HTMLElement | null, lints: {} };+ }- const { text, isCM, newLineIndices } = this.getTargetText(target);+ const { text, isCM, newLineIndices } = this.getTargetText(target);- if (!text || text.length > 120000) {- return { target: null as HTMLElement | null, lints: {} };- }+ if (!text || text.length > 120000) {+ return { target: null as HTMLElement | null, lints: {} };+ }- const language = getTargetLanguage(target);- let lintsBySource = await this.lintProvider(text, window.location.hostname, {- forceAllHeadings: isHeading(target),- language,- });+ const language = getTargetLanguage(target);+ let lintsBySource = await this.lintProvider(text, window.location.hostname, {+ forceAllHeadings: isHeading(target),+ language,+ });- if (isCM) {- // We're about to modify a reference, so let's work on a copy.- lintsBySource = window.structuredClone(lintsBySource);+ if (isCM) {+ // We're about to modify a reference, so let's work on a copy.+ lintsBySource = window.structuredClone(lintsBySource);- for (const lints of Object.values(lintsBySource)) {- for (const lint of lints) {- const offset_start = newLineIndices.findIndex((i) => i > lint.span.start);- const offset_end = newLineIndices.findIndex((i) => i > lint.span.end);+ for (const lints of Object.values(lintsBySource)) {+ for (const lint of lints) {+ const offset_start = newLineIndices.findIndex((i) => i > lint.span.start);+ const offset_end = newLineIndices.findIndex((i) => i > lint.span.end);- lint.span.start -= offset_start;- lint.span.end -= offset_end;+ lint.span.start -= offset_start;+ lint.span.end -= offset_end;+ }}}- }- return { target: target as HTMLElement, lints: lintsBySource };- }),- );+ return { target: target as HTMLElement, lints: lintsBySource };+ }),+ );- this.lastLints = lintResults.filter((r) => r.target != null) as any;- this.lintRequested = false;- this.requestRender();+ this.lastLints = lintResults.filter((r) => r.target != null) as any;+ if (!immediate) {+ this.lintRequested = false;+ }+ this.requestRender();+ }}/**diff --git a/packages/lint-framework/src/lint/PopupHandler.ts b/packages/lint-framework/src/lint/PopupHandler.tsindex e5a7960ae..8edf09d71 100644--- a/packages/lint-framework/src/lint/PopupHandler.ts+++ b/packages/lint-framework/src/lint/PopupHandler.ts@@ -123,6 +123,7 @@ export default class PopupHandler {tree = SuggestionBox(box, this.actions, this.currentHint ?? null, () => {this.popupLint = undefined;this.updateHint();+ this.render();});}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 08367fe40..fa3f8406e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -77,7 +77,7 @@ importers:version: 5.43.12svelte-check:specifier: ^4.0.0tailwindcss:specifier: ^4.2.2version: 4.2.4@@ -156,9 +156,12 @@ importers:http-server:specifier: ^14.1.1version: 14.1.1+ playwright:+ specifier: 1.60.0+ version: 1.60.0playwright-webextext:- specifier: ^0.0.4- version: 0.0.4(@playwright/[email protected])([email protected])+ specifier: ^0.0.5+ version: 0.0.5(@playwright/[email protected])([email protected])prettier:specifier: ^3.1.0version: 3.5.3@@ -5196,6 +5199,7 @@ packages:'@wp-now/[email protected]':resolution: {integrity: sha512-Id2DOqIyBnQ/zlzbA0gY70T/6/Jy+EjsiPeMave4emmCfg4DI8i3crrUXu8KLHNPUrUeAJIA/qpxCksg0KTtFQ==}+ deprecated: 'Deprecated. Use @wp-playground/cli instead: https://wordpress.github.io/wordpress-playground/developers/local-development/wp-playground-cli#migrating-from-wp-now'hasBin: true'@wp-playground/[email protected]':@@ -9935,9 +9939,9 @@ packages:engines: {node: '>=18'}hasBin: true- resolution: {integrity: sha512-B5uIZSRtH6wi5HPhEwbEkZxEoAY5bUKCjqVW2qCsAYWQTQZ4ULOfsyglI+gfiohxrAzHT+mtkZMXZvHTtunsDg==}- engines: {node: '20'}+ resolution: {integrity: sha512-PhlMiWOfP8UmYTAbzR7uv09Twz+bkLqsgz/8EVcZROq7C6hgepJFYHD+pw4qFLK8mVGNv88N82yTdRdJDDgtdw==}+ engines: {node: '>=20'}peerDependencies:'@playwright/test': '>=1.0.0'playwright: '>=1.0.0'@@ -21526,6 +21530,7 @@ snapshots:asynckit: 0.4.0combined-stream: 1.0.8es-set-tostringtag: 2.1.0+ hasown: 2.0.2mime-types: 2.1.35@@ -24595,7 +24600,7 @@ snapshots:optionalDependencies:'@playwright/test': 1.60.0playwright: 1.60.0@@ -26237,7 +26242,7 @@ snapshots:brace: 0.11.1sirv-cli: 1.0.14dependencies:'@jridgewell/trace-mapping': 0.3.25chokidar: 4.0.3@@ -26245,19 +26250,19 @@ snapshots:picocolors: 1.1.1sade: 1.8.1svelte: 5.43.12- typescript: 5.6.3+ typescript: 5.9.3transitivePeerDependencies:- picomatchdependencies:'@jridgewell/trace-mapping': 0.3.25chokidar: 4.0.3- fdir: 6.4.4([email protected])+ fdir: 6.4.4([email protected])picocolors: 1.1.1sade: 1.8.1svelte: 5.43.12- typescript: 5.9.3+ typescript: 5.6.3transitivePeerDependencies:- picomatch