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.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
feat: support shortcuts on web (#6474)
Kilu.He19a3df6d4754
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-not-outdent-at-top-level.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-not-outdent-at-top-level.snap.pngnew file mode 100644index 0000000000..79f64bb421Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-not-outdent-at-top-level.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-outdent-deeply-nested-paragraph.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-outdent-deeply-nested-paragraph.snap.pngnew file mode 100644index 0000000000..d3d3f42cbaBinary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-outdent-deeply-nested-paragraph.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-outdent-nested-toggle-list.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-outdent-nested-toggle-list.snap.pngnew file mode 100644index 0000000000..5e227811fbBinary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/ShiftTabKeyBehavior/should-outdent-nested-toggle-list.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-indent-nested-block-at-index-0-1.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-indent-nested-block-at-index-0-1.snap.pngnew file mode 100644index 0000000000..e6df020548Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-indent-nested-block-at-index-0-1.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-indent-paragraph.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-indent-paragraph.snap.pngnew file mode 100644index 0000000000..3a3a7bf6d2Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-indent-paragraph.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-not-indent-at-start-of-document.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-not-indent-at-start-of-document.snap.pngnew file mode 100644index 0000000000..d0b6b16b0aBinary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-not-indent-at-start-of-document.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-not-indent-at-start-of-nested-block.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-not-indent-at-start-of-nested-block.snap.pngnew file mode 100644index 0000000000..67ffdfa5eaBinary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/TabKeyBehavior/should-not-indent-at-start-of-nested-block.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/snapshots/shortcuts/BIUS.cy.snap.png b/frontend/appflowy_web_app/cypress/snapshots/shortcuts/BIUS.cy.snap.pngnew file mode 100644index 0000000000..ea983815ceBinary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/shortcuts/BIUS.cy.snap.png differdiff --git a/frontend/appflowy_web_app/cypress/support/component.ts b/frontend/appflowy_web_app/cypress/support/component.tsindex 86d20b565a..84df06273f 100644--- a/frontend/appflowy_web_app/cypress/support/component.ts+++ b/frontend/appflowy_web_app/cypress/support/component.ts@@ -13,6 +13,7 @@// https://on.cypress.io/configuration// ***********************************************************import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command';+import 'cypress-real-events';// Import commands.js using ES2015 syntax:import '@cypress/code-coverage/support';diff --git a/frontend/appflowy_web_app/package.json b/frontend/appflowy_web_app/package.jsonindex dd0b09abc8..9eb8699d4e 100644--- a/frontend/appflowy_web_app/package.json+++ b/frontend/appflowy_web_app/package.json@@ -46,6 +46,7 @@"dexie-react-hooks": "^1.1.7","emoji-mart": "^5.5.2","emoji-regex": "^10.2.1",+ "escape-string-regexp": "^5.0.0","events": "^3.3.0","google-protobuf": "^3.15.12","highlight.js": "^11.10.0",@@ -150,6 +151,7 @@"cross-env": "^7.0.3","cypress": "^13.7.2","cypress-image-snapshot": "^4.0.1",+ "cypress-real-events": "^1.13.0","eslint": "^8.57.0","eslint-plugin-react": "^7.32.2","eslint-plugin-react-hooks": "^4.6.0",diff --git a/frontend/appflowy_web_app/pnpm-lock.yaml b/frontend/appflowy_web_app/pnpm-lock.yamlindex c02373ffa3..eecd89ab68 100644--- a/frontend/appflowy_web_app/pnpm-lock.yaml+++ b/frontend/appflowy_web_app/pnpm-lock.yaml@@ -71,6 +71,9 @@ dependencies:emoji-regex:specifier: ^10.2.1version: 10.3.0+ escape-string-regexp:+ specifier: ^5.0.0+ version: 5.0.0events:specifier: ^3.3.0version: 3.3.0@@ -379,6 +382,9 @@ devDependencies:cypress-image-snapshot:specifier: ^4.0.1version: 4.0.1([email protected])([email protected])+ cypress-real-events:+ specifier: ^1.13.0+ version: 1.13.0([email protected])eslint:specifier: ^8.57.0version: 8.57.0@@ -5801,6 +5807,14 @@ packages:- jestdev: true+ resolution: {integrity: sha512-LoejtK+dyZ1jaT8wGT5oASTPfsNV8/ClRp99ruN60oPj8cBJYod80iJDyNwfPAu4GCxTXOhhAv9FO65Hpwt6Hg==}+ peerDependencies:+ cypress: ^4.x || ^5.x || ^6.x || ^7.x || ^8.x || ^9.x || ^10.x || ^11.x || ^12.x || ^13.x+ dependencies:+ cypress: 13.7.2+ dev: true+resolution: {integrity: sha512-FF5hFI5wlRIHY8urLZjJjj/YvfCBrRpglbZCLr/cYcL9MdDe0+5usa8kTIrDHthlEc9lwihbkb5dmwqBDNS2yw==}engines: {node: ^16.0.0 || ^18.0.0 || >=20.0.0}@@ -6378,6 +6392,11 @@ packages:resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}+ engines: {node: '>=12'}+ dev: false+resolution: {integrity: sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==}engines: {node: '>=6.0'}diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/withTestingYjsEditor.ts b/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/withTestingYjsEditor.tsindex 02b37633a8..6736e3d940 100644--- a/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/withTestingYjsEditor.ts+++ b/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/withTestingYjsEditor.ts@@ -20,6 +20,7 @@ export function generateId () {export function withTestingYjsEditor (editor: Editor, doc: Y.Doc) {const yjdEditor = withYjs(editor, doc, {localOrigin: CollabOrigin.Local,+ readOnly: true,});return yjdEditor;diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/command/const.ts b/frontend/appflowy_web_app/src/application/slate-yjs/command/const.tsnew file mode 100644index 0000000000..2c05c7b6ca--- /dev/null+++ b/frontend/appflowy_web_app/src/application/slate-yjs/command/const.ts@@ -0,0 +1,16 @@+import { BlockType } from '@/application/types';++/** List block types */+export const ListBlockTypes = [BlockType.TodoListBlock, BlockType.BulletedListBlock, BlockType.NumberedListBlock];++/** Container block types */+export const CONTAINER_BLOCK_TYPES = [+ BlockType.ToggleListBlock,+ BlockType.TodoListBlock,+ BlockType.Paragraph,+ BlockType.QuoteBlock,+ BlockType.BulletedListBlock,+ BlockType.NumberedListBlock,+ BlockType.Page,+];+export const SOFT_BREAK_TYPES = [BlockType.CalloutBlock, BlockType.CodeBlock];\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts b/frontend/appflowy_web_app/src/application/slate-yjs/command/index.tsindex d382657176..6336ed2165 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,17 +1,35 @@import { YjsEditor } from '@/application/slate-yjs/plugins/withYjs';+import { EditorMarkFormat } from '@/application/slate-yjs/types';import {dataStringTOJson,executeOperations,- getBlock, getBlockEntry, getSelectionOrThrow, getSharedRoot,- handleCollapsedBreak, handleDeleteEntireDocument, handleMergeBlockBackward, handleNonParagraphBlockBackspace,- handleRangeBreak, handleShouldLiftBlockBackspace,- handleMergeBlockForward,- removeRange,+ getBlock,+ getBlockEntry,+ getSelectionOrThrow,+ getSharedRoot,+ handleCollapsedBreakWithTxn,+ handleDeleteEntireDocumentWithTxn,+ handleIndentBlockWithTxn,+ handleLiftBlockOnBackspaceAndEnterWithTxn,+ handleLiftBlockOnTabWithTxn,+ handleMergeBlockBackwardWithTxn,+ handleMergeBlockForwardWithTxn,+ handleNonParagraphBlockBackspaceAndEnterWithTxn,+ handleRangeBreak,+ removeRangeWithTxn,+ turnToBlock,} from '@/application/slate-yjs/utils/yjsOperations';-import { BlockData, BlockType, InlineBlockType, Mention, MentionType, YjsEditorKey } from '@/application/types';-import { FormulaNode } from '@/components/editor/editor.type';+import {+ BlockData,+ BlockType,+ MentionType,+ TodoListBlockData,+ ToggleListBlockData,+ YjsEditorKey,+} from '@/application/types';import { renderDate } from '@/utils/time';-import { BaseRange, Editor, Element, Node, NodeEntry, Range, Text, Transforms } from 'slate';+import isEqual from 'lodash-es/isEqual';+import { BasePoint, BaseRange, Editor, Element, Node, NodeEntry, Path, Range, Text, Transforms } from 'slate';import { ReactEditor } from 'slate-react';export const CustomEditor = {@@ -25,19 +43,6 @@ export const CustomEditor = {},// Get the text content of a block node, including the text content of its children and formula nodesgetBlockTextContent (node: Node): string {- if (Element.isElement(node)) {- if (node.type === InlineBlockType.Formula) {- return (node as FormulaNode).data || '';- }-- if (node.type === InlineBlockType.Mention && (node.data as Mention)?.type === MentionType.Date) {- const date = (node.data as Mention).date || '';- const isUnix = date?.length === 10;-- return renderDate(date, 'MMM DD, YYYY', isUnix);- }- }-if (Text.isText(node)) {if (node.formula) {return node.formula;@@ -63,9 +68,8 @@ export const CustomEditor = {},setBlockData<T = BlockData> (editor: YjsEditor, blockId: string, updateData: T, select?: boolean) {- const readonly = editor.isElementReadOnly(editor);- if (readonly) {+ if (editor.readOnly) {return;}@@ -75,25 +79,36 @@ export const CustomEditor = {...oldData,...updateData,};- const operations = [() => {- block.set(YjsEditorKey.block_data, JSON.stringify(newData));- }];- const entry = Editor.above(editor, {++ const newProperties = {+ data: newData,+ } as Partial<Element>;+ const [entry] = editor.nodes({+ at: [],match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId === blockId,});- executeOperations(editor.sharedRoot, operations, 'setBlockData');-- if (!select) return;-if (!entry) {- Transforms.select(editor, Editor.start(editor, [0]));+ console.error('Block not found');return;}- const nodePath = entry[1];+ const [, path] = entry;+ let atChild = false;+ const { selection } = editor;++ if (selection && Path.isAncestor(path, selection.anchor.path)) {+ atChild = true;+ }++ Transforms.setNodes(editor, newProperties, { at: path });++ if (!select) return;++ if (atChild) {+ Transforms.select(editor, Editor.start(editor, path));+ }- Transforms.select(editor, Editor.start(editor, nodePath));},// Insert break line at the specified pathinsertBreak (editor: YjsEditor, at?: BaseRange) {@@ -103,7 +118,7 @@ export const CustomEditor = {const isCollapsed = Range.isCollapsed(newAt);if (isCollapsed) {- handleCollapsedBreak(editor, sharedRoot, newAt);+ handleCollapsedBreakWithTxn(editor, sharedRoot, newAt);} else {handleRangeBreak(editor, sharedRoot, newAt);}@@ -126,18 +141,18 @@ export const CustomEditor = {const blockType = block.get(YjsEditorKey.block_type) as BlockType;if (blockType !== BlockType.Paragraph) {- handleNonParagraphBlockBackspace(sharedRoot, block);+ handleNonParagraphBlockBackspaceAndEnterWithTxn(sharedRoot, block);return;}- if (path.length > 1 && handleShouldLiftBlockBackspace(editor, sharedRoot, block, point)) {+ if (path.length > 1 && handleLiftBlockOnBackspaceAndEnterWithTxn(editor, sharedRoot, block, point)) {return;}- handleMergeBlockBackward(editor, node, point);+ handleMergeBlockBackwardWithTxn(editor, node, point);} else {Transforms.collapse(editor, { edge: 'start' });- removeRange(editor, sharedRoot, newAt);+ removeRangeWithTxn(editor, sharedRoot, newAt);}},@@ -154,18 +169,103 @@ export const CustomEditor = {const [node] = blockEntry as NodeEntry<Element>;- handleMergeBlockForward(editor, node, point);+ handleMergeBlockForwardWithTxn(editor, node, point);} else {Transforms.collapse(editor, { edge: 'start' });- removeRange(editor, sharedRoot, newAt);+ removeRangeWithTxn(editor, sharedRoot, newAt);}},deleteEntireDocument (editor: YjsEditor) {- handleDeleteEntireDocument(editor);+ handleDeleteEntireDocumentWithTxn(editor);},removeRange (editor: YjsEditor, at: BaseRange) {- removeRange(editor, getSharedRoot(editor), at);+ removeRangeWithTxn(editor, getSharedRoot(editor), at);+ },++ tabForward (editor: YjsEditor, point: BasePoint) {+ const sharedRoot = getSharedRoot(editor);+ const [node] = getBlockEntry(editor, point);++ const block = getBlock(node.blockId as string, sharedRoot);++ handleIndentBlockWithTxn(editor, sharedRoot, block, point);+ },++ tabBackward (editor: YjsEditor, point: BasePoint) {+ const sharedRoot = getSharedRoot(editor);+ const [node] = getBlockEntry(editor, point);++ const block = getBlock(node.blockId as string, sharedRoot);++ handleLiftBlockOnTabWithTxn(editor, sharedRoot, block, point);+ },++ toggleToggleList (editor: YjsEditor, blockId: string) {+ const sharedRoot = getSharedRoot(editor);+ const data = dataStringTOJson(getBlock(blockId, sharedRoot).get(YjsEditorKey.block_data)) as ToggleListBlockData;+ const { selection } = editor;++ if (!selection) return;++ if (Range.isExpanded(selection)) {+ Transforms.collapse(editor, { edge: 'start' });+ }++ const point = Editor.start(editor, selection);++ const [node] = getBlockEntry(editor, point);++ CustomEditor.setBlockData(editor, blockId, {+ collapsed: !data.collapsed,+ }, node.blockId !== blockId);+ },++ toggleTodoList (editor: YjsEditor, blockId: string) {+ const sharedRoot = getSharedRoot(editor);+ const data = dataStringTOJson(getBlock(blockId, sharedRoot).get(YjsEditorKey.block_data)) as TodoListBlockData;++ CustomEditor.setBlockData(editor, blockId, {+ checked: !data.checked,+ }, false);+ },++ toggleMark (editor: ReactEditor, {+ key, value,+ }: {+ key: EditorMarkFormat, value: boolean | string+ }) {+ if (editor.marks && Object.keys(editor.marks).includes(key)) {+ editor.removeMark(key);+ } else {+ editor.addMark(key, value);+ }+ },++ addMark (editor: ReactEditor, {+ key, value,+ }: {+ key: EditorMarkFormat, value: boolean | string+ }) {+ editor.addMark(key, value);+ },++ turnToBlock<T extends BlockData> (editor: YjsEditor, blockId: string, type: BlockType, data: T) {+ const operations: (() => void)[] = [];+ const sharedRoot = getSharedRoot(editor);+ const sourceBlock = getBlock(blockId, sharedRoot);+ const sourceType = sourceBlock.get(YjsEditorKey.block_type) as BlockType;+ const oldData = dataStringTOJson(sourceBlock.get(YjsEditorKey.block_data));++ if (sourceType === type && isEqual(oldData, data)) {+ return;+ }++ operations.push(() => {+ turnToBlock(sharedRoot, sourceBlock, type, data);+ });++ executeOperations(sharedRoot, operations, 'turnToBlock');},};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.tsindex 5c92deb032..be8f7a6c18 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@@ -39,7 +39,7 @@ export function withYHistory<T extends YjsEditor> (): T & YHistoryEditor {const e = editor as T & YHistoryEditor;- if (Editor.isElementReadOnly(e, e)) {+ if (e.readOnly) {return e;}@@ -52,6 +52,7 @@ export function withYHistory<T extends YjsEditor> (e.onChange = () => {onChange();+const selection = e.selection;try {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.tsindex 2484fb90bd..69d9225d92 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@@ -11,6 +11,7 @@ type LocalChange = {};export interface YjsEditor extends Editor {+ readOnly: boolean;isYjsEditor: (value: unknown) => value is YjsEditor;connect: () => void;disconnect: () => void;@@ -71,16 +72,18 @@ export function withYjs<T extends Editor> (editor: T,doc: Y.Doc,opts?: {+ readOnly: boolean;localOrigin: CollabOrigin;readSummary?: boolean;onContentChange?: (content: Descendant[]) => void;},): T & YjsEditor {- const { localOrigin = CollabOrigin.Local, readSummary, onContentChange } = opts ?? {};+ const { localOrigin = CollabOrigin.Local, readSummary, onContentChange, readOnly = true } = opts ?? {};const e = editor as T & YjsEditor;const { apply, onChange } = e;e.interceptLocalChange = false;+ e.readOnly = readOnly;e.sharedRoot = doc.getMap(YjsEditorKey.data_section) as YSharedRoot;diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/types.ts b/frontend/appflowy_web_app/src/application/slate-yjs/types.tsindex f3f751015c..9d69589193 100644--- a/frontend/appflowy_web_app/src/application/slate-yjs/types.ts+++ b/frontend/appflowy_web_app/src/application/slate-yjs/types.ts@@ -20,3 +20,17 @@ export interface BlockJson {external_id?: string;}+export enum EditorMarkFormat {+ Bold = 'bold',+ Italic = 'italic',+ Underline = 'underline',+ StrikeThrough = 'strikethrough',+ Code = 'code',+ Href = 'href',+ Formula = 'formula',+ Mention = 'mention',+ FontColor = 'font_color',+ BgColor = 'bg_color',+ Align = 'align',+}+diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/applyToYjs.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/applyToYjs.tsindex 681edda52c..5690ec512d 100644--- a/frontend/appflowy_web_app/src/application/slate-yjs/utils/applyToYjs.ts+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/applyToYjs.ts@@ -1,47 +1,132 @@import { CustomEditor } from '@/application/slate-yjs/command';-import { getText } from '@/application/slate-yjs/utils/yjsOperations';+import { EditorMarkFormat } from '@/application/slate-yjs/types';import { calculateOffsetRelativeToParent } from '@/application/slate-yjs/utils/positions';+import { getBlock, getNodeAtPath, getText } from '@/application/slate-yjs/utils/yjsOperations';import { YjsEditorKey, YSharedRoot } from '@/application/types';-import { Operation, Element, Editor, InsertTextOperation, RemoveTextOperation, Descendant } from 'slate';+import {+ Descendant,+ Editor,+ Element, InsertNodeOperation,+ InsertTextOperation,+ Operation,+ RemoveTextOperation,+ SetNodeOperation,+ Text,+} from 'slate';import * as Y from 'yjs';// transform slate op to yjs op and apply it to ydocexport function applyToYjs (ydoc: Y.Doc, editor: Editor, op: Operation, slateContent: Descendant[]) {if (op.type === 'set_selection') return;- console.log('applySlateOp', op);+ console.log('applySlateOp', op, slateContent);switch (op.type) {case 'insert_text':return applyInsertText(ydoc, editor, op, slateContent);case 'remove_text':return applyRemoveText(ydoc, editor, op, slateContent);+ case 'set_node':+ return applySetNode(ydoc, editor, op, slateContent);+ case 'insert_node':+ return applyInsertNode(ydoc, editor, op, slateContent);default:return;}}-function applyInsertText (ydoc: Y.Doc, editor: Editor, op: InsertTextOperation, _slateContent: Descendant[]) {- const { path, offset, text } = op;+function getAttributesAtOffset (ytext: Y.Text, offset: number): object | null {+ const delta = ytext.toDelta();+ let currentOffset = 0;++ for (const op of delta) {+ if ('insert' in op) {+ const length = op.insert.length;++ if (currentOffset <= offset && offset < currentOffset + length) {+ return op.attributes || null;+ }++ currentOffset += length;+ }+ }++ return null;+}++function insertText (ydoc: Y.Doc, editor: Editor, { path, offset, text, attributes }: InsertTextOperation & {+ attributes?: object;+}) {const node = findSlateNode(editor, path);const textId = node.textId as string;const sharedRoot = ydoc.getMap(YjsEditorKey.data_section) as YSharedRoot;const yText = getText(textId, sharedRoot);++ if (!yText) return;const point = { path, offset };const relativeOffset = Math.min(calculateOffsetRelativeToParent(node, point), yText.toJSON().length);+ const beforeAttributes = getAttributesAtOffset(yText, relativeOffset - 1);++ console.log('beforeAttributes', beforeAttributes);++ if (beforeAttributes && ('formula' in beforeAttributes || 'mention' in beforeAttributes)) {+ const newAttributes = {+ ...attributes,+ };++ if ('formula' in beforeAttributes) {+ Object.assign({+ formula: undefined,+ });+ }- yText.insert(relativeOffset, text);+ if ('mention' in beforeAttributes) {+ Object.assign({+ mention: undefined,+ });+ }++ yText.insert(relativeOffset, text, newAttributes);+ } else {+ yText.insert(relativeOffset, text, attributes);+ }++ console.log('insertText', attributes, yText.toDelta());++}++function applyInsertText (ydoc: Y.Doc, editor: Editor, op: InsertTextOperation, _slateContent: Descendant[]) {+ const { path, offset, text } = op;++ insertText(ydoc, editor, { path, offset, text, type: 'insert_text' });+}++function applyInsertNode (ydoc: Y.Doc, editor: Editor, op: InsertNodeOperation, _slateContent: Descendant[]) {+ const { path, node } = op;++ if (!Text.isText(node)) return;+ const text = node.text;+ const offset = 0;++ insertText(ydoc, editor, {+ path, offset, text, type: 'insert_text',+ });}function applyRemoveText (ydoc: Y.Doc, editor: Editor, op: RemoveTextOperation, slateContent: Descendant[]) {const { path, offset, text } = op;- const node = (slateContent[0] as Element)?.children?.[0] as Element;++ const node = getNodeAtPath(slateContent, path.slice(0, -1)) as Element;+const textId = node.textId;if (!textId) return;const sharedRoot = ydoc.getMap(YjsEditorKey.data_section) as YSharedRoot;const yText = getText(textId, sharedRoot);++ if (!yText) return;+const point = { path, offset };const relativeOffset = Math.min(calculateOffsetRelativeToParent(node, point), yText.toJSON().length);@@ -53,4 +138,54 @@ function findSlateNode (editor: Editor, path: number[]): Element {const entry = CustomEditor.findTextNode(editor, path);return entry[0];+}++function applySetNode (ydoc: Y.Doc, editor: Editor, op: SetNodeOperation, slateContent: Descendant[]) {+ const { newProperties, path } = op;+ const leafKeys = Object.values(EditorMarkFormat) as string[];+ const properties = Object.keys(newProperties);++ const isLeaf = properties.some((prop: string) => leafKeys.includes(prop));+ const isData = properties.some((prop: string) => prop === 'data');+ const sharedRoot = ydoc.getMap(YjsEditorKey.data_section) as YSharedRoot;++ console.log('applySetNode isLeaf', isLeaf, op);+ if (isLeaf) {+ const node = getNodeAtPath(slateContent, path.slice(0, -1)) as Element;+ const textId = node.textId;++ if (!textId) return;++ const yText = getText(textId, sharedRoot);+ const [start, end] = Editor.edges(editor, path);++ const startRelativeOffset = Math.min(calculateOffsetRelativeToParent(node, start), yText.toJSON().length);+ const endRelativeOffset = Math.min(calculateOffsetRelativeToParent(node, end), yText.toJSON().length);++ const length = endRelativeOffset - startRelativeOffset;++ yText.format(startRelativeOffset, length, newProperties);+ return;+ }++ if (isData) {+ const node = getNodeAtPath(slateContent, path) as Element;+ const blockId = node.blockId as string;++ if (!blockId) {+ console.error('blockId is not found in node', node, newProperties);+ return;+ }++ const block = getBlock(blockId, sharedRoot);++ if (+ 'data' in newProperties+ ) {+ block.set(YjsEditorKey.block_data, JSON.stringify(newProperties.data));+ return;+ }+ }++ console.error('set_node operation is not supported', op);}\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.tsindex 5394716645..d424f1b010 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@@ -1,6 +1,8 @@+import { CONTAINER_BLOCK_TYPES, ListBlockTypes } from '@/application/slate-yjs/command/const';import {BlockData,- BlockType, ToggleListBlockData,+ BlockType,+ ToggleListBlockData,YBlock,YBlocks,YChildrenMap,@@ -13,7 +15,7 @@ import {import { nanoid } from 'nanoid';import Delta, { Op } from 'quill-delta';-import { BaseRange, Editor, Element, Node, NodeEntry, Path, Point, Range, Transforms } from 'slate';+import { BaseRange, Descendant, Editor, Element, Node, NodeEntry, Path, Point, Range, Transforms } from 'slate';import * as Y from 'yjs';import { YjsEditor } from '../plugins/withYjs';import { slatePointToRelativePosition } from './positions';@@ -105,9 +107,9 @@ export function updateBlockParent (sharedRoot: YSharedRoot, block: YBlock, parenparentChildren.insert(index, [block.get(YjsEditorKey.block_id)]);}-export function handleCollapsedBreak (editor: YjsEditor, sharedRoot: YSharedRoot, at: BaseRange) {+export function handleCollapsedBreakWithTxn (editor: YjsEditor, sharedRoot: YSharedRoot, at: BaseRange) {const { startBlock, startOffset } = getBreakInfo(editor, sharedRoot, at);- const [blockNode] = startBlock;+ const [blockNode, path] = startBlock;const blockId = blockNode.blockId as string;const block = getBlock(blockId, sharedRoot);@@ -115,6 +117,22 @@ export function handleCollapsedBreak (editor: YjsEditor, sharedRoot: YSharedRootthrow new Error('Block not found');}+ const blockType = block.get(YjsEditorKey.block_type);+ const yText = getText(block.get(YjsEditorKey.block_external_id), sharedRoot);++ if (yText.length === 0) {+ if (blockType !== BlockType.Paragraph) {+ handleNonParagraphBlockBackspaceAndEnterWithTxn(sharedRoot, block);+ return;+ }++ const point = Editor.start(editor, at);++ if (path.length > 1 && handleLiftBlockOnBackspaceAndEnterWithTxn(editor, sharedRoot, block, point)) {+ return;+ }+ }+const { operations, select } = getSplitBlockOperations(sharedRoot, block, startOffset);executeOperations(sharedRoot, operations, 'insertBreak');@@ -126,7 +144,7 @@ export function handleCollapsedBreak (editor: YjsEditor, sharedRoot: YSharedRoot}}-export function removeRange (editor: YjsEditor, sharedRoot: YSharedRoot, range: Range) {+export function removeRangeWithTxn (editor: YjsEditor, sharedRoot: YSharedRoot, range: Range) {const { startBlock, endBlock, middleBlocks, startRange, endRange } = getAffectedBlocks(editor, range);const operations: (() => void)[] = [];const isSameBlock = startBlock[0].blockId === endBlock[0].blockId;@@ -166,13 +184,13 @@ export function liftChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targ}export function handleRangeBreak (editor: YjsEditor, sharedRoot: YSharedRoot, range: Range) {- removeRange(editor, sharedRoot, range);+ removeRangeWithTxn(editor, sharedRoot, range);const selection = editor.selection;if (!selection) return;- handleCollapsedBreak(editor, sharedRoot, selection);+ handleCollapsedBreakWithTxn(editor, sharedRoot, selection);}export function copyBlockText (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {@@ -197,8 +215,6 @@ export function turnToBlock<T extends BlockData> (sharedRoot: YSharedRoot, sourccopyBlockText(sharedRoot, sourceBlock, newBlock);- transferChildren(sharedRoot, sourceBlock, newBlock);-const parent = getBlock(sourceBlock.get(YjsEditorKey.block_parent), sharedRoot);if (!parent) return;@@ -206,10 +222,16 @@ export function turnToBlock<T extends BlockData> (sharedRoot: YSharedRoot, sourcconst parentChildren = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);const index = parentChildren.toArray().findIndex((id) => id === sourceBlock.get(YjsEditorKey.block_id));+ updateBlockParent(sharedRoot, newBlock, parent, index);++ if (CONTAINER_BLOCK_TYPES.includes(type)) {+ transferChildren(sharedRoot, sourceBlock, newBlock);+ } else {+ liftChildren(sharedRoot, sourceBlock, newBlock);+ }+// delete source blockdeleteBlock(sharedRoot, sourceBlock.get(YjsEditorKey.block_id));-- updateBlockParent(sharedRoot, newBlock, parent, index);}function getSplitBlockOperations (sharedRoot: YSharedRoot, block: YBlock, offset: number): {@@ -219,31 +241,21 @@ function getSplitBlockOperations (sharedRoot: YSharedRoot, block: YBlock, offsetconst operations: (() => void)[] = [];if (offset === 0) {- const yText = getText(block.get(YjsEditorKey.block_external_id), sharedRoot);-- if (yText.length === 0) {- operations.push(() => {- turnToBlock(sharedRoot, block, BlockType.Paragraph, {});- });- return { operations, select: false };- } else {- operations.push(() => {- const listBlockTypes = [BlockType.TodoListBlock, BlockType.BulletedListBlock, BlockType.NumberedListBlock];- const type = block.get(YjsEditorKey.block_type);- const data = dataStringTOJson(block.get(YjsEditorKey.block_data));- const isList = listBlockTypes.includes(type);- const newBlock = createBlock(sharedRoot, {- ty: isList ? type : BlockType.Paragraph,- data: isList ? data : {},- });- 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 prevIndex = index <= 0 ? 0 : index;-- updateBlockParent(sharedRoot, newBlock, parent, prevIndex);+ operations.push(() => {+ const type = block.get(YjsEditorKey.block_type);+ const data = dataStringTOJson(block.get(YjsEditorKey.block_data));+ const isList = ListBlockTypes.includes(type);+ const newBlock = createBlock(sharedRoot, {+ ty: isList ? type : BlockType.Paragraph,+ data: isList ? data : {},});- }+ 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 prevIndex = index <= 0 ? 0 : index;++ updateBlockParent(sharedRoot, newBlock, parent, prevIndex);+ });return { operations, select: true };}@@ -354,7 +366,6 @@ 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 };}@@ -365,7 +376,6 @@ function getTextIdFromSlateNode (node: Element) {export function deleteSlateRangeInBlock (sharedRoot: YSharedRoot, editor: Editor, block: Element, range: BaseRange) {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, end);@@ -392,10 +402,8 @@ 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 (@@ -433,14 +441,7 @@ export function mergeBlocks (function mergeBlockChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {const targetType = targetBlock.get(YjsEditorKey.block_type);- if ([- BlockType.ToggleListBlock,- BlockType.TodoListBlock,- BlockType.Paragraph,- BlockType.QuoteBlock,- BlockType.BulletedListBlock,- BlockType.NumberedListBlock,- ].includes(targetType)) {+ if (CONTAINER_BLOCK_TYPES.includes(targetType)) {transferChildren(sharedRoot, sourceBlock, targetBlock, 0);} else {liftChildren(sharedRoot, sourceBlock, targetBlock);@@ -543,11 +544,13 @@ export function getSplitBlockType (block: YBlock) {}}- case BlockType.HeadingBlock:- case BlockType.QuoteBlock:- return BlockType.Paragraph;- default:+ case BlockType.BulletedListBlock:+ case BlockType.NumberedListBlock:+ case BlockType.TodoListBlock:return block.get(YjsEditorKey.block_type);++ default:+ return BlockType.Paragraph;}}@@ -572,7 +575,7 @@ export function splitBlock (sharedRoot: YSharedRoot, block: YBlock, offset: numbconst blockType = block.get(YjsEditorKey.block_type);- if (blockType === BlockType.ToggleListBlock) {+ if (blockType === BlockType.ToggleListBlock || blockType === BlockType.QuoteBlock) {const data = dataStringTOJson(block.get(YjsEditorKey.block_data)) as ToggleListBlockData;if (!data.collapsed) {@@ -644,7 +647,6 @@ 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);@@ -723,7 +725,14 @@ export function getSelectionOrThrow (editor: YjsEditor, at?: BaseRange) {return newAt;}-export function getBlockEntry (editor: YjsEditor, point: Point) {+export function getBlockEntry (editor: YjsEditor, point?: Point) {+ const { selection } = editor;+ const at = point || (selection ? Editor.start(editor, selection) : null);++ if (!at) {+ throw new Error('Point not found');+ }+const blockEntry = editor.above({at: point,match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,@@ -736,7 +745,7 @@ export function getBlockEntry (editor: YjsEditor, point: Point) {return blockEntry as NodeEntry<Element>;}-export function handleNonParagraphBlockBackspace (sharedRoot: YSharedRoot, block: YBlock) {+export function handleNonParagraphBlockBackspaceAndEnterWithTxn (sharedRoot: YSharedRoot, block: YBlock) {const operations: (() => void)[] = [];operations.push(() => {@@ -745,27 +754,109 @@ export function handleNonParagraphBlockBackspace (sharedRoot: YSharedRoot, blockexecuteOperations(sharedRoot, operations, 'turnToBlock');}-export function handleShouldLiftBlockBackspace (editor: YjsEditor, sharedRoot: YSharedRoot, block: YBlock, point: Point) {+export function handleLiftBlockOnTabWithTxn (editor: YjsEditor, sharedRoot: YSharedRoot, block: YBlock, point: Point) {+ const operations: (() => void)[] = [];+ const [, path] = getBlockEntry(editor, point);++ let newPath: number[] | undefined;++ operations.push(() => {+ newPath = liftEditorNode(editor, sharedRoot, block, point);+ });++ executeOperations(sharedRoot, operations, 'liftBlock');+ if (!newPath) return;++ const newPoint = {+ path: [...newPath, ...point.path.slice(path.length)],+ offset: point.offset,+ };++ // After the lift operation is complete, move the cursor to the start of the newly lifted block+ Transforms.select(editor, newPoint);+}++export function handleLiftBlockOnBackspaceAndEnterWithTxn (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 [, path] = getBlockEntry(editor, point);const hasNextSibling = index < parentChildren.length - 1;const hasChildren = getChildrenArray(block.get(YjsEditorKey.block_children), sharedRoot).length > 0;if (!hasChildren && !hasNextSibling) {+ let newPath: number[] | undefined;+operations.push(() => {- liftEditorNode(editor, sharedRoot, block, point);+ newPath = liftEditorNode(editor, sharedRoot, block, point);});- executeOperations(sharedRoot, operations, 'deleteBlockBackward');+ executeOperations(sharedRoot, operations, 'liftBlock');+ if (!newPath) return;++ const newPoint = {+ path: [...newPath, ...point.path.slice(path.length)],+ offset: point.offset,+ };++ // After the lift operation is complete, move the cursor to the start of the newly lifted block+ Transforms.select(editor, newPoint);return true;}return false;}-export function handleMergeBlockBackward (editor: YjsEditor, node: Element, point: Point) {+export function handleIndentBlockWithTxn (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 parentType = parent.get(YjsEditorKey.block_type);+ const [, path] = getBlockEntry(editor, point);++ // Check if the parent block is a container block+ if (!CONTAINER_BLOCK_TYPES.includes(parentType)) {+ return false;+ }++ // Check if the block can be indented (not the first child)+ if (index === 0) {+ return false;+ }++ // Get the previous sibling+ const previousSiblingId = parentChildren.get(index - 1);+ const previousSibling = getBlock(previousSiblingId, sharedRoot);++ if (!previousSibling) {+ return false;+ }++ let newPath: number[] | undefined;++ operations.push(() => {+ newPath = indentEditorNode(editor, sharedRoot, block, point);+ });++ executeOperations(sharedRoot, operations, 'indentBlock');++ if (!newPath) return;++ const newPoint = {+ path: [...newPath, ...point.path.slice(path.length)],+ offset: point.offset,+ };++ console.log('newPath:', newPath, 'newPoint:', newPoint);++ Transforms.select(editor, newPoint);++ return true;+}++export function handleMergeBlockBackwardWithTxn (editor: YjsEditor, node: Element, point: Point) {const operations: (() => void)[] = [];const sharedRoot = getSharedRoot(editor);@@ -799,7 +890,7 @@ export function handleMergeBlockBackward (editor: YjsEditor, node: Element, poinexecuteOperations(sharedRoot, operations, 'deleteBlockBackward');}-export function handleMergeBlockForward (editor: YjsEditor, node: Element, point: Point) {+export function handleMergeBlockForwardWithTxn (editor: YjsEditor, node: Element, point: Point) {const operations: (() => void)[] = [];const sharedRoot = getSharedRoot(editor);@@ -850,8 +941,40 @@ export function liftEditorNode (editor: YjsEditor, sharedRoot: YSharedRoot, bloc// Calculate the position where the new block should be after the lift operationconst 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));+ return nextPath;++}++export function indentEditorNode (editor: YjsEditor, sharedRoot: YSharedRoot, block: YBlock, point: Point) {+ // Find the path of the current block+ const [, path] = getBlockEntry(editor, point);+ const index = path[path.length - 1];++ console.log('indentEditorNode:', block.get(YjsEditorKey.block_id), 'at index', index, editor.children);+ // Check if the block can be indented (not the first child)+ if (index === 0) {+ console.warn('Cannot indent: block is the first child');+ return;+ }++ // Get the previous sibling's path+ const previousSiblingPath = Path.previous(path);+ const previousSibling = Editor.above(editor, {+ at: [...previousSiblingPath, 0],+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,+ });+ const [previousNode] = previousSibling as NodeEntry<Element>;++ // This is to prevent errors caused by invalid paths when the original node is deleted during the indent process+ Transforms.select(editor, Editor.start(editor, previousSiblingPath));++ // Perform the indent operation on the Yjs document+ indentBlock(sharedRoot, block);++ const newPath = [...previousSiblingPath, previousNode.children.length];++ return newPath;+}export function liftBlock (sharedRoot: YSharedRoot, block: YBlock) {@@ -888,7 +1011,55 @@ export function liftBlock (sharedRoot: YSharedRoot, block: YBlock) {moveNode(sharedRoot, block, grandParent, parentIndex + 1);}+export function indentBlock (sharedRoot: YSharedRoot, block: YBlock) {+ const parentId = block.get(YjsEditorKey.block_parent);+ const parent = getBlock(parentId, sharedRoot);++ if (!parent) {+ console.warn('Cannot indent block: parent not found');+ return;+ }++ const parentChildrenArray = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);++ if (!parentChildrenArray) {+ console.warn('Cannot indent block: parent children array not found');+ return;+ }++ const blockIndex = parentChildrenArray.toArray().findIndex((id) => id === block.get(YjsEditorKey.block_id));++ if (blockIndex === -1) {+ console.warn('Cannot indent block: block not found in parent\'s children');+ return;+ }++ if (blockIndex === 0) {+ console.warn('Cannot indent block: block is the first child');+ return;+ }++ const previousSiblingId = parentChildrenArray.get(blockIndex - 1);+ const previousSibling = getBlock(previousSiblingId, sharedRoot);++ if (!previousSibling) {+ console.warn('Cannot indent block: previous sibling not found');+ return;+ }++ const previousSiblingChildrenArray = getChildrenArray(previousSibling.get(YjsEditorKey.block_children), sharedRoot);++ if (!previousSiblingChildrenArray) {+ console.warn('Cannot indent block: previous sibling children array not found');+ return;+ }++ return moveNode(sharedRoot, block, previousSibling, previousSiblingChildrenArray.length);+}+export function moveNode (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetParent: YBlock, targetIndex: number) {+ console.log('moveNode:', sourceBlock.get(YjsEditorKey.block_id), 'to', targetParent.get(YjsEditorKey.block_id), 'at index', targetIndex);+const copiedBlockId = deepCopyBlock(sharedRoot, sourceBlock);if (!copiedBlockId) {@@ -906,6 +1077,8 @@ export function moveNode (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetPaupdateBlockParent(sharedRoot, copiedBlock, targetParent, targetIndex);deleteBlock(sharedRoot, sourceBlock.get(YjsEditorKey.block_id));++ return copiedBlockId;}export function deepCopyBlock (sharedRoot: YSharedRoot, sourceBlock: YBlock): string | null {@@ -966,7 +1139,7 @@ export function appendEmptyParagraph (sharedRoot: YSharedRoot): string {return newBlock.get(YjsEditorKey.block_id);}-export function handleDeleteEntireDocument (editor: YjsEditor) {+export function handleDeleteEntireDocumentWithTxn (editor: YjsEditor) {const sharedRoot = getSharedRoot(editor);const operations = [() => {editor.deselect();@@ -985,4 +1158,30 @@ export function handleDeleteEntireDocument (editor: YjsEditor) {executeOperations(sharedRoot, operations, 'deleteEntireDocument');Transforms.select(editor, Editor.start(editor, [0]));+}++export function getNodeAtPath (children: Descendant[], path: Path): Descendant | null {+ let currentNode: Descendant | null = null;+ let currentChildren = children;++ for (let i = 0; i < path.length; i++) {+ const index = path[i];++ if (index >= currentChildren.length) {+ return null;+ }++ currentNode = currentChildren[index];+ if (i === path.length - 1) {+ return currentNode;+ }++ if (!Element.isElement(currentNode) || !currentNode.children) {+ return null;+ }++ currentChildren = currentNode.children;+ }++ return currentNode;}\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/_shared/katex-math/KatexMath.tsx b/frontend/appflowy_web_app/src/components/_shared/katex-math/KatexMath.tsxindex e6c7cac5ed..22bb1fb434 100644--- a/frontend/appflowy_web_app/src/components/_shared/katex-math/KatexMath.tsx+++ b/frontend/appflowy_web_app/src/components/_shared/katex-math/KatexMath.tsx@@ -3,14 +3,15 @@ import 'katex/dist/katex.min.css';import { BlockMath, InlineMath } from 'react-katex';import './index.css';-function KatexMath({ latex, isInline = false }: { latex: string; isInline?: boolean }) {+function KatexMath ({ latex, isInline = false }: { latex: string; isInline?: boolean }) {+return isInline ? (<InlineMath math={latex} />) : (<BlockMathrenderError={(error) => {return (- <div className='flex h-[51px] items-center justify-center'>+ <div className="flex h-[51px] items-center justify-center">{error.name}: {error.message}</div>);diff --git a/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx b/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsxindex 92f2e15373..43387ef60b 100644--- a/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx+++ b/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx@@ -14,6 +14,7 @@ const defaultInitialValue: Descendant[] = [];function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {const context = useEditorContext();const readSummary = context.readSummary;+ const readOnly = context.readOnly;const localOrigin = CollabOrigin.Local;const [, setClock] = useState(0);const onContentChange = useCallback(() => {@@ -26,6 +27,7 @@ function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {withReact(withYHistory(withYjs(createEditor(), doc, {+ readOnly: readOnly,localOrigin,readSummary,onContentChange,@@ -33,7 +35,7 @@ function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {),),) as YjsEditor),- [onContentChange, readSummary, doc, localOrigin],+ [doc, readOnly, localOrigin, readSummary, onContentChange],);const [, setIsConnected] = useState(false);diff --git a/frontend/appflowy_web_app/src/components/editor/Editable.tsx b/frontend/appflowy_web_app/src/components/editor/Editable.tsxindex fe9ffed384..9980671154 100644--- a/frontend/appflowy_web_app/src/components/editor/Editable.tsx+++ b/frontend/appflowy_web_app/src/components/editor/Editable.tsx@@ -1,6 +1,7 @@import { useDecorate } from '@/components/editor/components/blocks/code/useDecorate';import { Leaf } from '@/components/editor/components/leaf';import { useEditorContext } from '@/components/editor/EditorContext';+import { useShortcuts } from '@/components/editor/shortcut.hooks';import React, { Suspense, useCallback } from 'react';import { NodeEntry, Range } from 'slate';import { Editable, RenderElementProps, useSlate } from 'slate-react';@@ -19,6 +20,11 @@ const EditorEditable = () => {</Suspense>);}, []);++ const {+ onKeyDown,+ } = useShortcuts(editor);+const onCompositionStart = useCallback(() => {const { selection } = editor;@@ -45,6 +51,7 @@ const EditorEditable = () => {autoCorrect={'off'}autoComplete={'off'}onCompositionStart={onCompositionStart}+ onKeyDown={onKeyDown}/></>);diff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/TabBehavior.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/TabBehavior.cy.tsxnew file mode 100644index 0000000000..d70215a541--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/TabBehavior.cy.tsx@@ -0,0 +1,211 @@+import { mountEditor, moveCursor } from '@/components/editor/__tests__/mount';+import { DocumentTest, FromBlockJSON } from 'cypress/support/document';++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('Tab key behavior', () => {++ beforeEach(() => {+ cy.viewport(1280, 720);+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });+ initializeEditor(initialData);+ const selector = '[role="textbox"]';++ cy.get(selector).as('editor');+ });++ it('should indent paragraph when tab at start of paragraph', () => {+ moveCursor(1, 0); // Move to 'Toggle list'+ cy.get('@editor').realPress('Tab');+ assertJSON([+ {+ ...initialData[0],+ children: [initialData[1]],+ },+ initialData[2],+ ]);++ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/TabKeyBehavior/should-indent-paragraph');+ });++ it('should indent nested block at index 0/1 when tab at start', () => {+ // Test 1: move to children[0]+ moveCursor(2, 0); // Move to 'Nested paragraph 1'+ cy.get('@editor').realPress('Tab');+ assertJSON(initialData);++ // Test 2: move to children[1]+ moveCursor(4, 0); // Move to 'Deeply nested paragraph'+ cy.get('@editor').realPress('Tab');+ assertJSON([+ initialData[0],+ {+ ...initialData[1],+ children: [+ {+ ...initialData[1].children[0],+ children: [initialData[1].children[0].children[0], initialData[1].children[1]],+ },+ initialData[1].children[2],+ ],+ },+ initialData[2],+ ]);++ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/TabKeyBehavior/should-indent-nested-block-at-index-0-1');+ });++ it('should not indent at start of document', () => {+ moveCursor(0, 0);+ cy.get('@editor').realPress('Tab');+ assertJSON(initialData);++ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/TabKeyBehavior/should-not-indent-at-start-of-document');+ });++ it('should not indent at start of nested block', () => {+ moveCursor(2, 0);+ cy.get('@editor').realPress('Tab');+ assertJSON(initialData);++ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/TabKeyBehavior/should-not-indent-at-start-of-nested-block');+ });+});++describe('Shift+Tab key behavior', () => {+ beforeEach(() => {+ cy.viewport(1280, 720);+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });+ initializeEditor(initialData);+ const selector = '[role="textbox"]';++ cy.get(selector).as('editor');+ });++ it('should outdent deeply nested paragraph when shift+tab at start', () => {+ moveCursor(3, 3); // Move to 'Deeply nested paragraph'+ cy.get('@editor').realPress(['Shift', 'Tab']);+ assertJSON([+ initialData[0],+ {+ ...initialData[1],+ children: [+ {+ ...initialData[1].children[0],+ children: [],+ },+ initialData[1].children[0].children[0],+ initialData[1].children[1],+ initialData[1].children[2],+ ],+ },+ initialData[2],+ ]);+ //+ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/ShiftTabKeyBehavior/should-outdent-deeply-nested-paragraph');+ });++ it('should outdent Nested toggle list when shift+tab at start', () => {+ moveCursor(4, 1); // Move to 'Nested toggle list'+ cy.get('@editor').realPress(['Shift', 'Tab']);+ assertJSON([+ initialData[0],+ {+ ...initialData[1],+ children: [+ initialData[1].children[0],+ initialData[1].children[2],+ ],+ },+ initialData[1].children[1],+ initialData[2],+ ]);+ //+ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/ShiftTabKeyBehavior/should-outdent-nested-toggle-list');+ });++ it('should not outdent at top level', () => {+ moveCursor(0, 0); // Move to 'Outer paragraph'+ cy.get('@editor').realPress(['Shift', 'Tab']);+ assertJSON(initialData);++ moveCursor(7, 0); // Move to 'Final outer paragraph'+ cy.get('@editor').realPress(['Shift', 'Tab']);+ assertJSON(initialData);+ // Optional: Add visual regression test+ cy.matchImageSnapshot('behavior/ShiftTabKeyBehavior/should-not-outdent-at-top-level');+ });++});\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/blocks/Paragraph.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/blocks/Paragraph.cy.tsxindex 22d5747f0f..eb7bc6aed2 100644--- a/frontend/appflowy_web_app/src/components/editor/__tests__/blocks/Paragraph.cy.tsx+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/blocks/Paragraph.cy.tsx@@ -54,7 +54,7 @@ describe('<Paragraph />', () => {cy.get('[role="textbox"]').should('exist');cy.get('[role="textbox"]').type('{movetostart}').type('{rightarrow}'.repeat(10))- .type(' New text at the `world` middle ');+ .type(` New text at the 'world' middle `);cy.get('[role="textbox"]').type('{movetoend}').type('{leftarrow}'.repeat(6)).type('{backspace}'.repeat(4));cy.wrap(null).then(() => {@@ -65,7 +65,7 @@ describe('<Paragraph />', () => {text: [{ insert: 'Hello, ' },{- insert: 'wor New text at the `world` middle ld!',+ insert: `wor New text at the 'world' middle ld!`,attributes: {italic: true,underline: true,diff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsxindex 335be09c85..9d91aa4145 100644--- a/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/mount.tsx@@ -28,19 +28,25 @@ export const moveToLineStart = (lineIndex: number) => {}};-export const moveAndEnter = (lineIndex: number, moveCount: number) => {+export const moveCursor = (lineIndex: number, charIndex: number) => {moveToLineStart(lineIndex);// Move the cursor with right arrow key and batch the movementconst batchSize = 5;- const batches = Math.ceil(moveCount / batchSize);+ const batches = Math.ceil(charIndex / batchSize);for (let i = 0; i < batches; i++) {- const remainingMoves = Math.min(batchSize, moveCount - i * batchSize);+ const remainingMoves = Math.min(batchSize, charIndex - i * batchSize);cy.get('@targetBlock').type('{rightarrow}'.repeat(remainingMoves)).wait(50);}+};++export const moveAndEnter = (lineIndex: number, moveCount: number) => {+ moveToLineStart(lineIndex);+ // Move the cursor with right arrow key and batch the movement+ moveCursor(lineIndex, moveCount);cy.get('@targetBlock').type('{enter}');};\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/shortcuts/BIUS.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/shortcuts/BIUS.cy.tsxnew file mode 100644index 0000000000..4753192bf9--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/shortcuts/BIUS.cy.tsx@@ -0,0 +1,162 @@+import { mountEditor } from '@/components/editor/__tests__/mount';+import { DocumentTest, FromBlockJSON } from 'cypress/support/document';++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);+ });+};++const getModKey = () => {+ if (Cypress.platform === 'darwin') {+ return 'Meta';+ } else {+ return 'Control';+ }+};++describe('BIUS.cy', () => {+ beforeEach(() => {+ cy.viewport(1280, 720);+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });+ initializeEditor(initialData);+ const selector = '[role="textbox"]';++ cy.get(selector).as('editor');+ });++ it('should handle `Mod+B/I/U` and `Mod + Shift + S` key press', () => {+ cy.selectMultipleText(['ter parag']);+ cy.get('@editor').focus();+ cy.get('@editor').realPress([getModKey(), 'b']);+ cy.get('@editor').realPress([getModKey(), 'i']);+ cy.get('@editor').realPress([getModKey(), 'u']);+ cy.get('@editor').realPress([getModKey(), 'Shift', 's']);+ assertJSON([+ {+ ...initialData[0],+ text: [{ insert: 'Ou' }, {+ insert: 'ter parag',+ attributes: { bold: true, italic: true, underline: true, strikethrough: true },+ }, { insert: 'raph' }],+ },+ initialData[1],+ initialData[2],+ ]);++ cy.selectMultipleText(['sted toggle list', 'paragraph 2']);+ cy.get('@editor').realPress([getModKey(), 'b']);+ cy.get('@editor').realPress([getModKey(), 'i']);+ cy.get('@editor').realPress([getModKey(), 'u']);+ cy.get('@editor').realPress([getModKey(), 'Shift', 's']);+ assertJSON([+ {+ ...initialData[0],+ text: [{ insert: 'Ou' }, {+ insert: 'ter parag',+ attributes: { bold: true, italic: true, underline: true, strikethrough: true },+ }, { insert: 'raph' }],+ },+ {+ ...initialData[1],+ children: [+ initialData[1].children[0],+ {+ type: 'toggle_list',+ data: {},+ text: [{ insert: 'Ne' }, {+ insert: 'sted toggle list',+ attributes: { bold: true, italic: true, underline: true, strikethrough: true },+ }],+ children: [+ {+ type: 'paragraph',+ data: {},+ text: [{+ insert: 'Deeply nested paragraph',+ attributes: { bold: true, italic: true, underline: true, strikethrough: true },+ }],+ children: [],+ },+ ],+ },+ {+ type: 'paragraph',+ data: {},+ text: [{+ insert: 'Nested paragraph 2',+ attributes: { bold: true, italic: true, underline: true, strikethrough: true },+ }, { insert: '.' }],+ children: [],+ },+ ],+ },+ initialData[2],+ ]);++ // Optional: Add visual regression test+ cy.matchImageSnapshot('shortcuts/BIUS.cy');+ });+});\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/shortcuts/Markdown.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/shortcuts/Markdown.cy.tsxnew file mode 100644index 0000000000..79af89b24f--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/shortcuts/Markdown.cy.tsx@@ -0,0 +1,328 @@+import { mountEditor, moveCursor } from '@/components/editor/__tests__/mount';+import { DocumentTest, FromBlockJSON } from 'cypress/support/document';++let documentTest: DocumentTest;+const initialData: FromBlockJSON[] = [{+ type: 'paragraph',+ data: {},+ text: [{ insert: 'First 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('Markdown editing', () => {+ beforeEach(() => {+ cy.viewport(1280, 720);+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });+ initializeEditor(initialData);+ const selector = '[role="textbox"]';++ cy.get(selector).as('editor');+ });++ it('should handle all markdown inputs', () => {+ moveCursor(0, 6);+ let expectedJson: FromBlockJSON[] = initialData;++ // Test `Bold`+ cy.get('@editor').type('**bold');+ cy.get('@editor').realPress(['*', '*']);+ expectedJson = [{+ type: 'paragraph',+ data: {},+ text: [{ insert: 'First ' }, { insert: 'bold', attributes: { bold: true } }, { insert: 'paragraph' }],+ children: [],+ }];+ assertJSON(expectedJson);+ cy.get('@editor').type('{moveToEnd}');++ cy.get('@editor').realPress('Enter');+ // Test 1: heading+ cy.get('@editor').type('##');+ cy.get('@editor').realPress('Space');+ cy.get('@editor').type('Heading 2');+ expectedJson = [...expectedJson, {+ type: 'heading',+ data: { level: 2 },+ text: [{ insert: 'Heading 2' }],+ children: [],+ }];++ assertJSON(expectedJson);+ // Test `Italic`+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('_italic');+ cy.get('@editor').realPress(['_']);+ expectedJson = [+ ...expectedJson,+ {+ type: 'paragraph',+ data: {},+ text: [{ insert: 'italic', attributes: { italic: true } }],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ cy.get('@editor').type('__bold italic');+ cy.get('@editor').realPress(['_', '_']);+ expectedJson = [+ ...expectedJson.slice(0, -1),+ {+ type: 'paragraph',+ data: {},+ text: [{ insert: 'italic', attributes: { italic: true } }, {+ insert: 'bold italic',+ attributes: { bold: true, italic: true },+ }],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ // Test `Code`+ cy.get('@editor').type(' `code');+ cy.get('@editor').realPress(['`']);+ expectedJson = [+ ...expectedJson.slice(0, -1),+ {+ type: 'paragraph',+ data: {},+ text: [{ insert: 'italic', attributes: { italic: true } }, {+ insert: 'bold italic ',+ attributes: { bold: true, italic: true },+ },+ {+ insert: 'code',+ attributes: { code: true, italic: true, bold: true },+ }],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ // Test `Inline formula`+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('$E=mc^2');+ cy.get('@editor').realPress(['$']);+ expectedJson = [+ ...expectedJson,+ {+ type: 'paragraph',+ data: {},+ text: [{ insert: '$', attributes: { formula: 'E=mc^2' } }],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ // Test `Strikethrough`+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('~~strikethrough');+ cy.get('@editor').realPress(['~', '~']);+ expectedJson = [+ ...expectedJson,+ {+ type: 'paragraph',+ data: {},+ text: [{ insert: 'strikethrough', attributes: { strikethrough: true } }],+ children: [],+ },+ ];+ assertJSON(expectedJson);++ // Test 2: quote+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('"');+ cy.get('@editor').realPress('Space');+ cy.get('@editor').type('quote list');++ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('quote child');++ expectedJson = [+ ...expectedJson,+ {+ type: 'quote',+ data: {},+ text: [{ insert: 'quote list' }],+ children: [{+ type: 'paragraph',+ data: {},+ children: [],+ text: [{ insert: 'quote child' }],+ }],+ },+ ];+ assertJSON(expectedJson);+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').realPress(['Shift', 'Tab']);++ // Test 3: Todo list+ cy.get('@editor').type('-[]');+ cy.get('@editor').realPress('Space');++ expectedJson = [+ ...expectedJson,+ {+ type: 'todo_list',+ data: { checked: false },+ text: [],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ cy.get('@editor').realPress('Backspace');+ cy.get('@editor').type('-[x]');+ cy.get('@editor').realPress('Space');+ expectedJson = [+ ...expectedJson.slice(0, -1),+ {+ type: 'todo_list',+ data: { checked: true },+ text: [],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ cy.get('@editor').realPress('Backspace');+ cy.get('@editor').type('-[ ]');+ cy.get('@editor').realPress('Space');+ expectedJson = [+ ...expectedJson.slice(0, -1),+ {+ type: 'todo_list',+ data: { checked: false },+ text: [],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ cy.get('@editor').type('todo list unchecked');+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('-[x]');+ cy.get('@editor').realPress('Space');+ cy.get('@editor').type('todo list checked');+ expectedJson = [+ ...expectedJson.slice(0, -1),+ {+ type: 'todo_list',+ data: { checked: false },+ text: [{ insert: 'todo list unchecked' }],+ children: [],+ },+ {+ type: 'todo_list',+ data: { checked: true },+ text: [{ insert: 'todo list checked' }],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').realPress('Backspace');++ // Test 4: Toggle list+ cy.get('@editor').type('>');+ cy.get('@editor').realPress('Space');+ cy.get('@editor').type('toggle list');+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('toggle list child');+ expectedJson = [+ ...expectedJson,+ {+ type: 'toggle_list',+ data: { collapsed: false },+ text: [{ insert: 'toggle list' }],+ children: [{+ type: 'paragraph',+ data: {},+ children: [],+ text: [{ insert: 'toggle list child' }],+ }],+ },+ ];+ assertJSON(expectedJson);++ // Test 5: Bullted List+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').realPress('Backspace');+ cy.get('@editor').type('-');+ cy.get('@editor').realPress('Space');+ cy.get('@editor').type('bulleted list');+ expectedJson = [+ ...expectedJson,+ {+ type: 'bulleted_list',+ data: {},+ text: [{ insert: 'bulleted list' }],+ children: [],+ },++ ];+ assertJSON(expectedJson);+ // Test 5: Numbered List+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').type('2.');+ cy.get('@editor').realPress('Space');+ cy.get('@editor').type('numbered list');+ expectedJson = [+ ...expectedJson,+ {+ type: 'numbered_list',+ data: { number: 2 },+ text: [{ insert: 'numbered list' }],+ children: [],+ },+ ];+ assertJSON(expectedJson);++ // Test 6: Code block+ cy.get('@editor').realPress('Enter');+ cy.get('@editor').realPress('Backspace');+ cy.get('@editor').type('```');+ cy.get('@editor').type(`function main() {\n console.log('Hello, World!');\n}`);+ cy.get('@editor').realPress(['Shift', 'Enter']);+ expectedJson = [+ ...expectedJson,+ {+ type: 'code',+ data: {},+ text: [{+ insert: 'function main() {\n console.log(\'Hello, World!\');\n}',+ }],+ children: [],+ },+ {+ type: 'paragraph',+ data: {},+ text: [],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ // Last test: Divider+ cy.get('@editor').type('--');+ cy.get('@editor').realPress('-');+ expectedJson = [+ ...expectedJson.slice(0, -1),+ {+ type: 'divider',+ data: {},+ text: [],+ children: [],+ },+ ];+ assertJSON(expectedJson);+ });+});\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/math-equation/MathEquation.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/math-equation/MathEquation.tsxindex e30b446489..7ffc5f221e 100644--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/math-equation/MathEquation.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/math-equation/MathEquation.tsx@@ -4,7 +4,7 @@ import RightTopActionsToolbar from '@/components/editor/components/block-actionsimport { EditorElementProps, MathEquationNode } from '@/components/editor/editor.type';import { copyTextToClipboard } from '@/utils/copy';import { ReactComponent as MathSvg } from '@/assets/math.svg';-import React, { forwardRef, memo, useMemo, useRef, useState } from 'react';+import React, { forwardRef, memo, Suspense, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';export const MathEquation = memo(@@ -41,7 +41,9 @@ export const MathEquation = memo(className={newClassName}>{formula ? (- <KatexMath latex={formula} />+ <Suspense fallback={formula}>+ <KatexMath latex={formula} />+ </Suspense>) : (<divclassName={diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/Quote.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/Quote.tsxindex 6e69990fbf..75e799f740 100644--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/Quote.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/Quote.tsx@@ -4,15 +4,18 @@ import React, { forwardRef, memo, useMemo } from 'react';export const Quote = memo(forwardRef<HTMLDivElement, EditorElementProps<QuoteNode>>(({ node: _, children, ...attributes }, ref) => {const className = useMemo(() => {- return `my-1 ${attributes.className ?? ''}`;+ return `my-1 ${attributes.className ?? ''} pl-3`;}, [attributes.className]);return (<div {...attributes} ref={ref} className={className}>- {children}+ <div className={'border-l-4 border-fill-default pl-2'}>+ {children}+ </div>+</div>);- })+ }),);export default Quote;diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/QuoteIcon.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/QuoteIcon.tsxdeleted file mode 100644index fec907ced6..0000000000--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/quote/QuoteIcon.tsx+++ /dev/null@@ -1,11 +0,0 @@-import React from 'react';--function QuoteIcon({ className }: { className: string }) {- return (- <span data-playwright-selected={false} contentEditable={false} draggable={false} className={`${className}`}>- <div className={'h-full w-[4px] bg-fill-default'}></div>- </span>- );-}--export default QuoteIcon;diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/text/StartIcon.hooks.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/text/StartIcon.hooks.tsxindex 03cbd68397..136e9583d2 100644--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/text/StartIcon.hooks.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/text/StartIcon.hooks.tsx@@ -1,7 +1,6 @@import { BlockType } from '@/application/types';import { BulletedListIcon } from '@/components/editor/components/blocks/bulleted-list';import { NumberListIcon } from '@/components/editor/components/blocks/numbered-list';-import QuoteIcon from '@/components/editor/components/blocks/quote/QuoteIcon';import ToggleIcon from '@/components/editor/components/blocks/toggle-list/ToggleIcon';import { TextNode } from '@/components/editor/editor.type';import React, { FC, useCallback, useMemo } from 'react';@@ -9,7 +8,7 @@ import { ReactEditor, useSlate } from 'slate-react';import { Editor, Element } from 'slate';import CheckboxIcon from '@/components/editor/components/blocks/todo-list/CheckboxIcon';-export function useStartIcon(node: TextNode) {+export function useStartIcon (node: TextNode) {const editor = useSlate();const path = ReactEditor.findPath(editor, node);const block = Editor.parent(editor, path)?.[0] as Element | null;@@ -28,8 +27,6 @@ export function useStartIcon(node: TextNode) {return NumberListIcon;case BlockType.BulletedListBlock:return BulletedListIcon;- case BlockType.QuoteBlock:- return QuoteIcon;default:return null;}@@ -42,11 +39,7 @@ export function useStartIcon(node: TextNode) {const classList = ['text-block-icon relative w-[24px]'];- if (block.type === BlockType.QuoteBlock) {- classList.push('h-full min-w-[24px]');- } else {- classList.push('h-6');- }+ classList.push('h-6');return <Component className={classList.join(' ')} block={block} />;}, [Component, block]);diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/todo-list/CheckboxIcon.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/todo-list/CheckboxIcon.tsxindex 034a3987bf..4a76234f48 100644--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/todo-list/CheckboxIcon.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/todo-list/CheckboxIcon.tsx@@ -1,20 +1,43 @@+import { YjsEditor } from '@/application/slate-yjs';+import { CustomEditor } from '@/application/slate-yjs/command';import { TodoListNode } from '@/components/editor/editor.type';-import React from 'react';+import { debounce } from 'lodash-es';+import React, { useCallback, useMemo } from 'react';import { ReactComponent as CheckboxCheckSvg } from '$icons/16x/check_filled.svg';import { ReactComponent as CheckboxUncheckSvg } from '$icons/16x/uncheck.svg';+import { useReadOnly, useSlateStatic } from 'slate-react';-function CheckboxIcon({ block, className }: { block: TodoListNode; className: string }) {+function CheckboxIcon ({ block, className }: { block: TodoListNode; className: string }) {const { checked } = block.data;+ const editor = useSlateStatic();+ const readOnly = useReadOnly();++ const toggleChecked = useMemo(() => {+ if (readOnly) {+ return;+ }++ return debounce(() => {+ CustomEditor.toggleTodoList(editor as YjsEditor, block.blockId);+ }, 100);+ }, [readOnly, editor, block.blockId]);++ const handleClick = useCallback((e: React.MouseEvent) => {+ e.stopPropagation();+ e.preventDefault();+ toggleChecked?.();+ }, [toggleChecked]);return (<span+ onClick={handleClick}data-playwright-selected={false}contentEditable={false}draggable={false}onMouseDown={(e) => {e.preventDefault();}}- className={`${className} pr-1 text-xl text-fill-default`}+ className={`${className} ${readOnly ? '' : 'cursor-pointer hover:text-fill-default'} pr-1 text-xl`}>{checked ? <CheckboxCheckSvg /> : <CheckboxUncheckSvg />}</span>diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/toggle-list/ToggleIcon.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/toggle-list/ToggleIcon.tsxindex 808319e913..f0fb5d4ba7 100644--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/toggle-list/ToggleIcon.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/toggle-list/ToggleIcon.tsx@@ -17,11 +17,9 @@ function ToggleIcon ({ block, className }: { block: ToggleListNode; className: s}return debounce(() => {- CustomEditor.setBlockData(editor as YjsEditor, block.blockId, {- collapsed: !collapsed,- }, true);+ CustomEditor.toggleToggleList(editor as YjsEditor, block.blockId);}, 100);- }, [readOnly, editor, block.blockId, collapsed]);+ }, [readOnly, editor, block.blockId]);const handleClick = useCallback((e: React.MouseEvent) => {e.stopPropagation();diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/Leaf.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/Leaf.tsxindex 9389b1e1bc..b5b070c8cb 100644--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/Leaf.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/Leaf.tsx@@ -58,6 +58,7 @@ export function Leaf ({ attributes, children, leaf, text }: RenderLeafProps) {/> : leaf.formula ? <FormulaLeaf formula={leaf.formula} text={text} /> : null;newChildren = <>+{node}<span className={'absolute opacity-0 left-0'}>{newChildren}diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/FormulaLeaf.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/FormulaLeaf.tsxindex 2220fe190b..04e42d1c77 100644--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/FormulaLeaf.tsx+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/FormulaLeaf.tsx@@ -1,6 +1,6 @@import { KatexMath } from '@/components/_shared/katex-math';import { useLeafSelected } from '@/components/editor/components/leaf/leaf.hooks';-import React, { useMemo } from 'react';+import React, { Suspense, useMemo } from 'react';import { Text } from 'slate';import { useReadOnly } from 'slate-react';@@ -11,7 +11,7 @@ function FormulaLeaf ({ formula, text }: {const { isSelected, select } = useLeafSelected(text);const readonly = useReadOnly();const className = useMemo(() => {- const classList = ['formula-inline', 'relative', 'rounded', 'p-0.5'];+ const classList = ['formula-inline', 'relative', 'rounded', 'p-0.5 select-none'];if (readonly) classList.push('cursor-default');else classList.push('cursor-pointer');@@ -25,9 +25,13 @@ function FormulaLeaf ({ formula, text }: {e.preventDefault();select();}}- contentEditable={false} className={className}+ contentEditable={false}+ className={className}>+ <Suspense fallback={formula}>+<KatexMath latex={formula || ''} isInline />+ </Suspense></span>);}diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/leaf.hooks.ts b/frontend/appflowy_web_app/src/components/editor/components/leaf/leaf.hooks.tsindex 3ff5afd975..06a1551ac1 100644--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/leaf.hooks.ts+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/leaf.hooks.ts@@ -11,17 +11,22 @@ export function useLeafSelected (text: Text) {const isSelected = useMemo(() => {if (readonly || !selection || !elementIsSelected || !text) return false;- const path = ReactEditor.findPath(editor, text);-- // get the start and end point of the mention- const start = Editor.start(editor, path);- const end = Editor.end(editor, path);+ try {+ const path = ReactEditor.findPath(editor, text);++ // get the start and end point of the mention+ const start = Editor.start(editor, path);+ const end = Editor.end(editor, path);++ // check if the selection is inside the mention+ return !!(Range.intersection(selection, {+ anchor: start,+ focus: end,+ }));+ } catch (e) {+ return false;+ }- // check if the selection is inside the mention- return !!(Range.intersection(selection, {- anchor: start,- focus: end,- }));}, [editor, elementIsSelected, readonly, selection, text]);const select = useCallback(() => {diff --git a/frontend/appflowy_web_app/src/components/editor/editor.scss b/frontend/appflowy_web_app/src/components/editor/editor.scssindex 4455c89be3..2d48831fb4 100644--- a/frontend/appflowy_web_app/src/components/editor/editor.scss+++ b/frontend/appflowy_web_app/src/components/editor/editor.scss@@ -10,6 +10,12 @@margin-left: 24px;}+.block-element[data-block-type="quote"] {+ .block-element {+ margin-left: 0 !important;+ }+}+.block-element[data-block-type="table/cell"] {margin-left: 0 !important;diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/index.ts b/frontend/appflowy_web_app/src/components/editor/plugins/index.tsindex 7c32230c50..ac1e3d783b 100644--- a/frontend/appflowy_web_app/src/components/editor/plugins/index.ts+++ b/frontend/appflowy_web_app/src/components/editor/plugins/index.ts@@ -1,7 +1,9 @@import { withDelete } from '@/components/editor/plugins/withDelete';import { withInsertBreak } from '@/components/editor/plugins/withInsertBreak';+import { withInsertText } from '@/components/editor/plugins/withInsertText';+import { withMarkdown } from '@/components/editor/plugins/withMarkdown';import { ReactEditor } from 'slate-react';export function withPlugins (editor: ReactEditor) {- return withInsertBreak(withDelete(editor));+ return withMarkdown(withInsertBreak(withDelete(withInsertText(editor))));}diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.ts b/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.tsindex 7f280a0225..7731e5d41a 100644--- a/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.ts+++ b/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.ts@@ -6,7 +6,7 @@ export function withInsertBreak (editor: ReactEditor) {const { insertBreak } = editor;editor.insertBreak = () => {- if (editor.isElementReadOnly(editor)) {+ if ((editor as YjsEditor).readOnly) {insertBreak();return;}diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/withInsertText.ts b/frontend/appflowy_web_app/src/components/editor/plugins/withInsertText.tsnew file mode 100644index 0000000000..a36c2f30d4--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/plugins/withInsertText.ts@@ -0,0 +1,36 @@+import { BaseRange, NodeEntry, Range, Text, Transforms } from 'slate';+import { ReactEditor } from 'slate-react';+import { TextInsertTextOptions } from 'slate/dist/interfaces/transforms/text';++export const withInsertText = (editor: ReactEditor) => {+ const { insertText } = editor;++ editor.insertText = (text: string, options?: TextInsertTextOptions) => {+ const newAt = (options?.at || editor.selection) as BaseRange;++ if (!newAt || !Range.isCollapsed(newAt)) {+ insertText(text, options);+ return;+ }++ const point = newAt.anchor;+ const [textEntry] = editor.nodes({+ at: point, match: n => {+ return Text.isText(n);+ },+ });+ const [textNode] = textEntry as NodeEntry<Text>;++ // If the text node is a formula or mention, split the node and insert the text+ if (textNode.formula || textNode.mention) {+ Transforms.splitNodes(editor, { at: point });+ Transforms.insertNodes(editor, { text }, { at: point, select: true, voids: false });++ return;+ }++ insertText(text, options);+ };++ return editor;+};\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/plugins/withMarkdown.ts b/frontend/appflowy_web_app/src/components/editor/plugins/withMarkdown.tsnew file mode 100644index 0000000000..dd2018b1d9--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/plugins/withMarkdown.ts@@ -0,0 +1,19 @@+import { YjsEditor } from '@/application/slate-yjs';+import { allTriggerChars, applyMarkdown } from '@/components/editor/utils/markdown';+import { ReactEditor } from 'slate-react';+import { TextInsertTextOptions } from 'slate/dist/interfaces/transforms/text';++export const withMarkdown = (editor: ReactEditor) => {+ const { insertText } = editor;++ editor.insertText = (text: string, options?: TextInsertTextOptions) => {++ if (allTriggerChars.has(text) && applyMarkdown(editor as ReactEditor & YjsEditor, text)) {+ return;+ }++ insertText(text, options);+ };++ return editor;+};\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/shortcut.hooks.ts b/frontend/appflowy_web_app/src/components/editor/shortcut.hooks.tsnew file mode 100644index 0000000000..13e89d6056--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/shortcut.hooks.ts@@ -0,0 +1,177 @@+import { YjsEditor } from '@/application/slate-yjs';+import { CustomEditor } from '@/application/slate-yjs/command';+import { SOFT_BREAK_TYPES } from '@/application/slate-yjs/command/const';+import { EditorMarkFormat } from '@/application/slate-yjs/types';+import { getBlockEntry } from '@/application/slate-yjs/utils/yjsOperations';+import { BlockType } from '@/application/types';+import { createHotkey, HOT_KEY_NAME } from '@/utils/hotkeys';+import { KeyboardEvent, useCallback } from 'react';+import { ReactEditor, useReadOnly } from 'slate-react';++export function useShortcuts (editor: ReactEditor) {+ const yjsEditor = editor as YjsEditor;+ const readOnly = useReadOnly();+ const onKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {+ const e = event.nativeEvent;+ const { selection } = editor;++ // Add more cases here for general shortcuts+ switch (true) {+ /**+ * Escape: Esc+ * Default behavior: Deselect editor+ */+ case createHotkey(HOT_KEY_NAME.ESCAPE)(e):+ editor.deselect();+ break;++ default:+ break;+ }++ // Do not process shortcuts if editor is read-only or no selection+ if (readOnly || !selection) return;+ const [point, endPoint] = editor.edges(selection);+ const node = getBlockEntry(yjsEditor, point);+ const endNode = getBlockEntry(yjsEditor, endPoint);+ const isSameBlock = node[0].blockId === endNode[0].blockId;++ // Add more cases here for editing shortcuts+ switch (!readOnly) {+ /**+ * Select all: Mod+A+ * Default behavior: Select all text in the editor+ * Special case for select all in code block: Only select all text in code block+ */+ case createHotkey(HOT_KEY_NAME.SELECT_ALL)(e):+ if (node && node[0].type === BlockType.CodeBlock) {+ event.preventDefault();+ editor.select(node[1]);+ }++ break;+ /**+ * Indent block: Tab+ * Default behavior: Indent block+ */+ case createHotkey(HOT_KEY_NAME.INDENT_BLOCK)(e):+ event.preventDefault();++ if (!isSameBlock) return;+ if (SOFT_BREAK_TYPES.includes(node[0]?.type as BlockType)) {+ editor.insertText('\t');+ break;+ }++ CustomEditor.tabForward(yjsEditor, point);+ break;+ /**+ * Outdent block: Shift+Tab+ * Default behavior: Outdent block+ */+ case createHotkey(HOT_KEY_NAME.OUTDENT_BLOCK)(e):+ event.preventDefault();+ if (!isSameBlock) return;+ CustomEditor.tabBackward(yjsEditor, point);+ break;+ /**+ * Split block: Enter+ * Default behavior: Split block+ * Special case for soft break types: Insert \n+ */+ case createHotkey(HOT_KEY_NAME.SPLIT_BLOCK)(e):+ if (SOFT_BREAK_TYPES.includes(node[0]?.type as BlockType)) {+ event.preventDefault();+ editor.insertText('\n');+ }++ break;+ /**+ * Insert soft break: Shift+Enter+ * Default behavior: Insert \n+ * Special case for soft break types: Split block+ */+ case createHotkey(HOT_KEY_NAME.INSERT_SOFT_BREAK)(e):+ event.preventDefault();+ if (node && SOFT_BREAK_TYPES.includes(node[0]?.type as BlockType)) {+ editor.insertBreak();+ } else {+ editor.insertText('\n');+ }++ break;+ /**+ * Toggle todo: Mod+Enter+ * Default behavior: Toggle todo+ * Special case for toggle list block: Toggle collapse+ */+ case createHotkey(HOT_KEY_NAME.TOGGLE_TODO)(e):+ case createHotkey(HOT_KEY_NAME.TOGGLE_COLLAPSE)(e):+ event.preventDefault();++ if (node[0].type === BlockType.ToggleListBlock) {+ CustomEditor.toggleToggleList(yjsEditor, node[0].blockId as string);+ } else if (node[0].type === BlockType.TodoListBlock) {+ CustomEditor.toggleTodoList(yjsEditor, node[0].blockId as string);+ }++ break;+ /**+ * Bold: Mod + B+ */+ case createHotkey(HOT_KEY_NAME.BOLD)(e):+ event.preventDefault();+ CustomEditor.toggleMark(editor, {+ key: EditorMarkFormat.Bold,+ value: true,+ });+ break;+ /**+ * Italic: Mod + I+ */+ case createHotkey(HOT_KEY_NAME.ITALIC)(e):+ event.preventDefault();+ CustomEditor.toggleMark(editor, {+ key: EditorMarkFormat.Italic,+ value: true,+ });+ break;+ /**+ * Underline: Mod + U+ */+ case createHotkey(HOT_KEY_NAME.UNDERLINE)(e):+ event.preventDefault();+ CustomEditor.toggleMark(editor, {+ key: EditorMarkFormat.Underline,+ value: true,+ });+ break;+ /**+ * Strikethrough: Mod + Shift + S / Mod + Shift + X+ */+ case createHotkey(HOT_KEY_NAME.STRIKETHROUGH)(e):+ event.preventDefault();+ CustomEditor.toggleMark(editor, {+ key: EditorMarkFormat.StrikeThrough,+ value: true,+ });+ break;+ /**+ * Code: Mod + E+ */+ case createHotkey(HOT_KEY_NAME.CODE)(e):+ event.preventDefault();+ CustomEditor.toggleMark(editor, {+ key: EditorMarkFormat.Code,+ value: true,+ });+ break;+ default:+ break;+ }+ }, [editor, yjsEditor, readOnly]);++ return {+ onKeyDown,+ };+}\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/editor/utils/markdown.ts b/frontend/appflowy_web_app/src/components/editor/utils/markdown.tsnew file mode 100644index 0000000000..ab61e57ae4--- /dev/null+++ b/frontend/appflowy_web_app/src/components/editor/utils/markdown.ts@@ -0,0 +1,335 @@+import { YjsEditor } from '@/application/slate-yjs';+import { CustomEditor } from '@/application/slate-yjs/command';+import { EditorMarkFormat } from '@/application/slate-yjs/types';+import { getBlock, getBlockEntry, getSharedRoot, getText } from '@/application/slate-yjs/utils/yjsOperations';+import {+ BlockType,+ HeadingBlockData,+ NumberedListBlockData,+ TodoListBlockData,+ ToggleListBlockData,+ YjsEditorKey,+} from '@/application/types';+import { Editor, Range, Transforms } from 'slate';++type TriggerHotKey = {+ [key in BlockType | EditorMarkFormat]?: string[];+};++const defaultTriggerChar: TriggerHotKey = {+ [BlockType.HeadingBlock]: [' '],+ [BlockType.QuoteBlock]: [' '],+ [BlockType.CodeBlock]: ['`'],+ [BlockType.BulletedListBlock]: [' '],+ [BlockType.NumberedListBlock]: [' '],+ [BlockType.TodoListBlock]: [' '],+ [BlockType.ToggleListBlock]: [' '],+ [BlockType.DividerBlock]: ['-', '*'],+ [EditorMarkFormat.Bold]: ['*', '_'],+ [EditorMarkFormat.Italic]: ['*', '_'],+ [EditorMarkFormat.StrikeThrough]: ['~'],+ [EditorMarkFormat.Code]: ['`'],+ [EditorMarkFormat.Formula]: ['$'],+};++// create a set of all trigger characters+export const allTriggerChars = new Set(Object.values(defaultTriggerChar).flat());++// Define the rules for markdown shortcuts+type Rule = {+ type: 'block' | 'mark'+ match: RegExp+ format: string+ transform?: (editor: YjsEditor, match: RegExpMatchArray) => void+ filter?: (editor: YjsEditor, match: RegExpMatchArray) => boolean+}++function deletePrefix (editor: YjsEditor, offset: number) {+ const [, path] = getBlockEntry(editor);++ const { selection } = editor;++ if (!selection) return;+ editor.select({+ anchor: editor.start(path),+ focus: { path: selection.focus.path, offset: offset },+ });+ editor.delete();+}++function getNodeType (editor: YjsEditor) {+ const [node] = getBlockEntry(editor);++ return node.type as BlockType;+}++function getBlockData (editor: YjsEditor) {+ const [node] = getBlockEntry(editor);++ return node.data;+}++function isEmptyLine (editor: YjsEditor, offset: number) {+ const [node] = getBlockEntry(editor);+ const sharedRoot = getSharedRoot(editor);+ const block = getBlock(node.blockId as string, sharedRoot);+ const yText = getText(block.get(YjsEditorKey.block_external_id), sharedRoot);++ return yText.toJSON().length === offset;+}++const rules: Rule[] = [+ // Blocks+ {+ type: 'block',+ match: /^(#{1,6})\s/,+ format: BlockType.HeadingBlock,+ filter: (editor, match) => {+ const level = match[1].length;+ const blockType = getNodeType(editor);+ const blockData = getBlockData(editor);++ return blockType === BlockType.HeadingBlock && (blockData as HeadingBlockData).level === level;+ },+ transform: (editor, match) => {+ const level = match[1].length;+ const [node] = getBlockEntry(editor);++ deletePrefix(editor, level);+ CustomEditor.turnToBlock<HeadingBlockData>(editor, node.blockId as string, BlockType.HeadingBlock, { level });+ },+ },+ {+ type: 'block',+ match: /^"\s/,+ format: BlockType.QuoteBlock,+ filter: (editor) => {+ return getNodeType(editor) === BlockType.QuoteBlock;+ },+ transform: (editor) => {+ deletePrefix(editor, 1);+ CustomEditor.turnToBlock(editor, getBlockEntry(editor)[0].blockId as string, BlockType.QuoteBlock, {});+ },+ },+ {+ type: 'block',+ match: /^(-)?\[(x| )?\]\s/,+ format: BlockType.TodoListBlock,+ filter: (editor, match) => {+ const checked = match[2] === 'x';+ const blockType = getNodeType(editor);+ const blockData = getBlockData(editor);++ return blockType === BlockType.TodoListBlock && (blockData as TodoListBlockData).checked === checked;+ },+ transform: (editor, match) => {+ deletePrefix(editor, match[0].length - 1);+ const checked = match[2] === 'x';++ CustomEditor.turnToBlock<TodoListBlockData>(editor, getBlockEntry(editor)[0].blockId as string, BlockType.TodoListBlock, { checked });+ },+ },+ {+ type: 'block',+ match: /^>\s/,+ format: BlockType.ToggleListBlock,+ filter: (editor) => {+ return getNodeType(editor) === BlockType.ToggleListBlock;+ },+ transform: (editor) => {+ deletePrefix(editor, 1);+ CustomEditor.turnToBlock<ToggleListBlockData>(editor, getBlockEntry(editor)[0].blockId as string, BlockType.ToggleListBlock, { collapsed: false });+ },+ },+ {+ type: 'block',+ match: /^(`){3,}$/,+ format: BlockType.CodeBlock,+ filter: (editor) => {+ return !isEmptyLine(editor, 2) || getNodeType(editor) === BlockType.CodeBlock;+ },+ transform: (editor) => {+ deletePrefix(editor, 2);++ CustomEditor.turnToBlock(editor, getBlockEntry(editor)[0].blockId as string, BlockType.CodeBlock, {});+ },+ },+ {+ type: 'block',+ match: /^(-|\*|\+)\s/,+ format: BlockType.BulletedListBlock,+ filter: (editor) => {+ return getNodeType(editor) === BlockType.BulletedListBlock;+ },+ transform: (editor) => {+ deletePrefix(editor, 1);+ CustomEditor.turnToBlock(editor, getBlockEntry(editor)[0].blockId as string, BlockType.BulletedListBlock, {});+ },+ },+ {+ type: 'block',+ match: /^(\d+)\.\s/,+ format: BlockType.NumberedListBlock,+ filter: (editor, match) => {+ const start = parseInt(match[1]);+ const blockType = getNodeType(editor);+ const blockData = getBlockData(editor);++ return blockType === BlockType.HeadingBlock || (blockType === BlockType.NumberedListBlock && (blockData as NumberedListBlockData).number === start);+ },+ transform: (editor, match) => {+ const start = parseInt(match[1]);++ deletePrefix(editor, String(start).length + 1);+ CustomEditor.turnToBlock<NumberedListBlockData>(editor, getBlockEntry(editor)[0].blockId as string, BlockType.NumberedListBlock, { number: start });+ },+ },++ {+ type: 'block',+ match: /^([-*_]){3,}$/,+ format: BlockType.DividerBlock,+ filter: (editor) => {+ return !isEmptyLine(editor, 2) || getNodeType(editor) === BlockType.DividerBlock;+ },+ transform: (editor) => {+ deletePrefix(editor, 2);+ CustomEditor.turnToBlock(editor, getBlockEntry(editor)[0].blockId as string, BlockType.DividerBlock, {});+ },+ },++ // marks+ {+ type: 'mark',+ match: /\*\*(.*?)\*\*|__(.*?)__/,+ format: EditorMarkFormat.Bold,+ },+ {+ type: 'mark',+ match: /\*(.*?)\*|_(.*?)_/,+ format: EditorMarkFormat.Italic,+ filter: (_editor, match) => {+ const key = match[0];++ if (key === '**') return true;+ const text = match[1] || match[2];++ console.log('applyMarkdown italic', text);+ return !text || text.length === 0;+ },+ },+ {+ type: 'mark',+ match: /~~(.*?)~~/,+ format: EditorMarkFormat.StrikeThrough,+ },+ {+ type: 'mark',+ match: /`(.*?)`/,+ format: EditorMarkFormat.Code,+ filter: (_editor, match) => {+ const text = match[1];++ return text.length === 0;+ },+ },+ {+ type: 'mark',+ match: /\$(.*?)\$/,+ format: EditorMarkFormat.Formula,+ transform: (editor, match) => {+ const formula = match[1];+ const { selection } = editor;++ if (!selection) return;+ const path = selection.anchor.path;+ const start = match.index!;++ editor.insertText('$');+ Transforms.select(editor, {+ anchor: { path, offset: start },+ focus: { path, offset: start + 1 },+ });++ CustomEditor.addMark(editor, { key: EditorMarkFormat.Formula, value: formula });+ },+ },+];++export const applyMarkdown = (editor: YjsEditor, insertText: string): boolean => {+ const { selection } = editor;++ if (!selection || !Range.isCollapsed(selection)) return false;++ const [, path] = getBlockEntry(editor);+ const start = Editor.start(editor, path);+ const text = editor.string({+ anchor: start,+ focus: selection.focus,+ }) + insertText;++ for (const rule of rules) {+ if (rule.type === 'block') {+ const match = text.match(rule.match);++ console.log('applyMarkdown match', match, rule.match, text);+ if (match && !rule.filter?.(editor, match)) {++ if (rule.transform) {+ rule.transform(editor, match);+ }++ return true;+ }+ } else if (rule.type === 'mark') {+ const path = selection.anchor.path;+ const text = editor.string({+ anchor: {+ path,+ offset: 0,+ },+ focus: selection.focus,+ }) + insertText;++ const matches = [...text.matchAll(new RegExp(rule.match, 'g'))];++ console.log('applyMarkdown mark', rule.match, text, matches);++ if (matches.length > 0 && matches.every((match) => !rule.filter?.(editor, match))) {+ for (const match of matches.reverse()) {+ const start = match.index!;+ const end = start + match[0].length - 1;+ const matchRange = {+ anchor: { path, offset: start },+ focus: { path, offset: end },+ };++ Transforms.select(editor, matchRange);+ editor.delete();++ if (rule.transform) {+ rule.transform(editor, match);+ } else {+ const formatText = match[1] || match[2];++ editor.insertText(formatText);+ Transforms.select(editor, {+ anchor: { path, offset: start },+ focus: { path, offset: start + formatText.length },+ });++ CustomEditor.addMark(editor, { key: rule.format as EditorMarkFormat, value: true });+ }++ Transforms.collapse(editor, { edge: 'end' });++ }++ return true;+ }++ }+ }++ return false;+};\ No newline at end of filediff --git a/frontend/appflowy_web_app/src/components/main/useAppThemeMode.ts b/frontend/appflowy_web_app/src/components/main/useAppThemeMode.tsindex 62b4af8c85..5a5745bf7f 100644--- a/frontend/appflowy_web_app/src/components/main/useAppThemeMode.ts+++ b/frontend/appflowy_web_app/src/components/main/useAppThemeMode.ts@@ -1,4 +1,5 @@-import { useEffect, useState, createContext } from 'react';+import { createHotkey, HOT_KEY_NAME } from '@/utils/hotkeys';+import { useEffect, useState, createContext, useCallback } from 'react';export const ThemeModeContext = createContext<| {@@ -24,6 +25,24 @@ export function useAppThemeMode () {return darkMode === 'true';});+ const onKeyDown = useCallback((e: KeyboardEvent) => {+ switch (true) {+ case createHotkey(HOT_KEY_NAME.TOGGLE_THEME)(e):+ e.preventDefault();+ setIsDark(prev => !prev);+ break;+ default:+ break;+ }+ }, []);++ useEffect(() => {+ window.addEventListener('keydown', onKeyDown);+ return () => {+ window.removeEventListener('keydown', onKeyDown);+ };+ }, [onKeyDown]);+useEffect(() => {if (fixedTheme) return;diff --git a/frontend/appflowy_web_app/tsconfig.json b/frontend/appflowy_web_app/tsconfig.jsonindex 96bf51d65b..406c32bc7a 100644--- a/frontend/appflowy_web_app/tsconfig.json+++ b/frontend/appflowy_web_app/tsconfig.json@@ -25,7 +25,8 @@"types": ["cypress","node",- "jest"+ "jest",+ "cypress-real-events"],"baseUrl": ".","paths": {