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
New implementation for editor changes and mutations
Hakan Shehu6edad3a9cd31
diff --git a/desktop/src/components/documents/document-editor.tsx b/desktop/src/components/documents/document-editor.tsxindex 21410768..dbf04d4c 100644--- a/desktop/src/components/documents/document-editor.tsx+++ b/desktop/src/components/documents/document-editor.tsx@@ -48,28 +48,19 @@ import {import { EditorBubbleMenu } from '@/editor/menu/bubble-menu';import { LocalNode } from '@/types/nodes';-import {- editorNodeMapEquals,- mapEditorNodesToJSONContent,- mapJSONContentToEditorNodes,- mapNodesToEditorNodes,-} from '@/editor/utils';-import { EditorNode } from '@/types/editor';-import { Editor } from '@tiptap/core';-import { debounce, isEqual } from 'lodash';import { useWorkspace } from '@/contexts/workspace';-import { NeuronId } from '@/lib/id';-import { CompiledQuery } from 'kysely';+import { EditorObserver } from '@/editor/observer';interface DocumentEditorProps {node: LocalNode;- nodes: LocalNode[];+ nodes: Map<string, LocalNode>;}export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {const workspace = useWorkspace();- const nodesSnapshot = React.useRef<Map<string, EditorNode>>(- mapNodesToEditorNodes(nodes),+ const observer = React.useMemo<EditorObserver>(+ () => new EditorObserver(workspace, workspace.schema, node, nodes),+ [node.id],);const editor = useEditor(@@ -129,12 +120,12 @@ export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {spellCheck: 'false',},},- content: mapEditorNodesToJSONContent(node.id, nodesSnapshot.current),+ content: observer.getEditorContent(),shouldRerenderOnTransaction: false,autofocus: 'start',onUpdate: async ({ editor, transaction }) => {if (transaction.docChanged) {- await checkForLocalChanges(editor);+ observer.onEditorUpdate(editor);}},},@@ -142,173 +133,8 @@ export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {);React.useEffect(() => {- checkForRemoteChanges(nodes, editor);- }, [editor, nodes]);-- const checkForLocalChanges = React.useCallback(- debounce(async (editor: Editor) => {- const editorContent = editor.getJSON();- const newEditorNodes = mapJSONContentToEditorNodes(- node.id,- editorContent,- );-- if (editorNodeMapEquals(newEditorNodes, nodesSnapshot.current)) {- return;- }-- const queries: CompiledQuery[] = [];- for (const newEditorNode of newEditorNodes.values()) {- const existingEditorNode = nodesSnapshot.current.get(newEditorNode.id);- if (!existingEditorNode) {- const query = workspace.schema- .insertInto('nodes')- .values({- id: newEditorNode.id,- type: newEditorNode.type,- parent_id: newEditorNode.parentId,- index: newEditorNode.index,- attrs: newEditorNode.attrs- ? JSON.stringify(newEditorNode.attrs)- : null,- content: newEditorNode.content- ? JSON.stringify(newEditorNode.content)- : null,- created_at: new Date().toISOString(),- created_by: workspace.userId,- version_id: NeuronId.generate(NeuronId.Type.Version),- })- .compile();-- queries.push(query);- } else if (!isEqual(existingEditorNode, newEditorNode)) {- const updateNodeMutation = workspace.schema- .updateTable('nodes')- .set({- type: newEditorNode.type,- parent_id: newEditorNode.parentId,- index: newEditorNode.index,- attrs: newEditorNode.attrs- ? JSON.stringify(newEditorNode.attrs)- : null,- content: newEditorNode.content- ? JSON.stringify(newEditorNode.content)- : null,- updated_at: new Date().toISOString(),- updated_by: workspace.userId,- version_id: NeuronId.generate(NeuronId.Type.Version),- })- .where('id', '=', newEditorNode.id)- .compile();-- queries.push(updateNodeMutation);- }- }-- const toDeleteIds: string[] = [];- for (const existingEditorNode of nodesSnapshot.current.values()) {- if (!newEditorNodes.has(existingEditorNode.id)) {- toDeleteIds.push(existingEditorNode.id);- }- }-- if (toDeleteIds.length > 0) {- const deleteNodesMutation = workspace.schema- .deleteFrom('nodes')- .where('id', 'in', toDeleteIds)- .compile();-- queries.push(deleteNodesMutation);- }-- if (queries.length > 0) {- await workspace.mutate(queries);- }-- nodesSnapshot.current = newEditorNodes;- }, 500),- [node.id],- );-- const checkForRemoteChanges = React.useCallback(- debounce((remoteNodes: LocalNode[], editor: Editor) => {- const remoteEditorNodes = mapNodesToEditorNodes(remoteNodes);- if (editorNodeMapEquals(remoteEditorNodes, nodesSnapshot.current)) {- return;- }-- const currentEditorContent = editor.getJSON();- const currentEditorNodes = mapJSONContentToEditorNodes(- node.id,- currentEditorContent,- );-- const editorNodeIds = new Set<string>([- ...currentEditorNodes.keys(),- ...remoteEditorNodes.keys(),- ]);-- const newEditorNodes: Map<string, EditorNode> = new Map();- let hasChanges = false;- for (const editorNodeId of editorNodeIds) {- const currentEditorNode = currentEditorNodes.get(editorNodeId);- const snapshotEditorNode = nodesSnapshot.current.get(editorNodeId);- const remoteEditorNode = remoteEditorNodes.get(editorNodeId);-- if (!currentEditorNode) {- newEditorNodes.set(editorNodeId, remoteEditorNode);- hasChanges = true;- continue;- }-- if (!snapshotEditorNode) {- newEditorNodes.set(editorNodeId, currentEditorNode);- continue;- }-- if (!remoteEditorNode) {- newEditorNodes.set(editorNodeId, currentEditorNode);- continue;- }-- if (!isEqual(currentEditorNode, snapshotEditorNode)) {- newEditorNodes.set(editorNodeId, currentEditorNode);- continue;- }-- if (!isEqual(snapshotEditorNode, remoteEditorNode)) {- newEditorNodes.set(editorNodeId, remoteEditorNode);- hasChanges = true;- continue;- }-- newEditorNodes.set(editorNodeId, currentEditorNode);- }-- if (!hasChanges) {- return;- }-- const newEditorContent = mapEditorNodesToJSONContent(- node.id,- newEditorNodes,- );-- const selection = editor.state.selection;- if (selection.$anchor != null && selection.$head != null) {- editor- .chain()- .setContent(newEditorContent)- .setTextSelection(selection)- .run();- } else {- editor.chain().setContent(newEditorContent).run();- }-- nodesSnapshot.current = newEditorNodes;- }, 500),- [node.id],- );+ observer.onNodesChange(nodes, editor);+ }, [nodes]);return (<div className="min-h-[500px]">diff --git a/desktop/src/components/documents/document.tsx b/desktop/src/components/documents/document.tsxindex 2b9bc840..9d86f8fe 100644--- a/desktop/src/components/documents/document.tsx+++ b/desktop/src/components/documents/document.tsx@@ -44,6 +44,6 @@ export const Document = ({ node }: DocumentProps) => {}const rows = data.rows;- const nodes = rows.map((row) => mapNode(row));+ const nodes = new Map(rows.map((row) => [row.id, mapNode(row)]));return <DocumentEditor key={node.id} node={node} nodes={nodes} />;};diff --git a/desktop/src/editor/observer.ts b/desktop/src/editor/observer.tsnew file mode 100644index 00000000..65833fae--- /dev/null+++ b/desktop/src/editor/observer.ts@@ -0,0 +1,421 @@+import { WorkspaceDatabaseSchema } from '@/data/schemas/workspace';+import { LeafNodeTypes } from '@/lib/constants';+import { NeuronId } from '@/lib/id';+import { compareNodeIndex, generateNodeIndex } from '@/lib/nodes';+import { LocalNode, NodeBlock } from '@/types/nodes';+import { Workspace } from '@/types/workspaces';+import { Editor, JSONContent } from '@tiptap/core';+import { CompiledQuery, Kysely } from 'kysely';+import { debounce, isEqual } from 'lodash';++export class EditorObserver {+ private readonly workspace: Workspace;+ private readonly database: Kysely<WorkspaceDatabaseSchema>;+ private readonly rootNode: LocalNode;+ private readonly nodesMap: Map<string, LocalNode>;+ private editorContent: JSONContent;++ private readonly onEditorUpdateDebounced: () => void;+ private readonly onNodesChangeDebounced: (+ newNodesMap: Map<string, LocalNode>,+ editor: Editor,+ ) => void;++ constructor(+ workspace: Workspace,+ database: Kysely<WorkspaceDatabaseSchema>,+ rootNode: LocalNode,+ nodesMap: Map<string, LocalNode>,+ ) {+ this.workspace = workspace;+ this.database = database;+ this.rootNode = rootNode;+ this.nodesMap = nodesMap;+ this.editorContent = this.buildEditorContent();+ this.onEditorUpdateDebounced = debounce(+ this.checkEditorContentChanges,+ 500,+ );+ this.onNodesChangeDebounced = debounce(this.checkNodesChanges, 500);+ }++ public getEditorContent(): JSONContent {+ return this.editorContent;+ }++ public onEditorUpdate(editor: Editor) {+ this.editorContent = editor.getJSON();+ this.onEditorUpdateDebounced();+ }++ public onNodesChange(nodes: Map<string, LocalNode>, editor: Editor) {+ this.onNodesChangeDebounced(nodes, editor);+ }++ private buildEditorContent(): JSONContent {+ const nodesArray = Array.from(this.nodesMap.values());+ const contents: JSONContent[] = [];+ const childrenNodes = nodesArray+ .filter((node) => node.parentId === this.rootNode.id)+ .sort((a, b) => compareNodeIndex(a, b));++ for (const child of childrenNodes) {+ const content = this.buildEditorContentFromNode(child, nodesArray);+ contents.push(content);+ }++ if (!contents.length) {+ contents.push({+ type: 'paragraph',+ });+ }++ return {+ type: 'doc',+ content: contents,+ };+ }++ private buildEditorContentFromNode(+ node: LocalNode,+ nodesArray: LocalNode[],+ ): JSONContent {+ const editorContent: JSONContent = {+ type: node.type,+ attrs: {+ ...node.attrs,+ id: node.id,+ },+ };++ const childrenNodes = nodesArray+ .filter((n) => n.parentId === node.id)+ .sort((a, b) => compareNodeIndex(a, b));++ if (childrenNodes.length > 0) {+ editorContent.content = editorContent.content || [];+ childrenNodes.forEach((child) => {+ editorContent.content.push(+ this.buildEditorContentFromNode(child, nodesArray),+ );+ });+ } else if (node.content && node.content.length > 0) {+ editorContent.content = editorContent.content || [];+ node.content.forEach((child) => {+ const childContent: JSONContent = {+ type: child.type,+ text: child.text,+ };++ if (child.marks && child.marks.length > 0) {+ childContent.marks = child.marks.map((mark) => {+ return {+ type: mark.type,+ attrs: mark.attrs,+ };+ });+ }++ editorContent.content.push(childContent);+ });+ }++ return editorContent;+ }++ private async checkEditorContentChanges() {+ const newNodesMap = this.buildNodesMapFromEditorContent(this.editorContent);+ const allNodeIds = new Set([+ ...this.nodesMap.keys(),+ ...newNodesMap.keys(),+ ]);++ const insertQueries: CompiledQuery[] = [];+ const updateQueries: CompiledQuery[] = [];+ const deleteQueries: CompiledQuery[] = [];+ for (const nodeId of allNodeIds) {+ const oldNode = this.nodesMap.get(nodeId);+ const newNode = newNodesMap.get(nodeId);++ if (!oldNode) {+ const query = this.database+ .insertInto('nodes')+ .values({+ id: newNode.id,+ type: newNode.type,+ parent_id: newNode.parentId,+ index: newNode.index,+ attrs: newNode.attrs ? JSON.stringify(newNode.attrs) : null,+ content: newNode.content ? JSON.stringify(newNode.content) : null,+ created_at: newNode.createdAt,+ created_by: newNode.createdBy,+ version_id: newNode.versionId,+ })+ .compile();++ insertQueries.push(query);+ this.nodesMap.set(newNode.id, newNode);+ } else if (!newNode) {+ const query = this.database+ .deleteFrom('nodes')+ .where('id', '=', oldNode.id)+ .compile();++ deleteQueries.push(query);+ this.nodesMap.delete(oldNode.id);+ } else if (!this.nodeEquals(oldNode, newNode)) {+ newNode.updatedAt = new Date().toISOString();+ newNode.updatedBy = this.workspace.userId;+ newNode.versionId = NeuronId.generate(NeuronId.Type.Version);++ const query = this.database+ .updateTable('nodes')+ .set({+ type: newNode.type,+ parent_id: newNode.parentId,+ index: newNode.index,+ attrs: newNode.attrs ? JSON.stringify(newNode.attrs) : null,+ content: newNode.content ? JSON.stringify(newNode.content) : null,+ updated_at: newNode.updatedAt,+ updated_by: newNode.updatedBy,+ version_id: newNode.versionId,+ })+ .where('id', '=', newNode.id)+ .compile();++ updateQueries.push(query);+ this.nodesMap.set(newNode.id, newNode);+ }+ }++ if (+ insertQueries.length > 0 ||+ updateQueries.length > 0 ||+ deleteQueries.length > 0+ ) {+ const queries = [...insertQueries, ...updateQueries, ...deleteQueries];+ await window.neuron.executeWorkspaceMutation(+ this.workspace.accountId,+ this.workspace.id,+ queries,+ );+ }+ }++ private buildNodesMapFromEditorContent(+ editorContent: JSONContent,+ ): Map<string, LocalNode> {+ const newNodesMap = new Map<string, LocalNode>();+ if (editorContent.content && editorContent.content.length > 0) {+ for (const child of editorContent.content) {+ this.buildNodeFromEditorContent(this.rootNode.id, child, newNodesMap);+ }+ }+ this.validateNodesIndexes(newNodesMap);+ return newNodesMap;+ }++ private buildNodeFromEditorContent(+ parentId: string,+ content: JSONContent,+ newNodesMap: Map<string, LocalNode>,+ ) {+ let id = content.attrs?.id;+ if (!id) {+ id = NeuronId.generate(NeuronId.getIdTypeFromNode(content.type));+ }++ const existingNode = this.nodesMap.get(id);+ const newNode: LocalNode = existingNode+ ? { ...existingNode }+ : {+ id,+ type: content.type,+ parentId,+ index: null,+ attrs: null,+ content: null,+ createdAt: new Date().toISOString(),+ createdBy: this.workspace.userId,+ updatedAt: null,+ updatedBy: null,+ versionId: NeuronId.generate(NeuronId.Type.Version),+ serverCreatedAt: null,+ serverUpdatedAt: null,+ serverVersionId: null,+ };++ if (parentId !== newNode.parentId) {+ newNode.parentId = parentId;+ }++ if (content.attrs) {+ let attrs = { ...content.attrs };+ delete attrs.id;++ if (Object.keys(attrs).length > 0) {+ newNode.attrs = attrs;+ }+ }++ const contentChildren = content.content;+ const hasContentChildren = contentChildren && contentChildren.length > 0;+ const isLeafNode = LeafNodeTypes.includes(content.type);++ if (hasContentChildren && isLeafNode) {+ const nodeContent: NodeBlock[] = [];++ 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,+ };+ });+ }++ nodeContent.push(nodeBlock);+ }++ if (nodeContent.length > 0) {+ newNode.content = nodeContent;+ }+ }++ newNodesMap.set(newNode.id, newNode);++ if (hasContentChildren && !isLeafNode) {+ for (const child of content.content) {+ this.buildNodeFromEditorContent(newNode.id, child, newNodesMap);+ }+ }+ }++ private validateNodesIndexes(nodesMap: Map<string, LocalNode>) {+ //group by parentId+ const groupedNodes: { [key: string]: LocalNode[] } = {};+ for (const node of nodesMap.values()) {+ 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);+ }+ }+ }+ }++ private checkNodesChanges(+ newNodesMap: Map<string, LocalNode>,+ editor: Editor,+ ) {+ const allNodeIds = new Set([+ ...this.nodesMap.keys(),+ ...newNodesMap.keys(),+ ]);+ let hasChanges = false;++ for (const nodeId of allNodeIds) {+ const oldNode = this.nodesMap.get(nodeId);+ const newNode = newNodesMap.get(nodeId);++ if (!oldNode) {+ this.nodesMap.set(newNode.id, newNode);+ hasChanges = true;+ } else if (!newNode) {+ this.nodesMap.delete(oldNode.id);+ hasChanges = true;+ } else if (+ !this.nodeEquals(oldNode, newNode) &&+ oldNode.updatedAt !== null &&+ newNode.updatedAt !== null+ ) {+ const oldUpdatedAt = new Date(oldNode.updatedAt);+ const newUpdatedAt = new Date(newNode.updatedAt);+ if (oldUpdatedAt < newUpdatedAt) {+ this.nodesMap.set(newNode.id, newNode);+ hasChanges = true;+ }+ }+ }++ if (hasChanges) {+ this.editorContent = this.buildEditorContent();+ const selection = editor.state.selection;+ if (selection.$anchor != null && selection.$head != null) {+ editor+ .chain()+ .setContent(this.editorContent)+ .setTextSelection(selection)+ .run();+ } else {+ editor.chain().setContent(this.editorContent).run();+ }+ }+ }++ private nodeEquals(oldNode: LocalNode, newNode: LocalNode): boolean {+ if (oldNode.index !== newNode.index) {+ return false;+ }++ if (oldNode.parentId !== newNode.parentId) {+ return false;+ }++ if (oldNode.type !== newNode.type) {+ return false;+ }++ if (!isEqual(oldNode.attrs, newNode.attrs)) {+ return false;+ }++ if (!isEqual(oldNode.content, newNode.content)) {+ return false;+ }++ return true;+ }+}diff --git a/desktop/src/editor/utils.ts b/desktop/src/editor/utils.tsdeleted file mode 100644index 56eebd0a..00000000--- a/desktop/src/editor/utils.ts+++ /dev/null@@ -1,294 +0,0 @@-import { LocalNode, 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 mapNodesToEditorNodes = (- nodes: LocalNode[],-): Map<string, EditorNode> => {- const editorNodes = new Map<string, EditorNode>();- for (const node of nodes) {- const editorNode = mapNodeToEditorNode(node);- editorNodes.set(editorNode.id, editorNode);- }-- return editorNodes;-};--export const mapNodeToEditorNode = (node: LocalNode): EditorNode => {- return {- id: node.id,- type: node.type,- parentId: node.parentId,- attrs:- node.attrs !== null &&- node.attrs !== undefined &&- Object.keys(node.attrs).length > 0- ? node.attrs- : null,- content:- node.content !== null &&- node.content !== undefined &&- node.content.length > 0- ? node.content- : null,- index: node.index,- };-};--export const mapEditorNodesToJSONContent = (- rootId: string,- editorNodesMap: Map<string, EditorNode>,-): JSONContent => {- const editorNodes = Array.from(editorNodesMap.values());- const contents: JSONContent[] = [];- const childrenNodes = editorNodes- .filter((node) => node.parentId === rootId)- .sort((a, b) => {- if (a.index < b.index) {- return -1;- } else if (a.index > b.index) {- return 1;- }-- return 0;- });-- for (const child of childrenNodes) {- const content = mapEditorNodeToJSONContent(child, editorNodes);- contents.push(content);- }-- if (!contents.length) {- contents.push({- type: 'paragraph',- });- }-- return {- type: 'doc',- content: contents,- };-};--const mapEditorNodeToJSONContent = (- node: EditorNode,- nodes: EditorNode[],-): JSONContent => {- const nodeJSONContent: JSONContent = {- type: node.type,- attrs: {- ...node.attrs,- id: node.id,- index: node.index,- },- };-- const childrenNodes = nodes- .filter((n) => n.parentId === node.id)- .sort((a, b) => {- if (a.index < b.index) {- return -1;- } else if (a.index > b.index) {- return 1;- }-- return 0;- });-- if (childrenNodes.length > 0) {- nodeJSONContent.content = nodeJSONContent.content || [];- childrenNodes.forEach((child) => {- nodeJSONContent.content.push(mapEditorNodeToJSONContent(child, nodes));- });- } else if (node.content && node.content.length > 0) {- nodeJSONContent.content = nodeJSONContent.content || [];- node.content.forEach((child) => {- const childContent: JSONContent = {- type: child.type,- text: child.text,- };-- if (child.marks && child.marks.length > 0) {- childContent.marks = child.marks.map((mark) => {- return {- type: mark.type,- attrs: mark.attrs,- };- });- }-- nodeJSONContent.content.push(childContent);- });- }-- return nodeJSONContent;-};--export const mapJSONContentToEditorNodes = (- rootId: string,- content: JSONContent,-): Map<string, EditorNode> => {- const nodes: Map<string, EditorNode> = new Map();- 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: Map<string, 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,- content: null,- };- editorNodes.set(id, editorNode);-- if (!content.content) {- return;- }-- 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: Map<string, EditorNode>,-): void => {- //group by parentId- const groupedNodes: { [key: string]: EditorNode[] } = {};- for (const node of editorNodes.values()) {- 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 (!isEqual(a[i], b[i])) {- return false;- }- }-- return true;-};--export const editorNodeMapEquals = (- a: Map<string, EditorNode>,- b: Map<string, EditorNode>,-): boolean => {- if (a.size !== b.size) {- return false;- }-- for (const [key, value] of a) {- const otherValue = b.get(key);- if (!otherValue || !isEqual(value, otherValue)) {- return false;- }- }-- return true;-};diff --git a/desktop/src/lib/nodes.ts b/desktop/src/lib/nodes.tsindex 1a3c63ba..c8d05337 100644--- a/desktop/src/lib/nodes.ts+++ b/desktop/src/lib/nodes.ts@@ -41,5 +41,16 @@ export const mapNode = (row: SelectNode): LocalNode => {versionId: row.version_id,serverCreatedAt: row.server_created_at,serverUpdatedAt: row.server_updated_at,+ serverVersionId: row.server_version_id,};};++export const compareNodeIndex = (a: LocalNode, b: LocalNode): number => {+ if (a.index < b.index) {+ return -1;+ } else if (a.index > b.index) {+ return 1;+ }++ return 0;+};diff --git a/desktop/src/types/editor.ts b/desktop/src/types/editor.tsindex f3de5f42..36e0e8ee 100644--- a/desktop/src/types/editor.ts+++ b/desktop/src/types/editor.ts@@ -18,12 +18,3 @@ 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;-};diff --git a/desktop/src/types/nodes.ts b/desktop/src/types/nodes.tsindex 9875ae05..5266676e 100644--- a/desktop/src/types/nodes.ts+++ b/desktop/src/types/nodes.ts@@ -1,18 +1,18 @@export type LocalNode = {id: string;- parentId?: string | null;+ parentId: string | null;type: string;- index?: string | null;- attrs?: Record<string, any> | null;- content?: NodeBlock[] | null;+ index: string | null;+ attrs: Record<string, any> | null;+ content: NodeBlock[] | null;createdAt: string;createdBy: string;- updatedAt?: string | null;- updatedBy?: string | null;+ updatedAt: string | null;+ updatedBy: string | null;versionId: string;- serverCreatedAt?: string | null;- serverUpdatedAt?: string | null;- serverVersionId?: string | null;+ serverCreatedAt: string | null;+ serverUpdatedAt: string | null;+ serverVersionId: string | null;};export type NodeBlock = {@@ -32,16 +32,16 @@ export type LocalNodeWithChildren = LocalNode & {export type ServerNode = {id: string;- parentId?: string | null;+ parentId: string | null;type: string;- index?: string | null;- attrs?: Record<string, any> | null;- content?: NodeBlock[] | null;+ index: string | null;+ attrs: Record<string, any> | null;+ content: NodeBlock[] | null;createdAt: string;createdBy: string;- updatedAt?: string | null;- updatedBy?: string | null;+ updatedAt: string | null;+ updatedBy: string | null;versionId: string;- serverCreatedAt?: string | null;- serverUpdatedAt?: string | null;+ serverCreatedAt: string | null;+ serverUpdatedAt: string | null;};