Skip to content
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
209 changes: 209 additions & 0 deletions libs/shared-react/src/plugins/usj/ParaMarkerSelectionPlugin.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
$createUnknownNode,
$getSelectedParaMarker,
$isGutterMarkerNode,
$isImpliedParaNode,
$isParaNode,
$selectParaMarker,
createEmptyHistoryState,
Expand Down Expand Up @@ -789,6 +790,214 @@ describe.each(["off", "guarded"] as const)(
},
);

describe("ParaMarkerSelectionPlugin — the selected marker of an empty paragraph after a chapter", () => {
/** `\c 1`, an empty `\s`, then `\p first`, with the plugins a delete on the marker passes through. */
async function emptyAfterChapterEnvironment(structureProtectionMode: StructureProtectionMode) {
let empty: ParaNode;
const { editor } = await baseTestEnvironment(
() => {
empty = $createParaNode("s");
$getRoot().append(
$createImmutableChapterNode("1"),
empty.append($createGutterGlyphNode("s")),
$createParaNode("p").append($createGutterGlyphNode("p"), $createTextNode("first")),
);
},
<>
<StructureKeyboardPlugin structureProtectionMode={structureProtectionMode} />
<ParaMarkerSelectionPlugin structureProtectionMode={structureProtectionMode} />
</>,
);
return { editor, empty: empty! };
}

const removed = [{ marker: "p", glyphs: 1, text: "first" }];

/** Asserts the caret landed in the `\p` after the removed paragraph. */
function expectCaretInNextPara(editor: LexicalEditor) {
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) throw new Error("expected a range selection");
const caretPara = selection.focus.getNode().getTopLevelElementOrThrow();
expect($isParaNode(caretPara) && caretPara.getMarker()).toBe("p");
});
}

it.each(["Backspace", "Delete"])(
'under "guarded", the first %s arms its removal and the second removes it',
async (key) => {
const { editor, empty } = await emptyAfterChapterEnvironment("guarded");
await selectMarkerOf(editor, empty);
const before = documentJson(editor);

await pressKey(editor, key);

expect(documentJson(editor)).toBe(before);
expect(editor.getRootElement()?.getAttribute("data-verse-delete-kind")).toBe(
"removeEmptyPara",
);

await pressKey(editor, key);

expect(paragraphsOf(editor)).toEqual(removed);
expectCaretInNextPara(editor);
},
);

it.each(["Backspace", "Delete"])('under "off", %s removes it in one press', async (key) => {
const { editor, empty } = await emptyAfterChapterEnvironment("off");
await selectMarkerOf(editor, empty);

const event = await pressKey(editor, key);

expect(event.defaultPrevented).toBe(true);
expect(paragraphsOf(editor)).toEqual(removed);
expectCaretInNextPara(editor);
});

it('under "off", a backward delete from the caret in it removes it in one press', async () => {
const { editor, empty } = await emptyAfterChapterEnvironment("off");
await sutUpdate(editor, () => empty.selectEnd());

await act(async () => {
editor.dispatchCommand(DELETE_CHARACTER_COMMAND, true);
});

expect(paragraphsOf(editor)).toEqual(removed);
expectCaretInNextPara(editor);
});

it.each([
["guarded", 2],
["off", 1],
] as const)(
'under "%s", alone in its chapter, leaves a blank line with no marker and the caret in it',
async (structureProtectionMode, presses) => {
let empty: ParaNode;
const { editor } = await baseTestEnvironment(
() => {
empty = $createParaNode("s");
$getRoot().append(
$createImmutableChapterNode("1"),
empty.append($createGutterGlyphNode("s")),
$createImmutableChapterNode("2"),
);
},
<>
<StructureKeyboardPlugin structureProtectionMode={structureProtectionMode} />
<ParaMarkerSelectionPlugin structureProtectionMode={structureProtectionMode} />
</>,
);
await selectMarkerOf(editor, empty!);

for (let i = 0; i < presses; i++) await pressKey(editor, "Backspace");

editor.getEditorState().read(() => {
const [, blank] = $getRoot().getChildren();
expect($isImpliedParaNode(blank) && blank.getTextContent()).toBe("");
const selection = $getSelection();
if (!$isRangeSelection(selection)) throw new Error("expected a range selection");
expect(selection.focus.getNode().getTopLevelElementOrThrow().is(blank)).toBe(true);
});
},
);
});

describe("ParaMarkerSelectionPlugin — Delete on the selected marker of an empty paragraph", () => {
it.each([
["guarded", 2],
["off", 1],
] as const)(
'under "%s", joins it to the paragraph before and leaves the caret there',
async (structureProtectionMode, presses) => {
let first: ParaNode;
let empty: ParaNode;
const { editor } = await baseTestEnvironment(
() => {
first = $createParaNode("p");
empty = $createParaNode("s");
$getRoot().append(
first.append($createGutterGlyphNode("p"), $createTextNode("first")),
empty.append($createGutterGlyphNode("s")),
$createParaNode("q1").append($createGutterGlyphNode("q1"), $createTextNode("second")),
);
},
<>
<StructureKeyboardPlugin structureProtectionMode={structureProtectionMode} />
<ParaMarkerSelectionPlugin structureProtectionMode={structureProtectionMode} />
</>,
);
await selectMarkerOf(editor, empty!);

for (let i = 0; i < presses; i++) await pressKey(editor, "Delete");

expect(paragraphsOf(editor)).toEqual([
{ marker: "p", glyphs: 1, text: "first" },
{ marker: "q1", glyphs: 1, text: "second" },
]);
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) throw new Error("expected a range selection");
expect(selection.focus.getNode().getTopLevelElementOrThrow().getKey()).toBe(
first!.getKey(),
);
});
},
);
});

describe("ParaMarkerSelectionPlugin — a backward delete from the start of the paragraph after an empty one", () => {
it.each([
["guarded", 2],
["off", 1],
] as const)(
'under "%s", removes the empty paragraph and keeps this one\'s marker and the caret',
async (structureProtectionMode, presses) => {
let second: ParaNode;
let secondText: TextNode;
const { editor } = await baseTestEnvironment(
() => {
second = $createParaNode("q1");
secondText = $createTextNode("second");
$getRoot().append(
$createParaNode("p").append($createGutterGlyphNode("p"), $createTextNode("first")),
$createParaNode("s").append($createGutterGlyphNode("s")),
second.append($createGutterGlyphNode("q1"), secondText),
);
},
<>
<StructureKeyboardPlugin structureProtectionMode={structureProtectionMode} />
<ParaMarkerSelectionPlugin structureProtectionMode={structureProtectionMode} />
</>,
);
await sutUpdate(editor, () => secondText!.select(0, 0));
// Where the removal itself leaves the caret, read from the update that removes the paragraph:
// jsdom's DOM selection can move the editor's afterward, which a browser's would not.
let caretParaKey: string | undefined;
const unregister = editor.registerUpdateListener(({ editorState }) =>
editorState.read(() => {
const selection = $getSelection();
if (caretParaKey || $getRoot().getChildrenSize() > 2 || !$isRangeSelection(selection))
return;
caretParaKey = selection.focus.getNode().getTopLevelElementOrThrow().getKey();
}),
);

for (let i = 0; i < presses; i++)
await act(async () => {
editor.dispatchCommand(DELETE_CHARACTER_COMMAND, true);
});
unregister();

expect(paragraphsOf(editor)).toEqual([
{ marker: "p", glyphs: 1, text: "first" },
{ marker: "q1", glyphs: 1, text: "second" },
]);
expect(caretParaKey).toBe(second!.getKey());
},
);
});

describe("ParaMarkerSelectionPlugin — deletion without a Backspace/Delete keydown", () => {
const merged = [
{ marker: "p", glyphs: 1, text: "firstsecond" },
Expand Down
41 changes: 26 additions & 15 deletions libs/shared-react/src/plugins/usj/ParaMarkerSelectionPlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import {
} from "./ParaMarkerPrefixCursorGuardPlugin";
import { StructureProtectionMode } from "./structure-protection.model";
import {
$canMergeIntoPrevious,
$canDeletePara,
$deletePara,
$getEmptyParaBefore,
$getGutterParaWithCaretAtStart,
$mergeParaIntoPrevious,
$placeCaretAfterParaChild,
} from "./structureKeyboard.utils";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
Expand Down Expand Up @@ -100,10 +101,14 @@ const TARGETED_INPUT_TYPES = new Set([
* spellcheck replacement, a drop) acts there instead.
* - Removing the marker (Backspace/Delete, by key, command or input event, or a Backspace from the
* start of the text of a paragraph with no leading verse) merges its paragraph into the one
Comment thread
tjcouch-sil marked this conversation as resolved.
Resolved
* before (`$mergeParaIntoPrevious`) — a no-op with nothing before it, and refused under
* before, or removes it when it is empty and right after a chapter (`$deletePara`), leaving a
* blank line with no marker when it is the only one in its chapter — a no-op with nothing else
* before it. A Backspace from the start of the text whose paragraph has an
* empty one before it removes that empty one instead, so this paragraph's text never lands
* under the empty one's marker. Refused under
* `"protected"`, as `StructureKeyboardPlugin` refuses the same merge from a caret. Under
* `"guarded"`, it is `StructureKeyboardPlugin`'s two-step delete, as from a caret: the first
* press arms the merge and keeps the marker selected, the second merges.
* press arms the delete and keeps the marker selected, the second performs it.
* - Pointer and clipboard: a click elsewhere, or a cut, copy or paste after the browser's selection
* moved elsewhere, uses that selection; otherwise paste lands at the content start and cut, copy
* and drag-start are refused (the glyph is not content). A drop lands at its drop point, and is
Expand Down Expand Up @@ -154,18 +159,20 @@ export function ParaMarkerSelectionPlugin({
const $getActivePara = (): ParaNode | undefined =>
editor.isEditable() ? $getSelectedParaMarkerPara($getSelection()) : undefined;

// Removing the marker merges its paragraph into the previous one — the paragraph is the
// operand, never the glyph. Refused under "protected", as `StructureKeyboardPlugin` refuses
// the same merge from a caret, and a no-op with no paragraph before it. Callers claim the key
// either way: let through, rich-text would delete the selected glyph itself.
// Removing the marker merges its paragraph into the previous one, or removes it when it is
// empty and right after a chapter (blanking it when it is the only one in its chapter) — the
// paragraph is the operand, never the glyph. Refused
// under "protected", as `StructureKeyboardPlugin` refuses the same merge from a caret, and a
// no-op with no paragraph before it. Callers claim the key either way: let through, rich-text
// would delete the selected glyph itself.
const $removeMarker = (para: SomeParaNode) => {
if (structureProtectionModeRef.current !== "protected") $mergeParaIntoPrevious(para);
if (structureProtectionModeRef.current !== "protected") $deletePara(para);
};

// Under "guarded", a merge that would happen is left to `StructureKeyboardPlugin`'s two-step
// delete, which arms it on the first press and performs it on the second.
// Under "guarded", a merge or removal that would happen is left to `StructureKeyboardPlugin`'s
// two-step delete, which arms it on the first press and performs it on the second.
const $deferToTwoStepDelete = (para: SomeParaNode) =>
structureProtectionModeRef.current === "guarded" && $canMergeIntoPrevious(para);
structureProtectionModeRef.current === "guarded" && $canDeletePara(para);

/**
* Adopts the browser's selection when it has moved off the glyph — a right-click on other text,
Expand Down Expand Up @@ -276,8 +283,9 @@ export function ParaMarkerSelectionPlugin({
// Ctrl+H / Ctrl+D, or a programmatic dispatch) removes a selected marker. With no structure
// protection, so does a backward delete from the start of the text of a paragraph with no
// leading verse (a `\q2` line, say), which would otherwise delete the gutter glyph before the
// caret. Under "guarded" and "protected" that caret gets `StructureKeyboardPlugin`'s answer —
// arm, or refuse — the one a Backspace keydown there gets.
// caret — or, when the paragraph before is empty, it removes that empty one instead. Under
// "guarded" and "protected" that caret gets `StructureKeyboardPlugin`'s answer — arm, or
// refuse — the one a Backspace keydown there gets.
const $handleDeleteCharacter = (isBackward: boolean): boolean => {
if (!editor.isEditable()) return false;
const markerPara = $getActivePara();
Expand All @@ -289,7 +297,10 @@ export function ParaMarkerSelectionPlugin({
if (!isBackward || structureProtectionModeRef.current !== "off") return false;
const para = $getGutterParaWithCaretAtStart($getSelection());
if (!para) return false;
$mergeParaIntoPrevious(para);
// An empty paragraph before goes itself, rather than taking this one's text under its marker.
const emptyBefore = $getEmptyParaBefore(para);
if (emptyBefore) $deletePara(emptyBefore, "deleteForward");
else $deletePara(para);
return true;
};

Expand Down
Loading
Loading