Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Improve node creation and conversation state management

Hakan Shehu020c8922af92
diff --git a/desktop/src/components/accounts/email-login.tsx b/desktop/src/components/accounts/email-login.tsx
index e4754b8b..01658839 100644
--- a/desktop/src/components/accounts/email-login.tsx
+++ b/desktop/src/components/accounts/email-login.tsx
@@ -14,9 +14,9 @@ import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoginOutput } from '@/types/accounts';
import { toast } from '@/components/ui/use-toast';
-import {parseApiError} from "@/lib/axios";
-import {Icon} from "@/components/ui/icon";
-import axios from "axios";
+import { parseApiError } from '@/lib/axios';
+import { Icon } from '@/components/ui/icon';
+import axios from 'axios';
const formSchema = z.object({
email: z.string().min(2).email(),
@@ -57,7 +57,7 @@ export const EmailLogin = ({ serverUrl, onLogin }: EmailLoginProps) => {
} finally {
setIsPending(false);
}
- }
+ };
return (
<Form {...form}>
@@ -102,4 +102,4 @@ export const EmailLogin = ({ serverUrl, onLogin }: EmailLoginProps) => {
</form>
</Form>
);
-}
+};
diff --git a/desktop/src/components/messages/conversation.tsx b/desktop/src/components/messages/conversation.tsx
index 28fb30e8..dc0f76aa 100644
--- a/desktop/src/components/messages/conversation.tsx
+++ b/desktop/src/components/messages/conversation.tsx
@@ -1,16 +1,24 @@
import React from 'react';
import { MessageList } from '@/components/messages/message-list';
import { MessageCreate } from '@/components/messages/message-create';
+import { useConversation } from '@/hooks/use-conversation';
+import { observer } from 'mobx-react-lite';
interface ConversationProps {
nodeId: string;
}
-export const Conversation = ({ nodeId }: ConversationProps) => {
+export const Conversation = observer(({ nodeId }: ConversationProps) => {
+ const { nodes, isLoading, createMessage } = useConversation(nodeId);
+
+ if (isLoading) {
+ return <div>Loading...</div>;
+ }
+
return (
<React.Fragment>
- <MessageList nodeId={nodeId} />
- <MessageCreate nodeId={nodeId} />
+ <MessageList conversationId={nodeId} nodes={nodes} />
+ <MessageCreate nodeId={nodeId} onSubmit={createMessage} />
</React.Fragment>
);
-};
+});
diff --git a/desktop/src/components/messages/message-create.tsx b/desktop/src/components/messages/message-create.tsx
index f1d528e9..2bf2bede 100644
--- a/desktop/src/components/messages/message-create.tsx
+++ b/desktop/src/components/messages/message-create.tsx
@@ -1,71 +1,27 @@
import React from 'react';
import { MessageEditor } from '@/components/messages/message-editor';
import { observer } from 'mobx-react-lite';
-import { useWorkspace } from '@/contexts/workspace';
import { JSONContent } from '@tiptap/core';
-import { Node } from '@/types/nodes';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
-import { buildNodes } from '@/editor/utils';
interface MessageCreateProps {
nodeId: string;
+ onSubmit: (content: JSONContent) => void;
}
-export const MessageCreate = observer(({ nodeId }: MessageCreateProps) => {
- const workspace = useWorkspace();
-
- const handleSubmit = async (content: JSONContent) => {
- // Create a new message
- const message: Node = {
- id: NeuronId.generate(NeuronId.Type.Message),
- parentId: nodeId,
- type: NodeTypes.Message,
- content: [],
- workspaceId: workspace.id,
- attrs: {},
- createdAt: new Date(),
- createdBy: workspace.userNodeId,
- versionId: NeuronId.generate(NeuronId.Type.Version),
- };
-
- const childNodes = buildNodes(workspace, message, content.content, []);
-
- const newNodes = [message, ...childNodes];
- await workspace.addNodes(newNodes);
- };
-
- return (
- <div className="mt-1 px-10">
- <div className="flex flex-col">
- {/*{replyTo && conversationId !== user.id && (*/}
- {/* <div className="flex flex-row items-center justify-between rounded-t-lg border-b-2 bg-gray-100 p-2 text-foreground">*/}
- {/* <p className="text-sm">*/}
- {/* Replying to{' '}*/}
- {/* <span className="font-semibold">{replyTo.actor.name}</span>*/}
- {/* </p>*/}
- {/* <button*/}
- {/* className="cursor-pointer"*/}
- {/* onClick={() => {*/}
- {/* setReplyTo(null);*/}
- {/* if (messageEditorRef.current) {*/}
- {/* messageEditorRef.current.focus();*/}
- {/* }*/}
- {/* }}*/}
- {/* >*/}
- {/* <Icon name="close-circle-line" />*/}
- {/* </button>*/}
- {/* </div>*/}
- {/*)}*/}
-
- <MessageEditor
- nodeId={nodeId}
- onSubmit={handleSubmit}
- canEdit={true}
- canSubmit={true}
- />
+export const MessageCreate = observer(
+ ({ nodeId, onSubmit }: MessageCreateProps) => {
+ return (
+ <div className="mt-1 px-10">
+ <div className="flex flex-col">
+ <MessageEditor
+ nodeId={nodeId}
+ onSubmit={onSubmit}
+ canEdit={true}
+ canSubmit={true}
+ />
+ </div>
+ <div className="flex h-8 min-h-8 items-center text-xs text-muted-foreground"></div>
</div>
- <div className="flex h-8 min-h-8 items-center text-xs text-muted-foreground"></div>
- </div>
- );
-});
+ );
+ },
+);
diff --git a/desktop/src/components/messages/message-list.tsx b/desktop/src/components/messages/message-list.tsx
index 43b068d5..bd88f1ba 100644
--- a/desktop/src/components/messages/message-list.tsx
+++ b/desktop/src/components/messages/message-list.tsx
@@ -1,20 +1,26 @@
import React from 'react';
+import { Node } from '@/types/nodes';
import { ScrollArea } from '@/components/ui/scroll-area';
import { InView } from 'react-intersection-observer';
import { Message } from '@/components/messages/message';
-import { useWorkspace } from '@/contexts/workspace';
interface MessageListProps {
- nodeId: string;
+ conversationId: string;
+ nodes: Node[];
}
-export const MessageList = ({ nodeId }: MessageListProps) => {
- const workspace = useWorkspace();
- const nodes = workspace.getNodes();
-
- const messages = nodes.filter(
- (node) => node.type === 'message' && node.parentId === nodeId,
- );
+export const MessageList = ({ conversationId, nodes }: MessageListProps) => {
+ const messages = nodes
+ .filter((node) => node.type === 'message')
+ .sort((a, b) => {
+ if (a.id > b.id) {
+ return 1;
+ } else if (a.id < b.id) {
+ return -1;
+ } else {
+ return 0;
+ }
+ });
const viewportRef = React.useRef<HTMLDivElement>(null);
const containerRef = React.useRef<HTMLDivElement>(null);
@@ -52,9 +58,7 @@ export const MessageList = ({ nodeId }: MessageListProps) => {
}
};
}
-
- return () => {};
- }, [nodeId]);
+ }, [conversationId]);
const handleScroll = () => {
if (viewportRef.current) {
@@ -106,7 +110,11 @@ export const MessageList = ({ nodeId }: MessageListProps) => {
<div className="flex-grow border-t border-gray-100" />
</div>
)}
- <Message message={message} previousMessage={previousMessage} />
+ <Message
+ message={message}
+ previousMessage={previousMessage}
+ nodes={nodes}
+ />
</React.Fragment>
);
})}
diff --git a/desktop/src/components/messages/message.tsx b/desktop/src/components/messages/message.tsx
index 4eecdf02..26fafa16 100644
--- a/desktop/src/components/messages/message.tsx
+++ b/desktop/src/components/messages/message.tsx
@@ -21,13 +21,11 @@ import { NodeRenderer } from '@/editor/renderers/node';
interface MessageProps {
message: Node;
previousMessage?: Node;
+ nodes: Node[];
}
export const Message = observer(
- ({ message, previousMessage }: MessageProps) => {
- const workspace = useWorkspace();
- const nodes = workspace.getNodes();
-
+ ({ message, previousMessage, nodes }: MessageProps) => {
const author = nodes.find((node) => node.id === message.createdBy) ?? {
attrs: {
id: message.createdBy,
@@ -36,6 +34,17 @@ export const Message = observer(
};
const shouldDisplayUserInfo = () => {
+ if (!previousMessage) {
+ return true;
+ }
+
+ const previousMessageDate = new Date(previousMessage.createdAt);
+ const currentMessageDate = new Date(message.createdAt);
+
+ if (previousMessageDate.getDate() !== currentMessageDate.getDate()) {
+ return true;
+ }
+
return (
!previousMessage || previousMessage.createdBy !== message.createdBy
);
@@ -104,7 +113,11 @@ export const Message = observer(
</li>
)}
<li className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200">
- <MessageReactionPicker onEmojiSelect={() => {}} />
+ <MessageReactionPicker
+ onEmojiSelect={(emoji) => {
+ console.log(emoji);
+ }}
+ />
</li>
<li
className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200"
diff --git a/desktop/src/components/spaces/space-create-dialog.tsx b/desktop/src/components/spaces/space-create-dialog.tsx
index 55a7ec49..1f434b93 100644
--- a/desktop/src/components/spaces/space-create-dialog.tsx
+++ b/desktop/src/components/spaces/space-create-dialog.tsx
@@ -23,9 +23,10 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
-import { Node } from '@/types/nodes';
+import { CreateNodeInput, Node } from '@/types/nodes';
import { NeuronId } from '@/lib/id';
import { generateKeyBetween } from 'fractional-indexing-jittered';
+import { NodeTypes } from '@/lib/constants';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -59,48 +60,37 @@ export const SpaceCreateDialog = ({
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
setIsPending(true);
- const spaceNode: Node = {
+ const spaceInput: CreateNodeInput = {
id: NeuronId.generate(NeuronId.Type.Space),
- type: 'space',
+ type: NodeTypes.Space,
parentId: null,
attrs: {
name: values.name,
description: values.description,
},
- workspaceId: workspace.id,
- createdAt: new Date(),
- createdBy: workspace.userNodeId,
- versionId: NeuronId.generate(NeuronId.Type.Version),
};
- const pageNode: Node = {
+
+ const pageInput: CreateNodeInput = {
id: NeuronId.generate(NeuronId.Type.Page),
- type: 'page',
+ type: NodeTypes.Page,
attrs: {
name: 'Home',
},
index: generateKeyBetween(null, null),
- workspaceId: workspace.id,
- parentId: spaceNode.id,
- createdAt: new Date(),
- createdBy: workspace.userNodeId,
- versionId: NeuronId.generate(NeuronId.Type.Version),
+ parentId: spaceInput.id,
};
- const channelNode: Node = {
+ const channelInput: CreateNodeInput = {
id: NeuronId.generate(NeuronId.Type.Channel),
- type: 'channel',
+ type: NodeTypes.Channel,
attrs: {
name: 'Discussions',
},
- index: generateKeyBetween(pageNode.index, null),
- workspaceId: workspace.id,
- parentId: spaceNode.id,
- createdAt: new Date(),
- createdBy: workspace.userNodeId,
- versionId: NeuronId.generate(NeuronId.Type.Version),
+ index: generateKeyBetween(pageInput.index, null),
+ parentId: spaceInput.id,
};
- await workspace.addNodes([spaceNode, pageNode, channelNode]);
+ await workspace.createNodes([spaceInput, pageInput, channelInput]);
setIsPending(false);
onOpenChange(false);
};
diff --git a/desktop/src/components/workspaces/workspace.tsx b/desktop/src/components/workspaces/workspace.tsx
index ed4f1714..aeb0de72 100644
--- a/desktop/src/components/workspaces/workspace.tsx
+++ b/desktop/src/components/workspaces/workspace.tsx
@@ -19,21 +19,19 @@ export const Workspace = observer(() => {
<WorkspaceContext.Provider
value={{
...workspace,
- addNode: async (node) => {
- await window.workspaceDb.addNode(
+ createNode: async (input) => {
+ await window.workspaceDb.createNode(
workspace.accountId,
workspace.id,
- node,
+ input,
);
- workspace.setNode(node);
},
- addNodes: async (nodes) => {
- await window.workspaceDb.addNodes(
+ createNodes: async (inputs) => {
+ await window.workspaceDb.createNodes(
workspace.accountId,
workspace.id,
- nodes,
+ inputs,
);
- nodes.forEach((node) => workspace.setNode(node));
},
getNodes: () => {
return workspace.getNodes();
@@ -57,6 +55,15 @@ export const Workspace = observer(() => {
setContainerNode: (nodeId) => {
workspace.setContainerNode(nodeId);
},
+ getConversationNodes: async (conversationId, count, after) => {
+ return await window.workspaceDb.getConversationNodes(
+ workspace.accountId,
+ workspace.id,
+ conversationId,
+ count,
+ after,
+ );
+ },
}}
>
<div className="flex h-screen max-h-screen flex-row">
diff --git a/desktop/src/contexts/workspace.ts b/desktop/src/contexts/workspace.ts
index 0a826548..77e90345 100644
--- a/desktop/src/contexts/workspace.ts
+++ b/desktop/src/contexts/workspace.ts
@@ -1,14 +1,16 @@
import { createContext, useContext } from 'react';
import { Workspace } from '@/types/workspaces';
-import { Node } from '@/types/nodes';
+import { CreateNodeInput, Node } from '@/types/nodes';
interface WorkspaceContext extends Workspace {
- addNode: (node: Node) => Promise<void>;
- addNodes: (nodes: Node[]) => Promise<void>;
+ createNode: (input: CreateNodeInput) => Promise<void>;
+ createNodes: (inputs: CreateNodeInput[]) => Promise<void>;
getNodes: () => Node[];
updateNode: (node: Node) => Promise<void>;
deleteNode: (nodeId: string) => Promise<void>;
setContainerNode: (nodeId?: string | null) => void;
+
+ getConversationNodes: (conversationId: string, count: number, after?: string | null) => Promise<Node[]>;
}
export const WorkspaceContext = createContext<WorkspaceContext>(
diff --git a/desktop/src/electron/database/global/index.ts b/desktop/src/electron/database/global/index.ts
index 9c0c3572..7329b16d 100644
--- a/desktop/src/electron/database/global/index.ts
+++ b/desktop/src/electron/database/global/index.ts
@@ -4,7 +4,7 @@ import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
import { GlobalDatabaseSchema } from '@/electron/database/global/schema';
import { Account } from '@/types/accounts';
import { Workspace } from '@/types/workspaces';
-import { Transaction } from '@/types/transactions';
+import { Transaction, TransactionType } from '@/types/transactions';
import { globalDatabaseMigrations } from '@/electron/database/global/migrations';
import { GlobalDatabaseData, WorkspaceDatabaseData } from '@/types/global';
import { WorkspaceDatabase } from '@/electron/database/workspace';
@@ -77,6 +77,7 @@ export class GlobalDatabase {
const workspaceDatabase = new WorkspaceDatabase(
workspace.accountId,
workspace.id,
+ workspace.userNodeId,
this,
);
await workspaceDatabase.migrate();
@@ -164,8 +165,8 @@ export class GlobalDatabase {
id: transaction.id,
type: transaction.type,
account_id: transaction.accountId,
+ user_id: transaction.userId,
input: transaction.input,
- node_id: transaction.nodeId,
created_at: transaction.createdAt.toISOString(),
workspace_id: transaction.workspaceId,
})
@@ -183,7 +184,8 @@ export class GlobalDatabase {
id: transaction.id,
workspaceId: transaction.workspace_id,
accountId: transaction.account_id,
- type: transaction.type,
+ userId: transaction.user_id,
+ type: transaction.type as TransactionType,
nodeId: transaction.node_id,
input: transaction.input,
createdAt: new Date(transaction.created_at),
diff --git a/desktop/src/electron/database/global/migrations.ts b/desktop/src/electron/database/global/migrations.ts
index bfc8ae9a..44fed7cd 100644
--- a/desktop/src/electron/database/global/migrations.ts
+++ b/desktop/src/electron/database/global/migrations.ts
@@ -44,8 +44,8 @@ const createTransactionsTable: Migration = {
.addColumn('id', 'text', (col) => col.notNull().primaryKey())
.addColumn('workspace_id', 'text', (col) => col.notNull())
.addColumn('account_id', 'text', (col) => col.notNull())
+ .addColumn('user_id', 'text', (col) => col.notNull())
.addColumn('type', 'text', (col) => col.notNull())
- .addColumn('node_id', 'text', (col) => col.notNull())
.addColumn('input', 'text', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
.execute();
diff --git a/desktop/src/electron/database/global/schema.ts b/desktop/src/electron/database/global/schema.ts
index 912c5bb9..902cb4af 100644
--- a/desktop/src/electron/database/global/schema.ts
+++ b/desktop/src/electron/database/global/schema.ts
@@ -23,6 +23,7 @@ export interface TransactionsTableSchema {
id: string;
workspace_id: string;
account_id: string;
+ user_id: string;
type: string;
node_id: string;
input: string;
diff --git a/desktop/src/electron/database/workspace/index.ts b/desktop/src/electron/database/workspace/index.ts
index 0a64b768..3bdad72e 100644
--- a/desktop/src/electron/database/workspace/index.ts
+++ b/desktop/src/electron/database/workspace/index.ts
@@ -5,23 +5,26 @@ import { WorkspaceDatabaseSchema } from '@/electron/database/workspace/schema';
import { workspaceDatabaseMigrations } from '@/electron/database/workspace/migrations';
import * as fs from 'node:fs';
import { GlobalDatabase } from '@/electron/database/global';
-import { Node } from '@/types/nodes';
+import { CreateNodeInput, Node } from '@/types/nodes';
import { NeuronId } from '@/lib/id';
export class WorkspaceDatabase {
accountId: string;
workspaceId: string;
+ userId: string;
database: Kysely<WorkspaceDatabaseSchema>;
globalDatabase: GlobalDatabase;
constructor(
accountId: string,
workspaceId: string,
+ userId: string,
globalDatabase: GlobalDatabase,
) {
this.accountId = accountId;
this.workspaceId = workspaceId;
this.globalDatabase = globalDatabase;
+ this.userId = userId;
const appPath = app.getPath('userData');
const accountPath = `${appPath}/account_${accountId}`;
@@ -57,70 +60,95 @@ export class WorkspaceDatabase {
}));
};
- addNode = async (node: Node) => {
- await this.database
+ createNode = async (input: CreateNodeInput) => {
+ const insertedRow = await this.database
.insertInto('nodes')
.values({
- id: node.id,
- type: node.type,
- index: node.index,
- parent_id: node.parentId,
+ id: input.id,
+ type: input.type,
+ index: input.index,
+ parent_id: input.parentId,
workspace_id: this.workspaceId,
- created_at: new Date(node.createdAt).toISOString(),
- created_by: node.createdBy,
- version_id: node.versionId,
- attrs: JSON.stringify(node.attrs),
- content: JSON.stringify(node.content),
- updated_at: node.updatedAt
- ? new Date(node.updatedAt).toISOString()
- : null,
- updated_by: node.updatedBy,
+ created_at: new Date().toISOString(),
+ created_by: this.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ attrs: input.attrs && JSON.stringify(input.attrs),
+ content: input.content && JSON.stringify(input.content)
})
- .execute();
+ .returningAll()
+ .executeTakeFirst();
+
+ const node: Node = {
+ id: insertedRow.id,
+ type: insertedRow.type,
+ index: insertedRow.index,
+ parentId: insertedRow.parent_id,
+ workspaceId: insertedRow.workspace_id,
+ attrs: insertedRow.attrs && JSON.parse(insertedRow.attrs),
+ content: insertedRow.content && JSON.parse(insertedRow.content),
+ createdAt: new Date(insertedRow.created_at),
+ createdBy: insertedRow.created_by,
+ updatedAt: insertedRow.updated_at ? new Date(insertedRow.updated_at) : null,
+ updatedBy: insertedRow.updated_by,
+ versionId: insertedRow.version_id,
+ }
await this.globalDatabase.addTransaction({
id: NeuronId.generate(NeuronId.Type.Transaction),
- nodeId: node.id,
type: 'create_node',
- workspaceId: node.workspaceId,
+ workspaceId: this.workspaceId,
+ userId: this.userId,
accountId: this.accountId,
input: JSON.stringify(node),
createdAt: new Date(),
});
};
- addNodes = async (nodes: Node[]) => {
- await this.database
+ createNodes = async (inputs: CreateNodeInput[]) => {
+ const insertedRows = await this.database
.insertInto('nodes')
.values(
- nodes.map((node) => ({
- id: node.id,
- type: node.type,
- index: node.index,
- parent_id: node.parentId,
+ inputs.map((input) => ({
+ id: input.id,
+ type: input.type,
+ index: input.index,
+ parent_id: input.parentId,
workspace_id: this.workspaceId,
- created_at: node.createdAt.toISOString(),
- created_by: node.createdBy,
- version_id: node.versionId,
- attrs: JSON.stringify(node.attrs),
- content: JSON.stringify(node.content),
+ created_at: new Date().toISOString(),
+ created_by: this.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ attrs: input.attrs && JSON.stringify(input.attrs),
+ content: input.content && JSON.stringify(input.content),
})),
)
+ .returningAll()
.execute();
-
- // TODO: insert as single transaction
- for (const node of nodes) {
- await this.globalDatabase.addTransaction({
- id: NeuronId.generate(NeuronId.Type.Transaction),
- nodeId: node.id,
- type: 'create_node',
- workspaceId: node.workspaceId,
- accountId: this.accountId,
- input: JSON.stringify(node),
- createdAt: new Date(),
- });
- }
- };
+
+ const nodes = insertedRows.map((node) => ({
+ id: node.id,
+ type: node.type,
+ index: node.index,
+ parentId: node.parent_id,
+ workspaceId: node.workspace_id,
+ attrs: node.attrs && JSON.parse(node.attrs),
+ content: node.content && JSON.parse(node.content),
+ createdAt: new Date(node.created_at),
+ createdBy: node.created_by,
+ updatedAt: node.updated_at ? new Date(node.updated_at) : null,
+ updatedBy: node.updated_by,
+ versionId: node.version_id,
+ }));
+
+ await this.globalDatabase.addTransaction({
+ id: NeuronId.generate(NeuronId.Type.Transaction),
+ type: 'create_nodes',
+ workspaceId: this.workspaceId,
+ userId: this.userId,
+ accountId: this.accountId,
+ input: JSON.stringify(nodes),
+ createdAt: new Date(),
+ });
+ }
updateNode = async (node: Node) => {
await this.database
@@ -138,29 +166,29 @@ export class WorkspaceDatabase {
.where('id', '=', node.id)
.executeTakeFirst();
- await this.globalDatabase.addTransaction({
- id: NeuronId.generate(NeuronId.Type.Transaction),
- nodeId: node.id,
- type: 'update_node',
- workspaceId: node.workspaceId,
- accountId: this.accountId,
- input: JSON.stringify(node),
- createdAt: new Date(),
- });
+ // await this.globalDatabase.addTransaction({
+ // id: NeuronId.generate(NeuronId.Type.Transaction),
+ // nodeId: node.id,
+ // type: 'update_node',
+ // workspaceId: node.workspaceId,
+ // accountId: this.accountId,
+ // input: JSON.stringify(node),
+ // createdAt: new Date(),
+ // });
};
deleteNode = async (nodeId: string) => {
await this.database.deleteFrom('nodes').where('id', '=', nodeId).execute();
- await this.globalDatabase.addTransaction({
- id: NeuronId.generate(NeuronId.Type.Transaction),
- nodeId: nodeId,
- type: 'delete_node',
- workspaceId: this.workspaceId,
- accountId: this.accountId,
- input: JSON.stringify({ nodeId }),
- createdAt: new Date(),
- });
+ // await this.globalDatabase.addTransaction({
+ // id: NeuronId.generate(NeuronId.Type.Transaction),
+ // nodeId: nodeId,
+ // type: 'delete_node',
+ // workspaceId: this.workspaceId,
+ // accountId: this.accountId,
+ // input: JSON.stringify({ nodeId }),
+ // createdAt: new Date(),
+ // });
};
syncNodes = async (nodes: Node[]) => {
@@ -215,6 +243,60 @@ export class WorkspaceDatabase {
}
};
+ getConversationNodes = async (conversationId: string, count: number, after?: string | null): Promise<Node[]> => {
+ const messageQuery = this.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('type', '=', 'message')
+ .where('parent_id', '=', conversationId);
+
+ if (after) {
+ messageQuery.where('id', '<', after);
+ }
+
+ const messages = await messageQuery
+ .orderBy('created_at', 'desc')
+ .limit(count)
+ .execute();
+
+ const authorIds = messages.map((message) => message.created_by);
+ const authors = await this.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', 'in', authorIds)
+ .execute();
+
+ const parentIds = messages.map((message) => message.id);
+ const nodes = [...messages, ...authors];
+
+ while (parentIds.length > 0) {
+ const childNodes = await this.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', 'in', parentIds)
+ .execute();
+
+ nodes.push(...childNodes);
+ parentIds.splice(0, parentIds.length);
+ parentIds.push(...childNodes.map((node) => node.id));
+ }
+
+ return nodes.map((node) => ({
+ id: node.id,
+ type: node.type,
+ index: node.index,
+ parentId: node.parent_id,
+ workspaceId: node.workspace_id,
+ attrs: JSON.parse(node.attrs),
+ content: JSON.parse(node.content),
+ createdAt: new Date(node.created_at),
+ createdBy: node.created_by,
+ updatedAt: node.updated_at ? new Date(node.updated_at) : null,
+ updatedBy: node.updated_by,
+ versionId: node.version_id,
+ }));
+ }
+
migrate = async () => {
const migrator = new Migrator({
db: this.database,
diff --git a/desktop/src/hooks/use-conversation.tsx b/desktop/src/hooks/use-conversation.tsx
new file mode 100644
index 00000000..d8ad5c27
--- /dev/null
+++ b/desktop/src/hooks/use-conversation.tsx
@@ -0,0 +1,108 @@
+import React from 'react';
+import { CreateNodeInput, Node } from '@/types/nodes';
+import { useWorkspace } from '@/contexts/workspace';
+import { ConversationStore } from '@/store/conversation';
+import { JSONContent } from '@tiptap/core';
+import { NeuronId } from '@/lib/id';
+import { LeafNodeTypes } from '@/lib/constants';
+import { generateKeyBetween } from 'fractional-indexing-jittered';
+
+interface useConversationResult {
+ isLoading: boolean;
+ nodes: Node[];
+ hasMore: boolean;
+ loadMore: () => void;
+ isLoadingMore: boolean;
+ createMessage: (content: JSONContent) => void;
+}
+
+export const useConversation = (
+ conversationId: string,
+): useConversationResult => {
+ const workspace = useWorkspace();
+ const store = React.useMemo(() => new ConversationStore(), [conversationId]);
+
+ React.useEffect(() => {
+ const fetchNodes = async () => {
+ store.setIsLoading(true);
+ const nodes = await workspace.getConversationNodes(
+ conversationId,
+ 10,
+ null,
+ );
+ store.setNodes(nodes);
+ store.setIsLoading(false);
+ };
+
+ fetchNodes();
+ }, [conversationId]);
+
+ const createMessage = async (content: JSONContent) => {
+ const inputs = buildMessageCreateInputs(conversationId, content);
+ await workspace.createNodes(inputs);
+ };
+
+ return {
+ isLoading: store.isLoading,
+ nodes: store.getNodes(),
+ hasMore: store.hasMore,
+ loadMore: () => console.log('load more'),
+ isLoadingMore: store.isLoadingMore,
+ createMessage: createMessage,
+ };
+};
+
+const buildMessageCreateInputs = (
+ conversationId: string,
+ content: JSONContent,
+): CreateNodeInput[] => {
+ const inputs: CreateNodeInput[] = [];
+ buildMessageCreateInput(content, conversationId, inputs);
+ return inputs;
+};
+
+const buildMessageCreateInput = (
+ content: JSONContent,
+ parentId: string,
+ queue: CreateNodeInput[],
+ index?: string | null,
+): void => {
+ const id = content.attrs?.id ?? NeuronId.generate(NeuronId.Type.Message);
+ const input: CreateNodeInput = {
+ id: id,
+ parentId,
+ type: content.type,
+ attrs: {},
+ index,
+ };
+ queue.push(input);
+
+ if (content.attrs) {
+ delete content.attrs.id;
+ if (Object.keys(content.attrs).length > 0) {
+ input.attrs = content.attrs;
+ }
+ }
+
+ if (LeafNodeTypes.includes(content.type)) {
+ input.content = [];
+ for (const child of content.content) {
+ input.content.push({
+ type: child.type,
+ text: child.text,
+ marks: child.marks?.map((mark) => {
+ return {
+ type: mark.type,
+ attrs: mark.attrs,
+ };
+ }),
+ });
+ }
+ } else {
+ let lastIndex: string | null = null;
+ for (const child of content.content) {
+ lastIndex = generateKeyBetween(lastIndex, null);
+ buildMessageCreateInput(child, id, queue, lastIndex);
+ }
+ }
+};
diff --git a/desktop/src/hooks/use-document.tsx b/desktop/src/hooks/use-document.tsx
index 3801eed0..9abd32e4 100644
--- a/desktop/src/hooks/use-document.tsx
+++ b/desktop/src/hooks/use-document.tsx
@@ -31,16 +31,16 @@ export const useDocument = (node: Node): useNodeResult => {
childNodes,
);
- for (const newNode of newNodes) {
- const existingNode = childNodes.find((n) => n.id === newNode.id);
- if (existingNode) {
- newNode.updatedBy = workspace.userNodeId;
- newNode.updatedAt = new Date();
- await workspace.updateNode(newNode);
- } else {
- await workspace.addNode(newNode);
- }
- }
+ // for (const newNode of newNodes) {
+ // const existingNode = childNodes.find((n) => n.id === newNode.id);
+ // if (existingNode) {
+ // newNode.updatedBy = workspace.userNodeId;
+ // newNode.updatedAt = new Date();
+ // await workspace.updateNode(newNode);
+ // } else {
+ // await workspace.addNode(newNode);
+ // }
+ // }
const nodesToDelete = childNodes.filter(
(n) => n.id != node.id && !newNodes.find((nn) => nn.id === n.id),
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index 002e5464..902999cb 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -24,7 +24,7 @@ export class NeuronId {
return id.endsWith(type);
}
- public static getType(id: string): IdType {
+ public static getNodeTypeFromId(id: string): IdType {
return id.substring(id.length - 2) as IdType;
}
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index b4de5b94..4c148e3b 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -66,20 +66,20 @@ ipcMain.handle('add-transaction', async (_, transaction) =>
globalDatabase.addTransaction(transaction),
);
-ipcMain.handle('add-node', async (_, accountId, workspaceId, node) => {
+ipcMain.handle('create-node', async (_, accountId, workspaceId, input) => {
const workspaceDb = globalDatabase.getWorkspaceDatabase(
accountId,
workspaceId,
);
- await workspaceDb.addNode(node);
+ await workspaceDb.createNode(input);
});
-ipcMain.handle('add-nodes', async (_, accountId, workspaceId, nodes) => {
+ipcMain.handle('create-nodes', async (_, accountId, workspaceId, inputs) => {
const workspaceDb = globalDatabase.getWorkspaceDatabase(
accountId,
workspaceId,
);
- await workspaceDb.addNodes(nodes);
+ await workspaceDb.createNodes(inputs);
});
ipcMain.handle('get-nodes', async (_, accountId, workspaceId) => {
@@ -106,4 +106,12 @@ ipcMain.handle('delete-node', async (_, accountId, workspaceId, nodeId) => {
await workspaceDb.deleteNode(nodeId);
});
+ipcMain.handle('get-conversation-nodes', async (_, accountId, workspaceId, conversationId, count, after) => {
+ const workspaceDb = globalDatabase.getWorkspaceDatabase(
+ accountId,
+ workspaceId,
+ );
+ return await workspaceDb.getConversationNodes(conversationId, count, after);
+});
+
initEventLoop();
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 5423548b..59234baf 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -2,7 +2,7 @@ import { contextBridge, ipcRenderer } from 'electron';
import { Account } from '@/types/accounts';
import { Workspace } from '@/types/workspaces';
import { Transaction } from '@/types/transactions';
-import { Node } from '@/types/nodes';
+import { CreateNodeInput, Node } from '@/types/nodes';
contextBridge.exposeInMainWorld('globalDb', {
init: () => ipcRenderer.invoke('init'),
@@ -16,14 +16,17 @@ contextBridge.exposeInMainWorld('globalDb', {
});
contextBridge.exposeInMainWorld('workspaceDb', {
- addNode: (accountId: string, workspaceId: string, node: Node) =>
- ipcRenderer.invoke('add-node', accountId, workspaceId, node),
- addNodes: (accountId: string, workspaceId: string, nodes: Node[]) =>
- ipcRenderer.invoke('add-nodes', accountId, workspaceId, nodes),
+ createNode: (accountId: string, workspaceId: string, node: CreateNodeInput) =>
+ ipcRenderer.invoke('create-node', accountId, workspaceId, node),
+ createNodes: (accountId: string, workspaceId: string, nodes: CreateNodeInput[]) =>
+ ipcRenderer.invoke('create-nodes', accountId, workspaceId, nodes),
getNodes: (accountId: string, workspaceId: string) =>
ipcRenderer.invoke('get-nodes', accountId, workspaceId),
updateNode: (accountId: string, workspaceId: string, node: Node) =>
ipcRenderer.invoke('update-node', accountId, workspaceId, node),
deleteNode: (accountId: string, workspaceId: string, nodeId: string) =>
ipcRenderer.invoke('delete-node', accountId, workspaceId, nodeId),
+
+ getConversationNodes: (accountId: string, workspaceId: string, conversationId: string, count: number, after?: string | null) =>
+ ipcRenderer.invoke('get-conversation-nodes', accountId, workspaceId, conversationId, count, after),
});
diff --git a/desktop/src/store/conversation.ts b/desktop/src/store/conversation.ts
new file mode 100644
index 00000000..e50bd01b
--- /dev/null
+++ b/desktop/src/store/conversation.ts
@@ -0,0 +1,48 @@
+import { Node } from '@/types/nodes';
+import { makeAutoObservable } from 'mobx';
+
+export class ConversationStore {
+ public nodes: Record<string, Node>;
+ public isLoading: boolean;
+ public hasMore: boolean;
+ public isLoadingMore: boolean;
+
+ constructor() {
+ this.nodes = {};
+ this.isLoading = false;
+ this.hasMore = false;
+ this.isLoadingMore = false;
+
+ makeAutoObservable(this);
+ }
+
+ public setNode(node: Node) {
+ this.nodes[node.id] = node;
+ }
+
+ public setNodes(nodes: Node[]) {
+ nodes.forEach((node) => {
+ this.nodes[node.id] = node;
+ });
+ }
+
+ public setIsLoading(isLoading: boolean) {
+ this.isLoading = isLoading;
+ }
+
+ public setHasMore(hasMore: boolean) {
+ this.hasMore = hasMore;
+ }
+
+ public setIsLoadingMore(isLoadingMore: boolean) {
+ this.isLoadingMore = isLoadingMore;
+ }
+
+ public getNode(nodeId: string) {
+ return this.nodes[nodeId];
+ }
+
+ public getNodes() {
+ return Object.values(this.nodes);
+ }
+}
\ No newline at end of file
diff --git a/desktop/src/types/nodes.ts b/desktop/src/types/nodes.ts
index 965f556a..5993d178 100644
--- a/desktop/src/types/nodes.ts
+++ b/desktop/src/types/nodes.ts
@@ -28,3 +28,12 @@ export type NodeBlockMark = {
export type NodeWithChildren = Node & {
children: NodeWithChildren[];
};
+
+export type CreateNodeInput = {
+ id: string;
+ type: string;
+ parentId?: string | null;
+ index?: string | null;
+ attrs: any;
+ content?: NodeBlock[] | null;
+};
\ No newline at end of file
diff --git a/desktop/src/types/transactions.ts b/desktop/src/types/transactions.ts
index 12b68082..d29c7b4e 100644
--- a/desktop/src/types/transactions.ts
+++ b/desktop/src/types/transactions.ts
@@ -1,9 +1,11 @@
+export type TransactionType = 'create_node' | 'create_nodes' | 'update_node' | 'delete_node';
+
export type Transaction = {
id: string;
+ type: TransactionType;
workspaceId: string;
accountId: string;
- type: string;
- nodeId: string;
+ userId: string;
input: string;
createdAt: Date;
};
diff --git a/desktop/src/types/window.d.ts b/desktop/src/types/window.d.ts
index bdd30aff..2ebf2a25 100644
--- a/desktop/src/types/window.d.ts
+++ b/desktop/src/types/window.d.ts
@@ -1,7 +1,7 @@
import { Workspace } from '@/types/workspaces';
import { Transaction } from '@/types/transactions';
import { Account } from '@/types/accounts';
-import { Node } from '@/types/nodes';
+import { CreateNodeInput, Node } from '@/types/nodes';
import { GlobalDatabaseData } from '@/types/global';
export interface GlobalDbApi {
@@ -14,15 +14,15 @@ export interface GlobalDbApi {
}
export interface WorkspaceDbApi {
- addNode: (
+ createNode: (
accountId: string,
workspaceId: string,
- node: Node,
+ input: CreateNodeInput,
) => Promise<void>;
- addNodes: (
+ createNodes: (
accountId: string,
workspaceId: string,
- nodes: Node[],
+ inputs: CreateNodeInput[],
) => Promise<void>;
getNodes: (accountId: string, workspaceId: string) => Promise<Node[]>;
updateNode: (
@@ -35,6 +35,14 @@ export interface WorkspaceDbApi {
workspaceId: string,
nodeId: string,
) => Promise<void>;
+
+ getConversationNodes: (
+ accountId: string,
+ workspaceId: string,
+ conversationId: string,
+ count: number,
+ after?: string | null,
+ ) => Promise<Node[]>;
}
declare global {
diff --git a/desktop/tsconfig.json b/desktop/tsconfig.json
index a344bd99..19f787d2 100644
--- a/desktop/tsconfig.json
+++ b/desktop/tsconfig.json
@@ -15,5 +15,6 @@
"paths": {
"@/*": ["./src/*"]
}
- }
+ },
+ "exclude": ["node_modules", "build", "dist"],
}
diff --git a/server/src/routes/transactions.ts b/server/src/routes/transactions.ts
index f2f0fab7..9b91416b 100644
--- a/server/src/routes/transactions.ts
+++ b/server/src/routes/transactions.ts
@@ -1,6 +1,6 @@
import { Request, Response, Router } from 'express';
import { Transaction } from '@/types/transactions';
-import { Node } from '@/types/nodes';
+import { DeleteNodeTransactionInput, Node } from '@/types/nodes';
import { prisma } from '@/data/db';
export const transactionsRouter = Router();
@@ -28,6 +28,25 @@ transactionsRouter.post('/', async (req: Request, res: Response) => {
},
});
+ appliedTransactionIds.push(transaction.id);
+ } else if (transaction.type === 'create_nodes') {
+ const nodes = JSON.parse(transaction.input) as Node[];
+ await prisma.nodes.createMany({
+ data: nodes.map((node) => ({
+ id: node.id,
+ parentId: node.parentId,
+ workspaceId: node.workspaceId,
+ type: node.type,
+ index: node.index,
+ attrs: node.attrs,
+ createdAt: node.createdAt,
+ createdBy: node.createdBy,
+ versionId: node.versionId,
+ content: JSON.stringify(node.content),
+ state: node.state,
+ })),
+ });
+
appliedTransactionIds.push(transaction.id);
} else if (transaction.type === 'update_node') {
const node = JSON.parse(transaction.input) as Node;
@@ -46,10 +65,10 @@ transactionsRouter.post('/', async (req: Request, res: Response) => {
appliedTransactionIds.push(transaction.id);
} else if (transaction.type === 'delete_node') {
- // delete node
+ const input = JSON.parse(transaction.input) as DeleteNodeTransactionInput;
await prisma.nodes.delete({
where: {
- id: transaction.nodeId,
+ id: input.id,
},
});
diff --git a/server/src/types/nodes.ts b/server/src/types/nodes.ts
index 4d872dd0..8b7c5fd4 100644
--- a/server/src/types/nodes.ts
+++ b/server/src/types/nodes.ts
@@ -24,3 +24,7 @@ export type NodeBlockMark = {
type: string;
attrs: any;
};
+
+export type DeleteNodeTransactionInput = {
+ id: string;
+};
\ No newline at end of file
diff --git a/server/src/types/transactions.ts b/server/src/types/transactions.ts
index 12b68082..d29c7b4e 100644
--- a/server/src/types/transactions.ts
+++ b/server/src/types/transactions.ts
@@ -1,9 +1,11 @@
+export type TransactionType = 'create_node' | 'create_nodes' | 'update_node' | 'delete_node';
+
export type Transaction = {
id: string;
+ type: TransactionType;
workspaceId: string;
accountId: string;
- type: string;
- nodeId: string;
+ userId: string;
input: string;
createdAt: Date;
};