Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix: refactored how and when linting happens
Elijah Potter2e1bd7e6b35e
diff --git a/src/harper/Highlighter.tsx b/src/harper/Highlighter.tsxindex cab220065..ee03f7d63 100644--- a/src/harper/Highlighter.tsx+++ b/src/harper/Highlighter.tsx@@ -1,30 +1,14 @@import { select, dispatch } from '@wordpress/data';-import React, { useCallback, useRef } from 'react';+import React, { useCallback, useLayoutEffect, useRef } from 'react';import { useState, useEffect } from 'react';import { LocalLinter, Lint, WorkerLinter, Suggestion, Span } from 'harper.js';import SuggestionControl from './SuggestionControl';import { LintBox } from './Box';-import {- extractFromNodeList,- flattenNodeChildren as leafNodes,-} from './domUtils';+import { leafNodes } from './domUtils';let linter = new WorkerLinter();-let lints = new Map< string, Lint[] >();--async function memoizedLint( text: string ): Promise< Lint[] > {- if ( lints.has( text ) ) {- return Promise.resolve( lints.get( text )! );- }-- let newLints = await linter.lint( text );- lints.set( text, newLints );-- return newLints;-}--function getRangeForTextSpan( target: Element, span: Span ): Range | null {+function getRangeForTextSpan( target: HTMLElement, span: Span ): Range | null {let children = leafNodes( target );let range = document.createRange();@@ -33,7 +17,7 @@ function getRangeForTextSpan( target: Element, span: Span ): Range | null {let startFound = false;for ( let i = 0; i < children.length; i++ ) {- let child = children[ i ];+ let child = children[ i ] as HTMLElement;let childText = child.textContent;if ( traversed + childText.length > span.start && ! startFound ) {@@ -41,7 +25,7 @@ function getRangeForTextSpan( target: Element, span: Span ): Range | null {startFound = true;}- if ( startFound && traversed + childText.length > span.end ) {+ if ( startFound && traversed + childText.length >= span.end ) {range.setEnd( child, span.end - traversed );return range;}@@ -55,14 +39,13 @@ function getRangeForTextSpan( target: Element, span: Span ): Range | null {/** Get target boxes for a text node.* Each box represents a Harper lint in the Node. */async function computeLintBoxes(- target: Element,- container: Element+ target: HTMLElement,+ container: Element,+ lints: Lint[]): Promise< LintBox[] > {- let text = target.textContent ?? '';// The ID of the node we're looking atlet clientId = target.getAttribute( 'data-block' );-- let lints = await memoizedLint( text );+ let text = target.textContent;let boxes: LintBox[] = [];@@ -75,34 +58,36 @@ async function computeLintBoxes(continue;}- let targetRect = range.getBoundingClientRect();+ let targetRects = range.getClientRects();let contRect = container.getBoundingClientRect();- boxes.push( {- x: targetRect.x - contRect.x,- y: targetRect.y - contRect.y,- width: targetRect.width,- height: targetRect.height,- lint,- applySuggestion: async ( sug: Suggestion ) => {- console.log( clientId );-- let fixed = await linter.applySuggestion( text, sug, span );-- console.log( fixed );-- const { selectBlock, updateBlockAttributes } =- dispatch( 'core/block-editor' );-- selectBlock( clientId );- updateBlockAttributes( clientId, { content: fixed } );- },- } );+ for ( let targetRect of targetRects ) {+ boxes.push( {+ x: targetRect.x - contRect.x,+ y: targetRect.y - contRect.y,+ width: targetRect.width,+ height: targetRect.height,+ lint,+ applySuggestion: async ( sug: Suggestion ) => {+ let fixed = await linter.applySuggestion( text, sug, span );++ setBlockContent( clientId, fixed );+ },+ } );+ }}return boxes;}+function setBlockContent( clientId: string, text: string ) {+ const { selectBlock, updateBlockAttributes } =+ dispatch( 'core/block-editor' );++ selectBlock( clientId );+ updateBlockAttributes( clientId, { content: text } );+}+export default function Highlighter( {container,target,@@ -110,17 +95,37 @@ export default function Highlighter( {registerCloseHandler,}: {container: Element;- target: Element;+ target: HTMLElement;requestClosePopups: () => void;registerCloseHandler: ( handler: () => void ) => void;} ) {const [ targetBoxes, setTargetBoxes ] = useState< LintBox[] >( [] );+ const [ lints, setLints ] = useState< Lint[] >( [] );++ let updateLints = useCallback( () => {+ let text = target.textContent;+ text && linter.lint( text ).then( setLints );+ }, [] );++ useEffect( () => {+ updateLints();+ let observer = new MutationObserver( updateLints );+ observer.observe( target, {+ childList: true,+ characterData: true,+ subtree: true,+ } );++ return () => {+ observer.disconnect();+ };+ }, [ target ] );useEffect( () => {let running = true;function onFrame( _timestep: DOMHighResTimeStamp ) {- computeLintBoxes( target, container ).then( setTargetBoxes );+ computeLintBoxes( target, container, lints ).then( setTargetBoxes );if ( running ) {requestAnimationFrame( onFrame );diff --git a/src/harper/SuggestionControl.tsx b/src/harper/SuggestionControl.tsxindex 99e754eb8..a13cc2d31 100644--- a/src/harper/SuggestionControl.tsx+++ b/src/harper/SuggestionControl.tsx@@ -37,16 +37,17 @@ export default function SuggestionControl( {let { x, y, width, height, lint, applySuggestion } = lintBox;let underlineRef = useRef< HTMLElement | null >( null );+ let popoverRef = useRef< HTMLElement | null >( null );let suggestions = useMemo( () => lint.suggestions(), [ lint ] );- const [ showSuggestions, setShowSuggestions ] = useState( false );+ const [ showPopover, setShowPopover ] = useState( false );useEffect( () => {- registerCloseHandler( () => setShowSuggestions( false ) );+ registerCloseHandler( () => setShowPopover( () => false ) );}, [] );useEffect( () => {- function mouseMove( e: MouseEvent ) {+ function mouseUp( e: MouseEvent ) {if ( underlineRef.current == null ) {return;}@@ -59,45 +60,18 @@ export default function SuggestionControl( {e.clientY > rect.y &&e.clientY < rect.y + height) {- requestClosePopups();- setShowSuggestions( () => true );+ setShowPopover( () => true );+ } else {+ setShowPopover( false );}}- function mouseUp( e: MouseEvent ) {- if ( e.target != this ) {- return;- }-- let offsetX = underlineRef.current?.offsetLeft ?? 0;- let offsetY = underlineRef.current?.offsetLeft ?? 0;-- if (- e.pageX < offsetX ||- e.pageX > offsetX + width ||- e.pageY < offsetY ||- e.pageY > offsetY + height- ) {- requestClosePopups();- }- }-- underlineRef.current?.parentElement?.addEventListener(- 'mousemove',- mouseMove- );-underlineRef.current?.parentElement?.addEventListener('mouseup',mouseUp);return () => {- underlineRef.current?.parentElement?.removeEventListener(- 'mousemove',- mouseMove- );-underlineRef.current?.parentElement?.removeEventListener('mouseup',mouseUp@@ -119,8 +93,9 @@ export default function SuggestionControl( {zIndex: -100,} }></div>- { showSuggestions && (+ { showPopover && (<div+ ref={ popoverRef }className="harper-popover"style={ {position: 'absolute',diff --git a/src/harper/domUtils.ts b/src/harper/domUtils.tsindex f93ba4cd5..b25f4e561 100644--- a/src/harper/domUtils.ts+++ b/src/harper/domUtils.ts@@ -1,3 +1,16 @@+/** Turn a `NodeList` into a normal JavaScript array. */+export function extractFromHTMLCollection(+ collection: HTMLCollection+): Element[] {+ let elements: Element[] = [];++ for ( let el of collection ) {+ elements.push( el );+ }++ return elements;+}+/** Turn a `NodeList` into a normal JavaScript array. */export function extractFromNodeList< T extends Node >(list: NodeListOf< T >@@ -17,7 +30,7 @@ export function getNodesFromQuerySelector( element: Element, query: string ) {}/** Flatten a provided node, and it's children into a single array. */-export function flattenNodeChildren( node: Node ): Node[] {+export function leafNodes( node: Element ): Element[] {let out = [];let children = extractFromNodeList( node.childNodes );@@ -27,7 +40,7 @@ export function flattenNodeChildren( node: Node ): Node[] {}for ( let child of children ) {- let sub = flattenNodeChildren( child );+ let sub = leafNodes( child );sub.forEach( ( v ) => out.push( v ) );}