Skip to content

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

refactor: move logic into `DataBlock` class

Elijah Potter81b69f885356
diff --git a/src/harper/DataBlock.ts b/src/harper/DataBlock.ts
new file mode 100644
index 000000000..6761ef9b7
--- /dev/null
+++ b/src/harper/DataBlock.ts
@@ -0,0 +1,87 @@
+import { Lint, LocalLinter, Suggestion } from 'harper.js';
+import {
+ getNodesFromQuerySelector,
+ getRangeForTextSpan,
+ getRichTextContainers,
+} from './domUtils';
+import { LintBox } from './Box';
+import { setBlockContent } from './gutenbergUtils';
+
+/** Represents a Gutenberg block on-screen.
+ * So named because all of these blocks have a `data-block` attribute. */
+export default class DataBlock {
+ public targetElement: Element;
+
+ constructor( targetElement: Element ) {
+ this.targetElement = targetElement;
+ }
+
+ public static getAllDataBlocks(): DataBlock[] {
+ let container = this.getContainer();
+
+ let targetNodes = [
+ ...getNodesFromQuerySelector( container, '[data-block].rich-text' ),
+ ...getNodesFromQuerySelector(
+ container,
+ '[data-block].wp-block-list'
+ ),
+ ];
+
+ return targetNodes.map( ( node ) => new DataBlock( node ) );
+ }
+
+ public getTextContent(): string {
+ return this.targetElement.textContent!;
+ }
+
+ public computeLintBox( lint: Lint ): LintBox[] {
+ let container = DataBlock.getContainer();
+ let text = this.targetElement.textContent;
+ let span = lint.span();
+ let range = getRangeForTextSpan( this.targetElement, span );
+ let linter = new LocalLinter();
+
+ if ( range == null || text == null ) {
+ console.log( 'Could not locate range.' );
+ return [];
+ }
+
+ let targetRects = range.getClientRects();
+ let contRect = container.getBoundingClientRect();
+
+ let boxes: LintBox[] = [];
+
+ 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 );
+
+ console.log( 'Applying suggestion' );
+
+ setBlockContent( this.getClientId(), fixed );
+ },
+ } );
+ }
+
+ return boxes;
+ }
+
+ private getClientId(): string {
+ return this.targetElement.getAttribute( 'data-block' )!;
+ }
+
+ private static getContainer(): Element {
+ const iframe = document.querySelector( 'iframe[name="editor-canvas"]' );
+ const iframeDocument =
+ iframe?.contentDocument || iframe?.contentWindow.document;
+ const container =
+ iframeDocument?.body ||
+ document.querySelector( '.edit-post-visual-editor > div' );
+ return container;
+ }
+}
diff --git a/src/harper/Highlighter.tsx b/src/harper/Highlighter.tsx
index 96102b45b..3a7adfff8 100644
--- a/src/harper/Highlighter.tsx
+++ b/src/harper/Highlighter.tsx
@@ -5,71 +5,22 @@ import { Lint, WorkerLinter, Suggestion, Span } from 'harper.js';
import SuggestionControl from './SuggestionControl';
import { LintBox } from './Box';
import { getRangeForTextSpan } from './domUtils';
+import DataBlock from './DataBlock';
let linter = new WorkerLinter();
-/** Given an element and the lint results for it, create bounding boxes that represent those errors on-screen. */
-async function computeLintBoxes(
- target: HTMLElement,
- container: Element,
- lints: Lint[]
-): Promise< LintBox[] > {
- // The ID of the node we're looking at
- let clientId = target.getAttribute( 'data-block' );
- let text = target.textContent;
-
- let boxes: LintBox[] = [];
-
- for ( let lint of lints ) {
- let span = lint.span();
- let range = getRangeForTextSpan( target, span );
-
- if ( range == null ) {
- console.log( 'Could not locate range.' );
- continue;
- }
-
- let targetRects = range.getClientRects();
- let contRect = container.getBoundingClientRect();
-
- 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;
-}
-
-export default function Highlighter( {
- container,
- target,
-}: {
- container: Element;
- target: HTMLElement;
-} ) {
+export default function Highlighter( { block }: { block: DataBlock } ) {
const [ targetBoxes, setTargetBoxes ] = useState< LintBox[] >( [] );
const [ lints, setLints ] = useState< Lint[] >( [] );
let updateLints = useCallback( () => {
- let text = target.textContent;
- text && linter.lint( text ).then( setLints );
- }, [ target ] );
+ linter.lint( block.getTextContent() ).then( setLints );
+ }, [ block ] );
useEffect( () => {
updateLints();
let observer = new MutationObserver( updateLints );
- observer.observe( target, {
+ observer.observe( block.targetElement, {
childList: true,
characterData: true,
subtree: true,
@@ -78,13 +29,21 @@ export default function Highlighter( {
return () => {
observer.disconnect();
};
- }, [ target ] );
+ }, [ block ] );
+ // Update the lint boxes each frame.
+ // Probably overkill.
+ //
+ // TODO: revisit this to do more lazily.
+ // Maybe `onLayoutEffect`?
useEffect( () => {
let running = true;
function onFrame( _timestep: DOMHighResTimeStamp ) {
- computeLintBoxes( target, container, lints ).then( setTargetBoxes );
+ let lintBoxes = lints
+ .map( ( lint ) => block.computeLintBox( lint ) )
+ .flat();
+ setTargetBoxes( lintBoxes );
if ( running ) {
requestAnimationFrame( onFrame );
@@ -100,14 +59,14 @@ export default function Highlighter( {
// Disable browser spellchecking in favor of ours
useEffect( () => {
- target.spellcheck = false;
+ block.targetElement.spellcheck = false;
return () => {
- target.spellcheck = true;
+ block.targetElement.spellcheck = true;
};
- }, [ target ] );
+ }, [ block ] );
- let visible = target.checkVisibility();
+ let visible = block.targetElement.checkVisibility();
return (
<>
diff --git a/src/harper/SidebarControl.tsx b/src/harper/SidebarControl.tsx
index ec89ee047..7d9dd3ff7 100644
--- a/src/harper/SidebarControl.tsx
+++ b/src/harper/SidebarControl.tsx
@@ -1,6 +1,7 @@
+import DataBlock from './DataBlock';
import { ReactPortal, useCallback, useMemo, useRef } from 'react';
import useFrameCount from './useFrameCount';
-import { getNodesFromQuerySelector } from './domUtils';
+import { getNodesFromQuerySelector, getRichTextContainers } from './domUtils';
import { createPortal } from 'react-dom';
import Highlighter from './Highlighter';
import React from 'react';
@@ -20,25 +21,13 @@ export default function SidebarControl() {
let documentContainer = useMemo( getDocumentContainer, [] );
- let targetNodes = useMemo(
- () =>
- documentContainer
- ? getNodesFromQuerySelector(
- documentContainer,
- '[data-block].rich-text'
- )
- : [],
- [ documentContainer, frameCount ]
- );
+ let blocks = DataBlock.getAllDataBlocks();
let highlights =
documentContainer &&
- targetNodes.map( ( n ) => {
- return createPortal(
- <Highlighter container={ documentContainer } target={ n } />,
- documentContainer
- );
- } );
+ blocks.map( ( block ) =>
+ createPortal( <Highlighter block={ block } />, documentContainer )
+ );
return (
<>
diff --git a/src/harper/SuggestionControl.tsx b/src/harper/SuggestionControl.tsx
index 23ec56b0a..4c6755e61 100644
--- a/src/harper/SuggestionControl.tsx
+++ b/src/harper/SuggestionControl.tsx
@@ -1,10 +1,4 @@
-import React, {
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from 'react';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import { isPointInBox, LintBox } from './Box';
import { SuggestionKind } from 'harper.js';
diff --git a/src/harper/domUtils.ts b/src/harper/domUtils.ts
index 563bfbdfc..c8ee3408c 100644
--- a/src/harper/domUtils.ts
+++ b/src/harper/domUtils.ts
@@ -51,7 +51,7 @@ export function leafNodes( node: Element ): Element[] {
/** Given an element and a Span of text inside it, compute the Range that represents the region of the DOM represented. */
export function getRangeForTextSpan(
- target: HTMLElement,
+ target: Element,
span: Span
): Range | null {
let children = leafNodes( target );
@@ -80,3 +80,21 @@ export function getRangeForTextSpan(
return null;
}
+
+/** Locate the rich text containers inside a given element.
+ * Notice: this function may return the provided element. */
+export function getRichTextContainers( target: Element ): Element[] {
+ let elms: Element[] = [];
+
+ if ( target.classList.contains( 'rich-text' ) ) {
+ elms.push( target );
+ }
+
+ elms.push(
+ ...extractFromHTMLCollection(
+ target.getElementsByClassName( 'rich-text' )
+ )
+ );
+
+ return elms;
+}
diff --git a/src/harper/gutenbergUtils.ts b/src/harper/gutenbergUtils.ts
index 04aaab913..f4e52a9ac 100644
--- a/src/harper/gutenbergUtils.ts
+++ b/src/harper/gutenbergUtils.ts
@@ -1,9 +1,8 @@
import { dispatch } from '@wordpress/data';
-export function setBlockContent( clientId: string, text: string ) {
+export async function setBlockContent( clientId: string, text: string ) {
const { selectBlock, updateBlockAttributes } =
dispatch( 'core/block-editor' );
- selectBlock( clientId );
- updateBlockAttributes( clientId, { content: text } );
+ let k = await updateBlockAttributes( clientId, { content: text } );
}