Open-source and local-first Slack and Notion alternative that puts you in control of your data
TypeScript chatchat-applicationcrdteditorelectronknowledge-baselocal-firstnotionnotion-alternativerealtime-collaborationself-hostedslacksqliteteam-collaborationwikiyjs
Implement undo & redo for document editor (#83)
Hakan Shehu3f3c7b3719b2
diff --git a/packages/crdt/src/index.ts b/packages/crdt/src/index.tsindex 53ad7ad8..af8c1d8a 100644--- a/packages/crdt/src/index.ts+++ b/packages/crdt/src/index.ts@@ -15,11 +15,18 @@ export const decodeState = (state: string) => {return toUint8Array(state);};+const ORIGIN = 'this';+export class YDoc {private readonly doc: Y.Doc;+ private readonly undoManager: Y.UndoManager;constructor(state?: Uint8Array | string | Uint8Array[] | string[]) {this.doc = new Y.Doc();+ this.undoManager = new Y.UndoManager(this.doc, {+ trackedOrigins: new Set([ORIGIN]),+ });+if (state) {if (Array.isArray(state)) {for (const update of state) {@@ -65,7 +72,7 @@ export class YDoc {if (!parseResult.success) {throw new Error('Invalid object', parseResult.error);}- });+ }, ORIGIN);this.doc.off('update', onUpdateCallback);@@ -85,6 +92,58 @@ export class YDoc {return update;}+ public undo(): Uint8Array | null {+ const updates: Uint8Array[] = [];+ const onUpdateCallback: (update: Uint8Array) => void = (update) => {+ updates.push(update);+ };++ this.doc.on('update', onUpdateCallback);+ this.undoManager.undo();+ this.doc.off('update', onUpdateCallback);++ if (updates.length === 0) {+ return null;+ }++ if (updates.length > 1) {+ throw new Error('Invalid number of updates');+ }++ const update = updates[0];+ if (!update) {+ return null;+ }++ return update;+ }++ public redo(): Uint8Array | null {+ const updates: Uint8Array[] = [];+ const onUpdateCallback: (update: Uint8Array) => void = (update) => {+ updates.push(update);+ };++ this.doc.on('update', onUpdateCallback);+ this.undoManager.redo();+ this.doc.off('update', onUpdateCallback);++ if (updates.length === 0) {+ return null;+ }++ if (updates.length > 1) {+ throw new Error('Invalid number of updates');+ }++ const update = updates[0];+ if (!update) {+ return null;+ }++ return update;+ }+public getObject<T>(): T {const objectMap = this.doc.getMap('object');const object = objectMap.toJSON() as T;diff --git a/packages/ui/src/components/documents/document-editor.tsx b/packages/ui/src/components/documents/document-editor.tsxindex 571c6bf1..0d7f577d 100644--- a/packages/ui/src/components/documents/document-editor.tsx+++ b/packages/ui/src/components/documents/document-editor.tsx@@ -7,7 +7,7 @@ import {useEditor,} from '@tiptap/react';import { debounce, isEqual } from 'lodash-es';-import { Fragment, useEffect, useMemo, useRef } from 'react';+import { Fragment, useCallback, useEffect, useMemo, useRef } from 'react';import { toast } from 'sonner';import {@@ -237,6 +237,23 @@ export const DocumentEditor = ({'prose-lg prose-stone dark:prose-invert prose-headings:font-title font-default focus:outline-none max-w-full',spellCheck: 'false',},+ handleKeyDown: (_, event) => {+ if (event.key === 'z' && event.metaKey && !event.shiftKey) {+ event.preventDefault();+ undo();+ return true;+ }+ if (event.key === 'z' && event.metaKey && event.shiftKey) {+ event.preventDefault();+ redo();+ return true;+ }+ if (event.key === 'y' && event.metaKey) {+ event.preventDefault();+ redo();+ return true;+ }+ },},content: buildEditorContent(node.id,@@ -272,15 +289,19 @@ export const DocumentEditor = ({return;}- const newYDoc = buildYDoc(state, updates);- const afterContent = newYDoc.getObject<RichTextContent>();const beforeContent = ydocRef.current.getObject<RichTextContent>();+ ydocRef.current.applyUpdate(state.state);+ for (const update of updates) {+ ydocRef.current.applyUpdate(update.data);+ }++ const afterContent = ydocRef.current.getObject<RichTextContent>();+if (isEqual(afterContent, beforeContent)) {return;}- ydocRef.current = newYDoc;const editorContent = buildEditorContent(node.id, afterContent);revisionRef.current = state.revision;@@ -292,6 +313,74 @@ export const DocumentEditor = ({}}, [state, updates, editor]);+ const undo = useCallback(async () => {+ if (!editor) {+ return;+ }++ const beforeContent = ydocRef.current.getObject<RichTextContent>();+ const update = ydocRef.current.undo();++ if (!update) {+ return;+ }++ const afterContent = ydocRef.current.getObject<RichTextContent>();++ if (isEqual(beforeContent, afterContent)) {+ return;+ }++ const editorContent = buildEditorContent(node.id, afterContent);+ editor.chain().setContent(editorContent).run();++ const result = await window.colanode.executeMutation({+ type: 'document.update',+ accountId: workspace.accountId,+ workspaceId: workspace.id,+ documentId: node.id,+ update,+ });++ if (!result.success) {+ toast.error(result.error.message);+ }+ }, [node.id, editor]);++ const redo = useCallback(async () => {+ if (!editor) {+ return;+ }++ const beforeContent = ydocRef.current.getObject<RichTextContent>();+ const update = ydocRef.current.redo();++ if (!update) {+ return;+ }++ const afterContent = ydocRef.current.getObject<RichTextContent>();++ if (isEqual(beforeContent, afterContent)) {+ return;+ }++ const editorContent = buildEditorContent(node.id, afterContent);+ editor.chain().setContent(editorContent).run();++ const result = await window.colanode.executeMutation({+ type: 'document.update',+ accountId: workspace.accountId,+ workspaceId: workspace.id,+ documentId: node.id,+ update,+ });++ if (!result.success) {+ toast.error(result.error.message);+ }+ }, [node.id, editor]);+return (<div className="min-h-[500px]">{editor && canEdit && (