Skip to content

Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.

fix: add backspace behavior test cases (#6463)

Kilu.He4d4e3bfb8a7f
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-convert-non-paragraph-block-to-paragraph.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-convert-non-paragraph-block-to-paragraph.snap.png
new file mode 100644
index 0000000000..07973fe583
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-convert-non-paragraph-block-to-paragraph.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-content-across-different-nesting-levels.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-content-across-different-nesting-levels.snap.png
new file mode 100644
index 0000000000..36a2c9024e
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-content-across-different-nesting-levels.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-content-across-multiple-blocks.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-content-across-multiple-blocks.snap.png
new file mode 100644
index 0000000000..ca11a83b5d
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-content-across-multiple-blocks.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-entire-nested-structure.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-entire-nested-structure.snap.png
new file mode 100644
index 0000000000..5ced87aa2f
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-entire-nested-structure.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-nested-content-within-a-toggle-list.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-nested-content-within-a-toggle-list.snap.png
new file mode 100644
index 0000000000..0f9330e3e4
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-delete-nested-content-within-a-toggle-list.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-handle-backspace-at-start-of-document.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-handle-backspace-at-start-of-document.snap.png
new file mode 100644
index 0000000000..d0b6b16b0a
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-handle-backspace-at-start-of-document.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-handle-deletion-of-deeply-nested-content.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-handle-deletion-of-deeply-nested-content.snap.png
new file mode 100644
index 0000000000..fe96b4812d
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-handle-deletion-of-deeply-nested-content.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-lift-nested-paragraph.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-lift-nested-paragraph.snap.png
new file mode 100644
index 0000000000..3da0725a90
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-lift-nested-paragraph.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-maintain-structure-when-deleting-partial-content.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-maintain-structure-when-deleting-partial-content.snap.png
new file mode 100644
index 0000000000..63936e47bd
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-maintain-structure-when-deleting-partial-content.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-merge-nested-toggle-list.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-merge-nested-toggle-list.snap.png
new file mode 100644
index 0000000000..1b9b0cae9c
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-merge-nested-toggle-list.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-merge-paragraphs.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-merge-paragraphs.snap.png
new file mode 100644
index 0000000000..3e0cdf2644
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/BackspaceKeyBehavior/should-merge-paragraphs.snap.png differ
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts b/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts
index c452263808..d382657176 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts
@@ -1,10 +1,14 @@
import { YjsEditor } from '@/application/slate-yjs/plugins/withYjs';
import {
- dataStringTOJson, executeOperations,
- getBlock,
- handleCollapsedBreak, handleRangeBreak,
+ dataStringTOJson,
+ executeOperations,
+ getBlock, getBlockEntry, getSelectionOrThrow, getSharedRoot,
+ handleCollapsedBreak, handleDeleteEntireDocument, handleMergeBlockBackward, handleNonParagraphBlockBackspace,
+ handleRangeBreak, handleShouldLiftBlockBackspace,
+ handleMergeBlockForward,
+ removeRange,
} from '@/application/slate-yjs/utils/yjsOperations';
-import { BlockData, InlineBlockType, Mention, MentionType, YjsEditorKey } from '@/application/types';
+import { BlockData, BlockType, InlineBlockType, Mention, MentionType, YjsEditorKey } from '@/application/types';
import { FormulaNode } from '@/components/editor/editor.type';
import { renderDate } from '@/utils/time';
import { BaseRange, Editor, Element, Node, NodeEntry, Range, Text, Transforms } from 'slate';
@@ -93,25 +97,75 @@ export const CustomEditor = {
},
// Insert break line at the specified path
insertBreak (editor: YjsEditor, at?: BaseRange) {
- const sharedRoot = editor.sharedRoot;
+ const sharedRoot = getSharedRoot(editor);
+ const newAt = getSelectionOrThrow(editor, at);
- if (!sharedRoot || !sharedRoot.doc) {
- throw new Error('Shared root not found');
+ const isCollapsed = Range.isCollapsed(newAt);
+
+ if (isCollapsed) {
+ handleCollapsedBreak(editor, sharedRoot, newAt);
+ } else {
+ handleRangeBreak(editor, sharedRoot, newAt);
}
- const newAt = at || editor.selection;
+ },
+
+ deleteBlockBackward (editor: YjsEditor, at?: BaseRange) {
+ const sharedRoot = getSharedRoot(editor);
+ const newAt = getSelectionOrThrow(editor, at);
- if (!newAt) {
- throw new Error('Selection not found');
+ const isCollapsed = Range.isCollapsed(newAt);
+
+ if (isCollapsed) {
+ const point = newAt.anchor;
+
+ const blockEntry = getBlockEntry(editor, point);
+
+ const [node, path] = blockEntry as NodeEntry<Element>;
+ const block = getBlock(node.blockId as string, sharedRoot);
+ const blockType = block.get(YjsEditorKey.block_type) as BlockType;
+
+ if (blockType !== BlockType.Paragraph) {
+ handleNonParagraphBlockBackspace(sharedRoot, block);
+ return;
+ }
+
+ if (path.length > 1 && handleShouldLiftBlockBackspace(editor, sharedRoot, block, point)) {
+ return;
+ }
+
+ handleMergeBlockBackward(editor, node, point);
+ } else {
+ Transforms.collapse(editor, { edge: 'start' });
+ removeRange(editor, sharedRoot, newAt);
}
+ },
+
+ deleteBlockForward (editor: YjsEditor, at?: BaseRange) {
+ const sharedRoot = getSharedRoot(editor);
+ const newAt = getSelectionOrThrow(editor, at);
const isCollapsed = Range.isCollapsed(newAt);
if (isCollapsed) {
- handleCollapsedBreak(editor, sharedRoot, newAt);
+ const point = newAt.anchor;
+
+ const blockEntry = getBlockEntry(editor, point);
+
+ const [node] = blockEntry as NodeEntry<Element>;
+
+ handleMergeBlockForward(editor, node, point);
} else {
- handleRangeBreak(editor, sharedRoot, newAt);
+ Transforms.collapse(editor, { edge: 'start' });
+ removeRange(editor, sharedRoot, newAt);
}
+ },
+
+ deleteEntireDocument (editor: YjsEditor) {
+ handleDeleteEntireDocument(editor);
+ },
+ removeRange (editor: YjsEditor, at: BaseRange) {
+ removeRange(editor, getSharedRoot(editor), at);
},
};
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts
index f36dfa17e9..5c92deb032 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts
@@ -2,6 +2,7 @@ import { getDocument } from '@/application/slate-yjs/utils/yjsOperations';
import { relativeRangeToSlateRange, slateRangeToRelativeRange } from '@/application/slate-yjs/utils/positions';
import { CollabOrigin } from '@/application/types';
import { Editor, Transforms } from 'slate';
+import { ReactEditor } from 'slate-react';
import * as Y from 'yjs';
import { YjsEditor } from './withYjs';
import { HistoryStackItem, RelativeRange } from '../types';
@@ -44,16 +45,25 @@ export function withYHistory<T extends YjsEditor> (
e.undoManager = new Y.UndoManager(getDocument(e.sharedRoot), {
trackedOrigins: new Set([CollabOrigin.Local, null]),
+ captureTimeout: 200,
});
const { onChange } = e;
e.onChange = () => {
onChange();
- LAST_SELECTION.set(
- e,
- e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection),
- );
+ const selection = e.selection;
+
+ try {
+ const storeSelection = selection && slateRangeToRelativeRange(e.sharedRoot, e, selection);
+
+ LAST_SELECTION.set(
+ e,
+ storeSelection,
+ );
+ } catch (e) {
+ console.error(e);
+ }
};
const handleStackItemAdded = ({
@@ -62,12 +72,16 @@ export function withYHistory<T extends YjsEditor> (
stackItem: HistoryStackItem;
type: 'redo' | 'undo';
}) => {
- stackItem.meta.set(
- 'selection',
- e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection),
- );
-
- stackItem.meta.set('selectionBefore', LAST_SELECTION.get(e));
+ try {
+ stackItem.meta.set(
+ 'selection',
+ e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection),
+ );
+
+ stackItem.meta.set('selectionBefore', LAST_SELECTION.get(e));
+ } catch (e) {
+ // console.error(e);
+ }
};
@@ -77,7 +91,6 @@ export function withYHistory<T extends YjsEditor> (
stackItem: HistoryStackItem;
type: 'redo' | 'undo';
}) => {
-
const relativeSelection = stackItem.meta.get(
'selectionBefore',
) as RelativeRange | null;
@@ -92,7 +105,7 @@ export function withYHistory<T extends YjsEditor> (
relativeSelection,
);
- if (!selection) {
+ if (!selection || !ReactEditor.hasRange(editor, selection)) {
const startPoint = Editor.start(e, [0]);
Transforms.select(e, startPoint);
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withYjs.ts b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withYjs.ts
index 6ff29889ae..2484fb90bd 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withYjs.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withYjs.ts
@@ -1,6 +1,7 @@
import { CollabOrigin, YjsEditorKey, YSharedRoot } from '@/application/types';
import { applyToYjs } from '@/application/slate-yjs/utils/applyToYjs';
-import { Editor, Operation, Descendant } from 'slate';
+import { Editor, Operation, Descendant, Transforms } from 'slate';
+import { ReactEditor } from 'slate-react';
import Y, { YEvent, Transaction } from 'yjs';
import { yDocToSlateContent } from '@/application/slate-yjs/utils/convert';
@@ -72,9 +73,10 @@ export function withYjs<T extends Editor> (
opts?: {
localOrigin: CollabOrigin;
readSummary?: boolean;
+ onContentChange?: (content: Descendant[]) => void;
},
): T & YjsEditor {
- const { localOrigin = CollabOrigin.Local, readSummary } = opts ?? {};
+ const { localOrigin = CollabOrigin.Local, readSummary, onContentChange } = opts ?? {};
const e = editor as T & YjsEditor;
const { apply, onChange } = e;
@@ -89,12 +91,25 @@ export function withYjs<T extends Editor> (
return;
}
+ const selection = e.selection;
+
if (readSummary) {
e.children = content.children.slice(0, 10);
} else {
e.children = content.children;
}
+ if (selection && !ReactEditor.hasRange(editor, selection)) {
+ try {
+ Transforms.select(e, Editor.start(editor, [0]));
+
+ } catch (e) {
+ console.error(e);
+ editor.deselect();
+ }
+ }
+
+ onContentChange?.(content.children);
console.log('===initializeDocumentContent', e.children);
Editor.normalize(e, { force: true });
};
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts
index f534dcd9bd..8cb966b931 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts
@@ -83,6 +83,12 @@ export function yDataToSlateContent ({
try {
const slateDelta = delta.flatMap(deltaInsertToSlateNode);
+ if (slateDelta.length === 0) {
+ slateDelta.push({
+ text: '',
+ });
+ }
+
const textNode: Element = {
textId,
type: YjsEditorKey.text,
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts
index 3e2617766e..f6cc92c897 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts
@@ -39,6 +39,10 @@ export function slatePointToRelativePosition (
point: Y.RelativePosition;
entry: NodeEntry<Element>;
} {
+ if (!Editor.hasPath(editor, point.path)) {
+ throw new Error('Point is not in the editor');
+ }
+
const [entry] = editor.nodes({
at: point,
match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.textId !== undefined,
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts
index 25ad284c51..5394716645 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts
@@ -13,7 +13,7 @@ import {
import { nanoid } from 'nanoid';
import Delta, { Op } from 'quill-delta';
-import { BaseRange, Editor, Element, Node, NodeEntry, Path, Range, Transforms } from 'slate';
+import { BaseRange, Editor, Element, Node, NodeEntry, Path, Point, Range, Transforms } from 'slate';
import * as Y from 'yjs';
import { YjsEditor } from '../plugins/withYjs';
import { slatePointToRelativePosition } from './positions';
@@ -129,13 +129,14 @@ export function handleCollapsedBreak (editor: YjsEditor, sharedRoot: YSharedRoot
export function removeRange (editor: YjsEditor, sharedRoot: YSharedRoot, range: Range) {
const { startBlock, endBlock, middleBlocks, startRange, endRange } = getAffectedBlocks(editor, range);
const operations: (() => void)[] = [];
- const isSameBlock = Path.compare(startBlock[1], endBlock[1]) === 0;
+ const isSameBlock = startBlock[0].blockId === endBlock[0].blockId;
operations.push(() => {
deleteSlateRangeInBlock(sharedRoot, editor, startBlock[0], startRange);
if (!isSameBlock) {
deleteSlateRangeInBlock(sharedRoot, editor, endBlock[0], endRange);
mergeBlocks(sharedRoot, endBlock[0], startBlock[0]);
+
middleBlocks.forEach((block) => {
deleteBlock(sharedRoot, block[0].blockId as string);
});
@@ -174,14 +175,9 @@ export function handleRangeBreak (editor: YjsEditor, sharedRoot: YSharedRoot, ra
handleCollapsedBreak(editor, sharedRoot, selection);
}
-export function turnToBlock<T extends BlockData> (sharedRoot: YSharedRoot, sourceBlock: YBlock, type: BlockType, data: T) {
- const newBlock = createBlock(sharedRoot, {
- ty: type,
- data,
- });
-
+export function copyBlockText (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {
const sourceTextId = sourceBlock.get(YjsEditorKey.block_external_id);
- const targetTextId = newBlock.get(YjsEditorKey.block_external_id);
+ const targetTextId = targetBlock.get(YjsEditorKey.block_external_id);
if (!sourceTextId || !targetTextId) {
throw new Error('Text id not found');
@@ -191,6 +187,15 @@ export function turnToBlock<T extends BlockData> (sharedRoot: YSharedRoot, sourc
const targetText = getText(targetTextId, sharedRoot);
targetText.applyDelta(sourceText.toDelta());
+}
+
+export function turnToBlock<T extends BlockData> (sharedRoot: YSharedRoot, sourceBlock: YBlock, type: BlockType, data: T) {
+ const newBlock = createBlock(sharedRoot, {
+ ty: type,
+ data,
+ });
+
+ copyBlockText(sharedRoot, sourceBlock, newBlock);
transferChildren(sharedRoot, sourceBlock, newBlock);
@@ -330,7 +335,7 @@ export function getAffectedBlocks (editor: YjsEditor, range: Range): {
const middleBlocks: NodeEntry<Element>[] = [];
- const isSameBlock = Path.compare(startBlock[1], endBlock[1]) === 0;
+ const isSameBlock = startBlock[0].blockId === endBlock[0].blockId;
if (!isSameBlock) {
for (const entry of Editor.nodes(editor, {
@@ -349,6 +354,7 @@ export function getAffectedBlocks (editor: YjsEditor, range: Range): {
endRange = Editor.range(editor, Editor.start(editor, endBlock[1]), end);
}
+ console.log('startBlock', startBlock, endBlock, middleBlocks, startRange, endRange);
return { startBlock, endBlock, middleBlocks, startRange, endRange };
}
@@ -357,9 +363,12 @@ function getTextIdFromSlateNode (node: Element) {
}
export function deleteSlateRangeInBlock (sharedRoot: YSharedRoot, editor: Editor, block: Element, range: BaseRange) {
- const relativeOffset = slatePointToRelativePosition(sharedRoot, editor, range.anchor);
+ const [start, end] = Editor.edges(editor, range);
+
+ console.log('deleteSlateRangeInBlock', start, end);
+ const relativeOffset = slatePointToRelativePosition(sharedRoot, editor, start);
const startPos = Y.createAbsolutePositionFromRelativePosition(relativeOffset.point, assertDocExists(sharedRoot));
- const endRelativeOffset = slatePointToRelativePosition(sharedRoot, editor, range.focus);
+ const endRelativeOffset = slatePointToRelativePosition(sharedRoot, editor, end);
const endPos = Y.createAbsolutePositionFromRelativePosition(endRelativeOffset.point, assertDocExists(sharedRoot));
if (!startPos || !endPos) {
@@ -383,7 +392,10 @@ export function deleteRangeInBlock (
const yText = getText(textId, sharedRoot);
+ console.log('deleteRangeInBlock', start, end - start);
yText.delete(start, end - start);
+
+ console.log('deleteRangeInBlock', yText.toJSON());
}
export function mergeBlocks (
@@ -416,7 +428,6 @@ export function mergeBlocks (
mergeBlockChildren(sharedRoot, getBlock(sourceBlockId, sharedRoot), getBlock(targetBlockId, sharedRoot));
deleteBlock(sharedRoot, sourceBlock.blockId as string);
-
}
function mergeBlockChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {
@@ -430,7 +441,7 @@ function mergeBlockChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targe
BlockType.BulletedListBlock,
BlockType.NumberedListBlock,
].includes(targetType)) {
- transferChildren(sharedRoot, sourceBlock, targetBlock);
+ transferChildren(sharedRoot, sourceBlock, targetBlock, 0);
} else {
liftChildren(sharedRoot, sourceBlock, targetBlock);
}
@@ -595,14 +606,14 @@ function ensureBlockHasChildren (sharedRoot: YSharedRoot, block: YBlock) {
return getChildrenArray(block.get(YjsEditorKey.block_children), sharedRoot);
}
-export function transferChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {
+export function transferChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock, index?: number) {
const sourceChildrenArray = getChildrenArray(sourceBlock.get(YjsEditorKey.block_children), sharedRoot);
const targetChildrenArray = ensureBlockHasChildren(sharedRoot, targetBlock);
if (!sourceChildrenArray || !targetChildrenArray) return;
if (sourceChildrenArray.length > 0) {
- deepCopyChildren(sharedRoot, sourceChildrenArray, targetChildrenArray, targetBlock.get(YjsEditorKey.block_id));
+ deepCopyChildren(sharedRoot, sourceChildrenArray, targetChildrenArray, targetBlock.get(YjsEditorKey.block_id), index);
sourceChildrenArray.toArray().forEach((id) => {
deleteBlock(sharedRoot, id);
});
@@ -633,6 +644,7 @@ function deepCopyChildren (sharedRoot: YSharedRoot, sourceArray: Y.Array<string>
const sourceArraySorted = index === undefined ? sourceArray.toArray() : sourceArray.toArray().reverse();
+ console.log('deepCopyChildren', index);
sourceArraySorted.forEach((childId) => {
const sourceChild = getBlock(childId, sharedRoot);
@@ -663,4 +675,314 @@ function deepCopyChildren (sharedRoot: YSharedRoot, sourceArray: Y.Array<string>
updateBlockParent(sharedRoot, newChild, getBlock(targetBlockId, sharedRoot), targetIndex);
}
});
+}
+
+export function isAtBlockStart (editor: Editor, point: Point) {
+ const entry = Editor.above(editor, {
+ at: point,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.textId !== undefined,
+ });
+
+ if (!entry) return false;
+
+ const [, path] = entry;
+ const start = Editor.start(editor, path);
+
+ return Point.equals(point, start);
+}
+
+export function isAtBlockEnd (editor: Editor, point: Point) {
+ const entry = Editor.above(editor, {
+ at: point,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.textId !== undefined,
+ });
+
+ if (!entry) return false;
+
+ const [, path] = entry;
+ const end = Editor.end(editor, path);
+
+ return Point.equals(point, end);
+}
+
+export function getSharedRoot (editor: YjsEditor) {
+ if (!editor.sharedRoot || !editor.sharedRoot.doc) {
+ throw new Error('Shared root not found');
+ }
+
+ return editor.sharedRoot;
+}
+
+export function getSelectionOrThrow (editor: YjsEditor, at?: BaseRange) {
+ const newAt = at || editor.selection;
+
+ if (!newAt) {
+ throw new Error('Selection not found');
+ }
+
+ return newAt;
+}
+
+export function getBlockEntry (editor: YjsEditor, point: Point) {
+ const blockEntry = editor.above({
+ at: point,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,
+ });
+
+ if (!blockEntry) {
+ throw new Error('Block not found');
+ }
+
+ return blockEntry as NodeEntry<Element>;
+}
+
+export function handleNonParagraphBlockBackspace (sharedRoot: YSharedRoot, block: YBlock) {
+ const operations: (() => void)[] = [];
+
+ operations.push(() => {
+ turnToBlock(sharedRoot, block, BlockType.Paragraph, {});
+ });
+ executeOperations(sharedRoot, operations, 'turnToBlock');
+}
+
+export function handleShouldLiftBlockBackspace (editor: YjsEditor, sharedRoot: YSharedRoot, block: YBlock, point: Point) {
+ const operations: (() => void)[] = [];
+ const parent = getBlock(block.get(YjsEditorKey.block_parent), sharedRoot);
+ const parentChildren = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);
+ const index = parentChildren.toArray().findIndex((id) => id === block.get(YjsEditorKey.block_id));
+
+ const hasNextSibling = index < parentChildren.length - 1;
+ const hasChildren = getChildrenArray(block.get(YjsEditorKey.block_children), sharedRoot).length > 0;
+
+ if (!hasChildren && !hasNextSibling) {
+ operations.push(() => {
+ liftEditorNode(editor, sharedRoot, block, point);
+ });
+ executeOperations(sharedRoot, operations, 'deleteBlockBackward');
+ return true;
+ }
+
+ return false;
+}
+
+export function handleMergeBlockBackward (editor: YjsEditor, node: Element, point: Point) {
+ const operations: (() => void)[] = [];
+ const sharedRoot = getSharedRoot(editor);
+
+ try {
+ const prevPoint = Editor.before(editor, point);
+
+ if (!prevPoint) {
+ throw new Error('prevPoint not found');
+ }
+
+ const target = editor.above({
+ at: prevPoint,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,
+ });
+
+ if (!target) {
+ throw new Error('target not found');
+ }
+
+ const [targetNode] = target as NodeEntry<Element>;
+
+ operations.push(() => {
+ Transforms.move(editor, { distance: 1, reverse: true });
+ mergeBlocks(sharedRoot, node, targetNode);
+ });
+ } catch (e) {
+ // at the beginning of the document
+ console.info('at the beginning of the document');
+ }
+
+ executeOperations(sharedRoot, operations, 'deleteBlockBackward');
+}
+
+export function handleMergeBlockForward (editor: YjsEditor, node: Element, point: Point) {
+ const operations: (() => void)[] = [];
+ const sharedRoot = getSharedRoot(editor);
+
+ try {
+ const nextPoint = Editor.after(editor, point);
+
+ if (!nextPoint) {
+ throw new Error('nextPoint not found');
+ }
+
+ const source = editor.above({
+ at: nextPoint,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,
+ });
+
+ if (!source) {
+ throw new Error('source not found');
+ }
+
+ const [sourceNode] = source as NodeEntry<Element>;
+
+ operations.push(() => {
+ mergeBlocks(sharedRoot, sourceNode, node);
+ });
+ } catch (e) {
+ // at the end of the document
+ console.info('at the end of the document');
+ }
+
+ executeOperations(sharedRoot, operations, 'deleteBlockForward');
+}
+
+export function liftEditorNode (editor: YjsEditor, sharedRoot: YSharedRoot, block: YBlock, point: Point) {
+ // Find the path of the current block
+ const [, path] = getBlockEntry(editor, point);
+ const parentPath = path.slice(0, -1);
+ const level = path.length;
+
+ if (level < 2) {
+ return;
+ }
+
+ // This is to prevent errors caused by invalid paths when the original node is deleted during the lift process
+ Transforms.select(editor, Editor.start(editor, parentPath));
+
+ liftBlock(sharedRoot, block);
+
+ // Calculate the position where the new block should be after the lift operation
+ const nextPath = Path.next(parentPath);
+
+ // After the lift operation is complete, move the cursor to the start of the newly lifted block
+ Transforms.select(editor, Editor.start(editor, nextPath));
+}
+
+export function liftBlock (sharedRoot: YSharedRoot, block: YBlock) {
+ const parentId = block.get(YjsEditorKey.block_parent);
+ const parent = getBlock(parentId, sharedRoot);
+
+ if (!parent) {
+ console.warn('Cannot lift block: parent not found');
+ return;
+ }
+
+ const grandParentId = parent.get(YjsEditorKey.block_parent);
+ const grandParent = getBlock(grandParentId, sharedRoot);
+
+ if (!grandParent) {
+ console.warn('Cannot lift block: grandparent not found');
+ return;
+ }
+
+ const grandParentChildrenArray = getChildrenArray(grandParent.get(YjsEditorKey.block_children), sharedRoot);
+
+ if (!grandParentChildrenArray) {
+ console.warn('Cannot lift block: grandparent children array not found');
+ return;
+ }
+
+ const parentIndex = grandParentChildrenArray.toArray().findIndex((id) => id === parentId);
+
+ if (parentIndex === -1) {
+ console.warn('Cannot lift block: parent not found in grandparent\'s children');
+ return;
+ }
+
+ moveNode(sharedRoot, block, grandParent, parentIndex + 1);
+}
+
+export function moveNode (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetParent: YBlock, targetIndex: number) {
+ const copiedBlockId = deepCopyBlock(sharedRoot, sourceBlock);
+
+ if (!copiedBlockId) {
+ console.warn('Failed to copy block');
+ return;
+ }
+
+ const copiedBlock = getBlock(copiedBlockId, sharedRoot);
+
+ if (!copiedBlock) {
+ console.warn('Copied block not found');
+ return;
+ }
+
+ updateBlockParent(sharedRoot, copiedBlock, targetParent, targetIndex);
+
+ deleteBlock(sharedRoot, sourceBlock.get(YjsEditorKey.block_id));
+}
+
+export function deepCopyBlock (sharedRoot: YSharedRoot, sourceBlock: YBlock): string | null {
+ try {
+ const newBlock = createBlock(sharedRoot, {
+ ty: sourceBlock.get(YjsEditorKey.block_type),
+ data: dataStringTOJson(sourceBlock.get(YjsEditorKey.block_data)),
+ });
+
+ copyBlockText(sharedRoot, sourceBlock, newBlock);
+
+ const sourceChildrenArray = getChildrenArray(sourceBlock.get(YjsEditorKey.block_children), sharedRoot);
+ const targetChildrenArray = getChildrenArray(newBlock.get(YjsEditorKey.block_children), sharedRoot);
+
+ if (sourceChildrenArray && targetChildrenArray) {
+ deepCopyChildren(sharedRoot, sourceChildrenArray, targetChildrenArray, newBlock.get(YjsEditorKey.block_id));
+ }
+
+ return newBlock.get(YjsEditorKey.block_id);
+ } catch (error) {
+ console.error('Error in deepCopyBlock:', error);
+ return null;
+ }
+}
+
+export function isEntireDocumentSelected (editor: YjsEditor) {
+ const selection = getSelectionOrThrow(editor);
+ const [start, end] = Editor.edges(editor, selection);
+ const startEdge = Editor.start(editor, []);
+ const endEdge = Editor.end(editor, []);
+
+ return Point.equals(start, startEdge) && Point.equals(end, endEdge);
+}
+
+export function getBlocks (sharedRoot: YSharedRoot) {
+ const document = getDocument(sharedRoot);
+
+ return document.get(YjsEditorKey.blocks) as YBlocks;
+}
+
+export function getPageId (sharedRoot: YSharedRoot) {
+ const document = getDocument(sharedRoot);
+ const pageId = document.get(YjsEditorKey.page_id) as string;
+
+ return pageId;
+}
+
+export function appendEmptyParagraph (sharedRoot: YSharedRoot): string {
+ const pageId = getPageId(sharedRoot);
+ const page = getBlock(pageId, sharedRoot);
+ const newBlock = createBlock(sharedRoot, {
+ ty: BlockType.Paragraph,
+ data: {},
+ });
+
+ updateBlockParent(sharedRoot, newBlock, page, 0);
+
+ return newBlock.get(YjsEditorKey.block_id);
+}
+
+export function handleDeleteEntireDocument (editor: YjsEditor) {
+ const sharedRoot = getSharedRoot(editor);
+ const operations = [() => {
+ editor.deselect();
+
+ const blocks = getBlocks(sharedRoot);
+ const pageId = getPageId(sharedRoot);
+ const blockId = appendEmptyParagraph(sharedRoot);
+
+ blocks.forEach((_, k) => {
+ if (k !== pageId && k !== blockId) {
+ deleteBlock(sharedRoot, k);
+ }
+ });
+
+ }];
+
+ executeOperations(sharedRoot, operations, 'deleteEntireDocument');
+ Transforms.select(editor, Editor.start(editor, [0]));
}
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx b/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx
index b0df2b64f9..92f2e15373 100644
--- a/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx
@@ -4,7 +4,7 @@ import { withYjs, YjsEditor } from '@/application/slate-yjs/plugins/withYjs';
import EditorEditable from '@/components/editor/Editable';
import { useEditorContext } from '@/components/editor/EditorContext';
import { withPlugins } from '@/components/editor/plugins';
-import React, { useEffect, useMemo, useState } from 'react';
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { createEditor, Descendant } from 'slate';
import { Slate, withReact } from 'slate-react';
import * as Y from 'yjs';
@@ -15,6 +15,10 @@ function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {
const context = useEditorContext();
const readSummary = context.readSummary;
const localOrigin = CollabOrigin.Local;
+ const [, setClock] = useState(0);
+ const onContentChange = useCallback(() => {
+ setClock((prev) => prev + 1);
+ }, []);
const editor = useMemo(
() =>
doc &&
@@ -24,11 +28,12 @@ function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {
withYjs(createEditor(), doc, {
localOrigin,
readSummary,
+ onContentChange,
}),
),
),
) as YjsEditor),
- [readSummary, doc, localOrigin],
+ [onContentChange, readSummary, doc, localOrigin],
);
const [, setIsConnected] = useState(false);
@@ -45,7 +50,7 @@ function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {
return (
<Slate editor={editor} initialValue={defaultInitialValue}>
- <EditorEditable editor={editor} />
+ <EditorEditable />
</Slate>
);
}
diff --git a/frontend/appflowy_web_app/src/components/editor/Editable.tsx b/frontend/appflowy_web_app/src/components/editor/Editable.tsx
index 0173bced74..a3d2c35ee9 100644
--- a/frontend/appflowy_web_app/src/components/editor/Editable.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/Editable.tsx
@@ -1,16 +1,19 @@
+import { YjsEditor } from '@/application/slate-yjs';
+import { CustomEditor } from '@/application/slate-yjs/command';
import { useDecorate } from '@/components/editor/components/blocks/code/useDecorate';
import { Leaf } from '@/components/editor/components/leaf';
import { useEditorContext } from '@/components/editor/EditorContext';
import React, { Suspense, useCallback } from 'react';
-import { NodeEntry } from 'slate';
-import { Editable, ReactEditor, RenderElementProps } from 'slate-react';
+import { NodeEntry, Range } from 'slate';
+import { Editable, RenderElementProps, useSlate } from 'slate-react';
import { Element } from './components/element';
import { Skeleton } from '@mui/material';
-const EditorEditable = ({ editor }: { editor: ReactEditor }) => {
+const EditorEditable = () => {
const { readOnly } = useEditorContext();
- const codeDecorate = useDecorate(editor);
+ const editor = useSlate();
+ const codeDecorate = useDecorate(editor);
const renderElement = useCallback((props: RenderElementProps) => {
return (
<Suspense fallback={<Skeleton width={'100%'} height={24} />}>
@@ -18,6 +21,14 @@ const EditorEditable = ({ editor }: { editor: ReactEditor }) => {
</Suspense>
);
}, []);
+ const onCompositionStart = useCallback(() => {
+ const { selection } = editor;
+
+ if (!selection) return;
+ if (Range.isExpanded(selection)) {
+ CustomEditor.deleteBlockBackward(editor as YjsEditor, selection);
+ }
+ }, [editor]);
return (
<>
@@ -35,6 +46,7 @@ const EditorEditable = ({ editor }: { editor: ReactEditor }) => {
spellCheck={false}
autoCorrect={'off'}
autoComplete={'off'}
+ onCompositionStart={onCompositionStart}
/>
</>
);
diff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/BackspaceKeyBehavior.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/BackspaceKeyBehavior.cy.tsx
new file mode 100644
index 0000000000..f7cc3942d0
--- /dev/null
+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/BackspaceKeyBehavior.cy.tsx
@@ -0,0 +1,353 @@
+import { mountEditor, moveToLineStart } from '@/components/editor/__tests__/mount';
+import { DocumentTest, FromBlockJSON } from 'cypress/support/document';
+
+describe('Backspace key behavior', () => {
+ beforeEach(() => {
+ cy.viewport(1280, 720);
+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });
+ });
+ let documentTest: DocumentTest;
+ const initialData: FromBlockJSON[] = [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nested paragraph 1' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Deeply nested paragraph' }],
+ children: [],
+ }],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Nested toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Deeply nested paragraph' }],
+ children: [],
+ },
+ ],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nested paragraph 2.' }],
+ children: [],
+ },
+ ],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ];
+
+ const initializeEditor = (data: FromBlockJSON[]) => {
+ documentTest = new DocumentTest();
+ documentTest.fromJSON(data);
+ mountEditor({ readOnly: false, doc: documentTest.doc });
+ cy.get('[role="textbox"]').should('exist');
+ };
+
+ const assertJSON = (expectedJSON: FromBlockJSON[]) => {
+ cy.wrap(null).then(() => {
+ const finalJSON = documentTest.toJSON();
+
+ expect(finalJSON).to.deep.equal(expectedJSON);
+ });
+ };
+
+ describe('backspace key behavior with range selections', () => {
+
+ beforeEach(() => {
+ initializeEditor(initialData);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ });
+ it('should delete entire nested structure', () => {
+ cy.selectMultipleText(['Outer paragraph', 'Final outer paragraph']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{backspace}');
+
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-delete-entire-nested-structure');
+ });
+
+ it('should delete content across multiple blocks', () => {
+ cy.selectMultipleText(['Outer paragraph', 'Toggle list']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: initialData[1].children,
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-delete-content-across-multiple-blocks');
+ });
+
+ it('should delete nested content within a toggle list', () => {
+ cy.selectMultipleText(['Nested paragraph 1', 'Nested paragraph 2']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ initialData[0],
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: '.' }],
+ children: [],
+ },
+
+ ],
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-delete-nested-content-within-a-toggle-list');
+ });
+
+ it('should delete content across different nesting levels', () => {
+ cy.selectMultipleText(['Toggle list', 'Deeply nested']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: ' paragraph' }],
+ children: initialData[1].children.slice(1),
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-delete-content-across-different-nesting-levels');
+ });
+
+ it('should handle deletion of deeply nested content', () => {
+ cy.selectMultipleText(['ested paragraph 1', 'Deeply nested paragraph']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'N' }],
+ children: [],
+ }, ...initialData[1].children.slice(1)],
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-handle-deletion-of-deeply-nested-content');
+ });
+
+ it('should maintain structure when deleting partial content', () => {
+ cy.selectMultipleText(['paragraph', 'Toggle']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer list' }],
+ children: initialData[1].children,
+ },
+
+ initialData[2],
+ ]);
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-maintain-structure-when-deleting-partial-content');
+ });
+ });
+
+ describe('backspace key behavior with cursor selections', () => {
+ beforeEach(() => {
+ initializeEditor(initialData);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ });
+
+ it('should convert non-paragraph block to paragraph on backspace at start', () => {
+ moveToLineStart(1); // Move to start of toggle list
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: initialData[1].children,
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-convert-non-paragraph-block-to-paragraph');
+ });
+
+ it('should merge paragraphs when backspace at start of paragraph', () => {
+ moveToLineStart(2); // Move to start of "Nested paragraph 1"
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ initialData[0],
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle listNested paragraph 1' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Deeply nested paragraph' }],
+ children: [],
+ }, ...initialData[1].children.slice(1),
+ ],
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-merge-paragraphs');
+ });
+
+ it('should lift nested paragraph when backspace at start', () => {
+ moveToLineStart(3); // Move to "Deeply nested paragraph"
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ initialData[0],
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ ...initialData[1].children[0],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Deeply nested paragraph' }],
+ children: [],
+ },
+ ...initialData[1].children.slice(1),
+ ],
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-lift-nested-paragraph');
+ });
+
+ it('should merge nested toggle list when backspace at start', () => {
+ moveToLineStart(4); // Move to "Nested toggle list"
+ cy.get('@editor').type('{backspace}');
+ assertJSON([
+ initialData[0],
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ initialData[1].children[0],
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nested toggle list' }],
+ children: initialData[1].children[1].children,
+ },
+ initialData[1].children[2],
+ ],
+ },
+ initialData[2],
+ ]);
+
+ // Optional: Add visual regression test
+
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-merge-nested-toggle-list');
+ });
+
+ it('should handle backspace at start of document', () => {
+ moveToLineStart(0);
+ cy.get('@editor').type('{backspace}');
+ assertJSON(initialData);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/BackspaceKeyBehavior/should-handle-backspace-at-start-of-document');
+ });
+ });
+});
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx
index b8392189ea..51b3bf95cd 100644
--- a/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx
@@ -1,4 +1,4 @@
-import { mountEditor } from '@/components/editor/__tests__/mount';
+import { mountEditor, moveAndEnter, moveToLineStart } from '@/components/editor/__tests__/mount';
import { DocumentTest, FromBlockJSON } from 'cypress/support/document';
describe('Enter key behavior', () => {
@@ -15,36 +15,6 @@ describe('Enter key behavior', () => {
cy.get('[role="textbox"]').should('exist');
};
- const moveToLineStart = (lineIndex: number) => {
- const selector = '[role="textbox"]';
-
- cy.get(selector).as('targetBlock');
-
- if (lineIndex === 0) {
- cy.get('@targetBlock').type('{movetostart}').wait(50);
- } else {
- cy.get('@targetBlock').type('{movetostart}').type('{downarrow}'.repeat(lineIndex))
- .wait(50);
- }
- };
-
- const moveAndEnter = (lineIndex: number, moveCount: number) => {
- moveToLineStart(lineIndex);
- // Move the cursor with right arrow key and batch the movement
- const batchSize = 5;
- const batches = Math.ceil(moveCount / batchSize);
-
- for (let i = 0; i < batches; i++) {
- const remainingMoves = Math.min(batchSize, moveCount - i * batchSize);
-
- cy.get('@targetBlock')
- .type('{rightarrow}'.repeat(remainingMoves))
- .wait(50);
- }
-
- cy.get('@targetBlock').type('{enter}');
- };
-
const assertJSON = (expectedJSON: FromBlockJSON[]) => {
cy.wrap(null).then(() => {
const finalJSON = documentTest.toJSON();
diff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx
index e9f77d4e1d..335be09c85 100644
--- a/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx
@@ -13,4 +13,34 @@ export function mountEditor (props: EditorProps) {
});
cy.mount(<AppWrapper />);
-}
\ No newline at end of file
+}
+
+export const moveToLineStart = (lineIndex: number) => {
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('targetBlock');
+
+ if (lineIndex === 0) {
+ cy.get('@targetBlock').type('{movetostart}').wait(50);
+ } else {
+ cy.get('@targetBlock').type('{movetostart}').type('{downarrow}'.repeat(lineIndex))
+ .wait(50);
+ }
+};
+
+export const moveAndEnter = (lineIndex: number, moveCount: number) => {
+ moveToLineStart(lineIndex);
+ // Move the cursor with right arrow key and batch the movement
+ const batchSize = 5;
+ const batches = Math.ceil(moveCount / batchSize);
+
+ for (let i = 0; i < batches; i++) {
+ const remainingMoves = Math.min(batchSize, moveCount - i * batchSize);
+
+ cy.get('@targetBlock')
+ .type('{rightarrow}'.repeat(remainingMoves))
+ .wait(50);
+ }
+
+ cy.get('@targetBlock').type('{enter}');
+};
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/index.ts b/frontend/appflowy_web_app/src/components/editor/plugins/index.ts
index 7f0bdfe085..7c32230c50 100644
--- a/frontend/appflowy_web_app/src/components/editor/plugins/index.ts
+++ b/frontend/appflowy_web_app/src/components/editor/plugins/index.ts
@@ -1,6 +1,7 @@
+import { withDelete } from '@/components/editor/plugins/withDelete';
import { withInsertBreak } from '@/components/editor/plugins/withInsertBreak';
import { ReactEditor } from 'slate-react';
export function withPlugins (editor: ReactEditor) {
- return withInsertBreak(editor);
+ return withInsertBreak(withDelete(editor));
}
diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/withDelete.ts b/frontend/appflowy_web_app/src/components/editor/plugins/withDelete.ts
new file mode 100644
index 0000000000..07a1451d64
--- /dev/null
+++ b/frontend/appflowy_web_app/src/components/editor/plugins/withDelete.ts
@@ -0,0 +1,89 @@
+import { YjsEditor } from '@/application/slate-yjs';
+import { CustomEditor } from '@/application/slate-yjs/command';
+import { isAtBlockStart, isAtBlockEnd, isEntireDocumentSelected } from '@/application/slate-yjs/utils/yjsOperations';
+import { TextUnit, Range, EditorFragmentDeletionOptions } from 'slate';
+import { ReactEditor } from 'slate-react';
+import { TextDeleteOptions } from 'slate/dist/interfaces/transforms/text';
+
+export function withDelete (editor: ReactEditor) {
+ const { deleteForward, deleteBackward, delete: deleteText } = editor;
+
+ editor.delete = (options?: TextDeleteOptions) => {
+ const { selection } = editor;
+
+ if (!selection) return;
+
+ if (Range.isCollapsed(selection)) {
+ deleteText(options);
+ return;
+ }
+
+ CustomEditor.deleteBlockBackward(editor as YjsEditor, selection);
+ };
+
+ editor.deleteFragment = (options?: EditorFragmentDeletionOptions) => {
+ const deleteEntireDocument = isEntireDocumentSelected(editor as YjsEditor);
+
+ if (deleteEntireDocument) {
+ CustomEditor.deleteEntireDocument(editor as YjsEditor);
+ return;
+ }
+
+ const { selection } = editor;
+
+ if (!selection) return;
+ if (options?.direction === 'backward') {
+ CustomEditor.deleteBlockBackward(editor as YjsEditor, selection);
+ } else {
+ CustomEditor.deleteBlockForward(editor as YjsEditor, selection);
+ }
+ };
+
+ // Handle `delete` key press
+ editor.deleteForward = (unit: TextUnit) => {
+ const { selection } = editor;
+
+ if (!selection) {
+ return;
+ }
+
+ let shouldUseDefaultBehavior = false;
+
+ if (selection && Range.isCollapsed(selection)) {
+ shouldUseDefaultBehavior = !isAtBlockEnd(editor, selection.anchor);
+ }
+
+ if (shouldUseDefaultBehavior) {
+ deleteForward(unit);
+ return;
+ }
+
+ CustomEditor.deleteBlockForward(editor as YjsEditor, selection);
+ };
+
+ // Handle `backspace` key press
+ editor.deleteBackward = (unit: TextUnit) => {
+ const { selection } = editor;
+
+ if (!selection) {
+ return;
+ }
+
+ let shouldUseDefaultBehavior = false;
+
+ const isCollapsed = selection && Range.isCollapsed(selection);
+
+ if (isCollapsed) {
+ shouldUseDefaultBehavior = !isAtBlockStart(editor, selection.anchor);
+ }
+
+ if (shouldUseDefaultBehavior) {
+ deleteBackward(unit);
+ return;
+ }
+
+ CustomEditor.deleteBlockBackward(editor as YjsEditor, selection);
+ };
+
+ return editor;
+}