Skip to content

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

feat: improved look and reliability of hover detection

Elijah Potter30ca2d959a22
diff --git a/package.json b/package.json
index 23e558682..172160edc 100644
--- a/package.json
+++ b/package.json
@@ -18,7 +18,8 @@
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
"dependencies": {
+ "@wordpress/data": "^10.15.1",
"@wordpress/editor": "^14.15.1",
- "harper.js": "^0.14.0"
+ "harper.js": "^0.15.0"
}
}
diff --git a/src/harper/Highlighter.tsx b/src/harper/Highlighter.tsx
index f6d15eccb..1d0e54183 100644
--- a/src/harper/Highlighter.tsx
+++ b/src/harper/Highlighter.tsx
@@ -1,6 +1,7 @@
+import { select, dispatch } from '@wordpress/data';
import React, { useCallback, useRef } from 'react';
import { useState, useEffect } from 'react';
-import { LocalLinter, Lint, WorkerLinter, Suggestion } from 'harper.js';
+import { LocalLinter, Lint, WorkerLinter, Suggestion, Span } from 'harper.js';
import SuggestionControl from './SuggestionControl';
import { LintBox } from './Box';
@@ -19,24 +20,55 @@ async function memoizedLint( text: string ): Promise< Lint[] > {
return newLints;
}
+function getRangeForTextSpan( target: Element, span: Span ): Range | null {
+ let children = target.childNodes;
+ let range = document.createRange();
+ let traversed = 0;
+
+ let startFound = false;
+
+ for ( let i = 0; i < children.length; i++ ) {
+ let child = children[ i ];
+ let childText = child.textContent;
+
+ if ( traversed + childText?.length > span.start && ! startFound ) {
+ range.setStart( child, span.start - traversed );
+ startFound = true;
+ }
+
+ if ( startFound && traversed + childText?.length > span.end ) {
+ range.setEnd( child, span.end - traversed );
+ return range;
+ }
+
+ traversed += childText?.length ?? 0;
+ }
+
+ return null;
+}
+
/** Get target boxes for a text node.
* Each box represents a Harper lint in the Node. */
-async function getLintBoxesForNode(
- node: Node,
+async function computeLintBoxes(
+ target: Element,
container: Element
): Promise< LintBox[] > {
- let text = node.textContent ?? '';
+ let text = target.textContent ?? '';
+ // The ID of the node we're looking at
+ let clientId = target.getAttribute( 'data-block' );
let lints = await memoizedLint( text );
let boxes: LintBox[] = [];
for ( let lint of lints ) {
- let range = document.createRange();
let span = lint.span();
+ let range = getRangeForTextSpan( target, span );
- range.setStart( node, span.start );
- range.setEnd( node, span.end );
+ if ( range == null ) {
+ console.log( 'Could not locate range.' );
+ continue;
+ }
let targetRect = range.getBoundingClientRect();
let contRect = container.getBoundingClientRect();
@@ -49,7 +81,17 @@ async function getLintBoxesForNode(
lint,
applySuggestion: async ( sug: Suggestion ) => {
let fixed = await linter.applySuggestion( text, sug, span );
- node.textContent = fixed;
+
+ const { getBlocks } = select( 'core/block-editor' );
+ const { selectBlock, updateBlockAttributes } =
+ dispatch( 'core/block-editor' );
+
+ const updateBlocks = ( attributes ) => {
+ selectBlock( clientId );
+ updateBlockAttributes( clientId, attributes );
+ };
+
+ updateBlocks( { content: fixed } );
},
} );
}
@@ -57,6 +99,23 @@ async function getLintBoxesForNode(
return boxes;
}
+function locateBlock( clientId: string, blocks: any[] ): any {
+ let block = blocks.find( ( b ) => b.clientId == clientId );
+
+ if ( block ) return block;
+
+ for ( let block of blocks ) {
+ if ( block.innerBlocks ) {
+ let found = locateBlock( clientId, block.innerBlocks );
+ if ( found ) {
+ return found;
+ }
+ }
+ }
+
+ return null;
+}
+
export default function Highlighter( {
container,
target,
@@ -64,7 +123,7 @@ export default function Highlighter( {
registerCloseHandler,
}: {
container: Element;
- target: Node;
+ target: Element;
requestClosePopups: () => void;
registerCloseHandler: ( handler: () => void ) => void;
} ) {
@@ -76,7 +135,7 @@ export default function Highlighter( {
function onFrame( _timestep: DOMHighResTimeStamp ) {
//let contRect = container.getBoundingClientRect();
- getLintBoxesForNode( target, container ).then( setTargetBoxes );
+ computeLintBoxes( target, container ).then( setTargetBoxes );
if ( running ) {
requestAnimationFrame( onFrame );
@@ -96,7 +155,7 @@ export default function Highlighter( {
<SuggestionControl
lintBox={ b }
requestClosePopups={ requestClosePopups }
- registerCloseHandler={registerCloseHandler}
+ registerCloseHandler={ registerCloseHandler }
/>
) ) }
</>
diff --git a/src/harper/SidebarControl.tsx b/src/harper/SidebarControl.tsx
index cbb216ec5..74188e262 100644
--- a/src/harper/SidebarControl.tsx
+++ b/src/harper/SidebarControl.tsx
@@ -15,8 +15,8 @@ function getDocumentContainer(): Element | null {
}
/** Turn a NodeList into a normal JavaScript array. */
-function extractFromNodeList( list: NodeList ): Node[] {
- let elements: Node[] = [];
+function extractFromNodeList< T extends Node >( list: NodeListOf< T > ): T[] {
+ let elements: T[] = [];
for ( let i = 0; i < list.length; i++ ) {
let item = list[ i ];
@@ -58,24 +58,21 @@ export default function SidebarControl() {
closeHandlers.current.forEach( ( h ) => h() );
}, [] );
- let highlights = targetNodes.flatMap( ( n ) => {
- if ( ! documentContainer ) return [];
-
- let textChildren = extractFromNodeList( n.childNodes ).filter(
- ( n ) => n.nodeType === 3
- );
-
- return textChildren.map( ( n ) =>
- createPortal(
- <Highlighter container={ documentContainer } target={ n } requestClosePopups={requestClosePopups}
+ let highlights =
+ documentContainer &&
+ targetNodes.map( ( n ) => {
+ return createPortal(
+ <Highlighter
+ container={ documentContainer }
+ target={ n }
+ requestClosePopups={ requestClosePopups }
registerCloseHandler={ ( handler ) =>
closeHandlers.current.add( handler )
}
/>,
documentContainer
- )
- );
- } );
+ );
+ } );
return (
<>
diff --git a/src/harper/SuggestionControl.tsx b/src/harper/SuggestionControl.tsx
index 24124478d..bb26b6fd5 100644
--- a/src/harper/SuggestionControl.tsx
+++ b/src/harper/SuggestionControl.tsx
@@ -17,13 +17,15 @@ function suggestionText(
if ( kind == SuggestionKind.Remove ) {
return `Remove "${ problemText }"`;
} else if ( kind == SuggestionKind.Replace ) {
- return `Replace "${ problemText }" with "${ replacementText }"`;
+ return `Replace with "${ replacementText }"`;
} else {
- return `Insert "${ replacementText }" after ${ problemText }`;
+ return `Insert "${ replacementText }"`;
}
}
-/** A control for an individual suggestion shown on the screen. */
+/** A control for an individual suggestion shown on the screen.
+ * This includes both the underline to be shown, and the control that appears when you hover over it.
+ * */
export default function SuggestionControl( {
lintBox,
requestClosePopups,
@@ -36,7 +38,6 @@ export default function SuggestionControl( {
let { x, y, width, height, lint, applySuggestion } = lintBox;
let underlineRef = useRef< HTMLElement | null >( null );
- let [ offsetX, offsetY ] = useElementPosition( underlineRef );
let suggestions = useMemo( () => lint.suggestions(), [ lint ] );
const [ showSuggestions, setShowSuggestions ] = useState( false );
@@ -47,11 +48,15 @@ export default function SuggestionControl( {
useEffect( () => {
function mouseMove( e: MouseEvent ) {
+ if (underlineRef.current == null){return};
+
+ let rect = underlineRef.current.getBoundingClientRect();
+
if (
- e.pageX > offsetX &&
- e.pageX < offsetX + width &&
- e.pageY > offsetY &&
- e.pageY < offsetY + height
+ e.clientX > rect.x &&
+ e.clientX < rect.x + width &&
+ e.clientY > rect.y &&
+ e.clientY < rect.y + height
) {
requestClosePopups();
setShowSuggestions( () => true );
@@ -59,13 +64,15 @@ export default function SuggestionControl( {
}
function mouseUp( e: MouseEvent ) {
+ let offsetX = underlineRef.current?.offsetLeft ?? 0;
+ let offsetY = underlineRef.current?.offsetLeft ?? 0;
+
if (
- e.pageX < offsetX &&
- e.pageX > offsetX + width &&
- e.pageY < offsetY &&
+ e.pageX < offsetX ||
+ e.pageX > offsetX + width ||
+ e.pageY < offsetY ||
e.pageY > offsetY + height
) {
- setShowSuggestions( false );
requestClosePopups();
}
}
@@ -91,14 +98,13 @@ export default function SuggestionControl( {
mouseUp
);
};
- }, [ offsetX, offsetY, requestClosePopups ] );
-
-
+ }, [ requestClosePopups, underlineRef.current ] );
return (
<>
<div
ref={ underlineRef }
+ className={ `harper-underline-${ lint.lint_kind() }` }
style={ {
position: 'absolute',
top: `${ y }px`,
@@ -106,7 +112,6 @@ export default function SuggestionControl( {
width: `${ width }px`,
height: `${ height }px`,
zIndex: -100,
- borderBottom: '3px solid red',
} }
></div>
{ showSuggestions && (
@@ -119,7 +124,11 @@ export default function SuggestionControl( {
zIndex: 100,
} }
>
- { lint.message() }
+ <h1 className={ `harper-underline-${ lint.lint_kind() }` }>
+ { lint.lint_kind() }
+ </h1>
+
+ <p>{ lint.message() }</p>
{ suggestions.map( ( sug ) => (
<button onClick={ () => applySuggestion( sug ) }>
diff --git a/src/harper/index.css b/src/harper/index.css
index ce273b1c6..fd3285fa6 100644
--- a/src/harper/index.css
+++ b/src/harper/index.css
@@ -1,26 +1,71 @@
.harper-popover {
border-radius: 4px;
border: 1px solid black;
- padding: 4px;
+ padding: 8px;
background-color: white;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
- font-size: 16px;
- font-weight: 750;
filter: drop-shadow(5px 5px 5px #CCCCCC);
width: 200px;
-
display: flex;
flex-direction: column;
- align-items: center;
+ align-items: left;
text-align: left;
}
+.harper-popover > h1 {
+ font-size: 16px;
+ font-weight: 750;
+}
+
+.harper-popover > p {
+ font-size: 14px;
+ font-weight: 500;
+}
+
.harper-popover > button {
- width: 95%;
- padding: 4px;
- margin-top: 4px;
- border-radius: 4px;
+ width: 100%;
+ padding: 8px;
+ margin-top: 8px;
+ border-radius: 8px;
border: 0px;
- background-color: black;
- color: white;
+}
+
+.harper-popover > button:hover {
+ filter: brightness(0.9);
+}
+
+.harper-underline-Spelling {
+ border-bottom: 4px solid #EE4266;
+}
+
+.harper-underline-Capitalization {
+ border-bottom: 4px solid #540D6E;
+}
+
+.harper-underline-Style {
+ border-bottom: 4px solid #FFD23F;
+}
+
+.harper-underline-Formatting {
+ border-bottom: 4px solid #540D6E;
+}
+
+.harper-underline-Repetition {
+ border-bottom: 4px solid #3BCEAC;
+}
+
+.harper-underline-Enhancement {
+ border-bottom: 4px solid #0EAD69;
+}
+
+.harper-underline-Readability {
+ border-bottom: 4px solid #0EAD69;
+}
+
+.harper-underline-WordChoice {
+ border-bottom: 4px solid #0EAD69;
+}
+
+.harper-underline-Miscellaneous {
+ border-bottom: 4px solid #3BCEAC;
}
diff --git a/src/harper/useElementPosition.ts b/src/harper/useElementPosition.ts
deleted file mode 100644
index 7bc53f97e..000000000
--- a/src/harper/useElementPosition.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import {
- MutableRefObject,
- useCallback,
- useEffect,
- useLayoutEffect,
- useState,
-} from 'react';
-
-/** Get the pixel coordinates in page space, of an element's top left corner. */
-export default function useElementPosition(
- ref: MutableRefObject< HTMLElement | null >
-): [ number, number ] {
- let [ position, setPosition ] = useState< [ number, number ] >( [ 0, 0 ] );
-
- let handleUpdate = useCallback( () => {
- if ( ref.current != null ) {
- let rect = ref.current.getBoundingClientRect();
-
- setPosition( [
- rect.left + window.screenX,
- rect.top + window.screenY,
- ] );
- }
- }, [ ref.current ] );
-
- useEffect( () => {
- handleUpdate();
- }, [] );
-
- useLayoutEffect( () => {
- handleUpdate();
- window.addEventListener( 'resize', handleUpdate );
-
- return () => {
- window.removeEventListener( 'resize', handleUpdate );
- };
- }, [ ref.current, handleUpdate ] );
-
- return position;
-}
diff --git a/yarn.lock b/yarn.lock
index 6893f4e3b..8f0db34f5 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7014,10 +7014,10 @@ hard-rejection@^2.1.0:
resolved "https://registry.yarnpkg.com/hard-rejection/-/hard-rejection-2.1.0.tgz#1c6eda5c1685c63942766d79bb40ae773cecd883"
integrity sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==
-harper.js@^0.14.0:
- version "0.14.0"
- resolved "https://registry.yarnpkg.com/harper.js/-/harper.js-0.14.0.tgz#16d511070d4474dca501d4de1c76f7849ec0accb"
- integrity sha512-WRzop2PmFK2AZiqNMHHWDFIqFmS7DeoNVhyibyu7T6wuSe24E1Tunolz8ZzMPfcaKuBB2SY+yGbyTOyj+/QD8g==
+harper.js@^0.15.0:
+ version "0.15.0"
+ resolved "https://registry.yarnpkg.com/harper.js/-/harper.js-0.15.0.tgz#a02f25df2d911d35f868a580098559188efb0e46"
+ integrity sha512-K8y97LDwJ/2BPs8eTHi5WVMY2Rap0GhOCwAHghmt1T3w4/fs2Y0xE2MakvPT6E8OVLvM6/B8Qr/4vQggQTPIYA==
has-bigints@^1.0.2:
version "1.1.0"