Skip to content

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

feat: support withYHistory and editing document on web (#6438)

Kilu.Hec1cf58b99e7e
diff --git a/frontend/appflowy_web_app/.eslintrc.cjs b/frontend/appflowy_web_app/.eslintrc.cjs
index ff6f405885..be02b0d022 100644
--- a/frontend/appflowy_web_app/.eslintrc.cjs
+++ b/frontend/appflowy_web_app/.eslintrc.cjs
@@ -69,5 +69,5 @@ module.exports = {
],
},
- ignorePatterns: ['src/**/*.test.ts', '**/__tests__/**/*.json', 'package.json'],
+ ignorePatterns: ['src/**/*.test.ts', '**/__tests__/**/*.json', 'package.json', '__mocks__/*.ts'],
};
diff --git a/frontend/appflowy_web_app/__mocks__/nanoid.ts b/frontend/appflowy_web_app/__mocks__/nanoid.ts
new file mode 100644
index 0000000000..f001b10d5a
--- /dev/null
+++ b/frontend/appflowy_web_app/__mocks__/nanoid.ts
@@ -0,0 +1,10 @@
+const generateRandomId = (length: number): string => {
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ let result = '';
+ for (let i = 0; i < length; i++) {
+ result += characters.charAt(Math.floor(Math.random() * characters.length));
+ }
+ return result;
+};
+
+export const nanoid = jest.fn(() => generateRandomId(8));
diff --git a/frontend/appflowy_web_app/cypress.config.ts b/frontend/appflowy_web_app/cypress.config.ts
index 56197aa753..d8921bb893 100644
--- a/frontend/appflowy_web_app/cypress.config.ts
+++ b/frontend/appflowy_web_app/cypress.config.ts
@@ -9,6 +9,7 @@ export default defineConfig({
exclude: ['cypress/**/*.*', '**/__tests__/**/*.*', '**/*.test.*'],
},
},
+ watchForFileChanges: false,
component: {
devServer: {
framework: 'react',
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-empty-block-2.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-empty-block-2.snap.png
new file mode 100644
index 0000000000..4eda675a9d
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-empty-block-2.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-empty-block.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-empty-block.snap.png
new file mode 100644
index 0000000000..97d26112ec
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-empty-block.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-nested-paragraphs.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-nested-paragraphs.snap.png
new file mode 100644
index 0000000000..82633fb554
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-nested-paragraphs.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-across-blocks.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-across-blocks.snap.png
new file mode 100644
index 0000000000..9a64138a8a
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-across-blocks.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-anchor-focus.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-anchor-focus.snap.png
new file mode 100644
index 0000000000..857ad9a5b0
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-anchor-focus.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-1.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-1.snap.png
new file mode 100644
index 0000000000..59a8fa67b5
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-1.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-2.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-2.snap.png
new file mode 100644
index 0000000000..020de21320
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-2.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-3.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-3.snap.png
new file mode 100644
index 0000000000..2749f96402
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-3.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-4.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-4.snap.png
new file mode 100644
index 0000000000..505c4a6c50
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-different-nesting-levels-4.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-same-level-blocks.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-same-level-blocks.snap.png
new file mode 100644
index 0000000000..1e36d95a75
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-same-level-blocks.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-single-block.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-single-block.snap.png
new file mode 100644
index 0000000000..845da3eb59
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selection-single-block.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selections.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selections.snap.png
new file mode 100644
index 0000000000..e6e5ebde7e
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-range-selections.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-split-paragraph-block.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-split-paragraph-block.snap.png
new file mode 100644
index 0000000000..20a7962dda
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-split-paragraph-block.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-toggle-list-collapsed.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-toggle-list-collapsed.snap.png
new file mode 100644
index 0000000000..b87775e5a7
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-toggle-list-collapsed.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-toggle-list.snap.png b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-toggle-list.snap.png
new file mode 100644
index 0000000000..565a248330
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/behavior/enter-key-behavior-toggle-list.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/paragraph/editing-text-with-undo-redo.snap.png b/frontend/appflowy_web_app/cypress/snapshots/paragraph/editing-text-with-undo-redo.snap.png
new file mode 100644
index 0000000000..ecb9a09cf5
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/paragraph/editing-text-with-undo-redo.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/paragraph/editing-text.snap.png b/frontend/appflowy_web_app/cypress/snapshots/paragraph/editing-text.snap.png
new file mode 100644
index 0000000000..bce99702ab
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/paragraph/editing-text.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/paragraph/initial-render.snap.png b/frontend/appflowy_web_app/cypress/snapshots/paragraph/initial-render.snap.png
new file mode 100644
index 0000000000..cf4429601a
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/paragraph/initial-render.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/snapshots/paragraph/inline-formatting.snap.png b/frontend/appflowy_web_app/cypress/snapshots/paragraph/inline-formatting.snap.png
new file mode 100644
index 0000000000..07f89a9ada
Binary files /dev/null and b/frontend/appflowy_web_app/cypress/snapshots/paragraph/inline-formatting.snap.png differ
diff --git a/frontend/appflowy_web_app/cypress/support/component.ts b/frontend/appflowy_web_app/cypress/support/component.ts
index 76dbe83d71..86d20b565a 100644
--- a/frontend/appflowy_web_app/cypress/support/component.ts
+++ b/frontend/appflowy_web_app/cypress/support/component.ts
@@ -40,6 +40,9 @@ declare global {
mockDocument: (id: string) => void;
clickOutside: () => void;
getTestingSelector: (testId: string) => Chainable<JQuery<HTMLElement>>;
+ selectText: (text: string) => void;
+
+ selectMultipleText: (texts: string[]) => void;
}
}
}
@@ -68,6 +71,111 @@ Cypress.Commands.add('clickOutside', () => {
doc.elementFromPoint(x, y)?.dispatchEvent(evt);
});
});
+
+function mergeRanges (ranges: Range[]): Range | null {
+ if (ranges.length === 0) return null;
+
+ const mergedRange = ranges[0].cloneRange();
+
+ for (let i = 1; i < ranges.length; i++) {
+ if (ranges[i].compareBoundaryPoints(Range.START_TO_START, mergedRange) < 0) {
+ mergedRange.setStart(ranges[i].startContainer, ranges[i].startOffset);
+ }
+
+ if (ranges[i].compareBoundaryPoints(Range.END_TO_END, mergedRange) > 0) {
+ mergedRange.setEnd(ranges[i].endContainer, ranges[i].endOffset);
+ }
+ }
+
+ return mergedRange;
+}
+
+Cypress.Commands.add('selectMultipleText', (texts: string[]) => {
+ const ranges: Range[] = [];
+
+ cy.window().then((win) => {
+ const promises = texts.map((text) => {
+ return new Cypress.Promise((resolve) => {
+ cy.contains(text).then(($el) => {
+ if (!$el) {
+ throw new Error(`The text "${text}" was not found in the document`);
+ }
+
+ const el = $el[0] as HTMLElement;
+ const document = el.ownerDocument;
+ const range = document.createRange();
+
+ const fullText = el.textContent || '';
+ const startIndex = fullText.indexOf(text);
+ const endIndex = startIndex + text.length;
+
+ if (startIndex !== -1 && endIndex !== -1) {
+ range.setStart(el.firstChild as Node, startIndex);
+ range.setEnd(el.firstChild as Node, endIndex);
+ ranges.push(range);
+ } else {
+ throw new Error(`The text "${text}" was not found in the element`);
+ }
+
+ resolve();
+ });
+ });
+ });
+
+ void Cypress.Promise.all(promises).then(() => {
+ const selection = win.getSelection();
+
+ if (selection) {
+ const mergedRange = mergeRanges(ranges);
+
+ selection.removeAllRanges();
+ if (mergedRange) {
+ selection.addRange(mergedRange);
+
+ }
+ }
+
+ cy.document().trigger('mouseup');
+ cy.document().trigger('selectionchange');
+ });
+ });
+});
+Cypress.Commands.add('selectText', (text: string) => {
+ cy.contains(text).then(($el) => {
+ if (!$el) {
+ throw new Error(`The text "${text}" was not found in the document`);
+ }
+
+ const el = $el[0] as HTMLElement;
+ const document = el.ownerDocument;
+
+ const range = document.createRange();
+
+ range.selectNodeContents(el);
+
+ const fullText = el.textContent || '';
+ const startIndex = fullText.indexOf(text);
+ const endIndex = startIndex + text.length;
+
+ if (startIndex !== -1 && endIndex !== -1) {
+ range.setStart(el.firstChild as HTMLElement, startIndex);
+ range.setEnd(el.firstChild as HTMLElement, endIndex);
+
+ const selection = document.getSelection() as Selection;
+
+ selection.removeAllRanges();
+ selection.addRange(range);
+
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-expect-error
+ $el.trigger('mouseup');
+ cy.document().trigger('selectionchange');
+ } else {
+ throw new Error(`The text "${text}" was not found in the element`);
+ }
+ });
+});
+
// Example use:
// cy.mount(<MyComponent />)
diff --git a/frontend/appflowy_web_app/cypress/support/document.ts b/frontend/appflowy_web_app/cypress/support/document.ts
index f660fae09e..6edbf11872 100644
--- a/frontend/appflowy_web_app/cypress/support/document.ts
+++ b/frontend/appflowy_web_app/cypress/support/document.ts
@@ -110,14 +110,38 @@ export class DocumentTest {
}
const blockText = new Y.Text();
-
- blockText.applyDelta(child.text);
- console.log(blockText.toJSON());
+ blockText.applyDelta(child.text);
this.textMap.set(blockId, blockText);
+
+ const blockChildren = new Y.Array<BlockId>();
+
+ this.childrenMap.set(blockId, blockChildren);
this.fromJSONChildren(child.children, blockId);
}
}
+
+ toJSON () {
+ return this.toJSONChildren(this.pageId);
+ }
+
+ private toJSONChildren (parentId: BlockId): FromBlockJSON[] {
+ const parentChildren = this.childrenMap.get(parentId) ?? [];
+ const children = [];
+
+ for (const childId of parentChildren) {
+ const child = this.blocks.get(childId);
+
+ children.push({
+ type: child.get(YjsEditorKey.block_type),
+ data: JSON.parse(child.get(YjsEditorKey.block_data)),
+ text: this.textMap.get(childId).toDelta(),
+ children: this.toJSONChildren(childId),
+ });
+ }
+
+ return children;
+ }
}
diff --git a/frontend/appflowy_web_app/package.json b/frontend/appflowy_web_app/package.json
index d2ba26c297..dd0b09abc8 100644
--- a/frontend/appflowy_web_app/package.json
+++ b/frontend/appflowy_web_app/package.json
@@ -156,6 +156,7 @@
"eslint-plugin-react-refresh": "^0.4.6",
"istanbul-lib-coverage": "^3.2.2",
"jest-environment-jsdom": "^29.6.2",
+ "jest-node-exports-resolver": "^1.1.6",
"nyc": "^15.1.0",
"pino": "^9.2.0",
"pino-pretty": "^11.2.1",
diff --git a/frontend/appflowy_web_app/pnpm-lock.yaml b/frontend/appflowy_web_app/pnpm-lock.yaml
index 9fe4711846..c02373ffa3 100644
--- a/frontend/appflowy_web_app/pnpm-lock.yaml
+++ b/frontend/appflowy_web_app/pnpm-lock.yaml
@@ -397,6 +397,9 @@ devDependencies:
jest-environment-jsdom:
specifier: ^29.6.2
version: 29.6.2
+ jest-node-exports-resolver:
+ specifier: ^1.1.6
+ version: 1.1.6
nyc:
specifier: ^15.1.0
version: 15.1.0
@@ -7987,6 +7990,10 @@ packages:
'@types/node': 20.11.30
jest-util: 29.7.0
+ resolution: {integrity: sha512-NU412Qcb6WSRetCyEGMCC7IWHzO12LhSKaF1s9cyfM+EOYs4YN2gcNUT8hgu22X0oPFYNwLSPevgstBgLbD9ig==}
+ dev: true
+
resolution: {integrity: sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==}
engines: {node: '>=6'}
diff --git a/frontend/appflowy_web_app/src/application/database-yjs/__tests__/parse.test.ts b/frontend/appflowy_web_app/src/application/database-yjs/__tests__/parse.test.ts
index 23cc302a69..52e6df60e7 100644
--- a/frontend/appflowy_web_app/src/application/database-yjs/__tests__/parse.test.ts
+++ b/frontend/appflowy_web_app/src/application/database-yjs/__tests__/parse.test.ts
@@ -9,7 +9,10 @@ import {
parseNumberTypeOptions,
} from '@/application/database-yjs';
import { YDatabaseField, YDatabaseFieldTypeOption, YjsDatabaseKey } from '@/application/types';
-import { withNumberTestingField, withRelationTestingField } from '@/application/database-yjs/__tests__/withTestingField';
+import {
+ withNumberTestingField,
+ withRelationTestingField,
+} from '@/application/database-yjs/__tests__/withTestingField';
describe('parseYDatabaseCellToCell', () => {
it('should parse a DateTime cell', () => {
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/convert.test.ts b/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/convert.test.ts
index 161669a4ac..1d80680ec3 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/convert.test.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/convert.test.ts
@@ -3,6 +3,8 @@ import { yDocToSlateContent, deltaInsertToSlateNode, yDataToSlateContent } from
import { expect } from '@jest/globals';
import * as Y from 'yjs';
+jest.mock('nanoid');
+
describe('convert yjs data to slate content', () => {
it('should return undefined if root block is not exist', () => {
const doc = new Y.Doc();
@@ -231,38 +233,23 @@ describe('test deltaInsertToSlateNode', () => {
expect(node).toEqual({ text: 'Hello' });
});
- it('should generate formula inline node', () => {
- const node = deltaInsertToSlateNode({
- insert: '$$',
- attributes: { formula: 'world' },
- });
-
- expect(node).toEqual([
- {
- type: 'formula',
- data: 'world',
- children: [{ text: '$' }],
- },
- {
- type: 'formula',
- data: 'world',
- children: [{ text: '$' }],
- },
- ]);
- });
+ it('should ensure undo/redo works', () => {
- it('should generate mention inline node', () => {
- const node = deltaInsertToSlateNode({
- insert: '@',
- attributes: { mention: 'world' },
- });
+ const doc = new Y.Doc();
+ const sharedRoot = doc.getMap('data_section');
+ const document = new Y.Map();
+ sharedRoot.set('document', document);
+ const ytext = new Y.Text();
+ document.set('1', ytext);
+ const undoManager = new Y.UndoManager(sharedRoot, { trackedOrigins: new Set(['local', 'undo', null]) });
+
+ doc.transact(() => {
+ ytext.insert(0, 'Hello');
+ }, 'local');
+ undoManager.undo();
+ expect(ytext.toString()).toBe('');
+ undoManager.redo();
+ expect(ytext.toString()).toBe('Hello');
- expect(node).toEqual([
- {
- type: 'mention',
- data: 'world',
- children: [{ text: '@' }],
- },
- ]);
});
});
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/index.test.ts b/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/index.test.ts
index f261b2244f..100ca0e57c 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/index.test.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/__tests__/index.test.ts
@@ -10,6 +10,8 @@ import Y from 'yjs';
import { expect } from '@jest/globals';
import { YjsEditor } from '@/application/slate-yjs';
+jest.mock('nanoid');
+
describe('slate-yjs adapter', () => {
it('should pass the collaboration test', async () => {
await runCollaborationTest();
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.ts
index beca0a82b8..02b37633a8 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
@@ -13,19 +13,19 @@ import { Editor } from 'slate';
import * as Y from 'yjs';
import { v4 as uuidv4 } from 'uuid';
-export function generateId() {
+export function generateId () {
return uuidv4();
}
-export function withTestingYjsEditor(editor: Editor, doc: Y.Doc) {
+export function withTestingYjsEditor (editor: Editor, doc: Y.Doc) {
const yjdEditor = withYjs(editor, doc, {
- localOrigin: CollabOrigin.LocalSync,
+ localOrigin: CollabOrigin.Local,
});
return yjdEditor;
}
-export function getTestingDocData(doc: Y.Doc) {
+export function getTestingDocData (doc: Y.Doc) {
const sharedRoot = doc.getMap(YjsEditorKey.data_section) as YSharedRoot;
const document = sharedRoot.get(YjsEditorKey.document);
const blocks = document.get(YjsEditorKey.blocks) as YBlocks;
@@ -45,7 +45,7 @@ export function getTestingDocData(doc: Y.Doc) {
};
}
-export function withTestingYDoc(docId: string) {
+export function withTestingYDoc (docId: string) {
const doc = new Y.Doc();
const sharedRoot = doc.getMap(YjsEditorKey.data_section) as YSharedRoot;
const document = new Y.Map();
@@ -81,7 +81,7 @@ export interface BlockObject {
data: string;
}
-export function insertBlock({
+export function insertBlock ({
doc,
parentBlockId,
prevBlockId,
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts b/frontend/appflowy_web_app/src/application/slate-yjs/command/index.ts
index 6cbe63e0f2..c452263808 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,7 +1,13 @@
-import { InlineBlockType, Mention, MentionType } from '@/application/types';
+import { YjsEditor } from '@/application/slate-yjs/plugins/withYjs';
+import {
+ dataStringTOJson, executeOperations,
+ getBlock,
+ handleCollapsedBreak, handleRangeBreak,
+} from '@/application/slate-yjs/utils/yjsOperations';
+import { BlockData, InlineBlockType, Mention, MentionType, YjsEditorKey } from '@/application/types';
import { FormulaNode } from '@/components/editor/editor.type';
import { renderDate } from '@/utils/time';
-import { Editor, Element, Text, Node, NodeEntry } from 'slate';
+import { BaseRange, Editor, Element, Node, NodeEntry, Range, Text, Transforms } from 'slate';
import { ReactEditor } from 'slate-react';
export const CustomEditor = {
@@ -29,9 +35,83 @@ export const CustomEditor = {
}
if (Text.isText(node)) {
+ if (node.formula) {
+ return node.formula;
+ }
+
+ if (node.mention) {
+ if (node.mention.type === MentionType.Date) {
+ const date = node.mention.date || '';
+ const isUnix = date?.length === 10;
+
+ return renderDate(date, 'MMM DD, YYYY', isUnix);
+ } else {
+ const name = document.querySelector('[data-mention-id="' + node.mention.page_id + '"]')?.textContent || '';
+
+ return name;
+ }
+ }
+
return node.text || '';
}
return node.children.map((n) => CustomEditor.getBlockTextContent(n)).join('');
},
+
+ setBlockData<T = BlockData> (editor: YjsEditor, blockId: string, updateData: T, select?: boolean) {
+ const readonly = editor.isElementReadOnly(editor);
+
+ if (readonly) {
+ return;
+ }
+
+ const block = getBlock(blockId, editor.sharedRoot);
+ const oldData = dataStringTOJson(block.get(YjsEditorKey.block_data));
+ const newData = {
+ ...oldData,
+ ...updateData,
+ };
+ const operations = [() => {
+ block.set(YjsEditorKey.block_data, JSON.stringify(newData));
+ }];
+ const entry = Editor.above(editor, {
+ 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]));
+ return;
+ }
+
+ const nodePath = entry[1];
+
+ Transforms.select(editor, Editor.start(editor, nodePath));
+ },
+ // Insert break line at the specified path
+ insertBreak (editor: YjsEditor, at?: BaseRange) {
+ const sharedRoot = editor.sharedRoot;
+
+ if (!sharedRoot || !sharedRoot.doc) {
+ throw new Error('Shared root not found');
+ }
+
+ const newAt = at || editor.selection;
+
+ if (!newAt) {
+ throw new Error('Selection not found');
+ }
+
+ const isCollapsed = Range.isCollapsed(newAt);
+
+ if (isCollapsed) {
+ handleCollapsedBreak(editor, sharedRoot, newAt);
+ } else {
+ handleRangeBreak(editor, sharedRoot, newAt);
+ }
+
+ },
};
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts
new file mode 100644
index 0000000000..f36dfa17e9
--- /dev/null
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withHistory.ts
@@ -0,0 +1,136 @@
+import { getDocument } from '@/application/slate-yjs/utils/yjsOperations';
+import { relativeRangeToSlateRange, slateRangeToRelativeRange } from '@/application/slate-yjs/utils/positions';
+import { CollabOrigin } from '@/application/types';
+import { Editor, Transforms } from 'slate';
+import * as Y from 'yjs';
+import { YjsEditor } from './withYjs';
+import { HistoryStackItem, RelativeRange } from '../types';
+
+const LAST_SELECTION: WeakMap<Editor, RelativeRange | null> = new WeakMap();
+
+export type YHistoryEditor = YjsEditor & {
+ undoManager: Y.UndoManager;
+ undo: () => void;
+ redo: () => void;
+};
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const YHistoryEditor = {
+ isYHistoryEditor (value: unknown): value is YHistoryEditor {
+ return (
+ YjsEditor.isYjsEditor(value) &&
+ 'undoManager' in value &&
+ typeof (value as YHistoryEditor).undo === 'function' &&
+ typeof (value as YHistoryEditor).redo === 'function'
+ );
+ },
+
+ canUndo (editor: YHistoryEditor) {
+ return editor.undoManager.undoStack.length > 0;
+ },
+
+ canRedo (editor: YHistoryEditor) {
+ return editor.undoManager.redoStack.length > 0;
+ },
+};
+
+export function withYHistory<T extends YjsEditor> (
+ editor: T,
+): T & YHistoryEditor {
+ const e = editor as T & YHistoryEditor;
+
+ if (Editor.isElementReadOnly(e, e)) {
+ return e;
+ }
+
+ e.undoManager = new Y.UndoManager(getDocument(e.sharedRoot), {
+ trackedOrigins: new Set([CollabOrigin.Local, null]),
+ });
+
+ const { onChange } = e;
+
+ e.onChange = () => {
+ onChange();
+ LAST_SELECTION.set(
+ e,
+ e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection),
+ );
+ };
+
+ const handleStackItemAdded = ({
+ stackItem,
+ }: {
+ stackItem: HistoryStackItem;
+ type: 'redo' | 'undo';
+ }) => {
+ stackItem.meta.set(
+ 'selection',
+ e.selection && slateRangeToRelativeRange(e.sharedRoot, e, e.selection),
+ );
+
+ stackItem.meta.set('selectionBefore', LAST_SELECTION.get(e));
+
+ };
+
+ const handleStackItemPopped = ({
+ stackItem,
+ }: {
+ stackItem: HistoryStackItem;
+ type: 'redo' | 'undo';
+ }) => {
+
+ const relativeSelection = stackItem.meta.get(
+ 'selectionBefore',
+ ) as RelativeRange | null;
+
+ if (!relativeSelection) {
+ return;
+ }
+
+ const selection = relativeRangeToSlateRange(
+ e.sharedRoot,
+ e,
+ relativeSelection,
+ );
+
+ if (!selection) {
+ const startPoint = Editor.start(e, [0]);
+
+ Transforms.select(e, startPoint);
+ return;
+ }
+
+ Transforms.select(e, selection);
+ };
+
+ const { connect } = e;
+
+ e.connect = () => {
+ connect();
+ e.undoManager.on('stack-item-added', handleStackItemAdded);
+ e.undoManager.on('stack-item-popped', handleStackItemPopped);
+ };
+
+ const { disconnect } = e;
+
+ e.disconnect = () => {
+ e.undoManager.off('stack-item-added', handleStackItemAdded);
+ e.undoManager.off('stack-item-popped', handleStackItemPopped);
+ disconnect();
+ };
+
+ e.undo = () => {
+ if (YjsEditor.connected(e)) {
+ YjsEditor.flushLocalChanges(e);
+ e.undoManager.undo();
+ }
+ };
+
+ e.redo = () => {
+ if (YjsEditor.connected(e)) {
+ YjsEditor.flushLocalChanges(e);
+ e.undoManager.redo();
+ }
+ };
+
+ return e;
+}
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withYjs.ts b/frontend/appflowy_web_app/src/application/slate-yjs/plugins/withYjs.ts
index 036b17671e..6ff29889ae 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
@@ -10,12 +10,14 @@ type LocalChange = {
};
export interface YjsEditor extends Editor {
+ isYjsEditor: (value: unknown) => value is YjsEditor;
connect: () => void;
disconnect: () => void;
sharedRoot: YSharedRoot;
applyRemoteEvents: (events: Array<YEvent>, transaction: Transaction) => void;
flushLocalChanges: () => void;
storeLocalChange: (op: Operation) => void;
+ interceptLocalChange: boolean;
}
const connectSet = new WeakSet<YjsEditor>();
@@ -24,6 +26,17 @@ const localChanges = new WeakMap<YjsEditor, LocalChange[]>();
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const YjsEditor = {
+ isYjsEditor (value: unknown): value is YjsEditor {
+ return (
+ Editor.isEditor(value) &&
+ 'connect' in value &&
+ 'disconnect' in value &&
+ 'sharedRoot' in value &&
+ 'applyRemoteEvents' in value &&
+ 'flushLocalChanges' in value &&
+ 'storeLocalChange' in value
+ );
+ },
connected (editor: YjsEditor): boolean {
return connectSet.has(editor);
},
@@ -65,6 +78,8 @@ export function withYjs<T extends Editor> (
const e = editor as T & YjsEditor;
const { apply, onChange } = e;
+ e.interceptLocalChange = false;
+
e.sharedRoot = doc.getMap(YjsEditorKey.data_section) as YSharedRoot;
const initializeDocumentContent = () => {
@@ -74,45 +89,44 @@ export function withYjs<T extends Editor> (
return;
}
- console.log('===', content.children);
if (readSummary) {
e.children = content.children.slice(0, 10);
} else {
e.children = content.children;
}
- Editor.normalize(editor, { force: true });
+ console.log('===initializeDocumentContent', e.children);
+ Editor.normalize(e, { force: true });
};
const applyIntercept = (op: Operation) => {
- if (YjsEditor.connected(e)) {
+ if (YjsEditor.connected(e) && !e.interceptLocalChange) {
YjsEditor.storeLocalChange(e, op);
}
apply(op);
};
- const applyRemoteIntercept = (op: Operation) => {
- apply(op);
- };
-
- e.applyRemoteEvents = (_events: Array<YEvent>, _: Transaction) => {
+ e.applyRemoteEvents = (_events: Array<YEvent>, _transaction: Transaction) => {
+ console.time('applyRemoteEvents');
// Flush local changes to ensure all local changes are applied before processing remote events
YjsEditor.flushLocalChanges(e);
// Replace the apply function to avoid storing remote changes as local changes
- e.apply = applyRemoteIntercept;
+ e.interceptLocalChange = true;
// Initialize or update the document content to ensure it is in the correct state before applying remote events
initializeDocumentContent();
// Restore the apply function to store local changes after applying remote changes
- e.apply = applyIntercept;
+ e.interceptLocalChange = false;
+ console.timeEnd('applyRemoteEvents');
};
const handleYEvents = (events: Array<YEvent>, transaction: Transaction) => {
- if (transaction.origin === CollabOrigin.Remote) {
+ if (transaction.origin !== CollabOrigin.Local) {
YjsEditor.applyRemoteEvents(e, events, transaction);
}
+
};
e.connect = () => {
@@ -147,7 +161,7 @@ export function withYjs<T extends Editor> (
// parse changes and apply to ydoc
doc.transact(() => {
changes.forEach((change) => {
- applyToYjs(doc, editor, change.op);
+ applyToYjs(doc, editor, change.op, change.slateContent);
});
}, localOrigin);
};
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/types.ts b/frontend/appflowy_web_app/src/application/slate-yjs/types.ts
new file mode 100644
index 0000000000..f3f751015c
--- /dev/null
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/types.ts
@@ -0,0 +1,22 @@
+import { Element, NodeEntry } from 'slate';
+import type Y from 'yjs';
+
+export type HistoryStackItem = {
+ meta: Map<string, unknown>;
+};
+
+export type RelativeRange = {
+ anchor: Y.RelativePosition;
+ focus: Y.RelativePosition;
+ anchorEntry: NodeEntry<Element>;
+ focusEntry: NodeEntry<Element>;
+};
+
+export interface BlockJson {
+ id: string;
+ ty: string;
+ data?: string;
+ children?: string;
+ external_id?: string;
+}
+
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.ts
index 36287c6c10..681edda52c 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,51 +1,52 @@
import { CustomEditor } from '@/application/slate-yjs/command';
-import { YjsEditorKey, YMeta, YSharedRoot, YTextMap } from '@/application/types';
-import { Operation, Element, Editor, InsertTextOperation, RemoveTextOperation } from 'slate';
+import { getText } from '@/application/slate-yjs/utils/yjsOperations';
+import { calculateOffsetRelativeToParent } from '@/application/slate-yjs/utils/positions';
+import { YjsEditorKey, YSharedRoot } from '@/application/types';
+import { Operation, Element, Editor, InsertTextOperation, RemoveTextOperation, Descendant } from 'slate';
import * as Y from 'yjs';
// transform slate op to yjs op and apply it to ydoc
-export function applyToYjs (ydoc: Y.Doc, editor: Editor, op: Operation) {
+export function applyToYjs (ydoc: Y.Doc, editor: Editor, op: Operation, slateContent: Descendant[]) {
if (op.type === 'set_selection') return;
console.log('applySlateOp', op);
switch (op.type) {
case 'insert_text':
- return applyInsertText(ydoc, editor, op);
+ return applyInsertText(ydoc, editor, op, slateContent);
case 'remove_text':
- return applyRemoveText(ydoc, editor, op);
+ return applyRemoveText(ydoc, editor, op, slateContent);
default:
return;
}
}
-function applyInsertText (ydoc: Y.Doc, editor: Editor, op: InsertTextOperation) {
+function applyInsertText (ydoc: Y.Doc, editor: Editor, op: InsertTextOperation, _slateContent: Descendant[]) {
const { path, offset, text } = op;
const node = findSlateNode(editor, path);
- const textMap = getTextMap(ydoc);
const textId = node.textId as string;
- const yText = textMap.get(textId);
+ const sharedRoot = ydoc.getMap(YjsEditorKey.data_section) as YSharedRoot;
+ const yText = getText(textId, sharedRoot);
+ const point = { path, offset };
- yText.insert(offset, text);
+ const relativeOffset = Math.min(calculateOffsetRelativeToParent(node, point), yText.toJSON().length);
+
+ yText.insert(relativeOffset, text);
}
-function applyRemoveText (ydoc: Y.Doc, editor: Editor, op: RemoveTextOperation) {
+function applyRemoveText (ydoc: Y.Doc, editor: Editor, op: RemoveTextOperation, slateContent: Descendant[]) {
const { path, offset, text } = op;
- const node = findSlateNode(editor, path);
- const textMap = getTextMap(ydoc);
- const textId = node.textId as string;
- const yText = textMap.get(textId);
-
- yText.delete(offset, text.length);
-}
+ const node = (slateContent[0] as Element)?.children?.[0] as Element;
+ const textId = node.textId;
-function getTextMap (doc: Y.Doc) {
- const sharedRoot = doc.getMap(YjsEditorKey.data_section) as YSharedRoot;
+ if (!textId) return;
- const document = sharedRoot.get(YjsEditorKey.document);
+ const sharedRoot = ydoc.getMap(YjsEditorKey.data_section) as YSharedRoot;
+ const yText = getText(textId, sharedRoot);
+ const point = { path, offset };
- const meta = document.get(YjsEditorKey.meta) as YMeta;
+ const relativeOffset = Math.min(calculateOffsetRelativeToParent(node, point), yText.toJSON().length);
- return meta.get(YjsEditorKey.text_map) as YTextMap;
+ yText.delete(relativeOffset, text.length);
}
function findSlateNode (editor: Editor, path: number[]): Element {
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts
index 9a2e025952..f534dcd9bd 100644
--- a/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/convert.ts
@@ -1,17 +1,16 @@
+import { BlockJson } from '@/application/slate-yjs/types';
+import { sortTableCells } from '@/application/slate-yjs/utils/table';
import {
- InlineBlockType,
+ BlockData,
+ BlockType,
YBlocks,
YChildrenMap,
- YSharedRoot,
YDoc,
YjsEditorKey,
YMeta,
+ YSharedRoot,
YTextMap,
- BlockData,
- BlockType,
} from '@/application/types';
-import { sortTableCells } from '@/application/slate-yjs/utils/table';
-import { BlockJson } from '@/application/slate-yjs/utils/types';
import { TableCellNode } from '@/components/editor/editor.type';
import { Element, Text } from 'slate';
@@ -153,14 +152,6 @@ export interface YDelta {
}
export function deltaInsertToSlateNode ({ attributes, insert }: YDelta): Element | Text | Element[] {
- const matchInlines = transformToInlineElement({
- insert,
- attributes,
- });
-
- if (matchInlines.length > 0) {
- return matchInlines;
- }
if (attributes) {
dealWithEmptyAttribute(attributes);
@@ -179,46 +170,3 @@ function dealWithEmptyAttribute (attributes: Record<string, string | number | un
}
}
}
-
-export function transformToInlineElement (op: YDelta): Element[] {
- const attributes = op.attributes;
-
- if (!attributes) return [];
- const { formula, mention, ...attrs } = attributes;
-
- if (formula) {
- const texts = op.insert.split('');
-
- return texts.map((text) => {
- return {
- type: InlineBlockType.Formula,
- data: formula,
- children: [
- {
- text,
- ...attrs,
- },
- ],
- };
- });
- }
-
- if (mention) {
- const texts = op.insert.split('');
-
- return texts.map((text) => {
- return {
- type: InlineBlockType.Mention,
- data: mention,
- children: [
- {
- text,
- ...attrs,
- },
- ],
- };
- });
- }
-
- return [];
-}
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts
new file mode 100644
index 0000000000..3e2617766e
--- /dev/null
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/positions.ts
@@ -0,0 +1,150 @@
+import { getText } from '@/application/slate-yjs/utils/yjsOperations';
+import { YSharedRoot } from '@/application/types';
+import { BasePoint, BaseRange, Node, Element, Editor, NodeEntry, Text } from 'slate';
+import { RelativeRange } from '../types';
+import * as Y from 'yjs';
+
+export function slateRangeToRelativeRange (
+ sharedRoot: YSharedRoot,
+ editor: Editor,
+ range: BaseRange,
+): RelativeRange {
+
+ const { point: anchor, entry: anchorEntry } = slatePointToRelativePosition(sharedRoot, editor, range.anchor);
+ const { point: focus, entry: focusEntry } = slatePointToRelativePosition(sharedRoot, editor, range.focus);
+
+ return { anchor, focus, anchorEntry, focusEntry };
+}
+
+export function relativeRangeToSlateRange (
+ sharedRoot: YSharedRoot,
+ editor: Editor,
+ range: RelativeRange,
+): BaseRange | null {
+ const anchor = relativePositionToSlatePoint(sharedRoot, range.anchor, range.anchorEntry);
+ const focus = relativePositionToSlatePoint(sharedRoot, range.focus, range.focusEntry);
+
+ if (!anchor || !focus) {
+ return null;
+ }
+
+ return { anchor, focus };
+}
+
+export function slatePointToRelativePosition (
+ sharedRoot: YSharedRoot,
+ editor: Editor,
+ point: BasePoint,
+): {
+ point: Y.RelativePosition;
+ entry: NodeEntry<Element>;
+} {
+ const [entry] = editor.nodes({
+ at: point,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.textId !== undefined,
+ });
+
+ const [node] = entry as NodeEntry<Element>;
+
+ if (!node) {
+ throw new Error('Node not found');
+ }
+
+ const textId = node.textId as string;
+ const ytext = getText(textId, sharedRoot);
+
+ const offset = Math.min(calculateOffsetRelativeToParent(node, point), ytext.toJSON().length);
+
+ const relPos = Y.createRelativePositionFromTypeIndex(ytext, offset);
+
+ return {
+ point: relPos,
+ entry: entry as NodeEntry<Element>,
+ };
+}
+
+export function calculateOffsetRelativeToParent (slateNode: Element, point: BasePoint): number {
+ const { path, offset } = point;
+
+ if (path.length <= 1) {
+ return offset;
+ }
+
+ let actualOffset = offset;
+
+ const childIndex = path[path.length - 1];
+
+ for (let i = 0; i < childIndex; i++) {
+ const childNode = slateNode.children[i];
+
+ actualOffset += Node.string(childNode).length;
+ }
+
+ return actualOffset;
+}
+
+export function relativePositionToSlatePoint (
+ sharedRoot: YSharedRoot,
+ position: Y.RelativePosition,
+ entry: NodeEntry<Element>,
+): BasePoint | null {
+ if (!sharedRoot.doc) {
+ throw new Error('sharedRoot isn\'t attach to a yDoc');
+ }
+
+ const absPos = Y.createAbsolutePositionFromRelativePosition(
+ position,
+ sharedRoot.doc,
+ );
+
+ if (!absPos) {
+ return null;
+ }
+
+ const [node, path] = entry as NodeEntry<Element>;
+
+ if (!node) {
+ return null;
+ }
+
+ const absIndex = absPos.index;
+
+ return calculatePointFromParentOffset(node, path, absIndex);
+}
+
+function calculatePointFromParentOffset (slateNode: Element, path: number[], parentOffset: number): BasePoint {
+ let remainingOffset = parentOffset;
+ let childIndex = 0;
+
+ for (childIndex = 0; childIndex < slateNode.children.length; childIndex++) {
+ const childNode = slateNode.children[childIndex];
+
+ if (!childNode) {
+ break;
+ }
+
+ const childLength = Node.string(childNode).length;
+
+ if (remainingOffset <= childLength) {
+ break;
+ }
+
+ remainingOffset -= childLength;
+ }
+
+ if (childIndex === slateNode.children.length) {
+ childIndex--;
+ remainingOffset = Node.string(slateNode.children[childIndex]).length;
+ }
+
+ const childNode = slateNode.children[childIndex];
+
+ if (Text.isText(childNode)) {
+ return {
+ path: [...path, childIndex],
+ offset: remainingOffset,
+ };
+ }
+
+ return calculatePointFromParentOffset(childNode, [...path, childIndex], remainingOffset);
+}
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/types.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/types.ts
deleted file mode 100644
index 0dbe81a970..0000000000
--- a/frontend/appflowy_web_app/src/application/slate-yjs/utils/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { Node as SlateNode } from 'slate';
-
-export interface BlockJson {
- id: string;
- ty: string;
- data?: string;
- children?: string;
- external_id?: string;
-}
-
-export interface Operation {
- type: OperationType;
-}
-
-export enum OperationType {
- InsertNode = 'insert_node',
- InsertChildren = 'insert_children',
-}
-
-export interface InsertNodeOperation extends Operation {
- type: OperationType.InsertNode;
- node: SlateNode;
-}
-
-export interface InsertChildrenOperation extends Operation {
- type: OperationType.InsertChildren;
- blockId: string;
- children: string[];
-}
diff --git a/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts b/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts
new file mode 100644
index 0000000000..25ad284c51
--- /dev/null
+++ b/frontend/appflowy_web_app/src/application/slate-yjs/utils/yjsOperations.ts
@@ -0,0 +1,666 @@
+import {
+ BlockData,
+ BlockType, ToggleListBlockData,
+ YBlock,
+ YBlocks,
+ YChildrenMap,
+ YDoc,
+ YjsEditorKey,
+ YMeta,
+ YSharedRoot,
+ YTextMap,
+} from '@/application/types';
+
+import { nanoid } from 'nanoid';
+import Delta, { Op } from 'quill-delta';
+import { BaseRange, Editor, Element, Node, NodeEntry, Path, Range, Transforms } from 'slate';
+import * as Y from 'yjs';
+import { YjsEditor } from '../plugins/withYjs';
+import { slatePointToRelativePosition } from './positions';
+
+export function getText (textId: string, sharedRoot: YSharedRoot) {
+
+ const document = sharedRoot.get(YjsEditorKey.document);
+ const meta = document.get(YjsEditorKey.meta) as YMeta;
+ const textMap = meta.get(YjsEditorKey.text_map) as YTextMap;
+
+ return textMap.get(textId);
+}
+
+function assertDocExists (sharedRoot: YSharedRoot): YDoc {
+ const doc = sharedRoot.doc;
+
+ if (!doc) {
+ throw new Error('Document not found');
+ }
+
+ return doc;
+}
+
+export function getChildrenMap (sharedRoot: YSharedRoot) {
+ const document = sharedRoot.get(YjsEditorKey.document);
+ const meta = document.get(YjsEditorKey.meta) as YMeta;
+ const childrenMap = meta.get(YjsEditorKey.children_map) as YChildrenMap;
+
+ return childrenMap;
+}
+
+export function getChildrenArray (childrenId: string, sharedRoot: YSharedRoot) {
+ const childrenMap = getChildrenMap(sharedRoot);
+
+ return childrenMap.get(childrenId);
+}
+
+export function getDocument (sharedRoot: YSharedRoot) {
+ return sharedRoot.get(YjsEditorKey.document);
+}
+
+export function getBlock (blockId: string, sharedRoot: YSharedRoot) {
+ const document = sharedRoot.get(YjsEditorKey.document);
+ const blocks = document.get(YjsEditorKey.blocks) as YBlocks;
+
+ return blocks.get(blockId);
+}
+
+export function generateBlockId () {
+ return nanoid(8);
+}
+
+export function createBlock (sharedRoot: YSharedRoot, {
+ ty,
+ data,
+}: {
+ ty: BlockType;
+ data: object;
+}): YBlock {
+ const block = new Y.Map();
+ const id = generateBlockId();
+
+ block.set(YjsEditorKey.block_id, id);
+ block.set(YjsEditorKey.block_type, ty);
+ block.set(YjsEditorKey.block_children, id);
+ block.set(YjsEditorKey.block_external_id, id);
+ block.set(YjsEditorKey.block_external_type, 'text');
+ block.set(YjsEditorKey.block_data, JSON.stringify(data));
+
+ const document = getDocument(sharedRoot);
+ const blocks = document.get(YjsEditorKey.blocks) as YBlocks;
+
+ blocks.set(id, block);
+
+ const meta = document.get(YjsEditorKey.meta) as YMeta;
+ const childrenMap = meta.get(YjsEditorKey.children_map) as YChildrenMap;
+ const textMap = meta.get(YjsEditorKey.text_map) as YTextMap;
+
+ childrenMap.set(id, new Y.Array());
+ textMap.set(id, new Y.Text());
+
+ return block as YBlock;
+}
+
+export function updateBlockParent (sharedRoot: YSharedRoot, block: YBlock, parent: YBlock, index: number) {
+ block.set(YjsEditorKey.block_parent, parent.get(YjsEditorKey.block_id));
+ const parentChildren = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);
+
+ parentChildren.insert(index, [block.get(YjsEditorKey.block_id)]);
+}
+
+export function handleCollapsedBreak (editor: YjsEditor, sharedRoot: YSharedRoot, at: BaseRange) {
+ const { startBlock, startOffset } = getBreakInfo(editor, sharedRoot, at);
+ const [blockNode] = startBlock;
+ const blockId = blockNode.blockId as string;
+ const block = getBlock(blockId, sharedRoot);
+
+ if (!block) {
+ throw new Error('Block not found');
+ }
+
+ const { operations, select } = getSplitBlockOperations(sharedRoot, block, startOffset);
+
+ executeOperations(sharedRoot, operations, 'insertBreak');
+
+ if (select) {
+ moveToNextLine(editor, block, at, blockId);
+ } else {
+ Transforms.select(editor, Editor.start(editor, at));
+ }
+}
+
+export function removeRange (editor: YjsEditor, sharedRoot: YSharedRoot, range: Range) {
+ const { startBlock, endBlock, middleBlocks, startRange, endRange } = getAffectedBlocks(editor, range);
+ const operations: (() => void)[] = [];
+ const isSameBlock = Path.compare(startBlock[1], endBlock[1]) === 0;
+
+ operations.push(() => {
+ deleteSlateRangeInBlock(sharedRoot, editor, startBlock[0], startRange);
+ if (!isSameBlock) {
+ deleteSlateRangeInBlock(sharedRoot, editor, endBlock[0], endRange);
+ mergeBlocks(sharedRoot, endBlock[0], startBlock[0]);
+ middleBlocks.forEach((block) => {
+ deleteBlock(sharedRoot, block[0].blockId as string);
+ });
+ }
+ });
+ Transforms.collapse(editor, { edge: 'start' });
+ executeOperations(sharedRoot, operations, 'removeRange');
+
+}
+
+export function liftChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {
+ const sourceChildrenArray = getChildrenArray(sourceBlock.get(YjsEditorKey.block_children), sharedRoot);
+ const targetParent = getBlock(targetBlock.get(YjsEditorKey.block_parent), sharedRoot);
+ const targetChildrenArray = getChildrenArray(targetParent.get(YjsEditorKey.block_children), sharedRoot);
+
+ if (!sourceChildrenArray || !targetChildrenArray) return;
+ const index = targetChildrenArray.toArray().findIndex((id) => id === targetBlock.get(YjsEditorKey.block_id));
+ const targetIndex = index !== -1 ? index + 1 : targetChildrenArray.length;
+
+ if (sourceChildrenArray.length > 0) {
+ deepCopyChildren(sharedRoot, sourceChildrenArray, targetChildrenArray, targetParent.get(YjsEditorKey.block_id), targetIndex);
+ sourceChildrenArray.toArray().forEach((id) => {
+ deleteBlock(sharedRoot, id);
+ });
+ sourceChildrenArray.delete(0, sourceChildrenArray.length);
+ }
+}
+
+export function handleRangeBreak (editor: YjsEditor, sharedRoot: YSharedRoot, range: Range) {
+ removeRange(editor, sharedRoot, range);
+
+ const selection = editor.selection;
+
+ if (!selection) return;
+
+ handleCollapsedBreak(editor, sharedRoot, selection);
+}
+
+export function turnToBlock<T extends BlockData> (sharedRoot: YSharedRoot, sourceBlock: YBlock, type: BlockType, data: T) {
+ const newBlock = createBlock(sharedRoot, {
+ ty: type,
+ data,
+ });
+
+ const sourceTextId = sourceBlock.get(YjsEditorKey.block_external_id);
+ const targetTextId = newBlock.get(YjsEditorKey.block_external_id);
+
+ if (!sourceTextId || !targetTextId) {
+ throw new Error('Text id not found');
+ }
+
+ const sourceText = getText(sourceTextId, sharedRoot);
+ const targetText = getText(targetTextId, sharedRoot);
+
+ targetText.applyDelta(sourceText.toDelta());
+
+ transferChildren(sharedRoot, sourceBlock, newBlock);
+
+ const parent = getBlock(sourceBlock.get(YjsEditorKey.block_parent), sharedRoot);
+
+ if (!parent) return;
+
+ const parentChildren = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);
+ const index = parentChildren.toArray().findIndex((id) => id === sourceBlock.get(YjsEditorKey.block_id));
+
+ // delete source block
+ deleteBlock(sharedRoot, sourceBlock.get(YjsEditorKey.block_id));
+
+ updateBlockParent(sharedRoot, newBlock, parent, index);
+}
+
+function getSplitBlockOperations (sharedRoot: YSharedRoot, block: YBlock, offset: number): {
+ select: boolean;
+ operations: (() => void)[];
+} {
+ const 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);
+ });
+ }
+
+ return { operations, select: true };
+ }
+
+ const { nextLineDelta, parentInfo } = prepareBreakOperation(sharedRoot, block, offset);
+
+ operations.push(() => splitBlock(sharedRoot, block, offset, nextLineDelta, parentInfo));
+
+ return { operations, select: true };
+}
+
+function moveToNextLine (editor: Editor, block: YBlock, at: BaseRange, blockId: string) {
+ const { selection } = editor;
+
+ if (!selection) return;
+
+ const { anchor, focus } = selection;
+
+ if (!Node.has(editor, anchor.path) || !Node.has(editor, focus.path)) {
+ Transforms.select(editor, Editor.start(editor, at));
+ Transforms.move(editor, { distance: 1, unit: 'line' });
+ return;
+ }
+
+ const blockType = block.get(YjsEditorKey.block_type);
+ const isToggleListBlock = blockType === BlockType.ToggleListBlock;
+
+ if (isToggleListBlock) {
+ const blockData = dataStringTOJson(block.get(YjsEditorKey.block_data)) as ToggleListBlockData;
+ const isCollapsed = blockData.collapsed;
+
+ if (isCollapsed) {
+ const nextBlockPath = getNextSiblingBlockPath(editor, blockId);
+
+ if (nextBlockPath) {
+ Transforms.select(editor, Editor.start(editor, nextBlockPath));
+ } else {
+ Transforms.select(editor, Editor.start(editor, at));
+ }
+
+ return;
+ }
+ }
+
+ Transforms.move(editor, { distance: 1, unit: 'line' });
+}
+
+export function getNextSiblingBlockPath (editor: Editor, blockId: string) {
+ const [blockSlateNode] = editor.nodes({
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId === blockId,
+ });
+
+ if (!blockSlateNode) {
+ return;
+ }
+
+ const blockPath = blockSlateNode[1];
+ const blockParentPath = blockPath.slice(0, -1);
+ const index = blockPath[blockPath.length - 1];
+ const nextPath = [...blockParentPath, index + 1];
+
+ if (!nextPath || !Node.has(editor, nextPath)) {
+ return;
+ }
+
+ return nextPath;
+}
+
+export function getAffectedBlocks (editor: YjsEditor, range: Range): {
+ startBlock: NodeEntry<Element>;
+ endBlock: NodeEntry<Element>;
+ middleBlocks: NodeEntry<Element>[];
+ startRange: BaseRange;
+ endRange: BaseRange;
+} {
+ const [start, end] = Range.edges(range);
+ let startRange = range;
+ let endRange = range;
+
+ const startBlock = Editor.above(editor, {
+ at: start,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,
+ }) as NodeEntry<Element>;
+
+ const endBlock = Editor.above(editor, {
+ at: end,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,
+ }) as NodeEntry<Element>;
+
+ const middleBlocks: NodeEntry<Element>[] = [];
+
+ const isSameBlock = Path.compare(startBlock[1], endBlock[1]) === 0;
+
+ if (!isSameBlock) {
+ for (const entry of Editor.nodes(editor, {
+ at: range,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined && n.blockId !== startBlock[0].blockId && n.blockId !== endBlock[0].blockId,
+ })) {
+ const [, path] = entry as NodeEntry<Element>;
+ const isAncestorOfStart = Path.isAncestor(path, startBlock[1]);
+
+ if (!isAncestorOfStart) {
+ middleBlocks.push(entry as NodeEntry<Element>);
+ }
+ }
+
+ startRange = Editor.range(editor, start, Editor.end(editor, startBlock[1]));
+ endRange = Editor.range(editor, Editor.start(editor, endBlock[1]), end);
+ }
+
+ return { startBlock, endBlock, middleBlocks, startRange, endRange };
+}
+
+function getTextIdFromSlateNode (node: Element) {
+ return node.textId ?? (node.children[0] as Element).textId;
+}
+
+export function deleteSlateRangeInBlock (sharedRoot: YSharedRoot, editor: Editor, block: Element, range: BaseRange) {
+ const relativeOffset = slatePointToRelativePosition(sharedRoot, editor, range.anchor);
+ const startPos = Y.createAbsolutePositionFromRelativePosition(relativeOffset.point, assertDocExists(sharedRoot));
+ const endRelativeOffset = slatePointToRelativePosition(sharedRoot, editor, range.focus);
+ const endPos = Y.createAbsolutePositionFromRelativePosition(endRelativeOffset.point, assertDocExists(sharedRoot));
+
+ if (!startPos || !endPos) {
+ throw new Error('Unable to create absolute position');
+ }
+
+ deleteRangeInBlock(sharedRoot, block, startPos.index, endPos.index);
+}
+
+export function deleteRangeInBlock (
+ sharedRoot: YSharedRoot,
+ block: Element,
+ start: number,
+ end: number,
+) {
+ const textId = getTextIdFromSlateNode(block);
+
+ if (!textId) {
+ throw new Error('Text id not found');
+ }
+
+ const yText = getText(textId, sharedRoot);
+
+ yText.delete(start, end - start);
+}
+
+export function mergeBlocks (
+ sharedRoot: YSharedRoot,
+ sourceBlock: Element,
+ targetBlock: Element,
+) {
+ const sourceTextId = getTextIdFromSlateNode(sourceBlock);
+ const targetTextId = getTextIdFromSlateNode(targetBlock);
+
+ if (!sourceTextId || !targetTextId) {
+ throw new Error('Text id not found');
+ }
+
+ const sourceYText = getText(sourceTextId, sharedRoot);
+ const targetYText = getText(targetTextId, sharedRoot);
+
+ const sourceOps = sourceYText.toDelta() as Op[];
+ const targetOps = targetYText.toDelta() as Op[];
+
+ const sourceDelta = new Delta(sourceOps);
+ const targetDelta = new Delta(targetOps);
+ const concat = targetDelta.concat(sourceDelta);
+
+ targetYText.delete(0, targetYText.length);
+ targetYText.applyDelta(concat.ops);
+
+ const sourceBlockId = sourceBlock.blockId as string;
+ const targetBlockId = targetBlock.blockId as string;
+
+ mergeBlockChildren(sharedRoot, getBlock(sourceBlockId, sharedRoot), getBlock(targetBlockId, sharedRoot));
+ deleteBlock(sharedRoot, sourceBlock.blockId as string);
+
+}
+
+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)) {
+ transferChildren(sharedRoot, sourceBlock, targetBlock);
+ } else {
+ liftChildren(sharedRoot, sourceBlock, targetBlock);
+ }
+}
+
+export function deleteBlock (sharedRoot: YSharedRoot, blockId: string) {
+ const block = getBlock(blockId, sharedRoot);
+
+ if (!block) return;
+
+ const document = getDocument(sharedRoot);
+ const blocks = document.get(YjsEditorKey.blocks) as YBlocks;
+ const parentId = block.get(YjsEditorKey.block_parent);
+
+ blocks.delete(blockId);
+
+ const meta = document.get(YjsEditorKey.meta) as YMeta;
+ const childrenMap = meta.get(YjsEditorKey.children_map) as YChildrenMap;
+ const textMap = meta.get(YjsEditorKey.text_map) as YTextMap;
+
+ childrenMap.delete(blockId);
+ textMap.delete(blockId);
+
+ const parent = getBlock(parentId, sharedRoot);
+
+ if (!parent) return;
+
+ const parentChildren = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);
+ const index = parentChildren.toArray().findIndex((id) => id === blockId);
+
+ if (index !== -1) {
+ parentChildren.delete(index, 1);
+ }
+}
+
+export function getBreakInfo (editor: YjsEditor, sharedRoot: YSharedRoot, at: BaseRange) {
+ const startPoint = Editor.start(editor, at);
+ const doc = assertDocExists(sharedRoot);
+
+ const startRelativeRange = slatePointToRelativePosition(sharedRoot, editor, startPoint);
+ const startTextId = getTextIdFromSlateNode(startRelativeRange.entry[0]);
+
+ if (!startTextId) {
+ throw new Error('Text id not found');
+ }
+
+ const startPos = Y.createAbsolutePositionFromRelativePosition(
+ startRelativeRange.point,
+ doc,
+ );
+
+ if (!startPos) {
+ throw new Error('Unable to create absolute position');
+ }
+
+ const startBlock = Editor.above(editor, {
+ at: startPoint.path,
+ match: (n) => !Editor.isEditor(n) && Element.isElement(n) && n.blockId !== undefined,
+ }) as NodeEntry<Element>;
+
+ if (!startBlock) {
+ throw new Error('Block not found');
+ }
+
+ const yText = getText(startTextId, sharedRoot);
+ const startOffset = Math.min(startPos.index, yText.length);
+
+ return { startBlock, startOffset };
+}
+
+export function prepareBreakOperation (sharedRoot: YSharedRoot, block: YBlock, offset: number) {
+ const yText = getText(block.get(YjsEditorKey.block_external_id), sharedRoot);
+ const ops = yText.toDelta() as Op[];
+ const delta = new Delta(ops);
+ const nextLineDelta = delta.slice(offset);
+
+ const parentId = block.get(YjsEditorKey.block_parent);
+ const parent = getBlock(parentId, sharedRoot);
+
+ if (!parent) {
+ throw new Error('Parent block not found');
+ }
+
+ const parentChildren = getChildrenArray(parent.get(YjsEditorKey.block_children), sharedRoot);
+ const targetIndex = parentChildren.toArray().findIndex((id) => id === block.get(YjsEditorKey.block_id));
+
+ return { nextLineDelta, parentInfo: { parent, targetIndex, parentChildren } };
+}
+
+export function getSplitBlockType (block: YBlock) {
+ switch (block.get(YjsEditorKey.block_type)) {
+ case BlockType.ToggleListBlock: {
+ const data = dataStringTOJson(block.get(YjsEditorKey.block_data)) as ToggleListBlockData;
+
+ if (!data.collapsed) {
+ return BlockType.Paragraph;
+ } else {
+ return block.get(YjsEditorKey.block_type);
+ }
+ }
+
+ case BlockType.HeadingBlock:
+ case BlockType.QuoteBlock:
+ return BlockType.Paragraph;
+ default:
+ return block.get(YjsEditorKey.block_type);
+ }
+}
+
+export function splitBlock (sharedRoot: YSharedRoot, block: YBlock, offset: number, nextLineDelta: Delta, parentInfo: {
+ parent: YBlock,
+ targetIndex: number,
+ parentChildren: Y.Array<string>
+}) {
+ const { parent, targetIndex, parentChildren } = parentInfo;
+ const yText = getText(block.get(YjsEditorKey.block_external_id), sharedRoot);
+
+ yText.delete(offset, yText.length - offset);
+
+ const newBlock = createBlock(sharedRoot, {
+ ty: getSplitBlockType(block),
+ data: {},
+ });
+
+ const newBlockText = getText(newBlock.get(YjsEditorKey.block_external_id), sharedRoot);
+
+ newBlockText.applyDelta(nextLineDelta.ops);
+
+ const blockType = block.get(YjsEditorKey.block_type);
+
+ if (blockType === BlockType.ToggleListBlock) {
+ const data = dataStringTOJson(block.get(YjsEditorKey.block_data)) as ToggleListBlockData;
+
+ if (!data.collapsed) {
+ const blockChildrenArray = getChildrenArray(block.get(YjsEditorKey.block_children), sharedRoot);
+
+ if (blockChildrenArray) {
+ updateBlockParent(sharedRoot, newBlock, block, 0);
+ }
+
+ return;
+ }
+ } else {
+ transferChildren(sharedRoot, block, newBlock);
+ }
+
+ const index = targetIndex !== -1 ? targetIndex + 1 : parentChildren.length;
+
+ updateBlockParent(sharedRoot, newBlock, parent, index);
+}
+
+function ensureBlockHasChildren (sharedRoot: YSharedRoot, block: YBlock) {
+ const childrenArray = getChildrenArray(block.get(YjsEditorKey.block_children), sharedRoot);
+
+ if (!childrenArray) {
+ const newArray = new Y.Array<string>();
+ const childrenMap = getChildrenMap(sharedRoot);
+
+ childrenMap.set(block.get(YjsEditorKey.block_children), newArray);
+ }
+
+ return getChildrenArray(block.get(YjsEditorKey.block_children), sharedRoot);
+}
+
+export function transferChildren (sharedRoot: YSharedRoot, sourceBlock: YBlock, targetBlock: YBlock) {
+ const sourceChildrenArray = getChildrenArray(sourceBlock.get(YjsEditorKey.block_children), sharedRoot);
+
+ const targetChildrenArray = ensureBlockHasChildren(sharedRoot, targetBlock);
+
+ if (!sourceChildrenArray || !targetChildrenArray) return;
+ if (sourceChildrenArray.length > 0) {
+ deepCopyChildren(sharedRoot, sourceChildrenArray, targetChildrenArray, targetBlock.get(YjsEditorKey.block_id));
+ sourceChildrenArray.toArray().forEach((id) => {
+ deleteBlock(sharedRoot, id);
+ });
+ sourceChildrenArray.delete(0, sourceChildrenArray.length);
+ }
+}
+
+export function executeOperations (sharedRoot: YSharedRoot, operations: (() => void)[], operationName: string) {
+ console.time(operationName);
+ const doc = assertDocExists(sharedRoot);
+
+ doc.transact(() => {
+ operations.forEach((op) => op());
+ });
+
+ console.timeEnd(operationName);
+}
+
+export function dataStringTOJson (data: string): object {
+ try {
+ return JSON.parse(data);
+ } catch (e) {
+ return {};
+ }
+}
+
+function deepCopyChildren (sharedRoot: YSharedRoot, sourceArray: Y.Array<string>, targetArray: Y.Array<string>, targetBlockId: string, index?: number) {
+
+ const sourceArraySorted = index === undefined ? sourceArray.toArray() : sourceArray.toArray().reverse();
+
+ sourceArraySorted.forEach((childId) => {
+ const sourceChild = getBlock(childId, sharedRoot);
+
+ if (sourceChild) {
+ const oldData = dataStringTOJson(sourceChild.get(YjsEditorKey.block_data));
+ const newChild = createBlock(sharedRoot, {
+ ty: sourceChild.get(YjsEditorKey.block_type),
+ data: oldData,
+ });
+
+ const sourceText = getText(sourceChild.get(YjsEditorKey.block_external_id), sharedRoot);
+ const targetText = getText(newChild.get(YjsEditorKey.block_external_id), sharedRoot);
+
+ targetText.applyDelta(sourceText.toDelta());
+
+ const sourceChildrenArray = getChildrenArray(childId, sharedRoot);
+
+ if (sourceChildrenArray && sourceChildrenArray.length > 0) {
+ const newChildrenArray = getChildrenArray(newChild.get(YjsEditorKey.block_children), sharedRoot);
+
+ if (newChildrenArray) {
+ deepCopyChildren(sharedRoot, sourceChildrenArray, newChildrenArray, newChild.get(YjsEditorKey.block_id));
+ }
+ }
+
+ const targetIndex = index !== undefined ? index : targetArray.length;
+
+ updateBlockParent(sharedRoot, newChild, getBlock(targetBlockId, sharedRoot), targetIndex);
+ }
+ });
+}
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/application/types.ts b/frontend/appflowy_web_app/src/application/types.ts
index 2b78a88a92..3527213049 100644
--- a/frontend/appflowy_web_app/src/application/types.ts
+++ b/frontend/appflowy_web_app/src/application/types.ts
@@ -640,12 +640,11 @@ export enum Types {
}
export enum CollabOrigin {
- // from local changes and never sync to remote. used for read-only mode
+ // from local changes
Local = 'local',
// from remote changes and never sync to remote.
Remote = 'remote',
- // from local changes and sync to remote. used for collaborative mode
- LocalSync = 'local_sync',
+
}
export const layoutMap = {
diff --git a/frontend/appflowy_web_app/src/assets/arrow_circle_right.svg b/frontend/appflowy_web_app/src/assets/arrow_circle_right.svg
new file mode 100644
index 0000000000..c17ece66b4
--- /dev/null
+++ b/frontend/appflowy_web_app/src/assets/arrow_circle_right.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M22 12C22 6.48 17.52 2 12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12ZM4 12C4 7.58 7.58 4 12 4C16.42 4 20 7.58 20 12C20 16.42 16.42 20 12 20C7.58 20 4 16.42 4 12ZM16 12L12 16L10.59 14.59L12.17 13H8V11H12.17L10.58 9.41L12 8L16 12Z"
+ fill="currentColor"/>
+</svg>
diff --git a/frontend/appflowy_web_app/src/assets/published_with_changes.svg b/frontend/appflowy_web_app/src/assets/published_with_changes.svg
new file mode 100644
index 0000000000..97da39761d
--- /dev/null
+++ b/frontend/appflowy_web_app/src/assets/published_with_changes.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M18.6 19.4998H21V21.4998H15V15.4998H17V18.2298C18.83 16.7598 20 14.5198 20 11.9998C20 7.9298 16.94 4.5598 13 4.0698V2.0498C18.05 2.5498 22 6.8098 22 11.9998C22 14.9898 20.68 17.6698 18.6 19.4998ZM4 11.9998C4 9.4798 5.17 7.2298 7 5.7698V8.4998H9V2.4998H3V4.4998H5.4C3.32 6.3298 2 9.0098 2 11.9998C2 17.1898 5.95 21.4498 11 21.9498V19.9298C7.06 19.4398 4 16.0698 4 11.9998ZM16.24 8.1098L10.58 13.7698L7.75 10.9398L6.34 12.3498L10.58 16.5898L17.65 9.5198L16.24 8.1098Z"
+ fill="currentColor"/>
+</svg>
diff --git a/frontend/appflowy_web_app/src/components/app/header/RightMenu.tsx b/frontend/appflowy_web_app/src/components/app/header/RightMenu.tsx
index 401b8d35a8..27c8d495f0 100644
--- a/frontend/appflowy_web_app/src/components/app/header/RightMenu.tsx
+++ b/frontend/appflowy_web_app/src/components/app/header/RightMenu.tsx
@@ -1,12 +1,12 @@
import { NormalModal } from '@/components/_shared/modal';
import MoreActions from '@/components/_shared/more-actions/MoreActions';
import { openOrDownload } from '@/utils/open_schema';
-import { EditOutlined } from '@mui/icons-material';
import { Button, Divider, Tooltip } from '@mui/material';
import React from 'react';
import { useTranslation } from 'react-i18next';
import ShareButton from 'src/components/app/share/ShareButton';
import { ReactComponent as Logo } from '@/assets/logo.svg';
+import { ReactComponent as EditOutlined } from '@/assets/edit.svg';
function RightMenu () {
const { t } = useTranslation();
diff --git a/frontend/appflowy_web_app/src/components/app/landing-pages/ApproveRequestPage.tsx b/frontend/appflowy_web_app/src/components/app/landing-pages/ApproveRequestPage.tsx
index 289b1ccd4e..ecfb1a4cc3 100644
--- a/frontend/appflowy_web_app/src/components/app/landing-pages/ApproveRequestPage.tsx
+++ b/frontend/appflowy_web_app/src/components/app/landing-pages/ApproveRequestPage.tsx
@@ -11,7 +11,7 @@ import { notify } from '@/components/_shared/notify';
import { getAvatar } from '@/components/_shared/view-icon/utils';
import { AFConfigContext, useService } from '@/components/main/app.hooks';
import { downloadPage } from '@/utils/url';
-import { ArrowCircleRightOutlined } from '@mui/icons-material';
+import { ReactComponent as ArrowCircleRightOutlined } from '@/assets/arrow_circle_right.svg';
import { Avatar, Button, Divider, Paper, Typography } from '@mui/material';
import React, { useCallback, useContext, useEffect, useMemo } from 'react';
@@ -53,6 +53,7 @@ function ApproveRequestPage () {
setCurrentPlans(plans);
} catch (e) {
setErrorModalOpen(true);
+ setClicked(true);
}
}, [t, requestId, service]);
diff --git a/frontend/appflowy_web_app/src/components/app/share/ShareTabs.tsx b/frontend/appflowy_web_app/src/components/app/share/ShareTabs.tsx
index 3c94190dde..1a8bf25576 100644
--- a/frontend/appflowy_web_app/src/components/app/share/ShareTabs.tsx
+++ b/frontend/appflowy_web_app/src/components/app/share/ShareTabs.tsx
@@ -2,11 +2,11 @@ import { useAppView } from '@/components/app/app.hooks';
import PublishPanel from '@/components/app/share/PublishPanel';
import TemplatePanel from '@/components/app/share/TemplatePanel';
import { useCurrentUser } from '@/components/main/app.hooks';
-import { PublishedWithChanges } from '@mui/icons-material';
import React, { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ViewTabs, ViewTab, TabPanel } from 'src/components/_shared/tabs/ViewTabs';
import { ReactComponent as Templates } from '@/assets/template.svg';
+import { ReactComponent as PublishedWithChanges } from '@/assets/published_with_changes.svg';
enum TabKey {
PUBLISH = 'publish',
diff --git a/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx b/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx
index a29e52c56c..b0df2b64f9 100644
--- a/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/CollaborativeEditor.tsx
@@ -1,3 +1,4 @@
+import { withYHistory } from '@/application/slate-yjs/plugins/withHistory';
import { CollabOrigin } from '@/application/types';
import { withYjs, YjsEditor } from '@/application/slate-yjs/plugins/withYjs';
import EditorEditable from '@/components/editor/Editable';
@@ -13,17 +14,18 @@ const defaultInitialValue: Descendant[] = [];
function CollaborativeEditor ({ doc }: { doc: Y.Doc }) {
const context = useEditorContext();
const readSummary = context.readSummary;
- // if readOnly, collabOrigin is Local, otherwise RemoteSync
- const localOrigin = context.readOnly ? CollabOrigin.Local : CollabOrigin.LocalSync;
+ const localOrigin = CollabOrigin.Local;
const editor = useMemo(
() =>
doc &&
(withPlugins(
withReact(
- withYjs(createEditor(), doc, {
- localOrigin,
- readSummary,
- }),
+ withYHistory(
+ withYjs(createEditor(), doc, {
+ localOrigin,
+ readSummary,
+ }),
+ ),
),
) as YjsEditor),
[readSummary, doc, localOrigin],
diff --git a/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx
new file mode 100644
index 0000000000..b8392189ea
--- /dev/null
+++ b/frontend/appflowy_web_app/src/components/editor/__tests__/behavior/EnterKeyBehavior.cy.tsx
@@ -0,0 +1,1002 @@
+import { mountEditor } from '@/components/editor/__tests__/mount';
+import { DocumentTest, FromBlockJSON } from 'cypress/support/document';
+
+describe('Enter key behavior', () => {
+ beforeEach(() => {
+ cy.viewport(1280, 720);
+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });
+ });
+ let documentTest: DocumentTest;
+
+ const initializeEditor = (data: FromBlockJSON[]) => {
+ documentTest = new DocumentTest();
+ documentTest.fromJSON(data);
+ mountEditor({ readOnly: false, doc: documentTest.doc });
+ cy.get('[role="textbox"]').should('exist');
+ };
+
+ const moveToLineStart = (lineIndex: number) => {
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('targetBlock');
+
+ if (lineIndex === 0) {
+ cy.get('@targetBlock').type('{movetostart}').wait(50);
+ } else {
+ cy.get('@targetBlock').type('{movetostart}').type('{downarrow}'.repeat(lineIndex))
+ .wait(50);
+ }
+ };
+
+ const moveAndEnter = (lineIndex: number, moveCount: number) => {
+ moveToLineStart(lineIndex);
+ // Move the cursor with right arrow key and batch the movement
+ const batchSize = 5;
+ const batches = Math.ceil(moveCount / batchSize);
+
+ for (let i = 0; i < batches; i++) {
+ const remainingMoves = Math.min(batchSize, moveCount - i * batchSize);
+
+ cy.get('@targetBlock')
+ .type('{rightarrow}'.repeat(remainingMoves))
+ .wait(50);
+ }
+
+ cy.get('@targetBlock').type('{enter}');
+ };
+
+ const assertJSON = (expectedJSON: FromBlockJSON[]) => {
+ cy.wrap(null).then(() => {
+ const finalJSON = documentTest.toJSON();
+
+ expect(finalJSON).to.deep.equal(expectedJSON);
+ });
+ };
+
+ it('should split paragraph blocks correctly', () => {
+ const initialData: FromBlockJSON[] = [{
+ type: 'paragraph',
+ data: {},
+ text: [
+ { insert: 'First line ' },
+ { insert: 'bold format ', attributes: { bold: true } },
+ { insert: 'line end.' },
+ ],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second line' }],
+ children: [],
+ }];
+
+ initializeEditor(initialData);
+
+ // Test 1: Split in the middle of a formatted text
+ moveAndEnter(0, 16);
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First line ' }, { insert: 'bold ', attributes: { bold: true } }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'format ', attributes: { bold: true } }, { insert: 'line end.' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second line' }],
+ children: [],
+ }]);
+
+ // Test 2: Split at the end of a paragraph
+ moveAndEnter(2, 7);
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First line ' }, { insert: 'bold ', attributes: { bold: true } }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'format ', attributes: { bold: true } }, { insert: 'line end.' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second ' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'line' }],
+ children: [],
+ }]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-split-paragraph-block');
+ });
+
+ it('should handle enter key correctly with nested paragraphs', () => {
+ const initialData: FromBlockJSON[] = [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Parent paragraph' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph 2' }],
+ children: [],
+ }],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Sibling paragraph' }],
+ children: [],
+ }];
+
+ initializeEditor(initialData);
+
+ // Test 1: Split parent paragraph
+ moveAndEnter(0, 7);
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Parent ' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'paragraph' }],
+ children: initialData[0].children,
+ }, initialData[1]]);
+
+ // Test 2: Split first child paragraph
+ moveAndEnter(2, 6);
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Parent ' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'paragraph' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child ' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'paragraph 1' }],
+ children: [],
+ }, initialData[0].children[1]],
+ }, initialData[1]]);
+
+ // Test 3: Split last child paragraph and create a new sibling
+ moveAndEnter(4, 10);
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Parent ' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'paragraph' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child ' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'paragraph 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child para' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'graph 2' }],
+ children: [],
+ }],
+ }, initialData[1]]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-nested-paragraphs');
+ });
+
+ it('should handle enter key correctly with toggle_list', () => {
+ const initialData: FromBlockJSON[] = [{
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list item' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 2' }],
+ children: [],
+ }],
+ }];
+
+ initializeEditor(initialData);
+
+ // Test 1: Press enter at the end of toggle_list text
+ moveAndEnter(0, 16);
+ assertJSON([{
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list item' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 2' }],
+ children: [],
+ }],
+ }]);
+
+ // Test 2: Press enter in the middle of toggle_list text
+ moveAndEnter(0, 6);
+ assertJSON([{
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: ' list item' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 2' }],
+ children: [],
+ }],
+ }]);
+
+ // Test 3: Press enter at the start of toggle_list text
+ moveAndEnter(0, 0);
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: [],
+ }, {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: ' list item' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Existing child 2' }],
+ children: [],
+ }],
+ }]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-toggle-list');
+
+ });
+
+ it('should handle enter key correctly with toggle_list is collapsed', () => {
+ const collapsedToggleListData: FromBlockJSON[] = [{
+ type: 'toggle_list',
+ data: { collapsed: true },
+ text: [{ insert: 'Collapsed toggle list' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child that should not be inherited' }],
+ children: [],
+ }],
+ }];
+
+ initializeEditor(collapsedToggleListData);
+
+ moveAndEnter(0, 21); // Move to the end of "Collapsed toggle list"
+ assertJSON([{
+ type: 'toggle_list',
+ data: { collapsed: true },
+ text: [{ insert: 'Collapsed toggle list' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child that should not be inherited' }],
+ children: [],
+ }],
+ }, {
+ type: 'toggle_list',
+ data: {},
+ text: [],
+ children: [],
+ }]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-toggle-list-collapsed');
+ });
+
+ it('should handle enter key on the empty block but not the paragraph block', () => {
+ const initialData: FromBlockJSON[] = [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First paragraph' }],
+ children: [],
+ }, {
+ type: 'todo_list',
+ data: {
+ checked: true,
+ },
+ text: [{ insert: 'Todo list item' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph' }],
+ children: [],
+ }],
+ }];
+
+ initializeEditor(initialData);
+
+ // Test 1: Press enter at the start of the todo_list block
+ moveAndEnter(1, 0);
+
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First paragraph' }],
+ children: [],
+ }, {
+ type: 'todo_list',
+ data: {
+ checked: true,
+ },
+ text: [],
+ children: [],
+ }, {
+ type: 'todo_list',
+ data: {
+ checked: true,
+ },
+ text: [{ insert: 'Todo list item' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph' }],
+ children: [],
+ }],
+ }]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-empty-block');
+
+ // Test 2: Press enter at the start of the empty todo_list block
+ moveAndEnter(1, 0);
+
+ assertJSON([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First paragraph' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [],
+ children: [],
+ }, {
+ type: 'todo_list',
+ data: {
+ checked: true,
+ },
+ text: [{ insert: 'Todo list item' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph' }],
+ children: [],
+ }],
+ }]);
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-empty-block-2');
+ });
+
+ describe('Enter key behavior with range selections', () => {
+ const simpleInitialData: FromBlockJSON[] = [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Third paragraph' }],
+ children: [],
+ },
+ ];
+
+ const nestedInitialData: 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: '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: [],
+ },
+ ];
+
+ it('should handle range selection within a single block', () => {
+ initializeEditor(simpleInitialData);
+ moveToLineStart(0);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+
+ cy.get('@editor').selectText('rst para');
+ cy.get('@editor').type('{enter}');
+
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Fi' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'graph' }],
+ children: [],
+ },
+
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Third paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-single-block');
+ });
+
+ it('should handle range selection across two blocks', () => {
+ initializeEditor(simpleInitialData);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+
+ cy.selectMultipleText(['st paragraph', 'Second para']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{enter}');
+
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Fir' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'graph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Third paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-across-blocks');
+ });
+
+ it('should handle range selection across same level blocks', () => {
+ initializeEditor(nestedInitialData);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ cy.selectMultipleText(['paragraph 1', 'Nested paragraph 2']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{enter}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nested ' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: '.' }],
+ children: [],
+ },
+ ],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-same-level-blocks');
+ });
+
+ it('should handle range selection with different anchor and focus order', () => {
+ initializeEditor(nestedInitialData);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ cy.selectMultipleText(['paragraph 1', 'Deeply nested']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{enter}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nested ' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: ' paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nested paragraph 2.' }],
+ children: [],
+ },
+ ],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-different-anchor-focus');
+ });
+
+ it('should split nested paragraph when selection spans from outer to nested paragraph', () => {
+ initializeEditor(nestedInitialData);
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ cy.selectMultipleText(['ter paragraph', 'Nested paragraph']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{enter}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Ou' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: ' 1' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-different-nesting-levels-1');
+
+ });
+
+ it('should split toggle list and maintain nested structure when selection spans multiple nesting levels', () => {
+ initializeEditor([{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ }, {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: '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 selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ cy.selectMultipleText(['ed paragraph', 'Nested to']);
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{enter}');
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'toggle_list',
+ data: {},
+ text: [{ insert: 'Toggle list' }],
+ children: [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Nest' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'ggle 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: [],
+ },
+ ]);
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-different-nesting-levels-2');
+ });
+
+ it('should split paragraphs and maintain child structure when selection spans across parent paragraphs', () => {
+ const initialData: FromBlockJSON[] = [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First parent' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First parent - Child paragraph 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First parent - Child paragraph 2' }],
+ children: [],
+ }],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second parent' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second parent - Child paragraph 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second parent - Child paragraph 2' }],
+ children: [],
+ }],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ];
+
+ initializeEditor(initialData);
+
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+
+ cy.selectMultipleText(['st parent', 'Second ']);
+
+ cy.wait(500);
+ cy.get('@editor').focus();
+
+ cy.get('@editor').type('{enter}');
+
+ assertJSON([
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Outer paragraph' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Fir' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'parent' }],
+ children: [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second parent - Child paragraph 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Second parent - Child paragraph 2' }],
+ children: [],
+ }],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Final outer paragraph' }],
+ children: [],
+ },
+ ]);
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-different-nesting-levels-3');
+ });
+
+ it('should split heading and paragraph while preserving nested structure when selection spans different block types', () => {
+ const initialData: FromBlockJSON[] = [{
+ type: 'heading',
+ data: { level: 1 },
+ text: [{ insert: 'Heading 1' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'First paragraph' }],
+ children: [{
+ type: 'heading',
+ data: { level: 2 },
+ text: [{ insert: 'Heading 2' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph' }],
+ children: [],
+ }],
+ }];
+
+ initializeEditor(initialData);
+
+ const selector = '[role="textbox"]';
+
+ cy.get(selector).as('editor');
+ cy.selectMultipleText(['ing 1', 'First ']);
+
+ cy.wait(500);
+ cy.get('@editor').focus();
+ cy.get('@editor').type('{enter}');
+ assertJSON([
+ {
+ type: 'heading',
+ data: { level: 1 },
+ text: [{ insert: 'Head' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'paragraph' }],
+ children: [],
+ }, {
+ type: 'heading',
+ data: { level: 2 },
+ text: [{ insert: 'Heading 2' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Child paragraph' }],
+ children: [],
+ },
+ ]);
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('behavior/enter-key-behavior-range-selection-different-nesting-levels-4');
+ });
+
+ });
+});
+
diff --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.tsx
index 869bfc6381..22d5747f0f 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
@@ -4,6 +4,7 @@ import { DocumentTest, FromBlockJSON } from 'cypress/support/document';
describe('<Paragraph />', () => {
beforeEach(() => {
cy.viewport(1280, 720);
+ Object.defineProperty(window.navigator, 'language', { value: 'en-US' });
});
it('render paragraph', () => {
@@ -21,24 +22,228 @@ describe('<Paragraph />', () => {
it('edit paragraph text', () => {
const documentTest = new DocumentTest();
+ const data: FromBlockJSON[] = [{
+ type: 'paragraph',
+ data: {},
+ text: [
+ { insert: 'Hello, ' },
+ {
+ insert: 'world!', 'attributes': {
+ 'italic': true,
+ 'underline': true,
+ 'strikethrough': true,
+ 'font_color': '#ff0000',
+ 'bg_color': '#00ff00',
+ },
+ },
+ { insert: ' This is a ' },
+ {
+ insert: 'bold', 'attributes': {
+ 'bold': true,
+ },
+ },
+ { insert: ' text.' },
+ ],
+ children: [],
+ }];
+
+ documentTest.fromJSON(data);
+
+ mountEditor({ readOnly: false, doc: documentTest.doc });
- cy.fixture<FromBlockJSON[]>('editor/blocks/paragraph').then((data) => {
- documentTest.fromJSON(data);
- mountEditor({ readOnly: false, doc: documentTest.doc });
- }).as('documentTest');
cy.get('[role="textbox"]').should('exist');
- cy.get('[role="textbox"]').type('{selectall}').type('{rightarrow}')
- .type('New text at the end');
- cy.get('[role="textbox"]')
- .type('{movetoend}')
- .type('{leftarrow}'.repeat(10))
- .type('{backspace}'.repeat(5)).type('add').type('{backspace}'.repeat(2));
+
+ cy.get('[role="textbox"]').type('{movetostart}').type('{rightarrow}'.repeat(10))
+ .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(() => {
+ const finalJSON = documentTest.toJSON();
+ const expectJSON = [{
+ type: 'paragraph',
+ data: {},
+ text: [
+ { insert: 'Hello, ' },
+ {
+ insert: 'wor New text at the `world` middle ld!',
+ attributes: {
+ italic: true,
+ underline: true,
+ strikethrough: true,
+ font_color: '#ff0000',
+ bg_color: '#00ff00',
+ },
+ },
+ { insert: ' This is a text.' },
+ ],
+ children: [],
+ }];
+
+ expect(finalJSON).to.deep.equal(expectJSON);
+ });
+ // Optional: Add visual regression test
cy.matchImageSnapshot('paragraph/editing-text');
+ });
+
+ it('edit paragraphs with undo and redo', () => {
+ const documentTest = new DocumentTest();
+ const initialData: FromBlockJSON[] = [{
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world!' }],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world! New at the end' }],
+ children: [],
+ }];
+
+ documentTest.fromJSON(initialData);
+ mountEditor({ readOnly: false, doc: documentTest.doc });
+
+ cy.get('[role="textbox"]').should('exist');
+
+ // Initial edit: Add text to the end of the second paragraph
+ cy.get('[role="textbox"]').children().eq(1).type('{movetoend} More text');
+
+ // Check the result of the initial edit
+ cy.wrap(null).then(() => {
+ const editedJSON = documentTest.toJSON();
+ const expectedEditedJSON = [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world!' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world! New at the end More text' }],
+ children: [],
+ },
+ ];
+
+ expect(editedJSON).to.deep.equal(expectedEditedJSON);
+ });
- cy.then(() => {
- console.log('====', documentTest.doc.getMap('data').toJSON());
+ // Perform undo operation
+ if (Cypress.platform === 'darwin') {
+ cy.get('body').type('{cmd}z');
+ } else {
+ cy.get('body').type('{ctrl}z');
+ }
+
+ // Check the result after undo
+ cy.wrap(null).then(() => {
+ const undoneJSON = documentTest.toJSON();
+
+ expect(undoneJSON).to.deep.equal(initialData);
+ });
+
+ // Perform redo operation
+ if (Cypress.platform === 'darwin') {
+ cy.get('body').type('{cmd}{shift}z');
+ } else {
+ cy.get('body').type('{ctrl}y');
+ }
+
+ // Check the result after redo
+ cy.wrap(null).then(() => {
+ const redoneJSON = documentTest.toJSON();
+ const expectedRedoneJSON = [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world!' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world! New at the end More text' }],
+ children: [],
+ },
+ ];
+
+ expect(redoneJSON).to.deep.equal(expectedRedoneJSON);
+ });
+
+ // Perform additional edits: Modify the first paragraph
+ cy.get('[role="textbox"]').children().eq(0).type('{selectall}').type('{rightarrow}').type(' Additional content');
+
+ // Check the final result
+ cy.wrap(null).then(() => {
+ const finalJSON = documentTest.toJSON();
+ const expectedFinalJSON = [
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world! Additional content' }],
+ children: [],
+ },
+ {
+ type: 'paragraph',
+ data: {},
+ text: [{ insert: 'Hello, world! New at the end More text' }],
+ children: [],
+ },
+ ];
+
+ expect(finalJSON).to.deep.equal(expectedFinalJSON);
});
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('paragraph/editing-text-with-undo-redo');
});
+
+ it('render inline formatting', () => {
+ const documentTest = new DocumentTest();
+ const data: FromBlockJSON[] = [{
+ type: 'paragraph',
+ data: {},
+ text: [
+ { insert: 'Hello, ' },
+ {
+ insert: 'world!', 'attributes': {
+ 'italic': true,
+ 'underline': true,
+ 'strikethrough': true,
+ 'font_color': '#ff0000',
+ 'bg_color': '#00ff00',
+ },
+ },
+ { insert: ' This is a ' },
+ {
+ insert: 'bold', 'attributes': {
+ 'bold': true,
+ },
+ },
+ { insert: ' text.' },
+ ],
+ children: [],
+ }, {
+ type: 'paragraph',
+ data: {},
+ text: [
+ { insert: 'This is a date: ' },
+ { insert: '@', attributes: { mention: { type: 'date', 'date': Date.now().valueOf() } } },
+ { insert: 'This is a formula: ' },
+ { insert: '$', attributes: { formula: 'E=mc^2' } },
+ { insert: ' .' },
+ ],
+ children: [],
+ }];
+
+ documentTest.fromJSON(data);
+ mountEditor({ readOnly: false, doc: documentTest.doc });
+
+ // Optional: Add visual regression test
+ cy.matchImageSnapshot('paragraph/inline-formatting');
+
+ });
+
});
export {};
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/bulleted-list/BulletedListIcon.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/bulleted-list/BulletedListIcon.tsx
index 3fee74bfad..cfef8a3c99 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/bulleted-list/BulletedListIcon.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/bulleted-list/BulletedListIcon.tsx
@@ -1,7 +1,7 @@
import { BulletedListNode } from '@/components/editor/editor.type';
import { getListLevel } from '@/components/editor/utils/list';
import React, { useMemo } from 'react';
-import { ReactEditor, useSlateStatic } from 'slate-react';
+import { ReactEditor, useSlate } from 'slate-react';
import { ReactComponent as DiscIcon } from '@/assets/bulleted_list_icon_1.svg';
import { ReactComponent as CircleIcon } from '@/assets/bulleted_list_icon_2.svg';
import { ReactComponent as SquareIcon } from '@/assets/bulleted_list_icon_3.svg';
@@ -12,8 +12,8 @@ enum Letter {
Square,
}
-export function BulletedListIcon({ block, className }: { block: BulletedListNode; className: string }) {
- const staticEditor = useSlateStatic();
+export function BulletedListIcon ({ block, className }: { block: BulletedListNode; className: string }) {
+ const staticEditor = useSlate();
const path = ReactEditor.findPath(staticEditor, block);
const letter = useMemo(() => {
diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/numbered-list/NumberListIcon.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/numbered-list/NumberListIcon.tsx
index d8eb22a2ec..b27c1db120 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/numbered-list/NumberListIcon.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/numbered-list/NumberListIcon.tsx
@@ -1,7 +1,7 @@
import { NumberedListNode } from '@/components/editor/editor.type';
import { getListLevel, letterize, romanize } from '@/components/editor/utils/list';
import React, { useMemo } from 'react';
-import { ReactEditor, useSlate, useSlateStatic } from 'slate-react';
+import { ReactEditor, useSlate } from 'slate-react';
import { Element, Path } from 'slate';
enum Letter {
@@ -10,7 +10,7 @@ enum Letter {
Roman = 'roman',
}
-function getLetterNumber(index: number, letter: Letter) {
+function getLetterNumber (index: number, letter: Letter) {
if (letter === Letter.Number) {
return index;
} else if (letter === Letter.Letter) {
@@ -20,9 +20,8 @@ function getLetterNumber(index: number, letter: Letter) {
}
}
-export function NumberListIcon({ block, className }: { block: NumberedListNode; className: string }) {
+export function NumberListIcon ({ block, className }: { block: NumberedListNode; className: string }) {
const editor = useSlate();
- const staticEditor = useSlateStatic();
const path = ReactEditor.findPath(editor, block);
@@ -66,7 +65,7 @@ export function NumberListIcon({ block, className }: { block: NumberedListNode;
}, [editor, block, path]);
const letter = useMemo(() => {
- const level = getListLevel(staticEditor, block.type, path);
+ const level = getListLevel(editor, block.type, path);
if (level % 3 === 0) {
return Letter.Number;
@@ -75,7 +74,7 @@ export function NumberListIcon({ block, className }: { block: NumberedListNode;
} else {
return Letter.Roman;
}
- }, [block.type, staticEditor, path]);
+ }, [block.type, editor, path]);
const dataNumber = useMemo(() => {
return getLetterNumber(index, letter);
diff --git a/frontend/appflowy_web_app/src/components/editor/components/blocks/text/Text.tsx b/frontend/appflowy_web_app/src/components/editor/components/blocks/text/Text.tsx
index 8a500c1689..e3a228c1b5 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/blocks/text/Text.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/blocks/text/Text.tsx
@@ -17,12 +17,23 @@ export const Text = forwardRef<HTMLSpanElement, EditorElementProps<TextNode>>(
return classList.join(' ');
}, [classNameProp, hasStartIcon]);
+ const placeholder = useMemo(() => {
+ if (!isEmpty) return null;
+ return <Placeholder node={node} />;
+ }, [isEmpty, node]);
+
+ const content = useMemo(() => {
+ return <>
+ {placeholder}
+ <span className={`text-content ${isEmpty ? 'empty-text' : ''}`}>{children}</span>
+ </>;
+ }, [placeholder, isEmpty, children]);
+
return (
<span {...attributes} ref={ref} className={className}>
{renderIcon()}
- {isEmpty && <Placeholder node={node} />}
- <span className={`text-content ${isEmpty ? 'empty-text' : ''}`}>{children}</span>
+ {content}
</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.tsx
index b6ebfffe03..80c2aa6348 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
@@ -1,18 +1,43 @@
+import { YjsEditor } from '@/application/slate-yjs';
+import { CustomEditor } from '@/application/slate-yjs/command';
import { ToggleListNode } from '@/components/editor/editor.type';
-import React from 'react';
+import { debounce } from 'lodash-es';
+import React, { useCallback, useMemo } from 'react';
import { ReactComponent as ExpandSvg } from '$icons/16x/drop_menu_show.svg';
+import { useReadOnly, useSlateStatic } from 'slate-react';
-function ToggleIcon({ block, className }: { block: ToggleListNode; className: string }) {
+function ToggleIcon ({ block, className }: { block: ToggleListNode; className: string }) {
const { collapsed } = block.data;
+ const editor = useSlateStatic();
+ const readOnly = useReadOnly();
+
+ const toggleCollapsed = useMemo(() => {
+ if (readOnly) {
+ return;
+ }
+
+ return debounce(() => {
+ CustomEditor.setBlockData(editor as YjsEditor, block.blockId, {
+ collapsed: !collapsed,
+ }, true);
+ }, 100);
+ }, [readOnly, editor, block.blockId, collapsed]);
+
+ const handleClick = useCallback((e: React.MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ toggleCollapsed?.();
+ }, [toggleCollapsed]);
return (
<span
+ onClick={handleClick}
data-playwright-selected={false}
contentEditable={false}
onMouseDown={(e) => {
e.preventDefault();
}}
- className={`${className} pr-1 text-xl hover:text-fill-default`}
+ className={`${className} ${readOnly ? '' : 'cursor-pointer'} pr-1 text-xl hover:text-fill-default`}
>
{collapsed ? <ExpandSvg className={'-rotate-90 transform'} /> : <ExpandSvg />}
</span>
diff --git a/frontend/appflowy_web_app/src/components/editor/components/element/Element.tsx b/frontend/appflowy_web_app/src/components/editor/components/element/Element.tsx
index 719285bbf8..83db4a296c 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/element/Element.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/element/Element.tsx
@@ -1,4 +1,4 @@
-import { BlockData, BlockType, InlineBlockType, YjsEditorKey } from '@/application/types';
+import { BlockData, BlockType, YjsEditorKey } from '@/application/types';
import { BulletedList } from '@/components/editor/components/blocks/bulleted-list';
import { Callout } from '@/components/editor/components/blocks/callout';
import { CodeBlock } from '@/components/editor/components/blocks/code';
@@ -23,8 +23,6 @@ import smoothScrollIntoViewIfNeeded from 'smooth-scroll-into-view-if-needed';
import { TodoList } from 'src/components/editor/components/blocks/todo-list';
import { ToggleList } from 'src/components/editor/components/blocks/toggle-list';
import { UnSupportedBlock } from '@/components/editor/components/element/UnSupportedBlock';
-import { Formula } from '@/components/editor/components/leaf/formula';
-import { Mention } from '@/components/editor/components/leaf/mention';
import { FileBlock } from '@/components/editor/components/blocks/file';
import { EditorElementProps, TextNode } from '@/components/editor/editor.type';
import { renderColor } from '@/utils/color';
@@ -112,17 +110,6 @@ export const Element = ({
}
}, [node.type]) as FC<EditorElementProps>;
- const InlineComponent = useMemo(() => {
- switch (node.type) {
- case InlineBlockType.Formula:
- return Formula;
- case InlineBlockType.Mention:
- return Mention;
- default:
- return null;
- }
- }, [node.type]) as FC<EditorElementProps>;
-
const className = useMemo(() => {
const data = (node.data as BlockData) || {};
const align = data.align;
@@ -139,14 +126,6 @@ export const Element = ({
};
}, [node.data]);
- if (InlineComponent) {
- return (
- <InlineComponent {...attributes} node={node}>
- {children}
- </InlineComponent>
- );
- }
-
if (node.type === YjsEditorKey.text) {
return (
<Text {...attributes} node={node as TextNode}>
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.tsx
index 38ba65e3f2..9389b1e1bc 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
@@ -1,10 +1,13 @@
+import { Mention } from '@/application/types';
+import FormulaLeaf from '@/components/editor/components/leaf/formula/FormulaLeaf';
import { Href } from '@/components/editor/components/leaf/href';
+import MentionLeaf from '@/components/editor/components/leaf/mention/MentionLeaf';
import { getFontFamily } from '@/utils/font';
import React, { CSSProperties } from 'react';
import { RenderLeafProps } from 'slate-react';
import { renderColor } from '@/utils/color';
-export function Leaf({ attributes, children, leaf }: RenderLeafProps) {
+export function Leaf ({ attributes, children, leaf, text }: RenderLeafProps) {
let newChildren = children;
const classList = [leaf.prism_token, leaf.prism_token && 'token', leaf.class_name].filter(Boolean);
@@ -47,6 +50,21 @@ export function Leaf({ attributes, children, leaf }: RenderLeafProps) {
style['fontFamily'] = getFontFamily(leaf.font_family);
}
+ if (leaf.mention || leaf.formula) {
+ style['position'] = 'relative';
+ const node = leaf.mention ? <MentionLeaf
+ text={text}
+ mention={leaf.mention as Mention}
+ /> : leaf.formula ? <FormulaLeaf formula={leaf.formula} text={text} /> : null;
+
+ newChildren = <>
+ {node}
+ <span className={'absolute opacity-0 left-0'}>
+ {newChildren}
+ </span>
+ </>;
+ }
+
return (
<span {...attributes} style={style} className={`${classList.join(' ')}`}>
{newChildren}
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/Formula.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/Formula.tsx
deleted file mode 100644
index fd1a4766ff..0000000000
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/Formula.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { KatexMath } from '@/components/_shared/katex-math';
-import { EditorElementProps, FormulaNode } from '@/components/editor/editor.type';
-import React, { memo, forwardRef } from 'react';
-import { useSelected } from 'slate-react';
-
-export const Formula = memo(
- forwardRef<HTMLSpanElement, EditorElementProps<FormulaNode>>(({ node, children, ...attributes }, ref) => {
- const formula = node.data;
- const selected = useSelected();
-
- return (
- <span
- ref={ref}
- {...attributes}
- // contentEditable={false}
- className={`${attributes.className ?? ''} formula-inline relative cursor-pointer rounded py-0.5 ${
- selected ? 'selected' : ''
- }`}
- >
- <span className={''}>
- <KatexMath latex={formula || ''} isInline />
- </span>
-
- <span className={'absolute left-0 right-0 h-0 w-0 opacity-0'}>{children}</span>
- </span>
- );
- })
-);
-
-export default Formula;
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.tsx
new file mode 100644
index 0000000000..2220fe190b
--- /dev/null
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/FormulaLeaf.tsx
@@ -0,0 +1,35 @@
+import { KatexMath } from '@/components/_shared/katex-math';
+import { useLeafSelected } from '@/components/editor/components/leaf/leaf.hooks';
+import React, { useMemo } from 'react';
+import { Text } from 'slate';
+import { useReadOnly } from 'slate-react';
+
+function FormulaLeaf ({ formula, text }: {
+ formula: string;
+ text: Text;
+}) {
+ const { isSelected, select } = useLeafSelected(text);
+ const readonly = useReadOnly();
+ const className = useMemo(() => {
+ const classList = ['formula-inline', 'relative', 'rounded', 'p-0.5'];
+
+ if (readonly) classList.push('cursor-default');
+ else classList.push('cursor-pointer');
+ if (isSelected) classList.push('selected');
+ return classList.join(' ');
+ }, [readonly, isSelected]);
+
+ return (
+ <span
+ onClick={e => {
+ e.preventDefault();
+ select();
+ }}
+ contentEditable={false} className={className}
+ >
+ <KatexMath latex={formula || ''} isInline />
+ </span>
+ );
+}
+
+export default FormulaLeaf;
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/index.ts b/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/index.ts
index dc4ad2cd03..089c07004b 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/index.ts
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/formula/index.ts
@@ -1 +1 @@
-export * from './Formula';
+export * from './FormulaLeaf';
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.ts
new file mode 100644
index 0000000000..3ff5afd975
--- /dev/null
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/leaf.hooks.ts
@@ -0,0 +1,45 @@
+import { useCallback, useMemo } from 'react';
+import { Editor, Range, Text, Transforms } from 'slate';
+import { ReactEditor, useReadOnly, useSelected, useSlate } from 'slate-react';
+
+export function useLeafSelected (text: Text) {
+ const readonly = useReadOnly();
+ const editor = useSlate();
+ const elementIsSelected = useSelected();
+ const selection = editor.selection;
+
+ 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);
+
+ // check if the selection is inside the mention
+ return !!(Range.intersection(selection, {
+ anchor: start,
+ focus: end,
+ }));
+ }, [editor, elementIsSelected, readonly, selection, text]);
+
+ const select = useCallback(() => {
+ if (readonly || !text) return;
+
+ const path = ReactEditor.findPath(editor, text);
+ const start = Editor.start(editor, path);
+
+ ReactEditor.focus(editor);
+ Transforms.select(editor, {
+ anchor: start,
+ focus: Editor.end(editor, path),
+ });
+
+ }, [editor, readonly, text]);
+
+ return {
+ isSelected,
+ select,
+ };
+}
\ No newline at end of file
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/Mention.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/Mention.tsx
deleted file mode 100644
index 540a7ce17e..0000000000
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/Mention.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { EditorElementProps, MentionNode } from '@/components/editor/editor.type';
-import React, { forwardRef, memo } from 'react';
-import { useSelected } from 'slate-react';
-
-import MentionLeaf from './MentionLeaf';
-
-export const Mention = memo(
- forwardRef<HTMLSpanElement, EditorElementProps<MentionNode>>(({ node, children, ...attributes }, ref) => {
- const selected = useSelected();
-
- return (
- <span
- {...attributes}
- // contentEditable={false}
- className={`mention relative cursor-pointer ${selected ? 'selected' : ''}`}
- ref={ref}
- >
- <span className={'absolute right-0 top-0 h-full w-0 opacity-0'}>{children}</span>
- <MentionLeaf mention={node.data} />
- </span>
- );
- })
-);
-
-export default Mention;
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionDate.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionDate.tsx
index 89ec879784..2fdb25db9e 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionDate.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionDate.tsx
@@ -3,13 +3,13 @@ import React, { useMemo } from 'react';
import { ReactComponent as DateSvg } from '@/assets/date.svg';
import { ReactComponent as ReminderSvg } from '@/assets/clock_alarm.svg';
-function MentionDate({ date, reminder }: { date: string; reminder?: { id: string; option: string } }) {
+function MentionDate ({ date, reminder }: { date: string; reminder?: { id: string; option: string } }) {
const dateFormat = useMemo(() => {
return renderDate(date, 'MMM D, YYYY');
}, [date]);
return (
- <span className={'mention-inline cursor-text'}>
+ <span className={'mention-inline'}>
{reminder ? <ReminderSvg className={'mention-icon'} /> : <DateSvg className={'mention-icon'} />}
<span className={'mention-content'}>{dateFormat}</span>
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionLeaf.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionLeaf.tsx
index 3f1f18b82c..d62e846dec 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionLeaf.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionLeaf.tsx
@@ -1,24 +1,50 @@
import { Mention, MentionType } from '@/application/types';
+import { useLeafSelected } from '@/components/editor/components/leaf/leaf.hooks';
import MentionDate from '@/components/editor/components/leaf/mention/MentionDate';
import MentionPage from '@/components/editor/components/leaf/mention/MentionPage';
import { useMemo } from 'react';
+import { Text } from 'slate';
+import { useReadOnly } from 'slate-react';
-export function MentionLeaf({ mention }: { mention: Mention }) {
+export function MentionLeaf ({ mention, text }: {
+ mention: Mention;
+ text: Text;
+}) {
+ const readonly = useReadOnly();
const { type, date, page_id, reminder_id, reminder_option } = mention;
const reminder = useMemo(() => {
return reminder_id ? { id: reminder_id ?? '', option: reminder_option ?? '' } : undefined;
}, [reminder_id, reminder_option]);
- if (type === MentionType.PageRef && page_id) {
- return <MentionPage pageId={page_id} />;
- }
+ const content = useMemo(() => {
+ if (type === MentionType.PageRef && page_id) {
+ return <MentionPage pageId={page_id} />;
+ }
- if (type === MentionType.Date && date) {
- return <MentionDate date={date} reminder={reminder} />;
- }
+ if (type === MentionType.Date && date) {
+ return <MentionDate date={date} reminder={reminder} />;
+ }
+ }, [date, page_id, reminder, type]);
- return null;
+ // check if the mention is selected
+ const { isSelected, select } = useLeafSelected(text);
+ const className = useMemo(() => {
+ const classList = ['w-fit mention', 'relative', 'rounded', 'p-0.5'];
+
+ if (readonly) classList.push('cursor-default');
+ else classList.push('cursor-pointer');
+
+ if (isSelected) classList.push('selected');
+ return classList.join(' ');
+ }, [readonly, isSelected]);
+
+ return <span
+ onClick={select}
+ contentEditable={false} className={className}
+ >
+ {content}
+ </span>;
}
export default MentionLeaf;
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionPage.tsx b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionPage.tsx
index 650adcd46b..f2bc154bd3 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionPage.tsx
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/MentionPage.tsx
@@ -43,9 +43,10 @@ function MentionPage ({ pageId }: { pageId: string }) {
}}
className={`mention-inline px-1 underline`}
contentEditable={false}
+ data-mention-id={pageId}
>
{unPublished ? (
- <span className={'mention-unpublished cursor-text font-semibold text-text-caption'}>No Access</span>
+ <span className={'mention-unpublished font-semibold text-text-caption'}>No Access</span>
) : (
<>
<span className={`mention-icon ${isFlag ? 'icon' : ''}`}>
diff --git a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/index.ts b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/index.ts
index d3ee18034d..5548365ee8 100644
--- a/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/index.ts
+++ b/frontend/appflowy_web_app/src/components/editor/components/leaf/mention/index.ts
@@ -1 +1 @@
-export * from './Mention';
+export * from './MentionLeaf';
diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/index.ts b/frontend/appflowy_web_app/src/components/editor/plugins/index.ts
index 4a87275330..7f0bdfe085 100644
--- a/frontend/appflowy_web_app/src/components/editor/plugins/index.ts
+++ b/frontend/appflowy_web_app/src/components/editor/plugins/index.ts
@@ -1,6 +1,6 @@
-import { withInlines } from '@/components/editor/plugins/withInlineElement';
+import { withInsertBreak } from '@/components/editor/plugins/withInsertBreak';
import { ReactEditor } from 'slate-react';
-export function withPlugins(editor: ReactEditor) {
- return withInlines(editor);
+export function withPlugins (editor: ReactEditor) {
+ return withInsertBreak(editor);
}
diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/withInlineElement.ts b/frontend/appflowy_web_app/src/components/editor/plugins/withInlineElement.ts
deleted file mode 100644
index cd4794db8b..0000000000
--- a/frontend/appflowy_web_app/src/components/editor/plugins/withInlineElement.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { InlineBlockType } from '@/application/types';
-import { ReactEditor } from 'slate-react';
-import { Element } from 'slate';
-
-export function withInlines(editor: ReactEditor) {
- const { isInline, isElementReadOnly, isSelectable, isVoid, markableVoid } = editor;
-
- const matchInlineType = (element: Element) => {
- return Object.values(InlineBlockType).includes(element.type as InlineBlockType);
- };
-
- editor.isInline = (element) => {
- return matchInlineType(element) || isInline(element);
- };
-
- editor.isVoid = (element) => {
- return matchInlineType(element) || isVoid(element);
- };
-
- editor.markableVoid = (element) => {
- return matchInlineType(element) || markableVoid(element);
- };
-
- editor.isElementReadOnly = (element) =>
- Object.values(InlineBlockType).includes(element.type as InlineBlockType) || isElementReadOnly(element);
-
- editor.isSelectable = (element) =>
- !Object.values(InlineBlockType).includes(element.type as InlineBlockType) && isSelectable(element);
-
- return editor;
-}
diff --git a/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.ts b/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.ts
new file mode 100644
index 0000000000..7f280a0225
--- /dev/null
+++ b/frontend/appflowy_web_app/src/components/editor/plugins/withInsertBreak.ts
@@ -0,0 +1,18 @@
+import { YjsEditor } from '@/application/slate-yjs';
+import { CustomEditor } from '@/application/slate-yjs/command';
+import { ReactEditor } from 'slate-react';
+
+export function withInsertBreak (editor: ReactEditor) {
+ const { insertBreak } = editor;
+
+ editor.insertBreak = () => {
+ if (editor.isElementReadOnly(editor)) {
+ insertBreak();
+ return;
+ }
+
+ CustomEditor.insertBreak(editor as YjsEditor);
+ };
+
+ return editor;
+}
diff --git a/frontend/appflowy_web_app/src/slate-editor.d.ts b/frontend/appflowy_web_app/src/slate-editor.d.ts
index 58b7c8502e..b967276057 100644
--- a/frontend/appflowy_web_app/src/slate-editor.d.ts
+++ b/frontend/appflowy_web_app/src/slate-editor.d.ts
@@ -16,9 +16,11 @@ interface EditorInlineAttributes {
mention?: {
type: string;
// inline page ref id
- page?: string;
+ page_id?: string;
// reminder date ref id
date?: string;
+ reminder_id?: string;
+ reminder_option?: string;
};
}