Skip to content

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

feat: add sidebar with list of errors

Elijah Potter5b48bd2c5beb
diff --git a/src/harper/Highlighter.tsx b/src/harper/Highlighter.tsx
index fb6b2d69d..933233d52 100644
--- a/src/harper/Highlighter.tsx
+++ b/src/harper/Highlighter.tsx
@@ -1,64 +1,21 @@
-import React, { useCallback, useState, useEffect } from 'react';
-import { Lint } from 'harper.js';
+import React, { useEffect } from 'react';
import SuggestionControl from './SuggestionControl';
-import { LintBox } from './Box';
import RichText from './RichText';
-import { useLinter, useLinterConfig } from './HarperContext';
-
-export default function Highlighter({ richText }: { richText: RichText }) {
- const linter = useLinter();
- const [config] = useLinterConfig();
-
- const [targetBoxes, setTargetBoxes] = useState<LintBox[]>([]);
- const [lints, setLints] = useState<Lint[]>([]);
-
- const updateLints = useCallback(async () => {
- // We assume that a given index always refers to the same rich text field.
- const contents = richText.getTextContent();
- const newLints = await linter.lint(contents);
- setLints(newLints);
- }, [richText, linter, config]);
-
- useEffect(() => {
- updateLints();
- const observer = new MutationObserver(updateLints);
- observer.observe(richText.getTargetElement(), {
- childList: true,
- characterData: true,
- subtree: true,
- });
-
- return () => {
- observer.disconnect();
- };
- }, [richText, updateLints]);
-
- // Update the lint boxes each frame.
- // Probably overkill.
- //
- // TODO: revisit this to do more lazily.
- // Maybe `onLayoutEffect`?
- useEffect(() => {
- let running = true;
-
- function onFrame() {
- const lintBoxes = lints
- .map((lint) => richText.computeLintBox(lint))
- .flat();
- setTargetBoxes(lintBoxes);
-
- if (running) {
- requestAnimationFrame(onFrame);
- }
- }
-
- requestAnimationFrame(onFrame);
-
- return () => {
- running = false;
- };
- });
+import { LintBox } from './Box';
+/**
+ * Renders controls to the user around the errors.
+ * @param root0
+ * @param root0.lintBoxes
+ * @param root0.richText
+ */
+export default function Highlighter({
+ lintBoxes,
+ richText,
+}: {
+ lintBoxes: LintBox[];
+ richText: RichText;
+}) {
// Disable browser spellchecking in favor of ours
useEffect(() => {
richText.getTargetElement().spellcheck = false;
@@ -73,7 +30,7 @@ export default function Highlighter({ richText }: { richText: RichText }) {
return (
<>
{visible &&
- targetBoxes.map((b, index) => (
+ lintBoxes.map((b, index) => (
<SuggestionControl lintBox={b} key={index} />
))}
</>
diff --git a/src/harper/LintList.tsx b/src/harper/LintList.tsx
new file mode 100644
index 000000000..8c06306f3
--- /dev/null
+++ b/src/harper/LintList.tsx
@@ -0,0 +1,15 @@
+import React from 'react';
+import { LintBox } from './Box';
+import LintListItem from './LintListItem';
+
+export default function LintList({ lintBoxes }: { lintBoxes: LintBox[] }) {
+ return (
+ <>
+ {lintBoxes
+ .filter((box) => box.lint.suggestion_count() > 0)
+ .map((box, index) => (
+ <LintListItem key={index} box={box} />
+ ))}
+ </>
+ );
+}
diff --git a/src/harper/LintListItem.tsx b/src/harper/LintListItem.tsx
new file mode 100644
index 000000000..0b3b42a6d
--- /dev/null
+++ b/src/harper/LintListItem.tsx
@@ -0,0 +1,31 @@
+import { Card, Button, CardBody } from '@wordpress/components';
+import { LintBox } from './Box';
+import React from 'react';
+import { suggestionText } from './lintUtils';
+
+export default function LintListItem({ box }: { box: LintBox }) {
+ return (
+ <Card size="small" className="harper-lint-card">
+ <CardBody>
+ <h2 className={`harper-underline-${box.lint.lint_kind()}`}>
+ {box.lint.lint_kind()}
+ </h2>
+ <p>{box.lint.message()}</p>
+
+ {box.lint.suggestions().map((sug, index) => (
+ <Button
+ variant="primary"
+ key={index}
+ onClick={() => box.applySuggestion(sug)}
+ >
+ {suggestionText(
+ sug.kind(),
+ box.lint.get_problem_text(),
+ sug.get_replacement_text()
+ )}
+ </Button>
+ ))}
+ </CardBody>
+ </Card>
+ );
+}
diff --git a/src/harper/LintSettingList.tsx b/src/harper/LintSettingList.tsx
index 71d91ab3c..eb2a8af79 100644
--- a/src/harper/LintSettingList.tsx
+++ b/src/harper/LintSettingList.tsx
@@ -11,16 +11,20 @@ export default function LintSettingList() {
const defaultConfig = useDefaultLintConfig();
const descriptions = useLintDescriptions();
- return Object.entries(lintConfig).map(([key, value]) => (
- <LintSettingRow
- key={key}
- name={key}
- description={descriptions[key]}
- value={value}
- defaultValue={defaultConfig[key]!}
- setValue={(newValue) =>
- setLintConfig({ ...lintConfig, [key]: newValue })
- }
- />
- ));
+ return (
+ <div className="harper-lint-config-cont">
+ {Object.entries(lintConfig).map(([key, value]) => (
+ <LintSettingRow
+ key={key}
+ name={key}
+ description={descriptions[key]}
+ value={value}
+ defaultValue={defaultConfig[key]!}
+ setValue={(newValue) =>
+ setLintConfig({ ...lintConfig, [key]: newValue })
+ }
+ />
+ ))}
+ </div>
+ );
}
diff --git a/src/harper/LintSettingRow.tsx b/src/harper/LintSettingRow.tsx
index 2f9727526..879ab8673 100644
--- a/src/harper/LintSettingRow.tsx
+++ b/src/harper/LintSettingRow.tsx
@@ -23,7 +23,7 @@ export default function LintSettingRow({
linter.toTitleCase(name.replace(/_/g, ' ')).then(setTitle);
}, [linter, name]);
- return title ? (
+ return title && description ? (
<Animate type={title === null ? undefined : 'slide-in'}>
{({ className }) => (
<div className={`${className} harper-lint-config-row`}>
diff --git a/src/harper/SidebarControl.tsx b/src/harper/SidebarControl.tsx
index a78606f5d..84610fe03 100644
--- a/src/harper/SidebarControl.tsx
+++ b/src/harper/SidebarControl.tsx
@@ -2,7 +2,8 @@ import DataBlock from './DataBlock';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import Highlighter from './Highlighter';
-import LintSettingList from './LintSettingList';
+import SidebarTabContainer from './SidebarTabContainer';
+import useLintBoxes from './useLintBoxes';
export default function SidebarControl() {
const documentContainer = useMemo<Element>(
@@ -34,22 +35,26 @@ export default function SidebarControl() {
[blocks]
);
+ const lintBoxes = useLintBoxes(richTexts);
+
const highlights =
documentContainer &&
- richTexts.map((richText) =>
- createPortal(
+ richTexts.map((richText, index) => {
+ const boxes = lintBoxes[index] ?? [];
+ return createPortal(
<Highlighter
richText={richText}
key={richText.getTextContent()}
+ lintBoxes={boxes}
/>,
documentContainer
- )
- );
+ );
+ });
return (
<>
{highlights}
- <LintSettingList />
+ <SidebarTabContainer lintBoxes={lintBoxes.flat()} />
</>
);
}
diff --git a/src/harper/SidebarTabContainer.tsx b/src/harper/SidebarTabContainer.tsx
new file mode 100644
index 000000000..4a1c78a15
--- /dev/null
+++ b/src/harper/SidebarTabContainer.tsx
@@ -0,0 +1,29 @@
+import React from 'react';
+import LintSettingList from './LintSettingList';
+import { TabPanel } from '@wordpress/components';
+import LintList from './LintList';
+import { LintBox } from './Box';
+
+export default function SidebarTabContainer({
+ lintBoxes,
+}: {
+ lintBoxes: LintBox[];
+}) {
+ return (
+ <TabPanel
+ tabs={[
+ { name: 'errors', title: 'Errors' },
+ { name: 'settings', title: 'Settings' },
+ ]}
+ >
+ {(tab) => {
+ switch (tab.name) {
+ case 'errors':
+ return <LintList lintBoxes={lintBoxes} />;
+ case 'settings':
+ return <LintSettingList />;
+ }
+ }}
+ </TabPanel>
+ );
+}
diff --git a/src/harper/SuggestionControl.tsx b/src/harper/SuggestionControl.tsx
index d45f06be2..cedf0a2c9 100644
--- a/src/harper/SuggestionControl.tsx
+++ b/src/harper/SuggestionControl.tsx
@@ -2,19 +2,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react';
import { isPointInBox, LintBox } from './Box';
import { SuggestionKind } from 'harper.js';
import { Button, Popover } from '@wordpress/components';
-
-function suggestionText(
- kind: SuggestionKind,
- problemText: string,
- replacementText: string
-): string {
- if (kind === SuggestionKind.Remove) {
- return `Remove "${problemText}"`;
- } else if (kind === SuggestionKind.Replace) {
- return `Replace with “${replacementText}”`;
- }
- return `Insert "${replacementText}"`;
-}
+import { suggestionText } from './lintUtils';
/**
* A control for an individual suggestion shown on the screen.
diff --git a/src/harper/index.css b/src/harper/index.css
index f1a41147c..a195ff5a9 100644
--- a/src/harper/index.css
+++ b/src/harper/index.css
@@ -4,6 +4,24 @@
padding: 10px;
}
+.harper-lint-card {
+ margin: 4px;
+}
+
+.harper-lint-card h2 {
+ font-weight: bold;
+ font-size: large;
+}
+
+.harper-lint-card button {
+ width: 100%;
+ margin-top: 6px;
+}
+
+.harper-lint-config-cont {
+ overflow-x: hidden;
+}
+
.harper-lint-config-row {
padding: 6px;
}
diff --git a/src/harper/lintUtils.ts b/src/harper/lintUtils.ts
new file mode 100644
index 000000000..106bf3792
--- /dev/null
+++ b/src/harper/lintUtils.ts
@@ -0,0 +1,14 @@
+import { SuggestionKind } from 'harper.js';
+
+export function suggestionText(
+ kind: SuggestionKind,
+ problemText: string,
+ replacementText: string
+): string {
+ if (kind === SuggestionKind.Remove) {
+ return `Remove "${problemText}"`;
+ } else if (kind === SuggestionKind.Replace) {
+ return `Replace with “${replacementText}”`;
+ }
+ return `Insert "${replacementText}"`;
+}
diff --git a/src/harper/useLintBoxes.ts b/src/harper/useLintBoxes.ts
new file mode 100644
index 000000000..382220349
--- /dev/null
+++ b/src/harper/useLintBoxes.ts
@@ -0,0 +1,79 @@
+import { useCallback, useEffect, useState } from 'react';
+import { LintBox } from './Box';
+import RichText from './RichText';
+import { Lint } from 'harper.js';
+import { useLinter, useLinterConfig } from './HarperContext';
+
+/**
+ * Lint given elements and return the resulting error targets.
+ * @param richTexts
+ */
+export default function useLintBoxes(richTexts: RichText[]): LintBox[][] {
+ const linter = useLinter();
+ const [config] = useLinterConfig();
+
+ const [targetBoxes, setTargetBoxes] = useState<LintBox[][]>([]);
+ const [lints, setLints] = useState<Lint[][]>([]);
+
+ const updateLints = useCallback(async () => {
+ // We assume that a given index always refers to the same rich text field.
+ const newLints = await Promise.all(
+ richTexts.map((richText) => {
+ const contents = richText.getTextContent();
+ return linter.lint(contents);
+ })
+ );
+
+ setLints(newLints);
+ }, [richTexts, linter, config]);
+
+ useEffect(() => {
+ updateLints();
+
+ const observers = richTexts.map((richText) => {
+ const observer = new MutationObserver(updateLints);
+ observer.observe(richText.getTargetElement(), {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+ return observer;
+ });
+
+ return () => {
+ observers.forEach((observer) => observer.disconnect());
+ };
+ }, [richTexts, updateLints]);
+
+ // Update the lint boxes each frame.
+ // Probably overkill.
+ //
+ // TODO: revisit this to do more lazily.
+ // Maybe `onLayoutEffect`?
+ useEffect(() => {
+ let running = true;
+
+ function onFrame() {
+ const lintBoxes = lints.map((lintForText, index) => {
+ const richText = richTexts[index];
+ return lintForText.flatMap((lint) =>
+ richText.computeLintBox(lint)
+ );
+ });
+
+ setTargetBoxes(lintBoxes);
+
+ if (running) {
+ requestAnimationFrame(onFrame);
+ }
+ }
+
+ requestAnimationFrame(onFrame);
+
+ return () => {
+ running = false;
+ };
+ });
+
+ return targetBoxes;
+}