8000 Margin marks by kiran-brahma · Pull Request #89 · kiran-brahma/writing-tool · GitHub
[go: up one dir, main page]

Skip to content
7FFF
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,18 @@ The visual rendering of an Anchor. The Current Finding's Highlight is distinguis
_Avoid_: underline, marker

**Callout**:
The popover a click on a Highlight opens beside the prose: the open Findings on that text, with the
queue's verdicts. It does not change the Current Finding, so the Rail stays where the Writer left it
(ADR 0011).
The popover a click on a Highlight or a Margin mark opens beside the prose: the open Findings on that
text, with the queue's verdicts. It does not change the Current Finding, so the Rail stays where the
Writer left it (ADR 0011).
_Avoid_: tooltip, popup, card

**Margin mark**:
The obelus, with a count, in the right-hand margin beside a Paragraph where open Findings begin. A
Finding is counted once, beside the Paragraph it begins in; an Orphaned Finding has none. A click
opens the Callout with those Findings. Kept although the Anchor entry lists *mark* under _Avoid_: that
avoid is about naming an Anchor, and a Margin mark is not one.
_Avoid_: badge, pin, gutter icon, marker

**Orphaned**:
The condition of a Finding whose quoted text can no longer be found, so it points nowhere. A
condition, never a status.
Expand Down
51 changes: 38 additions & 13 deletions src/editor/DocumentEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EditorContent, useEditor, type Editor } from "@tiptap/react";
import { Selection } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import StarterKit from "@tiptap/starter-kit";
import { useEffect, useReducer, useRef, type ReactNode } from "react";
Expand All @@ -9,16 +10,20 @@ import {
} from "../core/anchor";
import type { DocTree } from "../core/docTree";
import type { Interval } from "../core/finding";
import type { HighlightRect } from "./callout";
import { marginMarks, type HighlightRect } from "./callout";
import {
HighlightExtension,
highlightsAt,
restyleHighlights,
setHighlightRanges,
type MarginMarkClick,
} from "./highlight";
import { TYPING_PAUSE_MS } from "./persistence";

/** A click on a Highlight: the Findings it draws, and where it sits on screen. */
/**
* A click on a Highlight or a Margin mark: the Findings it names, and where the
* prose they concern sits on screen.
*/
export interface HighlightHit {
findingIds: string[];
rect: HighlightRect;
Expand Down Expand Up @@ -55,8 +60,8 @@ export interface DocumentEditorProps {
*/
jumpRequest?: { blockIndex: number; nonce: number; focus?: boolean } | null;
/**
* A click landed on a Highlight, or the callout it opened should close
* (`null`): the click was on plain prose, the Writer typed, or the Highlight
* A click landed on a Highlight or a Margin mark, or the callout it opened
* should close (`null`): the click was on plain prose, the Writer typed, or the Highlight
* scrolled out of view. Reported again with a fresh `rect` as the prose
* scrolls, so the callout stays beside its Highlight.
*/
Expand Down Expand Up @@ -111,6 +116,25 @@ export function DocumentEditor({
return { left: coords.left, top: coords.top, bottom: coords.bottom };
};

/**
* A click on a Margin mark opens the Callout through the same report as a
* click on a Highlight, placed at the start of the prose the mark sits
* beside. Nothing else moves: not the caret, not the Current Finding.
*/
const editorRef = useRef<Editor | null>(null);
const openMarginMark = ({ findingIds, blockStart }: MarginMarkClick) => {
const view = editorRef.current?.view;
if (view === undefined) return;
const from = Selection.findFrom(view.state.doc.resolve(blockStart), 1, true)?.from;
if (from === undefined) return;
const rect = openHitRect(view, from);
if (rect === null) return;
openHitRef.current = { findingIds, from };
onHighlightClickRef.current?.({ findingIds, rect });
};
const openMarginMarkRef = useRef(openMarginMark);
openMarginMarkRef.current = openMarginMark;

const closeCallout = () => {
if (openHitRef.current === null) return;
openHitRef.current = null;
Expand Down Expand Up @@ -180,7 +204,9 @@ export function DocumentEditor({
StarterKit.configure({
heading: { levels: [1, 2, 3] },
}),
HighlightExtension,
HighlightExtension.configure({
onMarginMarkClick: (click) => openMarginMarkRef.current(click),
}),
],
content: initialContent,
editorProps: {
Expand Down Expand Up @@ -219,20 +245,19 @@ export function DocumentEditor({
},
});

// Draw the Highlights afresh when they were resolved against the prose as it
// stands. Mid-pause they were resolved against older text: a change then —
editorRef.current = editor;

// Draw the Highlights and Margin marks afresh when they were resolved against
// the prose as it stands. Mid-pause they were resolved against older text: a change then —
// the Current Finding moving, a Finding leaving the queue — restyles the
// Highlights ProseMirror has kept mapped through the edits, and the next
// resolution redraws them.
useEffect(() => {
if (editor === null) return;
const ranges = projectHighlightsOnto(
editor.getJSON() as unknown as DocTree,
highlightsResolvedAgainst,
highlights,
);
const tree = editor.getJSON() as unknown as DocTree;
const ranges = projectHighlightsOnto(tree, highlightsResolvedAgainst, highlights);
if (ranges !== null) {
setHighlightRanges(editor, ranges);
setHighlightRanges(editor, ranges, marginMarks(tree, highlights));
return;
}
restyleHighlights(
Expand Down
91 changes: 88 additions & 3 deletions src/editor/callout.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { describe, expect, it } from "vitest";
import { reResolveFindings, type FindingInterval } from "../core/anchor";
import { canonicalText } from "../core/canonicalText";
import type { DocTree } from "../core/docTree";
import type { Finding, FindingStatus } from "../core/finding";
import { calloutFindings, calloutPosition } from "./callout";
import { calloutFindings, calloutPosition, marginMarks } from "./callout";

function finding(id: string, status: FindingStatus = "open"): Finding {
function finding(id: string, status: FindingStatus = "open", quote = "very"): Finding {
return {
id,
passId: "hedges",
promptHash: "hash",
anchor: { quote: "very", offset: 0, state: "attached" },
anchor: { quote, offset: 0, state: "attached" },
issue: "issue",
diagnosis: "diagnosis",
status,
Expand Down Expand Up @@ -60,3 +63,85 @@ describe("calloutPosition", () => {
expect(position.left).toBe(1200 - 288 - 16);
});
});

describe("marginMarks", () => {
const tree: DocTree = {
type: "doc",
content: [
{ type: "heading", attrs: { level: 1 }, content: [{ type: "text", text: "A title" }] },
{ type: "paragraph", content: [{ type: "text", text: "The first paragraph is very long." }] },
{ type: "paragraph" },
{ type: "paragraph", content: [{ type: "text", text: "The second one is quite short." }] },
{
type: "bulletList",
content: [
{
type: "listItem",
content: [{ type: "paragraph", content: [{ type: "text", text: "A listed point." }] }],
},
],
},
],
};
const canonical = canonicalText(tree);

/** The resolved Highlight of a Finding whose Anchor quotes `quote`. */
function highlight(findingId: string, quote: string): FindingInterval {
const start = canonical.indexOf(quote);
if (start === -1) throw new Error(`"${quote}" is not in the Document`);
return { findingId, interval: { start, end: start + quote.length } };
}

it("gives one entry for an open Finding, at the top-level block where it begins", () => {
expect(marginMarks(tree, [highlight("a", "quite short")])).toEqual([
{ blockIndex: 3, findingIds: ["a"] },
]);
});

it("counts a Finding that spans several Paragraphs once, beside the first of them", () => {
const marks = marginMarks(tree, [highlight("a", "very long.\n\nThe second")]);

expect(marks).toEqual([{ blockIndex: 1, findingIds: ["a"] }]);
});

it("counts every Finding that begins in a shared block, and each block separately", () => {
const marks = marginMarks(tree, [
highlight("list", "listed"),
highlight("a", "first"),
highlight("title", "title"),
highlight("b", "very"),
highlight("c", "long"),
]);

expect(marks).toEqual([
{ blockIndex: 0, findingIds: ["title"] },
{ blockIndex: 1, findingIds: ["a", "b", "c"] },
{ blockIndex: 4, findingIds: ["list"] },
]);
});

it("names a Finding once when it is resolved twice", () => {
const marks = marginMarks(tree, [highlight("a", "first"), highlight("a", "first")]);

expect(marks).toEqual([{ blockIndex: 1, findingIds: ["a"] }]);
});

it("has no entry for an Orphaned Finding or one that has left the queue", () => {
const { highlights } = reResolveFindings(
[
finding("open", "open", "quite short"),
finding("orphaned", " 8 ;open&qu 10BC8 ot;, "a sentence the Writer deleted"),
finding("addressed", "addressed", "first paragraph"),
finding("declined", "declined", "listed point"),
],
canonical,
() => canonical,
);

expect(marginMarks(tree, highlights)).toEqual([{ blockIndex: 3, findingIds: ["open"] }]);
});

it("has no entries when no Finding is open", () => {
expect(marginMarks(tree, [])).toEqual([]);
});
});
59 changes: 59 additions & 0 deletions src/editor/callout.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import type { FindingInterval } from "../core/anchor";
import { canonicalBlocks } from "../core/canonicalText";
import type { DocTree } from "../core/docTree";
import { isOpenFinding, type Finding } from "../core/finding";

/**
Expand All @@ -22,6 +25,62 @@ export function calloutFindings(findingIds: string[], findings: Finding[]): Find
return shown;
}

/**
* A Margin mark: the top-level block it sits beside, and the Findings that
* begin there. The count it shows is the number of ids.
*/
export interface MarginMark {
blockIndex: number;
findingIds: string[];
}

/**
* The Margin marks for a Document: one per top-level block where at least one
* resolved Highlight begins, in Document order, each naming its Findings once
* and in the order given. A Finding that spans several Paragraphs is counted
* beside the first of them only, so the counts are honest (story 221).
*
* It reads the resolved Highlights, which hold only open, attached Findings:
* an Orphaned Finding has no interval and a Finding that has left the queue
* draws no Highlight, so neither gets a mark. Like the Callout it never sees a
* Finding's text — only ids and intervals.
*/
export function marginMarks(tree: DocTree, highlights: readonly FindingInterval[]): MarginMark[] {
// One render of the Document for every Highlight: a Document can carry
// hundreds, and each would otherwise render it again.
const blocks = canonicalBlocks(tree);
const byBlock = new Map<number, Set<string>>();
for (const { findingId, interval } of highlights) {
const blockIndex = blockBeginning(blocks, interval.start);
if (blockIndex === null) continue;
const ids = byBlock.get(blockIndex) ?? new Set<string>();
ids.add(findingId);
byBlock.set(blockIndex, ids);
}
return [...byBlock.entries()]
.sort(([left], [right]) => left - right)
.map(([blockIndex, ids]) => ({ blockIndex, findingIds: [...ids] }));
}

/**
* The top-level block a canonical offset falls in, or in the gap after, as
* `blockIndexForInterval` decides it: the first block whose end lies past the
* offset. Blocks are in canonical order, so this is a binary search.
*/
function blockBeginning(
blocks: readonly { index: number; end: number }[],
start: number,
): number | null {
let low = 0;
let high = blocks.length;
while (low < high) {
const middle = (low + high) >> 1;
if (start < blocks[middle].end) high = middle;
else low = middle + 1;
}
return low < blocks.length ? blocks[low].index : null;
}

/** Where a Highlight sits on screen, in viewport pixels. */
export interface HighlightRect {
left: number;
Expand Down
Loading
0