Skip to content

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

Introduce the event-bus for inter process communication

Hakan Shehua4b84e8fc5fc
diff --git a/desktop/src/electron/database/workspace/index.ts b/desktop/src/electron/database/workspace/index.ts
index 5b8ae904..91dfe02b 100644
--- a/desktop/src/electron/database/workspace/index.ts
+++ b/desktop/src/electron/database/workspace/index.ts
@@ -8,6 +8,7 @@ import { GlobalDatabase } from '@/electron/database/global';
import { CreateNodeInput, Node, UpdateNodeInput } from '@/types/nodes';
import { NeuronId } from '@/lib/id';
import { LeafNodeTypes, RootNodeTypes } from '@/lib/constants';
+import { eventBus } from '@/lib/event-bus';
export class WorkspaceDatabase {
accountId: string;
@@ -103,6 +104,11 @@ export class WorkspaceDatabase {
input: JSON.stringify(node),
createdAt: new Date(),
});
+
+ eventBus.publish({
+ event: 'node_created',
+ payload: node,
+ })
};
createNodes = async (inputs: CreateNodeInput[]) => {
@@ -149,6 +155,13 @@ export class WorkspaceDatabase {
input: JSON.stringify(nodes),
createdAt: new Date(),
});
+
+ nodes.forEach((node) => {
+ eventBus.publish({
+ event: 'node_created',
+ payload: node,
+ });
+ });
}
updateNode = async (input: UpdateNodeInput) => {
@@ -205,10 +218,19 @@ export class WorkspaceDatabase {
input: JSON.stringify(input),
createdAt: new Date(),
});
+
+ eventBus.publish({
+ event: 'node_updated',
+ payload: node,
+ });
};
deleteNode = async (nodeId: string) => {
- await this.database.deleteFrom('nodes').where('id', '=', nodeId).execute();
+ const deletedRow = await this.database
+ .deleteFrom('nodes')
+ .where('id', '=', nodeId)
+ .returningAll()
+ .executeTakeFirst();
await this.globalDatabase.addTransaction({
id: NeuronId.generate(NeuronId.Type.Transaction),
@@ -219,10 +241,34 @@ export class WorkspaceDatabase {
input: nodeId,
createdAt: new Date(),
});
+
+ const node: Node = {
+ id: deletedRow.id,
+ type: deletedRow.type,
+ index: deletedRow.index,
+ parentId: deletedRow.parent_id,
+ workspaceId: deletedRow.workspace_id,
+ attrs: deletedRow.attrs && JSON.parse(deletedRow.attrs),
+ content: deletedRow.content && JSON.parse(deletedRow.content),
+ createdAt: new Date(deletedRow.created_at),
+ createdBy: deletedRow.created_by,
+ updatedAt: deletedRow.updated_at ? new Date(deletedRow.updated_at) : null,
+ updatedBy: deletedRow.updated_by,
+ versionId: deletedRow.version_id,
+ };
+
+ eventBus.publish({
+ event: 'node_deleted',
+ payload: node,
+ });
};
deleteNodes = async (nodeIds: string[]) => {
- await this.database.deleteFrom('nodes').where('id', 'in', nodeIds).execute();
+ const deletedRows = await this.database
+ .deleteFrom('nodes')
+ .where('id', 'in', nodeIds)
+ .returningAll()
+ .execute();
await this.globalDatabase.addTransaction({
id: NeuronId.generate(NeuronId.Type.Transaction),
@@ -233,6 +279,28 @@ export class WorkspaceDatabase {
input: JSON.stringify(nodeIds),
createdAt: new Date(),
});
+
+ const nodes = deletedRows.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,
+ }));
+
+ nodes.forEach((node) => {
+ eventBus.publish({
+ event: 'node_deleted',
+ payload: node,
+ });
+ });
}
syncNodes = async (nodes: Node[]) => {
diff --git a/desktop/src/hooks/use-conversation.tsx b/desktop/src/hooks/use-conversation.tsx
index 8fd62507..f4ce24d6 100644
--- a/desktop/src/hooks/use-conversation.tsx
+++ b/desktop/src/hooks/use-conversation.tsx
@@ -6,6 +6,7 @@ import { JSONContent } from '@tiptap/core';
import { NeuronId } from '@/lib/id';
import { LeafNodeTypes } from '@/lib/constants';
import { generateNodeIndex } from '@/lib/nodes';
+import { useEventBus } from './use-event-bus';
interface useConversationResult {
isLoading: boolean;
@@ -20,6 +21,7 @@ export const useConversation = (
conversationId: string,
): useConversationResult => {
const workspace = useWorkspace();
+ const eventBus = useEventBus();
const store = React.useMemo(() => new ConversationStore(), [conversationId]);
React.useEffect(() => {
@@ -35,6 +37,14 @@ export const useConversation = (
};
fetchNodes();
+
+ const subscriptionId = eventBus.subscribe((event) => {
+ console.log('event', event);
+ });
+
+ return () => {
+ eventBus.unsubscribe(subscriptionId);
+ };
}, [conversationId]);
const createMessage = async (content: JSONContent) => {
diff --git a/desktop/src/hooks/use-document.tsx b/desktop/src/hooks/use-document.tsx
index 8d31dfbc..35d5e40b 100644
--- a/desktop/src/hooks/use-document.tsx
+++ b/desktop/src/hooks/use-document.tsx
@@ -12,6 +12,7 @@ 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 {
isLoading: boolean;
@@ -31,10 +32,11 @@ export type NodeFromEditor = {
export const useDocument = (node: Node): useNodeResult => {
const workspace = useWorkspace();
+ const eventBus = useEventBus();
const store = React.useMemo(() => new DocumentStore(), [node.id]);
React.useEffect(() => {
- const fetchNode = async () => {
+ const fetchNodes = async () => {
store.setIsLoading(true);
const nodes = await workspace.getDocumentNodes(node.id);
@@ -43,7 +45,35 @@ export const useDocument = (node: Node): useNodeResult => {
store.setIsLoading(false);
};
- fetchNode();
+ 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(
@@ -97,9 +127,9 @@ export const useDocument = (node: Node): useNodeResult => {
}
if (nodesToUpdate.length > 0) {
- nodesToUpdate.forEach((nodeToUpdate) => {
- workspace.updateNode(nodeToUpdate);
- });
+ for (const nodeToUpdate of nodesToUpdate) {
+ await workspace.updateNode(nodeToUpdate);
+ }
}
if (nodesToDelete.length > 0) {
@@ -261,13 +291,25 @@ const hasChanged = (existingNode: Node, editorNode: NodeFromEditor) => {
return true;
}
- if (!isEqual(existingNode.attrs, editorNode.attrs)) {
+ if (deepHasChanged(existingNode.attrs, editorNode.attrs)) {
return true;
}
- if (!isEqual(existingNode.content, editorNode.content)) {
+ 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/hooks/use-event-bus.tsx b/desktop/src/hooks/use-event-bus.tsx
new file mode 100644
index 00000000..f932d6ee
--- /dev/null
+++ b/desktop/src/hooks/use-event-bus.tsx
@@ -0,0 +1,3 @@
+export const useEventBus = () => {
+ return window.eventBus;
+};
diff --git a/desktop/src/lib/event-bus.ts b/desktop/src/lib/event-bus.ts
new file mode 100644
index 00000000..7455655e
--- /dev/null
+++ b/desktop/src/lib/event-bus.ts
@@ -0,0 +1,47 @@
+export interface Subscription {
+ id: string;
+ callback: (event: Event) => void;
+}
+
+export interface Event {
+ event: string;
+ payload: any;
+}
+
+export interface EventBus {
+ subscribe(callback: (payload: any) => void): string;
+ unsubscribe(subscriptionId: string): void;
+ publish(event: Event): void;
+}
+
+export class EventBusService {
+ private subscriptions: Map<string, Subscription>;
+ private id = 0;
+
+ public constructor() {
+ this.subscriptions = new Map<string, Subscription>();
+ }
+
+ public subscribe(callback: (event: Event) => void): string {
+ const id = (this.id++).toLocaleString();
+ this.subscriptions.set(id, {
+ callback,
+ id,
+ });
+ return id;
+ }
+
+ public unsubscribe(subscriptionId: string) {
+ if (!this.subscriptions.has(subscriptionId)) return;
+
+ this.subscriptions.delete(subscriptionId);
+ }
+
+ public publish(event: Event) {
+ this.subscriptions.forEach((subscription) => {
+ subscription.callback(event);
+ });
+ }
+}
+
+export const eventBus = new EventBusService();
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index 902999cb..7dc0eaf9 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -13,6 +13,7 @@ enum IdType {
Channel = 'ch',
Node = 'nd',
Message = 'ms',
+ Subscriber = 'sb',
}
export class NeuronId {
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 1a2c387e..3010441a 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -2,6 +2,9 @@ import { app, ipcMain, BrowserWindow } from 'electron';
import path from 'path';
import { globalDatabase } from '@/electron/database/global';
import { initEventLoop } from '@/electron/event-loop';
+import { eventBus } from '@/lib/event-bus';
+
+let subscriptionId: string | null = null;
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
@@ -28,6 +31,10 @@ const createWindow = () => {
// Open the DevTools.
mainWindow.webContents.openDevTools();
+
+ subscriptionId = eventBus.subscribe((event) => {
+ mainWindow.webContents.send('event', event);
+ });
};
// This method will be called when Electron has finished
@@ -52,6 +59,12 @@ app.on('activate', () => {
}
});
+app.on('before-quit', () => {
+ if (subscriptionId) {
+ eventBus.unsubscribe(subscriptionId);
+ }
+});
+
// inter process handlers
ipcMain.handle('init', async () => globalDatabase.init());
ipcMain.handle('get-accounts', async () => globalDatabase.getAccounts());
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 8a82a7e9..b5288621 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -3,6 +3,7 @@ import { Account } from '@/types/accounts';
import { Workspace } from '@/types/workspaces';
import { Transaction } from '@/types/transactions';
import { CreateNodeInput, UpdateNodeInput } from '@/types/nodes';
+import { eventBus, Event } from '@/lib/event-bus';
contextBridge.exposeInMainWorld('globalDb', {
init: () => ipcRenderer.invoke('init'),
@@ -35,3 +36,13 @@ contextBridge.exposeInMainWorld('workspaceDb', {
getDocumentNodes: (accountId: string, workspaceId: string, documentId: string) =>
ipcRenderer.invoke('get-document-nodes', accountId, workspaceId, documentId),
});
+
+contextBridge.exposeInMainWorld('eventBus', {
+ subscribe: (callback: (event: Event) => void) => eventBus.subscribe(callback),
+ unsubscribe: (id: string) => eventBus.unsubscribe(id),
+ publish: (event: Event) => eventBus.publish(event),
+});
+
+ipcRenderer.on('event', (_, event) => {
+ eventBus.publish(event);
+});
\ No newline at end of file
diff --git a/desktop/src/store/document.ts b/desktop/src/store/document.ts
index 3497a0f9..8d307a43 100644
--- a/desktop/src/store/document.ts
+++ b/desktop/src/store/document.ts
@@ -22,6 +22,10 @@ export class DocumentStore {
});
}
+ public deleteNode(nodeId: string) {
+ delete this.nodes[nodeId];
+ }
+
public setIsLoading(isLoading: boolean) {
this.isLoading = isLoading;
}
diff --git a/desktop/src/types/window.d.ts b/desktop/src/types/window.d.ts
index 785a1f1c..cd9a1b70 100644
--- a/desktop/src/types/window.d.ts
+++ b/desktop/src/types/window.d.ts
@@ -3,6 +3,7 @@ import { Transaction } from '@/types/transactions';
import { Account } from '@/types/accounts';
import { CreateNodeInput, Node, UpdateNodeInput } from '@/types/nodes';
import { GlobalDatabaseData } from '@/types/global';
+import { EventBus } from '@/lib/event-bus';
export interface GlobalDbApi {
init: () => Promise<GlobalDatabaseData>;
@@ -60,5 +61,6 @@ declare global {
interface Window {
globalDb: GlobalDbApi;
workspaceDb: WorkspaceDbApi;
+ eventBus: EventBus;
}
}