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 document editor with new version of mutations
Hakan Shehuc26b078a6d74
diff --git a/desktop/src/components/documents/document-editor.tsx b/desktop/src/components/documents/document-editor.tsxindex aed3e0be..0d970dc4 100644--- a/desktop/src/components/documents/document-editor.tsx+++ b/desktop/src/components/documents/document-editor.tsx@@ -1,6 +1,6 @@import React from 'react';import '@/styles/editor.css';-import { useEditor, EditorContent, JSONContent } from '@tiptap/react';+import { useEditor, EditorContent } from '@tiptap/react';import {ParagraphCommand,BlockquoteCommand,@@ -47,18 +47,36 @@ import {} from '@/editor/extensions';import { EditorBubbleMenu } from '@/editor/menu/bubble-menu';+import { Node } from '@/types/nodes';+import {+ editorNodeArrayEquals,+ mapEditorNodesToJSONContent,+ mapJSONContentToEditorNodes,+ mapNodesToEditorNodes,+} from '@/editor/utils';+import { EditorNode } from '@/types/editor';+import { Editor } from '@tiptap/core';+import { debounce, isEqual } from 'lodash';+import {+ LocalCreateNodesMutation,+ LocalDeleteNodesMutation,+ LocalUpdateNodeMutation,+} from '@/types/mutations';+import { useWorkspace } from '@/contexts/workspace';+import { NeuronId } from '@/lib/id';interface DocumentEditorProps {- id: string;- content: JSONContent;- onUpdate: (content: JSONContent) => void;+ node: Node;+ nodes: Node[];}-export const DocumentEditor = ({- id,- content,- onUpdate,-}: DocumentEditorProps) => {+export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {+ const workspace = useWorkspace();+ const databaseNodes = React.useRef<EditorNode[]>(+ mapNodesToEditorNodes(nodes),+ );+ const localNodes = React.useRef<EditorNode[]>(databaseNodes.current);+const editor = useEditor({extensions: [@@ -116,16 +134,134 @@ export const DocumentEditor = ({spellCheck: 'false',},},+ content: mapEditorNodesToJSONContent(node.id, localNodes.current),shouldRerenderOnTransaction: false,- content: content,- onUpdate: ({ editor, transaction }) => {+ autofocus: 'start',+ onUpdate: async ({ editor, transaction }) => {if (transaction.docChanged) {- onUpdate(editor.getJSON());+ await checkForLocalChanges(editor);}},- autofocus: 'start',},- [id],+ [node.id],+ );++ React.useEffect(() => {+ console.log('nodes changed', nodes);+ checkForDatabaseChanges(nodes, editor);+ }, [editor, nodes]);++ const checkForLocalChanges = React.useCallback(+ debounce(async (editor: Editor) => {+ const editorContent = editor.getJSON();+ const newEditorNodes = mapJSONContentToEditorNodes(+ node.id,+ editorContent,+ );++ if (editorNodeArrayEquals(newEditorNodes, localNodes.current)) {+ return;+ }++ localNodes.current = newEditorNodes;+ if (editorNodeArrayEquals(newEditorNodes, databaseNodes.current)) {+ return;+ }++ const createNodesMutation: LocalCreateNodesMutation = {+ type: 'create_nodes',+ data: {+ nodes: [],+ },+ };+ const updateNodeMutations: LocalUpdateNodeMutation[] = [];+ const deleteNodesMutation: LocalDeleteNodesMutation = {+ type: 'delete_nodes',+ data: {+ ids: [],+ },+ };++ for (const newEditorNode of newEditorNodes) {+ const existingEditorNode = databaseNodes.current.find(+ (n) => n.id === newEditorNode.id,+ );++ if (!existingEditorNode) {+ createNodesMutation.data.nodes.push({+ id: newEditorNode.id,+ type: newEditorNode.type,+ workspaceId: workspace.id,+ parentId: newEditorNode.parentId,+ index: newEditorNode.index,+ attrs: newEditorNode.attrs,+ content: newEditorNode.content,+ createdAt: new Date().toISOString(),+ createdBy: workspace.userId,+ versionId: NeuronId.generate(NeuronId.Type.Version),+ });+ } else if (!isEqual(existingEditorNode, newEditorNode)) {+ updateNodeMutations.push({+ type: 'update_node',+ data: {+ id: newEditorNode.id,+ type: newEditorNode.type,+ parentId: newEditorNode.parentId,+ index: newEditorNode.index,+ attrs: newEditorNode.attrs,+ content: newEditorNode.content,+ updatedAt: new Date().toISOString(),+ updatedBy: workspace.userId,+ versionId: NeuronId.generate(NeuronId.Type.Version),+ },+ });+ }+ }++ for (const existingEditorNode of databaseNodes.current) {+ if (!newEditorNodes.find((n) => n.id === existingEditorNode.id)) {+ deleteNodesMutation.data.ids.push(existingEditorNode.id);+ }+ }++ if (createNodesMutation.data.nodes.length > 0) {+ await workspace.mutate(createNodesMutation);+ }++ if (updateNodeMutations.length > 0) {+ for (const updateNodeMutation of updateNodeMutations) {+ await workspace.mutate(updateNodeMutation);+ }+ }++ if (deleteNodesMutation.data.ids.length > 0) {+ await workspace.mutate(deleteNodesMutation);+ }+ }, 500),+ [node.id],+ );++ const checkForDatabaseChanges = React.useCallback(+ debounce((newDatabaseNodes: Node[], editor: Editor) => {+ const newEditorNodes = mapNodesToEditorNodes(newDatabaseNodes);+ if (editorNodeArrayEquals(newEditorNodes, databaseNodes.current)) {+ return;+ }++ databaseNodes.current = newEditorNodes;+ if (editorNodeArrayEquals(newEditorNodes, localNodes.current)) {+ return;+ }++ //here we need to update the editor content+ const newEditorContent = mapEditorNodesToJSONContent(+ node.id,+ newEditorNodes,+ );+ editor.commands.setContent(newEditorContent);+ localNodes.current = newEditorNodes;+ }, 500),+ [node.id],);return (diff --git a/desktop/src/components/documents/document.tsx b/desktop/src/components/documents/document.tsxindex 219b43f9..bb04afb5 100644--- a/desktop/src/components/documents/document.tsx+++ b/desktop/src/components/documents/document.tsx@@ -1,20 +1,48 @@import React from 'react';-import { useDocument } from '@/hooks/use-document';import { Node } from '@/types/nodes';import { DocumentEditor } from './document-editor';-import { mapToDocumentContent } from '@/editor/utils';import { observer } from 'mobx-react-lite';+import { useQuery } from '@tanstack/react-query';+import { sql } from 'kysely';+import { NodesTableSchema } from '@/data/schemas/workspace';+import { useWorkspace } from '@/contexts/workspace';+import { mapNode } from '@/lib/nodes';interface DocumentProps {node: Node;}export const Document = observer(({ node }: DocumentProps) => {- const { isLoaded, nodes, onUpdate } = useDocument(node);- if (!isLoaded) {- return <div>Loading...</div>;+ const workspace = useWorkspace();+ const { data, isPending } = useQuery({+ queryKey: [`document:nodes:${node.id}`],+ queryFn: async ({ queryKey }) => {+ const query = sql<NodesTableSchema>`+ WITH RECURSIVE document_hierarchy AS (+ SELECT *+ FROM nodes+ WHERE parent_id = ${node.id}++ UNION ALL++ SELECT child.*+ FROM nodes child+ INNER JOIN document_hierarchy parent ON child.parent_id = parent.id+ )+ SELECT *+ FROM document_hierarchy;+ `.compile(workspace.schema);++ const queryId = queryKey[0];+ return await workspace.queryAndSubscribe(queryId, query);+ },+ });++ if (isPending) {+ return null;}- const content = mapToDocumentContent(node.id, nodes);- return <DocumentEditor id={node.id} content={content} onUpdate={onUpdate} />;+ const rows = data.rows;+ const nodes = rows.map((row) => mapNode(row));+ return <DocumentEditor key={node.id} node={node} nodes={nodes} />;});diff --git a/desktop/src/data/app-manager.ts b/desktop/src/data/app-manager.tsindex 3e95d8f0..f88fa61b 100644--- a/desktop/src/data/app-manager.ts+++ b/desktop/src/data/app-manager.ts@@ -41,6 +41,8 @@ class AppManager {this.database = new Kysely<AppDatabaseSchema>({dialect,});++ this.executeEventLoop = this.executeEventLoop.bind(this);}public async getAccount(@@ -223,8 +225,12 @@ class AppManager {}private async executeEventLoop(): Promise<void> {- for (const accountManager of this.accounts.values()) {- await accountManager.executeEventLoop();+ try {+ for (const accountManager of this.accounts.values()) {+ await accountManager.executeEventLoop();+ }+ } catch (error) {+ console.error('Error in event loop:', error);}setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);diff --git a/desktop/src/data/mutation-manager.ts b/desktop/src/data/mutation-manager.tsindex 90e73d49..67d3a463 100644--- a/desktop/src/data/mutation-manager.ts+++ b/desktop/src/data/mutation-manager.ts@@ -17,7 +17,7 @@ import {} from '@/types/mutations';import { Workspace } from '@/types/workspaces';import { Node } from '@/types/nodes';-import { AxiosInstance } from 'axios';+import Axios, { AxiosInstance } from 'axios';import { NeuronId } from '@/lib/id';export class MutationManager {@@ -362,22 +362,33 @@ export class MutationManager {break;}- const { data, status } = await this.axios.post<ServerMutation>(- 'v1/mutations',- {- workspaceId: this.workspace.id,- type: nextMutation.type,- data: JSON.parse(nextMutation.data),- },- );-- if (status === 200) {- await this.database- .deleteFrom('mutations')- .where('id', '=', nextMutation.id)- .execute();-- await this.executeServerMutation(data);+ try {+ const { data, status } = await this.axios.post<ServerMutation>(+ 'v1/mutations',+ {+ workspaceId: this.workspace.id,+ type: nextMutation.type,+ data: JSON.parse(nextMutation.data),+ },+ );++ if (status === 200) {+ await this.database+ .deleteFrom('mutations')+ .where('id', '=', nextMutation.id)+ .execute();++ await this.executeServerMutation(data);+ }+ } catch (error) {+ if (Axios.isAxiosError(error)) {+ if (error.response?.status === 404) {+ await this.database+ .deleteFrom('mutations')+ .where('id', '=', nextMutation.id)+ .execute();+ }+ }}} while (true);}diff --git a/desktop/src/editor/utils.ts b/desktop/src/editor/utils.tsindex 1a0e6fc5..06888939 100644--- a/desktop/src/editor/utils.ts+++ b/desktop/src/editor/utils.ts@@ -1,13 +1,33 @@-import { Node } from '@/types/nodes';+import { Node, NodeBlock } from '@/types/nodes';import { JSONContent } from '@tiptap/core';+import { NeuronId } from '@/lib/id';+import { EditorNode } from '@/types/editor';+import { LeafNodeTypes } from '@/lib/constants';+import { isEqual } from 'lodash';+import { generateNodeIndex } from '@/lib/nodes';-export const mapToDocumentContent = (- parentId: string,- nodes: Node[],+export const mapNodesToEditorNodes = (nodes: Node[]): EditorNode[] => {+ return nodes.map((node) => mapNodeToEditorNode(node));+};++export const mapNodeToEditorNode = (node: Node): EditorNode => {+ return {+ id: node.id,+ type: node.type,+ parentId: node.parentId,+ attrs: node.attrs,+ content: node.content,+ index: node.index,+ };+};++export const mapEditorNodesToJSONContent = (+ rootId: string,+ editorNodes: EditorNode[],): JSONContent => {const contents: JSONContent[] = [];- const childrenNodes = nodes- .filter((node) => node.parentId === parentId)+ const childrenNodes = editorNodes+ .filter((node) => node.parentId === rootId).sort((a, b) => {if (a.index < b.index) {return -1;@@ -19,7 +39,7 @@ export const mapToDocumentContent = (});for (const child of childrenNodes) {- const content = mapNodeToEditorContent(child, nodes);+ const content = mapEditorNodeToJSONContent(child, editorNodes);contents.push(content);}@@ -35,18 +55,21 @@ export const mapToDocumentContent = (};};-const mapNodeToEditorContent = (parent: Node, nodes: Node[]): JSONContent => {- const parentContent: JSONContent = {- type: parent.type,+const mapEditorNodeToJSONContent = (+ node: EditorNode,+ nodes: EditorNode[],+): JSONContent => {+ const nodeJSONContent: JSONContent = {+ type: node.type,attrs: {- ...parent.attrs,- id: parent.id,- index: parent.index,+ ...node.attrs,+ id: node.id,+ index: node.index,},};const childrenNodes = nodes- .filter((node) => node.parentId === parent.id)+ .filter((node) => node.parentId === node.id).sort((a, b) => {if (a.index < b.index) {return -1;@@ -58,15 +81,15 @@ const mapNodeToEditorContent = (parent: Node, nodes: Node[]): JSONContent => {});if (childrenNodes.length > 0) {- parentContent.content = parentContent.content || [];+ nodeJSONContent.content = nodeJSONContent.content || [];childrenNodes.forEach((child) => {- parentContent.content.push(mapNodeToEditorContent(child, nodes));+ nodeJSONContent.content.push(mapEditorNodeToJSONContent(child, nodes));});}- if (parent.content && parent.content.length > 0) {- parentContent.content = parentContent.content || [];- parent.content.forEach((child) => {+ if (node.content && node.content.length > 0) {+ nodeJSONContent.content = nodeJSONContent.content || [];+ node.content.forEach((child) => {const childContent: JSONContent = {type: child.type,text: child.text,@@ -81,9 +104,161 @@ const mapNodeToEditorContent = (parent: Node, nodes: Node[]): JSONContent => {});}- parentContent.content.push(childContent);+ nodeJSONContent.content.push(childContent);});}- return parentContent;+ return nodeJSONContent;+};++export const mapJSONContentToEditorNodes = (+ rootId: string,+ content: JSONContent,+): EditorNode[] => {+ const nodes: EditorNode[] = [];+ if (content.content && content.content.length > 0) {+ for (const child of content.content) {+ mapAndPushJSONContentToEditorNode(rootId, child, nodes);+ }+ }+ validateEditorNodeIndexes(nodes);+ return nodes;+};++const mapAndPushJSONContentToEditorNode = (+ parentId: string,+ content: JSONContent,+ editorNodes: EditorNode[],+) => {+ let id = content.attrs?.id;+ if (!id) {+ id = NeuronId.generate(NeuronId.getIdTypeFromNode(content.type));+ }++ const index = content.attrs?.index;+ let attrs = content.attrs ? { ...content.attrs } : null;+ if (attrs) {+ delete attrs.id;+ delete attrs.index;++ if (Object.keys(attrs).length === 0) {+ attrs = null;+ }+ }++ const editorNode: EditorNode = {+ id: id,+ type: content.type,+ parentId: parentId,+ index: index,+ attrs: attrs,+ };+ editorNodes.push(editorNode);++ if (LeafNodeTypes.includes(content.type)) {+ editorNode.content = [];+ for (const child of content.content) {+ const nodeBlock: NodeBlock = {+ type: child.type,+ text: child.text,+ };++ if (child.marks && child.marks.length > 0) {+ nodeBlock.marks = child.marks.map((mark) => {+ return {+ type: mark.type,+ attrs: mark.attrs,+ };+ });+ }++ editorNode.content.push(nodeBlock);+ }++ if (editorNode.content.length === 0) {+ editorNode.content = null;+ }+ } else {+ for (const child of content.content) {+ mapAndPushJSONContentToEditorNode(id, child, editorNodes);+ }+ }+};++const validateEditorNodeIndexes = (editorNodes: EditorNode[]): void => {+ //group by parentId+ const groupedNodes: { [key: string]: EditorNode[] } = {};+ for (const node of editorNodes) {+ if (!groupedNodes[node.parentId]) {+ groupedNodes[node.parentId] = [];+ }++ groupedNodes[node.parentId].push(node);+ }++ for (const parentId in groupedNodes) {+ const nodes = groupedNodes[parentId];+ for (let i = 0; i < nodes.length; i++) {+ const currentIndex = nodes[i].index;+ const beforeIndex = i === 0 ? null : nodes[i - 1].index;++ // find the lowest index after the current node+ // we do this because sometimes nodes can be ordered in such a way that+ // the current node's index is higher than one of its siblings+ // after the next sibling+ // for example: 1, {current}, 4, 3+ let afterIndex = i === nodes.length - 1 ? null : nodes[i + 1].index;+ for (let j = i + 1; j < nodes.length; j++) {+ if (nodes[j].index < afterIndex) {+ afterIndex = nodes[j].index;+ break;+ }+ }++ // extra check to make sure that the beforeIndex is less than the afterIndex+ // because otherwise the fractional index library will throw an error+ if (afterIndex < beforeIndex) {+ afterIndex = generateNodeIndex(null, beforeIndex);+ } else if (beforeIndex === afterIndex) {+ afterIndex = generateNodeIndex(beforeIndex, null);+ }++ if (+ !currentIndex ||+ currentIndex <= beforeIndex ||+ currentIndex > afterIndex+ ) {+ nodes[i].index = generateNodeIndex(beforeIndex, afterIndex);+ }+ }+ }+};++export const editorNodeArrayEquals = (+ a: EditorNode[],+ b: EditorNode[],+): boolean => {+ if (a.length !== b.length) {+ return false;+ }++ for (let i = 0; i < a.length; i++) {+ if (!deepEquals(a[i], b[i])) {+ return false;+ }+ }++ return true;+};++const deepEquals = (a: any, b: any): boolean => {+ if (a === b) {+ return false;+ }++ if ((a === null || a === undefined) && (b === null || b === undefined)) {+ return false;+ }++ return !isEqual(a, b);};diff --git a/desktop/src/hooks/use-document.tsx b/desktop/src/hooks/use-document.tsxdeleted file mode 100644index 3576d7de..00000000--- a/desktop/src/hooks/use-document.tsx+++ /dev/null@@ -1,328 +0,0 @@-import React from 'react';-import { debounce, isEqual } from 'lodash';-import { Node, NodeBlock } from '@/types/nodes';-import { useWorkspace } from '@/contexts/workspace';-import { JSONContent } from '@tiptap/core';-import { DocumentStore } from '@/store/document';-import { NeuronId } from '@/lib/id';-import { LeafNodeTypes } from '@/lib/constants';-import { generateNodeIndex } from '@/lib/nodes';-import { useEventBus } from '@/hooks/use-event-bus';--interface useNodeResult {- isLoaded: boolean;- nodes: Node[];- onUpdate: (content: JSONContent) => void;-}--export type NodeFromEditor = {- type: string;- id: string;- parentId?: string | null;- index?: string | null;- attrs?: any | null;- content?: NodeBlock[] | null;- children?: NodeFromEditor[];-};--export const useDocument = (node: Node): useNodeResult => {- const workspace = useWorkspace();- const eventBus = useEventBus();- const store = React.useMemo(() => new DocumentStore(), [node.id]);-- React.useEffect(() => {- const fetchNodes = async () => {- // const nodes = await workspace.getDocumentNodes(node.id);- // store.setNodes(nodes);-- store.setIsLoaded(true);- };-- fetchNodes();-- const subscriptionId = eventBus.subscribe((event) => {- if (event.event === 'node_created') {- const createdNode = event.payload as Node;- if (store.getNode(createdNode.id) || createdNode.parentId === node.id) {- store.setNode(createdNode);- } else {- const parent = store.getNode(createdNode.parentId);- if (parent) {- store.setNode(createdNode);- }- }- } else if (event.event === 'node_updated') {- const updatedNode = event.payload as Node;- if (store.getNode(updatedNode.id)) {- store.setNode(updatedNode);- }- } else if (event.event === 'node_deleted') {- const deletedNode = event.payload as Node;- if (store.getNode(deletedNode.id)) {- store.deleteNode(deletedNode.id);- }- }- });-- return () => {- window.eventBus.unsubscribe(subscriptionId);- };- }, [node.id]);-- const onUpdate = React.useMemo(- () =>- debounce(async (updatedContent: JSONContent) => {- // const childrenNodes = buildNodesFromEditor(- // updatedContent.content,- // node.id,- // );- //- // const nodesToCreate: CreateNodeInput[] = [];- // const nodesToUpdate: UpdateNodeInput[] = [];- // const nodesToDelete: string[] = [];- //- // const currentNodes = store.nodes;- // fillIndexesFromNodes(childrenNodes, currentNodes);- // validateIndexes(childrenNodes);- //- // const editorNodes = flattenNodesFromEditor(childrenNodes);- // for (const editorNode of editorNodes) {- // const existingNode = currentNodes[editorNode.id];- // if (!existingNode) {- // nodesToCreate.push({- // id: editorNode.id,- // type: editorNode.type,- // parentId: editorNode.parentId,- // index: editorNode.index,- // attrs: editorNode.attrs,- // content: editorNode.content,- // });- // } else if (hasChanged(existingNode, editorNode)) {- // nodesToUpdate.push({- // id: editorNode.id,- // parentId: editorNode.parentId,- // index: editorNode.index,- // attrs: editorNode.attrs,- // content: editorNode.content,- // });- // }- // }- //- // const currentNodeIds = Object.keys(currentNodes);- // for (const nodeId of currentNodeIds) {- // if (!editorNodes.find((node) => node.id === nodeId)) {- // nodesToDelete.push(nodeId);- // }- // }- //- // if (nodesToCreate.length > 0) {- // await workspace.createNodes(nodesToCreate);- // }- //- // if (nodesToUpdate.length > 0) {- // for (const nodeToUpdate of nodesToUpdate) {- // await workspace.updateNode(nodeToUpdate);- // }- // }- //- // if (nodesToDelete.length > 0) {- // await workspace.deleteNodes(nodesToDelete);- // }- }, 500),- [node.id],- );-- return {- isLoaded: store.isLoaded,- nodes: store.getNodes(),- onUpdate,- };-};--const buildNodesFromEditor = (- content: JSONContent[],- parentId: string,-): NodeFromEditor[] => {- if (!content || content.length === 0) {- return [];- }-- const children: NodeFromEditor[] = [];- for (let i = 0; i < content.length; i++) {- const child = buildNodeFromEditor(content[i], parentId);- children.push(child);- }-- return children;-};--const buildNodeFromEditor = (- content: JSONContent,- parentId: string,-): NodeFromEditor => {- let id = content.attrs?.id;- if (!id) {- id = NeuronId.generate(NeuronId.getIdTypeFromNode(content.type));- }-- const index = content.attrs?.index;- const attrs = content.attrs ? { ...content.attrs } : {};- if (attrs.id) {- delete attrs.id;- delete attrs.index;- }-- const nodeFromEditor: NodeFromEditor = {- id: id,- type: content.type,- parentId,- index: index,- attrs: attrs,- };-- if (!content.content || content.content.length === 0) {- return nodeFromEditor;- }-- if (LeafNodeTypes.includes(content.type)) {- nodeFromEditor.content = [];- for (const child of content.content) {- const nodeBlock: NodeBlock = {- type: child.type,- text: child.text,- };-- if (child.marks && child.marks.length > 0) {- nodeBlock.marks = child.marks.map((mark) => {- return {- type: mark.type,- attrs: mark.attrs,- };- });- }-- nodeFromEditor.content.push(nodeBlock);- }- } else {- nodeFromEditor.children = [];- for (let i = 0; i < content.content.length; i++) {- const childNode = buildNodeFromEditor(content.content[i], id);- nodeFromEditor.children.push(childNode);- }- }-- return nodeFromEditor;-};--const fillIndexesFromNodes = (- nodesFromEditor: NodeFromEditor[],- nodes: Record<string, Node>,-) => {- for (const nodeFromEditor of nodesFromEditor) {- const node = nodes[nodeFromEditor.id];- if (node) {- nodeFromEditor.index = node.index;- }-- if (nodeFromEditor.children) {- fillIndexesFromNodes(nodeFromEditor.children, nodes);- }- }-};--const validateIndexes = (nodes: NodeFromEditor[]) => {- for (let i = 0; i < nodes.length; i++) {- const currentIndex = nodes[i].index;- const beforeIndex = i === 0 ? null : nodes[i - 1].index;-- // find the lowest index after the current node- // we do this because sometimes nodes can be ordered in such a way that- // the current node's index is higher than one of its siblings- // after the next sibling- // for example: 1, {current}, 4, 3- let afterIndex = i === nodes.length - 1 ? null : nodes[i + 1].index;- for (let j = i + 1; j < nodes.length; j++) {- if (nodes[j].index < afterIndex) {- afterIndex = nodes[j].index;- break;- }- }-- // extra check to make sure that the beforeIndex is less than the afterIndex- // because otherwise the fractional index library will throw an error- if (afterIndex < beforeIndex) {- afterIndex = generateNodeIndex(null, beforeIndex);- } else if (beforeIndex === afterIndex) {- afterIndex = generateNodeIndex(beforeIndex, null);- }-- if (- !currentIndex ||- currentIndex <= beforeIndex ||- currentIndex > afterIndex- ) {- nodes[i].index = generateNodeIndex(beforeIndex, afterIndex);- }-- if (nodes[i].children) {- validateIndexes(nodes[i].children);- }- }-};--const flattenNodesFromEditor = (- nodesFromEditor: NodeFromEditor[],-): NodeFromEditor[] => {- const nodes: Node[] = [];- nodesFromEditor.forEach((node) => {- enumerateNodesFromEditor(node, nodes);- });-- return nodes;-};--const enumerateNodesFromEditor = (- node: NodeFromEditor,- nodes: NodeFromEditor[],-) => {- nodes.push(node);- node.children?.forEach((child) => {- enumerateNodesFromEditor(child, nodes);- });-};--const hasChanged = (existingNode: Node, editorNode: NodeFromEditor) => {- if (existingNode.type !== editorNode.type) {- return true;- }-- if (existingNode.parentId !== editorNode.parentId) {- return true;- }-- if (existingNode.index !== editorNode.index) {- return true;- }-- if (deepHasChanged(existingNode.attrs, editorNode.attrs)) {- return true;- }-- if (deepHasChanged(existingNode.content, editorNode.content)) {- return true;- }-- return false;-};--const deepHasChanged = (a: any, b: any): boolean => {- if (a === b) {- return false;- }-- if ((a === null || a === undefined) && (b === null || b === undefined)) {- return false;- }-- return !isEqual(a, b);-};diff --git a/desktop/src/types/editor.ts b/desktop/src/types/editor.tsindex c2b43ec3..9e3ff0cf 100644--- a/desktop/src/types/editor.ts+++ b/desktop/src/types/editor.ts@@ -1,4 +1,5 @@import { Editor, type Range } from '@tiptap/core';+import { NodeBlock } from '@/types/nodes';export type EditorCommandProps = {editor: Editor;@@ -17,3 +18,12 @@ export type EditorCommand = {handler: (props: EditorCommandProps) => void;disabled?: boolean;};++export type EditorNode = {+ id: string;+ parentId: string;+ type: string;+ index?: string | null;+ attrs?: Record<string, any> | null;+ content?: NodeBlock[] | null;+};