Skip to content

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

Refactor documents and text indexing

Hakan Shehu25fb7ac46a70
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00007-create-node-texts-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00007-create-node-texts-table.ts
new file mode 100644
index 00000000..dcd3197f
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00007-create-node-texts-table.ts
@@ -0,0 +1,14 @@
+import { Migration, sql } from 'kysely';
+
+export const createNodeTextsTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE VIRTUAL TABLE node_texts USING fts5(id UNINDEXED, name, attributes, content='', contentless_delete=1);
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TABLE IF EXISTS node_texts;
+ `.execute(db);
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00008-create-documents-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00008-create-documents-table.ts
index 5b2af904..650eef41 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00008-create-documents-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00008-create-documents-table.ts
@@ -1,12 +1,19 @@
-import { Migration } from 'kysely';
+import { Migration, sql } from 'kysely';
export const createDocumentsTable: Migration = {
up: async (db) => {
await db.schema
.createTable('documents')
.addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('revision', 'integer', (col) => col.notNull())
- .addColumn('state', 'blob', (col) => col.notNull())
+ .addColumn('type', 'text', (col) =>
+ col
+ .notNull()
+ .generatedAlwaysAs(sql`json_extract(content, '$.type')`)
+ .stored()
+ )
+ .addColumn('local_revision', 'integer', (col) => col.notNull())
+ .addColumn('server_revision', 'integer', (col) => col.notNull())
+ .addColumn('content', 'text', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
.addColumn('created_by', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00009-create-document-states-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00009-create-document-states-table.ts
new file mode 100644
index 00000000..4b8d545a
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00009-create-document-states-table.ts
@@ -0,0 +1,21 @@
+import { Migration } from 'kysely';
+
+export const createDocumentStatesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('document_states')
+ .addColumn('id', 'text', (col) =>
+ col
+ .notNull()
+ .primaryKey()
+ .references('documents.id')
+ .onDelete('cascade')
+ )
+ .addColumn('state', 'blob', (col) => col.notNull())
+ .addColumn('revision', 'integer', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('document_states').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00009-create-document-updates-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00010-create-document-updates-table.ts
similarity index 79%
rename from apps/desktop/src/main/databases/workspace/migrations/00009-create-document-updates-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00010-create-document-updates-table.ts
index 6955c211..81a6a6c5 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00009-create-document-updates-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00010-create-document-updates-table.ts
@@ -5,7 +5,9 @@ export const createDocumentUpdatesTable: Migration = {
await db.schema
.createTable('document_updates')
.addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('document_id', 'text', (col) => col.notNull())
+ .addColumn('document_id', 'text', (col) =>
+ col.notNull().references('documents.id').onDelete('cascade')
+ )
.addColumn('data', 'blob', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
.execute();
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00011-create-document-texts-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00011-create-document-texts-table.ts
new file mode 100644
index 00000000..aeb396f5
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00011-create-document-texts-table.ts
@@ -0,0 +1,14 @@
+import { Migration, sql } from 'kysely';
+
+export const createDocumentTextsTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE VIRTUAL TABLE document_texts USING fts5(id UNINDEXED, text, content='', contentless_delete=1);
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TABLE IF EXISTS document_texts;
+ `.execute(db);
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00007-create-collaborations-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00012-create-collaborations-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00007-create-collaborations-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00012-create-collaborations-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00013-create-file-states-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00013-create-file-states-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00011-create-mutations-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00014-create-mutations-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00011-create-mutations-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00014-create-mutations-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00012-create-tombstones-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00015-create-tombstones-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00012-create-tombstones-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00015-create-tombstones-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00013-create-cursors-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00016-create-cursors-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00013-create-cursors-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00016-create-cursors-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00014-create-metadata-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00017-create-metadata-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00014-create-metadata-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00017-create-metadata-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/index.ts b/apps/desktop/src/main/databases/workspace/migrations/index.ts
index f0646253..a7b8a60f 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/index.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/index.ts
@@ -6,14 +6,17 @@ import { createNodeStatesTable } from './00003-create-node-states-table';
import { createNodeUpdatesTable } from './00004-create-node-updates-table';
import { createNodeInteractionsTable } from './00005-create-node-interactions-table';
import { createNodeReactionsTable } from './00006-create-node-reactions-table';
-import { createCollaborationsTable } from './00007-create-collaborations-table';
+import { createNodeTextsTable } from './00007-create-node-texts-table';
import { createDocumentsTable } from './00008-create-documents-table';
-import { createDocumentUpdatesTable } from './00009-create-document-updates-table';
-import { createFileStatesTable } from './00010-create-file-states-table';
-import { createMutationsTable } from './00011-create-mutations-table';
-import { createTombstonesTable } from './00012-create-tombstones-table';
-import { createCursorsTable } from './00013-create-cursors-table';
-import { createMetadataTable } from './00014-create-metadata-table';
+import { createDocumentStatesTable } from './00009-create-document-states-table';
+import { createDocumentUpdatesTable } from './00010-create-document-updates-table';
+import { createDocumentTextsTable } from './00011-create-document-texts-table';
+import { createCollaborationsTable } from './00012-create-collaborations-table';
+import { createFileStatesTable } from './00013-create-file-states-table';
+import { createMutationsTable } from './00014-create-mutations-table';
+import { createTombstonesTable } from './00015-create-tombstones-table';
+import { createCursorsTable } from './00016-create-cursors-table';
+import { createMetadataTable } from './00017-create-metadata-table';
export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00001-create-users-table': createUsersTable,
@@ -22,12 +25,15 @@ export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00004-create-node-updates-table': createNodeUpdatesTable,
'00005-create-node-interactions-table': createNodeInteractionsTable,
'00006-create-node-reactions-table': createNodeReactionsTable,
- '00007-create-collaborations-table': createCollaborationsTable,
+ '00007-create-node-texts-table': createNodeTextsTable,
'00008-create-documents-table': createDocumentsTable,
- '00009-create-document-updates-table': createDocumentUpdatesTable,
- '00010-create-file-states-table': createFileStatesTable,
- '00011-create-mutations-table': createMutationsTable,
- '00012-create-tombstones-table': createTombstonesTable,
- '00013-create-cursors-table': createCursorsTable,
- '00014-create-metadata-table': createMetadataTable,
+ '00009-create-document-states-table': createDocumentStatesTable,
+ '00010-create-document-updates-table': createDocumentUpdatesTable,
+ '00011-create-document-texts-table': createDocumentTextsTable,
+ '00012-create-collaborations-table': createCollaborationsTable,
+ '00013-create-file-states-table': createFileStatesTable,
+ '00014-create-mutations-table': createMutationsTable,
+ '00015-create-tombstones-table': createTombstonesTable,
+ '00016-create-cursors-table': createCursorsTable,
+ '00017-create-metadata-table': createMetadataTable,
};
diff --git a/apps/desktop/src/main/databases/workspace/schema.ts b/apps/desktop/src/main/databases/workspace/schema.ts
index 5b0514e7..565efe2f 100644
--- a/apps/desktop/src/main/databases/workspace/schema.ts
+++ b/apps/desktop/src/main/databases/workspace/schema.ts
@@ -93,6 +93,16 @@ export type SelectNodeReaction = Selectable<NodeReactionTable>;
export type CreateNodeReaction = Insertable<NodeReactionTable>;
export type UpdateNodeReaction = Updateable<NodeReactionTable>;
+interface NodeTextTable {
+ id: ColumnType<string, string, never>;
+ name: ColumnType<string | null, string | null, string | null>;
+ attributes: ColumnType<string | null, string | null, string | null>;
+}
+
+export type SelectNodeText = Selectable<NodeTextTable>;
+export type CreateNodeText = Insertable<NodeTextTable>;
+export type UpdateNodeText = Updateable<NodeTextTable>;
+
interface CollaborationTable {
node_id: ColumnType<string, string, never>;
role: ColumnType<string, string, string>;
@@ -108,8 +118,10 @@ export type UpdateCollaboration = Updateable<CollaborationTable>;
interface DocumentTable {
id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, bigint, bigint>;
- state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
+ type: ColumnType<DocumentType, never, never>;
+ local_revision: ColumnType<bigint, bigint, bigint>;
+ server_revision: ColumnType<bigint, bigint, bigint>;
+ content: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
created_by: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
@@ -120,6 +132,16 @@ export type SelectDocument = Selectable<DocumentTable>;
export type CreateDocument = Insertable<DocumentTable>;
export type UpdateDocument = Updateable<DocumentTable>;
+interface DocumentStateTable {
+ id: ColumnType<string, string, never>;
+ state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
+ revision: ColumnType<bigint, bigint, bigint>;
+}
+
+export type SelectDocumentState = Selectable<DocumentStateTable>;
+export type CreateDocumentState = Insertable<DocumentStateTable>;
+export type UpdateDocumentState = Updateable<DocumentStateTable>;
+
interface DocumentUpdateTable {
id: ColumnType<string, string, never>;
document_id: ColumnType<string, string, never>;
@@ -131,6 +153,15 @@ export type SelectDocumentUpdate = Selectable<DocumentUpdateTable>;
export type CreateDocumentUpdate = Insertable<DocumentUpdateTable>;
export type UpdateDocumentUpdate = Updateable<DocumentUpdateTable>;
+interface DocumentTextTable {
+ id: ColumnType<string, string, never>;
+ text: ColumnType<string | null, string | null, string | null>;
+}
+
+export type SelectDocumentText = Selectable<DocumentTextTable>;
+export type CreateDocumentText = Insertable<DocumentTextTable>;
+export type UpdateDocumentText = Updateable<DocumentTextTable>;
+
interface FileStateTable {
id: ColumnType<string, string, never>;
version: ColumnType<string, string, string>;
@@ -213,9 +244,12 @@ export interface WorkspaceDatabaseSchema {
node_interactions: NodeInteractionTable;
node_updates: NodeUpdateTable;
node_reactions: NodeReactionTable;
- collaborations: CollaborationTable;
+ node_texts: NodeTextTable;
documents: DocumentTable;
+ document_states: DocumentStateTable;
document_updates: DocumentUpdateTable;
+ document_texts: DocumentTextTable;
+ collaborations: CollaborationTable;
file_states: FileStateTable;
mutations: MutationTable;
tombstones: TombstoneTable;
diff --git a/apps/desktop/src/main/lib/mappers.ts b/apps/desktop/src/main/lib/mappers.ts
index 1336ee16..d04550fc 100644
--- a/apps/desktop/src/main/lib/mappers.ts
+++ b/apps/desktop/src/main/lib/mappers.ts
@@ -16,6 +16,9 @@ import {
SelectNodeInteraction,
SelectNodeReaction,
SelectWorkspaceMetadata,
+ SelectDocument,
+ SelectDocumentState,
+ SelectDocumentUpdate,
} from '@/main/databases/workspace';
import { Account } from '@/shared/types/accounts';
import { Server } from '@/shared/types/servers';
@@ -30,6 +33,11 @@ import { LocalNode, NodeInteraction, NodeReaction } from '@/shared/types/nodes';
import { Emoji } from '@/shared/types/emojis';
import { Icon } from '@/shared/types/icons';
import { AppMetadata, AppMetadataKey } from '@/shared/types/apps';
+import {
+ Document,
+ DocumentState,
+ DocumentUpdate,
+} from '@/shared/types/documents';
export const mapUser = (row: SelectUser): User => {
return {
@@ -61,6 +69,37 @@ export const mapNode = (row: SelectNode): LocalNode => {
} as LocalNode;
};
+export const mapDocument = (row: SelectDocument): Document => {
+ return {
+ id: row.id,
+ localRevision: row.local_revision,
+ serverRevision: row.server_revision,
+ content: JSON.parse(row.content),
+ createdAt: row.created_at,
+ createdBy: row.created_by,
+ updatedAt: row.updated_at,
+ updatedBy: row.updated_by,
+ };
+};
+
+export const mapDocumentState = (row: SelectDocumentState): DocumentState => {
+ return {
+ id: row.id,
+ revision: row.revision,
+ state: row.state,
+ };
+};
+
+export const mapDocumentUpdate = (
+ row: SelectDocumentUpdate
+): DocumentUpdate => {
+ return {
+ id: row.id,
+ documentId: row.document_id,
+ data: row.data,
+ };
+};
+
export const mapAccount = (row: SelectAccount): Account => {
return {
id: row.id,
@@ -183,6 +222,7 @@ export const mapAppMetadata = (row: SelectAppMetadata): AppMetadata => {
updatedAt: row.updated_at,
};
};
+
export const mapWorkspaceMetadata = (
row: SelectWorkspaceMetadata
): WorkspaceMetadata => {
diff --git a/apps/desktop/src/main/lib/utils.ts b/apps/desktop/src/main/lib/utils.ts
index 99d431f5..fc6ad228 100644
--- a/apps/desktop/src/main/lib/utils.ts
+++ b/apps/desktop/src/main/lib/utils.ts
@@ -13,11 +13,10 @@ import { app } from 'electron';
import path from 'path';
import fs from 'fs';
-import {
- SelectNode,
- WorkspaceDatabaseSchema,
-} from '@/main/databases/workspace';
+import { WorkspaceDatabaseSchema } from '@/main/databases/workspace';
import { FileMetadata } from '@/shared/types/files';
+import { LocalNode } from '@/shared/types/nodes';
+import { mapNode } from '@/main/lib/mappers';
export const appPath = app.getPath('userData');
@@ -118,7 +117,7 @@ export const fetchNodeTree = async (
| Kysely<WorkspaceDatabaseSchema>
| Transaction<WorkspaceDatabaseSchema>,
nodeId: string
-): Promise<SelectNode[]> => {
+): Promise<LocalNode[]> => {
const nodes = await database
.withRecursive('ancestor_nodes', (cte) =>
cte
@@ -140,20 +139,22 @@ export const fetchNodeTree = async (
.selectAll()
.execute();
- return nodes.reverse();
+ return nodes.reverse().map(mapNode);
};
-export const fetchNode = (
+export const fetchNode = async (
database:
| Kysely<WorkspaceDatabaseSchema>
| Transaction<WorkspaceDatabaseSchema>,
entryId: string
-): Promise<SelectNode | undefined> => {
- return database
+): Promise<LocalNode | undefined> => {
+ const node = await database
.selectFrom('nodes')
.selectAll()
.where('id', '=', entryId)
.executeTakeFirst();
+
+ return node ? mapNode(node) : undefined;
};
export const fetchUserStorageUsed = async (
diff --git a/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts b/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
index b7f286dd..47525e2f 100644
--- a/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
@@ -20,7 +20,6 @@ export class NodeMarkOpenedMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const node = await fetchNode(workspace.database, input.nodeId);
-
if (!node) {
return {
success: false,
@@ -63,7 +62,7 @@ export class NodeMarkOpenedMutationHandler
last_opened_at: lastOpenedAt,
first_opened_at: firstOpenedAt,
revision: 0n,
- root_id: node.root_id,
+ root_id: node.rootId,
})
.onConflict((b) =>
b.columns(['node_id', 'collaborator_id']).doUpdateSet({
diff --git a/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts b/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
index 5ad231b8..d5cd7f78 100644
--- a/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
@@ -63,7 +63,7 @@ export class NodeMarkSeenMutationHandler
last_seen_at: lastSeenAt,
first_seen_at: firstSeenAt,
revision: 0n,
- root_id: node.root_id,
+ root_id: node.rootId,
})
.onConflict((b) =>
b.columns(['node_id', 'collaborator_id']).doUpdateSet({
diff --git a/apps/desktop/src/main/queries/documents/document-get.ts b/apps/desktop/src/main/queries/documents/document-get.ts
index bf7f3675..ef805883 100644
--- a/apps/desktop/src/main/queries/documents/document-get.ts
+++ b/apps/desktop/src/main/queries/documents/document-get.ts
@@ -1,10 +1,9 @@
-import { YDoc } from '@colanode/crdt';
-
import { Document } from '@/shared/types/documents';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
import { Event } from '@/shared/types/events';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { DocumentGetQueryInput } from '@/shared/queries/documents/document-get';
+import { mapDocument } from '@/main/lib/mappers';
export class DocumentGetQueryHandler
extends WorkspaceQueryHandlerBase
@@ -14,53 +13,17 @@ export class DocumentGetQueryHandler
input: DocumentGetQueryInput
): Promise<Document | null> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
const document = await workspace.database
.selectFrom('documents')
.selectAll()
.where('id', '=', input.documentId)
.executeTakeFirst();
- const documentUpdates = await workspace.database
- .selectFrom('document_updates')
- .selectAll()
- .where('document_id', '=', input.documentId)
- .orderBy('id', 'asc')
- .execute();
-
- if (documentUpdates.length === 0) {
- if (!document) {
- return null;
- }
-
- return {
- id: document.id,
- revision: document.revision,
- state: document.state,
- createdAt: document.created_at,
- createdBy: document.created_by,
- updatedAt: document.updated_at,
- updatedBy: document.updated_by,
- };
+ if (!document) {
+ return null;
}
- const ydoc = new YDoc(document?.state);
- for (const update of documentUpdates) {
- ydoc.applyUpdate(update.data);
- }
-
- const firstUpdate = documentUpdates[0]!;
- const lastUpdate = documentUpdates[documentUpdates.length - 1]!;
-
- return {
- id: input.documentId,
- revision: 0n,
- state: ydoc.getState(),
- createdAt: firstUpdate.created_at,
- createdBy: workspace.userId,
- updatedAt: lastUpdate.created_at,
- updatedBy: workspace.userId,
- };
+ return mapDocument(document);
}
public async checkForChanges(
@@ -83,38 +46,11 @@ export class DocumentGetQueryHandler
event.type === 'document_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.documentId === input.documentId
- ) {
- const newOutput = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newOutput,
- };
- }
-
- if (
- event.type === 'document_update_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.documentId === input.documentId
- ) {
- const newOutput = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newOutput,
- };
- }
-
- if (
- event.type === 'document_update_deleted' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.documentId === input.documentId
+ event.document.id === input.documentId
) {
- const newOutput = await this.handleQuery(input);
return {
hasChanges: true,
- result: newOutput,
+ result: event.document,
};
}
diff --git a/apps/desktop/src/main/queries/documents/document-state-get.ts b/apps/desktop/src/main/queries/documents/document-state-get.ts
new file mode 100644
index 00000000..faccfc6c
--- /dev/null
+++ b/apps/desktop/src/main/queries/documents/document-state-get.ts
@@ -0,0 +1,73 @@
+import { DocumentState } from '@/shared/types/documents';
+import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
+import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { DocumentStateGetQueryInput } from '@/shared/queries/documents/document-state-get';
+import { mapDocumentState } from '@/main/lib/mappers';
+
+export class DocumentStateGetQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<DocumentStateGetQueryInput>
+{
+ public async handleQuery(
+ input: DocumentStateGetQueryInput
+ ): Promise<DocumentState | null> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ const documentState = await workspace.database
+ .selectFrom('document_states')
+ .selectAll()
+ .where('id', '=', input.documentId)
+ .executeTakeFirst();
+
+ if (!documentState) {
+ return null;
+ }
+
+ return mapDocumentState(documentState);
+ }
+
+ public async checkForChanges(
+ event: Event,
+ input: DocumentStateGetQueryInput,
+ _: DocumentState | null
+ ): Promise<ChangeCheckResult<DocumentStateGetQueryInput>> {
+ if (
+ event.type === 'workspace_deleted' &&
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
+ ) {
+ return {
+ hasChanges: true,
+ result: null,
+ };
+ }
+
+ if (
+ event.type === 'document_state_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.documentState.id === input.documentId
+ ) {
+ return {
+ hasChanges: true,
+ result: event.documentState,
+ };
+ }
+
+ if (
+ event.type === 'node_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.id === input.documentId
+ ) {
+ return {
+ hasChanges: true,
+ result: null,
+ };
+ }
+
+ return {
+ hasChanges: false,
+ };
+ }
+}
diff --git a/apps/desktop/src/main/queries/documents/document-update-list.ts b/apps/desktop/src/main/queries/documents/document-update-list.ts
new file mode 100644
index 00000000..f3670378
--- /dev/null
+++ b/apps/desktop/src/main/queries/documents/document-update-list.ts
@@ -0,0 +1,88 @@
+import { DocumentUpdate } from '@/shared/types/documents';
+import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
+import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { DocumentUpdatesListQueryInput } from '@/shared/queries/documents/document-updates-list';
+import { mapDocumentUpdate } from '@/main/lib/mappers';
+
+export class DocumentUpdatesListQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<DocumentUpdatesListQueryInput>
+{
+ public async handleQuery(
+ input: DocumentUpdatesListQueryInput
+ ): Promise<DocumentUpdate[]> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ const documentUpdates = await workspace.database
+ .selectFrom('document_updates')
+ .selectAll()
+ .where('id', '=', input.documentId)
+ .execute();
+
+ if (!documentUpdates) {
+ return [];
+ }
+
+ return documentUpdates.map((update) => mapDocumentUpdate(update));
+ }
+
+ public async checkForChanges(
+ event: Event,
+ input: DocumentUpdatesListQueryInput,
+ output: DocumentUpdate[]
+ ): Promise<ChangeCheckResult<DocumentUpdatesListQueryInput>> {
+ if (
+ event.type === 'workspace_deleted' &&
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
+ ) {
+ return {
+ hasChanges: true,
+ result: [],
+ };
+ }
+
+ if (
+ event.type === 'document_update_created' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.documentUpdate.documentId === input.documentId
+ ) {
+ const newOutput = [...output, event.documentUpdate];
+ return {
+ hasChanges: true,
+ result: newOutput,
+ };
+ }
+
+ if (
+ event.type === 'document_update_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.documentId === input.documentId
+ ) {
+ const newOutput = output.filter((update) => update.id !== event.updateId);
+
+ return {
+ hasChanges: true,
+ result: newOutput,
+ };
+ }
+
+ if (
+ event.type === 'node_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.id === input.documentId
+ ) {
+ return {
+ hasChanges: true,
+ result: [],
+ };
+ }
+
+ return {
+ hasChanges: false,
+ };
+ }
+}
diff --git a/apps/desktop/src/main/queries/index.ts b/apps/desktop/src/main/queries/index.ts
index 3964e138..1f15f74c 100644
--- a/apps/desktop/src/main/queries/index.ts
+++ b/apps/desktop/src/main/queries/index.ts
@@ -32,6 +32,8 @@ import { UserGetQueryHandler } from '@/main/queries/users/user-get';
import { SpaceListQueryHandler } from '@/main/queries/spaces/space-list';
import { ChatListQueryHandler } from '@/main/queries/chats/chat-list';
import { DocumentGetQueryHandler } from '@/main/queries/documents/document-get';
+import { DocumentStateGetQueryHandler } from '@/main/queries/documents/document-state-get';
+import { DocumentUpdatesListQueryHandler } from '@/main/queries/documents/document-update-list';
import { WorkspaceMetadataListQueryHandler } from '@/main/queries/workspaces/workspace-metadata-list';
import { QueryHandler } from '@/main/lib/types';
import { QueryMap } from '@/shared/queries';
@@ -76,4 +78,6 @@ export const queryHandlerMap: QueryHandlerMap = {
space_list: new SpaceListQueryHandler(),
workspace_metadata_list: new WorkspaceMetadataListQueryHandler(),
document_get: new DocumentGetQueryHandler(),
+ document_state_get: new DocumentStateGetQueryHandler(),
+ document_updates_list: new DocumentUpdatesListQueryHandler(),
};
diff --git a/apps/desktop/src/main/queries/nodes/node-tree-get.ts b/apps/desktop/src/main/queries/nodes/node-tree-get.ts
index 1aedc480..3661272e 100644
--- a/apps/desktop/src/main/queries/nodes/node-tree-get.ts
+++ b/apps/desktop/src/main/queries/nodes/node-tree-get.ts
@@ -3,7 +3,6 @@ import { NodeTreeGetQueryInput } from '@/shared/queries/nodes/node-tree-get';
import { Event } from '@/shared/types/events';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { fetchNodeTree } from '@/main/lib/utils';
-import { mapNode } from '@/main/lib/mappers';
import { LocalNode } from '@/shared/types/nodes';
export class NodeTreeGetQueryHandler
@@ -12,8 +11,8 @@ export class NodeTreeGetQueryHandler
{
public async handleQuery(input: NodeTreeGetQueryInput): Promise<LocalNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const rows = await fetchNodeTree(workspace.database, input.nodeId);
- return rows.map(mapNode);
+ const tree = await fetchNodeTree(workspace.database, input.nodeId);
+ return tree;
}
public async checkForChanges(
diff --git a/apps/desktop/src/main/services/workspaces/document-service.ts b/apps/desktop/src/main/services/workspaces/document-service.ts
index 99b2960b..03f120f6 100644
--- a/apps/desktop/src/main/services/workspaces/document-service.ts
+++ b/apps/desktop/src/main/services/workspaces/document-service.ts
@@ -2,9 +2,11 @@ import {
CanUpdateDocumentContext,
createDebugger,
DocumentContent,
+ extractDocumentText,
generateId,
getNodeModel,
IdType,
+ NodeModel,
SyncDocumentUpdateData,
UpdateDocumentMutationData,
} from '@colanode/core';
@@ -13,7 +15,12 @@ import { encodeState, YDoc } from '@colanode/crdt';
import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
import { eventBus } from '@/shared/lib/event-bus';
import { fetchNodeTree } from '@/main/lib/utils';
-import { mapNode } from '@/main/lib/mappers';
+import { SelectDocument } from '@/main/databases/workspace';
+import {
+ mapDocument,
+ mapDocumentState,
+ mapDocumentUpdate,
+} from '@/main/lib/mappers';
const UPDATE_RETRIES_LIMIT = 10;
@@ -48,28 +55,52 @@ export class DocumentService {
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
},
- node: mapNode(node),
- tree: tree.map((node) => mapNode(node)),
+ node: node,
+ tree: tree,
};
if (!model.canUpdateDocument(context)) {
throw new Error('User does not have permission to update document');
}
- const document = await this.workspace.database
- .selectFrom('documents')
- .selectAll()
- .where('id', '=', node.id)
- .executeTakeFirst();
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ try {
+ const document = await this.workspace.database
+ .selectFrom('documents')
+ .selectAll()
+ .where('id', '=', id)
+ .executeTakeFirst();
+
+ if (document) {
+ const result = await this.tryUpdateDocument(model, document, update);
+ if (result) {
+ return true;
+ }
+ } else {
+ const result = await this.tryCreateDocument(model, id, update);
+ if (result) {
+ return true;
+ }
+ }
+ } catch (error) {
+ this.debug(`Failed to update document ${node.id}: ${error}`);
+ }
+ }
+ }
+ private async tryCreateDocument(
+ model: NodeModel,
+ id: string,
+ update: Uint8Array
+ ): Promise<boolean> {
const documentUpdates = await this.workspace.database
.selectFrom('document_updates')
.selectAll()
- .where('document_id', '=', node.id)
+ .where('document_id', '=', id)
.orderBy('id', 'asc')
.execute();
- const ydoc = new YDoc(document?.state);
+ const ydoc = new YDoc();
for (const update of documentUpdates) {
ydoc.applyUpdate(update.data);
}
@@ -77,22 +108,141 @@ export class DocumentService {
ydoc.applyUpdate(update);
const content = ydoc.getObject<DocumentContent>();
- if (!model.documentSchema.safeParse(content).success) {
+ if (!model.documentSchema?.safeParse(content).success) {
throw new Error('Invalid document state');
}
const updateId = generateId(IdType.Update);
const updatedAt = new Date().toISOString();
+ const text = extractDocumentText(id, content);
- const { createdUpdate, createdMutation } = await this.workspace.database
+ const { createdDocument, createdMutation } = await this.workspace.database
.transaction()
.execute(async (trx) => {
+ const createdDocument = await trx
+ .insertInto('documents')
+ .returningAll()
+ .values({
+ id: id,
+ content: JSON.stringify(content),
+ local_revision: 0n,
+ server_revision: 0n,
+ created_at: updatedAt,
+ created_by: this.workspace.userId,
+ })
+ .onConflict((cb) => cb.doNothing())
+ .executeTakeFirst();
+
+ if (!createdDocument) {
+ throw new Error('Failed to create document');
+ }
+
+ const createdMutation = await trx
+ .insertInto('mutations')
+ .returningAll()
+ .values({
+ id: generateId(IdType.Mutation),
+ type: 'update_document',
+ data: JSON.stringify({
+ documentId: id,
+ updateId: updateId,
+ data: encodeState(update),
+ createdAt: updatedAt,
+ }),
+ created_at: updatedAt,
+ retries: 0,
+ })
+ .executeTakeFirst();
+
+ await trx
+ .insertInto('document_texts')
+ .values({
+ id: id,
+ text: text,
+ })
+ .executeTakeFirst();
+
+ return { createdDocument, createdMutation };
+ });
+
+ if (createdDocument) {
+ eventBus.publish({
+ type: 'document_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ document: mapDocument(createdDocument),
+ });
+ }
+
+ if (createdMutation) {
+ this.workspace.mutations.triggerSync();
+ }
+
+ return true;
+ }
+
+ private async tryUpdateDocument(
+ model: NodeModel,
+ document: SelectDocument,
+ update: Uint8Array
+ ): Promise<boolean> {
+ const documentState = await this.workspace.database
+ .selectFrom('document_states')
+ .selectAll()
+ .where('id', '=', document.id)
+ .executeTakeFirst();
+
+ const documentUpdates = await this.workspace.database
+ .selectFrom('document_updates')
+ .selectAll()
+ .where('document_id', '=', document.id)
+ .orderBy('id', 'asc')
+ .execute();
+
+ const ydoc = new YDoc(documentState?.state);
+ for (const update of documentUpdates) {
+ ydoc.applyUpdate(update.data);
+ }
+
+ ydoc.applyUpdate(update);
+
+ const content = ydoc.getObject<DocumentContent>();
+ if (!model.documentSchema?.safeParse(content).success) {
+ throw new Error('Invalid document state');
+ }
+
+ const localRevision = BigInt(document.local_revision) + 1n;
+ const serverRevision = BigInt(document.server_revision) + 1n;
+ const updateId = generateId(IdType.Update);
+ const updatedAt = new Date().toISOString();
+ const text = extractDocumentText(document.id, content);
+
+ const { updatedDocument, createdUpdate, createdMutation } =
+ await this.workspace.database.transaction().execute(async (trx) => {
+ const updatedDocument = await trx
+ .updateTable('documents')
+ .returningAll()
+ .set({
+ content: JSON.stringify(content),
+ local_revision: localRevision,
+ server_revision: serverRevision,
+ updated_at: updatedAt,
+ updated_by: this.workspace.userId,
+ })
+ .where('id', '=', document.id)
+ .where('local_revision', '=', document.local_revision)
+ .executeTakeFirst();
+
+ if (!updatedDocument) {
+ throw new Error('Failed to update document');
+ }
+
const createdUpdate = await trx
.insertInto('document_updates')
.returningAll()
.values({
id: updateId,
- document_id: node.id,
+ document_id: document.id,
data: update,
created_at: updatedAt,
})
@@ -103,7 +253,7 @@ export class DocumentService {
}
const mutationData: UpdateDocumentMutationData = {
- documentId: id,
+ documentId: document.id,
updateId: updateId,
data: encodeState(update),
createdAt: updatedAt,
@@ -125,54 +275,205 @@ export class DocumentService {
throw new Error('Failed to create mutation');
}
+ await trx
+ .updateTable('document_texts')
+ .set({
+ text: text,
+ })
+ .where('id', '=', document.id)
+ .executeTakeFirst();
+
return {
- createdUpdate,
+ updatedDocument,
createdMutation,
+ createdUpdate,
};
});
+ if (updatedDocument) {
+ eventBus.publish({
+ type: 'document_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ document: mapDocument(updatedDocument),
+ });
+ }
+
if (createdUpdate) {
eventBus.publish({
type: 'document_update_created',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- documentId: node.id,
- updateId: createdUpdate.id,
+ documentUpdate: mapDocumentUpdate(createdUpdate),
});
}
if (createdMutation) {
this.workspace.mutations.triggerSync();
}
+
+ return true;
}
public async revertDocumentUpdate(data: UpdateDocumentMutationData) {
- const update = await this.workspace.database
- .selectFrom('document_updates')
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ try {
+ const result = await this.tryRevertDocumentUpdate(data);
+ if (result) {
+ return;
+ }
+ } catch (error) {
+ this.debug(
+ `Failed to revert document update ${data.documentId}: ${error}`
+ );
+ }
+ }
+ }
+
+ private async tryRevertDocumentUpdate(data: UpdateDocumentMutationData) {
+ const node = await this.workspace.database
+ .selectFrom('nodes')
.selectAll()
- .where('id', '=', data.updateId)
+ .where('id', '=', data.documentId)
.executeTakeFirst();
- if (!update) {
+ if (!node) {
return;
}
- const deletedUpdate = await this.workspace.database
- .deleteFrom('document_updates')
- .where('id', '=', update.id)
+ const document = await this.workspace.database
+ .selectFrom('documents')
+ .selectAll()
+ .where('id', '=', data.documentId)
.executeTakeFirst();
- if (!deletedUpdate) {
+ if (!document) {
return;
}
- eventBus.publish({
- type: 'document_update_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- documentId: data.documentId,
- updateId: data.updateId,
- });
+ const model = getNodeModel(node.type);
+
+ const documentUpdates = await this.workspace.database
+ .selectFrom('document_updates')
+ .selectAll()
+ .where('document_id', '=', data.documentId)
+ .orderBy('id', 'asc')
+ .execute();
+
+ const updateToDelete = documentUpdates.find(
+ (update) => update.id === data.updateId
+ );
+
+ if (!updateToDelete) {
+ return;
+ }
+
+ const documentState = await this.workspace.database
+ .selectFrom('document_states')
+ .selectAll()
+ .where('id', '=', data.documentId)
+ .executeTakeFirst();
+
+ if (!documentState && documentUpdates.length === 1) {
+ await this.workspace.database
+ .deleteFrom('documents')
+ .where('id', '=', data.documentId)
+ .executeTakeFirst();
+
+ await this.workspace.database
+ .deleteFrom('document_updates')
+ .where('id', '=', data.updateId)
+ .executeTakeFirst();
+
+ await this.workspace.database
+ .deleteFrom('document_texts')
+ .where('id', '=', data.documentId)
+ .executeTakeFirst();
+
+ eventBus.publish({
+ type: 'document_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ documentId: data.documentId,
+ });
+ }
+
+ const ydoc = new YDoc(documentState?.state);
+ for (const update of documentUpdates) {
+ if (update.id === data.updateId) {
+ continue;
+ }
+
+ ydoc.applyUpdate(update.data);
+ }
+
+ const content = ydoc.getObject<DocumentContent>();
+ if (!model.documentSchema?.safeParse(content).success) {
+ throw new Error('Invalid document state');
+ }
+
+ const localRevision = BigInt(document.local_revision) + BigInt(1);
+ const text = extractDocumentText(document.id, content);
+
+ const { updatedDocument, deletedUpdate } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const updatedDocument = await trx
+ .updateTable('documents')
+ .returningAll()
+ .set({
+ content: JSON.stringify(content),
+ local_revision: localRevision,
+ })
+ .where('id', '=', data.documentId)
+ .where('local_revision', '=', node.local_revision)
+ .executeTakeFirst();
+
+ if (!updatedDocument) {
+ throw new Error('Failed to update document');
+ }
+
+ const deletedUpdate = await trx
+ .deleteFrom('document_updates')
+ .returningAll()
+ .where('id', '=', updateToDelete.id)
+ .executeTakeFirst();
+
+ if (!deletedUpdate) {
+ throw new Error('Failed to delete update');
+ }
+
+ await trx
+ .updateTable('document_texts')
+ .set({
+ text: text,
+ })
+ .where('id', '=', document.id)
+ .executeTakeFirst();
+
+ return { updatedDocument, deletedUpdate };
+ });
+
+ if (updatedDocument) {
+ eventBus.publish({
+ type: 'document_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ document: mapDocument(updatedDocument),
+ });
+ }
+
+ if (deletedUpdate) {
+ eventBus.publish({
+ type: 'document_update_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ documentId: data.documentId,
+ updateId: updateToDelete.id,
+ });
+ }
+
+ return true;
}
public async syncServerDocumentUpdate(data: SyncDocumentUpdateData) {
@@ -197,6 +498,12 @@ export class DocumentService {
.where('id', '=', data.documentId)
.executeTakeFirst();
+ const documentState = await this.workspace.database
+ .selectFrom('document_states')
+ .selectAll()
+ .where('id', '=', data.documentId)
+ .executeTakeFirst();
+
const documentUpdates = await this.workspace.database
.selectFrom('document_updates')
.selectAll()
@@ -207,7 +514,12 @@ export class DocumentService {
const mergedUpdateIds =
data.mergedUpdates?.map((update) => update.id) ?? [];
- const ydoc = new YDoc(document?.state);
+ const ydoc = new YDoc(documentState?.state);
+ ydoc.applyUpdate(data.data);
+
+ const serverState = ydoc.getState();
+ const serverRevision = BigInt(data.revision);
+
for (const update of documentUpdates) {
if (update.id === data.id || mergedUpdateIds.includes(update.id)) {
continue;
@@ -216,37 +528,74 @@ export class DocumentService {
ydoc.applyUpdate(update.data);
}
- ydoc.applyUpdate(data.data);
- const revision = BigInt(data.revision);
+ const content = ydoc.getObject<DocumentContent>();
+
+ const localRevision = document
+ ? BigInt(document?.local_revision) + BigInt(1)
+ : BigInt(0);
+
const updatesToDelete = [data.id, ...mergedUpdateIds];
+ const text = extractDocumentText(data.documentId, content);
if (document) {
- const { updatedDocument } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
+ const { updatedDocument, upsertedState, deletedUpdates } =
+ await this.workspace.database.transaction().execute(async (trx) => {
const updatedDocument = await trx
.updateTable('documents')
.returningAll()
.set({
- state: ydoc.getState(),
- revision: revision,
+ content: JSON.stringify(content),
+ server_revision: serverRevision,
+ local_revision: localRevision,
updated_at: data.createdAt,
updated_by: data.createdBy,
})
.where('id', '=', data.documentId)
- .where('revision', '=', document.revision)
+ .where('local_revision', '=', document.local_revision)
.executeTakeFirst();
if (!updatedDocument) {
throw new Error('Failed to update document');
}
- await trx
+ const upsertedState = await trx
+ .insertInto('document_states')
+ .returningAll()
+ .values({
+ id: data.documentId,
+ state: serverState,
+ revision: serverRevision,
+ })
+ .onConflict((cb) =>
+ cb
+ .column('id')
+ .doUpdateSet({
+ state: serverState,
+ revision: serverRevision,
+ })
+ .where('revision', '=', BigInt(documentState?.revision ?? 0))
+ )
+ .executeTakeFirst();
+
+ if (!upsertedState) {
+ throw new Error('Failed to update document state');
+ }
+
+ const deletedUpdates = await trx
.deleteFrom('document_updates')
+ .returningAll()
.where('id', 'in', updatesToDelete)
.execute();
- return { updatedDocument };
+ await trx
+ .updateTable('document_texts')
+ .set({
+ text: text,
+ })
+ .where('id', '=', data.documentId)
+ .executeTakeFirst();
+
+ return { updatedDocument, upsertedState, deletedUpdates };
});
if (!updatedDocument) {
@@ -257,8 +606,29 @@ export class DocumentService {
type: 'document_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- documentId: data.documentId,
+ document: mapDocument(updatedDocument),
});
+
+ if (upsertedState) {
+ eventBus.publish({
+ type: 'document_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ documentState: mapDocumentState(upsertedState),
+ });
+ }
+
+ if (deletedUpdates) {
+ for (const update of deletedUpdates) {
+ eventBus.publish({
+ type: 'document_update_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ documentId: data.documentId,
+ updateId: update.id,
+ });
+ }
+ }
} else {
const { createdDocument } = await this.workspace.database
.transaction()
@@ -268,8 +638,9 @@ export class DocumentService {
.returningAll()
.values({
id: data.documentId,
- state: ydoc.getState(),
- revision: revision,
+ content: JSON.stringify(content),
+ server_revision: serverRevision,
+ local_revision: localRevision,
created_at: data.createdAt,
created_by: data.createdBy,
})
@@ -280,10 +651,28 @@ export class DocumentService {
throw new Error('Failed to create document');
}
+ const createdState = await trx
+ .insertInto('document_states')
+ .returningAll()
+ .values({
+ id: data.documentId,
+ state: serverState,
+ revision: serverRevision,
+ })
+ .onConflict((cb) => cb.doNothing())
+ .executeTakeFirst();
+
+ if (!createdState) {
+ throw new Error('Failed to create document state');
+ }
+
await trx
- .deleteFrom('document_updates')
- .where('id', 'in', updatesToDelete)
- .execute();
+ .insertInto('document_texts')
+ .values({
+ id: data.documentId,
+ text: text,
+ })
+ .executeTakeFirst();
return { createdDocument };
});
@@ -296,7 +685,7 @@ export class DocumentService {
type: 'document_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- documentId: data.documentId,
+ document: mapDocument(createdDocument),
});
}
diff --git a/apps/desktop/src/main/services/workspaces/node-reaction-service.ts b/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
index e1564e53..c8537f1e 100644
--- a/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
+++ b/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
@@ -13,7 +13,7 @@ import {
import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapNode, mapNodeReaction } from '@/main/lib/mappers';
+import { mapNodeReaction } from '@/main/lib/mappers';
import { SelectNodeReaction } from '@/main/databases/workspace';
import { MutationErrorCode, MutationError } from '@/shared/mutations';
import { fetchNodeTree } from '@/main/lib/utils';
@@ -65,8 +65,8 @@ export class NodeReactionService {
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
},
- tree: tree.map(mapNode),
- node: mapNode(node),
+ tree: tree,
+ node: node,
};
if (!model.canReact(context)) {
@@ -86,7 +86,7 @@ export class NodeReactionService {
node_id: nodeId,
collaborator_id: this.workspace.userId,
reaction,
- root_id: node.root_id,
+ root_id: node.rootId,
revision: 0n,
created_at: new Date().toISOString(),
})
@@ -104,7 +104,7 @@ export class NodeReactionService {
data: {
nodeId,
reaction,
- rootId: node.root_id,
+ rootId: node.rootId,
createdAt: new Date().toISOString(),
},
};
diff --git a/apps/desktop/src/main/services/workspaces/node-service.ts b/apps/desktop/src/main/services/workspaces/node-service.ts
index 46e44c40..7114d580 100644
--- a/apps/desktop/src/main/services/workspaces/node-service.ts
+++ b/apps/desktop/src/main/services/workspaces/node-service.ts
@@ -59,7 +59,7 @@ export class NodeService {
workspaceId: this.workspace.id,
accountId: this.workspace.accountId,
},
- tree: tree.map(mapNode),
+ tree: tree,
attributes: input.attributes,
};
@@ -76,6 +76,7 @@ export class NodeService {
const createdAt = new Date().toISOString();
const rootId = tree[0]?.id ?? input.id;
+ const nodeText = model.extractNodeText(input.id, input.attributes);
const { createdNode, createdMutation } = await this.workspace.database
.transaction()
@@ -134,6 +135,17 @@ export class NodeService {
throw new Error('Failed to create mutation');
}
+ if (nodeText) {
+ await trx
+ .insertInto('node_texts')
+ .values({
+ id: input.id,
+ name: nodeText.name,
+ attributes: nodeText.attributes,
+ })
+ .execute();
+ }
+
return {
createdNode,
createdMutation,
@@ -182,12 +194,11 @@ export class NodeService {
this.debug(`Updating node ${nodeId}`);
const tree = await fetchNodeTree(this.workspace.database, nodeId);
- const nodeRow = tree[tree.length - 1];
- if (!nodeRow || nodeRow.id !== nodeId) {
+ const node = tree[tree.length - 1];
+ if (!node || node.id !== nodeId) {
return 'not_found';
}
- const node = mapNode(nodeRow);
const updateId = generateId(IdType.Update);
const updatedAt = new Date().toISOString();
const updatedAttributes = updater(node.attributes as T);
@@ -201,7 +212,7 @@ export class NodeService {
workspaceId: this.workspace.id,
accountId: this.workspace.accountId,
},
- tree: tree.map(mapNode),
+ tree: tree,
node: node,
attributes: updatedAttributes,
};
@@ -240,6 +251,7 @@ export class NodeService {
const attributes = ydoc.getObject<NodeAttributes>();
const localRevision = BigInt(node.localRevision) + BigInt(1);
+ const nodeText = model.extractNodeText(nodeId, node.attributes);
const { updatedNode, createdMutation } = await this.workspace.database
.transaction()
@@ -299,6 +311,17 @@ export class NodeService {
throw new Error('Failed to create mutation');
}
+ if (nodeText) {
+ await trx
+ .insertInto('node_texts')
+ .values({
+ id: nodeId,
+ name: nodeText.name,
+ attributes: nodeText.attributes,
+ })
+ .execute();
+ }
+
return {
updatedNode,
createdMutation,
@@ -333,15 +356,12 @@ export class NodeService {
public async deleteNode(nodeId: string) {
const tree = await fetchNodeTree(this.workspace.database, nodeId);
- const nodeRow = tree[tree.length - 1];
- if (!nodeRow || nodeRow.id !== nodeId) {
+ const node = tree[tree.length - 1];
+ if (!node || node.id !== nodeId) {
return 'not_found';
}
- const node = mapNode(nodeRow);
-
const model = getNodeModel(node.attributes.type);
-
const canDeleteNodeContext: CanDeleteNodeContext = {
user: {
id: this.workspace.userId,
@@ -349,7 +369,7 @@ export class NodeService {
workspaceId: this.workspace.id,
accountId: this.workspace.accountId,
},
- tree: tree.map(mapNode),
+ tree: tree,
node: node,
};
@@ -440,6 +460,9 @@ export class NodeService {
const ydoc = new YDoc(node.state);
const attributes = ydoc.getObject<NodeAttributes>();
+ const model = getNodeModel(attributes.type);
+ const nodeText = model.extractNodeText(node.id, attributes);
+
const { createdNode } = await this.workspace.database
.transaction()
.execute(async (trx) => {
@@ -471,6 +494,17 @@ export class NodeService {
})
.executeTakeFirst();
+ if (nodeText) {
+ await trx
+ .insertInto('node_texts')
+ .values({
+ id: node.id,
+ name: nodeText.name,
+ attributes: nodeText.attributes,
+ })
+ .execute();
+ }
+
return { createdNode };
});
@@ -532,6 +566,9 @@ export class NodeService {
const attributes = ydoc.getObject<NodeAttributes>();
const localRevision = BigInt(existingNode.local_revision) + BigInt(1);
+ const model = getNodeModel(attributes.type);
+ const nodeText = model.extractNodeText(node.id, attributes);
+
const { updatedNode } = await this.workspace.database
.transaction()
.execute(async (trx) => {
@@ -562,6 +599,17 @@ export class NodeService {
.where('id', '=', node.id)
.executeTakeFirst();
+ if (nodeText) {
+ await trx
+ .insertInto('node_texts')
+ .values({
+ id: node.id,
+ name: nodeText.name,
+ attributes: nodeText.attributes,
+ })
+ .execute();
+ }
+
return { updatedNode };
});
@@ -631,6 +679,11 @@ export class NodeService {
.where('document_id', '=', tombstone.id)
.execute();
+ await trx
+ .deleteFrom('node_texts')
+ .where('id', '=', tombstone.id)
+ .execute();
+
return { deletedNode };
});
@@ -791,6 +844,10 @@ export class NodeService {
}
const attributes = ydoc.getObject<NodeAttributes>();
+ const model = getNodeModel(attributes.type);
+ const nodeText = model.extractNodeText(node.id, attributes);
+ const localRevision = BigInt(node.local_revision) + BigInt(1);
+
const updatedNode = await this.workspace.database
.transaction()
.execute(async (trx) => {
@@ -799,6 +856,7 @@ export class NodeService {
.returningAll()
.set({
attributes: JSON.stringify(attributes),
+ local_revision: localRevision,
})
.where('id', '=', mutation.id)
.where('local_revision', '=', node.local_revision)
@@ -812,6 +870,17 @@ export class NodeService {
.deleteFrom('node_updates')
.where('id', '=', mutation.updateId)
.execute();
+
+ if (nodeText) {
+ await trx
+ .insertInto('node_texts')
+ .values({
+ id: node.id,
+ name: nodeText.name,
+ attributes: nodeText.attributes,
+ })
+ .execute();
+ }
});
if (updatedNode) {
diff --git a/apps/desktop/src/renderer/components/documents/document-editor.tsx b/apps/desktop/src/renderer/components/documents/document-editor.tsx
index 4f6aba16..45aea24e 100644
--- a/apps/desktop/src/renderer/components/documents/document-editor.tsx
+++ b/apps/desktop/src/renderer/components/documents/document-editor.tsx
@@ -73,27 +73,40 @@ import {
buildEditorContent,
} from '@/shared/lib/editor';
import { LocalNode } from '@/shared/types/nodes';
-import { Document } from '@/shared/types/documents';
+import { DocumentState, DocumentUpdate } from '@/shared/types/documents';
import { toast } from '@/renderer/hooks/use-toast';
interface DocumentEditorProps {
node: LocalNode;
- document: Document | null | undefined;
+ state: DocumentState | null | undefined;
+ updates: DocumentUpdate[];
canEdit: boolean;
autoFocus?: FocusPosition;
}
+const buildYDoc = (
+ state: DocumentState | null | undefined,
+ updates: DocumentUpdate[]
+) => {
+ const ydoc = new YDoc(state?.state);
+ for (const update of updates) {
+ ydoc.applyUpdate(update.data);
+ }
+ return ydoc;
+};
+
export const DocumentEditor = ({
node,
- document,
+ state,
+ updates,
canEdit,
autoFocus,
}: DocumentEditorProps) => {
const workspace = useWorkspace();
const hasPendingChanges = React.useRef(false);
- const revisionRef = React.useRef(document?.revision ?? 0);
- const ydocRef = React.useRef<YDoc>(new YDoc(document?.state));
+ const revisionRef = React.useRef(state?.revision ?? 0);
+ const ydocRef = React.useRef<YDoc>(buildYDoc(state, updates));
const debouncedSave = React.useMemo(
() =>
@@ -248,7 +261,7 @@ export const DocumentEditor = ({
return;
}
- if (!document) {
+ if (!state) {
return;
}
@@ -256,12 +269,12 @@ export const DocumentEditor = ({
return;
}
- if (revisionRef.current === document?.revision) {
+ if (revisionRef.current === state?.revision) {
return;
}
const beforeContent = ydocRef.current.getObject<RichTextContent>();
- ydocRef.current.applyUpdate(document.state);
+ ydocRef.current.applyUpdate(state.state);
const afterContent = ydocRef.current.getObject<RichTextContent>();
if (isEqual(beforeContent, afterContent)) {
@@ -269,7 +282,7 @@ export const DocumentEditor = ({
}
const editorContent = buildEditorContent(node.id, afterContent);
- revisionRef.current = document.revision;
+ revisionRef.current = state.revision;
const relativeSelection = getRelativeSelection(editor);
editor.chain().setContent(editorContent).run();
@@ -277,7 +290,7 @@ export const DocumentEditor = ({
if (relativeSelection != null) {
restoreRelativeSelection(editor, relativeSelection);
}
- }, [document?.revision]);
+ }, [state?.revision]);
return (
<div className="min-h-[500px]">
diff --git a/apps/desktop/src/renderer/components/documents/document.tsx b/apps/desktop/src/renderer/components/documents/document.tsx
index 784d6073..d7acfc72 100644
--- a/apps/desktop/src/renderer/components/documents/document.tsx
+++ b/apps/desktop/src/renderer/components/documents/document.tsx
@@ -14,22 +14,34 @@ interface DocumentProps {
export const Document = ({ node, canEdit, autoFocus }: DocumentProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- type: 'document_get',
+ const { data: documentState, isPending: isDocumentStatePending } = useQuery({
+ type: 'document_state_get',
documentId: node.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
- if (isPending) {
+ const { data: documentUpdates, isPending: isDocumentUpdatesPending } =
+ useQuery({
+ type: 'document_updates_list',
+ documentId: node.id,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ });
+
+ if (isDocumentStatePending || isDocumentUpdatesPending) {
return null;
}
+ const state = documentState ?? null;
+ const updates = documentUpdates ?? [];
+
return (
<DocumentEditor
key={node.id}
node={node}
- document={data}
+ state={state}
+ updates={updates}
canEdit={canEdit}
autoFocus={autoFocus}
/>
diff --git a/apps/desktop/src/shared/queries/documents/document-state-get.ts b/apps/desktop/src/shared/queries/documents/document-state-get.ts
new file mode 100644
index 00000000..1bd37d4f
--- /dev/null
+++ b/apps/desktop/src/shared/queries/documents/document-state-get.ts
@@ -0,0 +1,17 @@
+import { DocumentState } from '@/shared/types/documents';
+
+export type DocumentStateGetQueryInput = {
+ type: 'document_state_get';
+ documentId: string;
+ accountId: string;
+ workspaceId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ document_state_get: {
+ input: DocumentStateGetQueryInput;
+ output: DocumentState | null;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/documents/document-updates-list.ts b/apps/desktop/src/shared/queries/documents/document-updates-list.ts
new file mode 100644
index 00000000..3beac9b1
--- /dev/null
+++ b/apps/desktop/src/shared/queries/documents/document-updates-list.ts
@@ -0,0 +1,17 @@
+import { DocumentUpdate } from '@/shared/types/documents';
+
+export type DocumentUpdatesListQueryInput = {
+ type: 'document_updates_list';
+ documentId: string;
+ accountId: string;
+ workspaceId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ document_updates_list: {
+ input: DocumentUpdatesListQueryInput;
+ output: DocumentUpdate[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/types/documents.ts b/apps/desktop/src/shared/types/documents.ts
index fb1a33f6..1453ec9d 100644
--- a/apps/desktop/src/shared/types/documents.ts
+++ b/apps/desktop/src/shared/types/documents.ts
@@ -1,9 +1,24 @@
+import { DocumentContent } from '@colanode/core';
+
export type Document = {
id: string;
- revision: bigint;
- state: Uint8Array;
+ localRevision: bigint;
+ serverRevision: bigint;
+ content: DocumentContent;
createdAt: string;
createdBy: string;
updatedAt: string | null;
updatedBy: string | null;
};
+
+export type DocumentState = {
+ id: string;
+ revision: bigint;
+ state: Uint8Array;
+};
+
+export type DocumentUpdate = {
+ id: string;
+ documentId: string;
+ data: Uint8Array;
+};
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index 76f148d9..d09ca6bc 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -7,6 +7,11 @@ import { Workspace, WorkspaceMetadata } from '@/shared/types/workspaces';
import { User } from '@/shared/types/users';
import { FileState } from '@/shared/types/files';
import { LocalNode, NodeInteraction, NodeReaction } from '@/shared/types/nodes';
+import {
+ Document,
+ DocumentState,
+ DocumentUpdate,
+} from '@/shared/types/documents';
export type UserCreatedEvent = {
type: 'user_created';
@@ -192,15 +197,28 @@ export type DocumentUpdatedEvent = {
type: 'document_updated';
accountId: string;
workspaceId: string;
+ document: Document;
+};
+
+export type DocumentDeletedEvent = {
+ type: 'document_deleted';
+ accountId: string;
+ workspaceId: string;
documentId: string;
};
+export type DocumentStateUpdatedEvent = {
+ type: 'document_state_updated';
+ accountId: string;
+ workspaceId: string;
+ documentState: DocumentState;
+};
+
export type DocumentUpdateCreatedEvent = {
type: 'document_update_created';
accountId: string;
workspaceId: string;
- documentId: string;
- updateId: string;
+ documentUpdate: DocumentUpdate;
};
export type DocumentUpdateDeletedEvent = {
@@ -243,5 +261,7 @@ export type Event =
| WorkspaceMetadataUpdatedEvent
| WorkspaceMetadataDeletedEvent
| DocumentUpdatedEvent
+ | DocumentDeletedEvent
+ | DocumentStateUpdatedEvent
| DocumentUpdateCreatedEvent
| DocumentUpdateDeletedEvent;
diff --git a/apps/server/src/data/migrations/00011-create-documents-table.ts b/apps/server/src/data/migrations/00011-create-documents-table.ts
index 082f1f89..ba4b6275 100644
--- a/apps/server/src/data/migrations/00011-create-documents-table.ts
+++ b/apps/server/src/data/migrations/00011-create-documents-table.ts
@@ -1,11 +1,13 @@
-import { Migration } from 'kysely';
+import { Migration, sql } from 'kysely';
export const createDocumentsTable: Migration = {
up: async (db) => {
await db.schema
.createTable('documents')
.addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('type', 'varchar(30)', (col) => col.notNull())
+ .addColumn('type', 'varchar(30)', (col) =>
+ col.generatedAlwaysAs(sql`(content->>'type')::VARCHAR(30)`).stored()
+ )
.addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
.addColumn('revision', 'bigint', (col) => col.notNull())
.addColumn('content', 'jsonb', (col) => col.notNull())
diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.ts
index 11c4179e..70a72241 100644
--- a/apps/server/src/data/schema.ts
+++ b/apps/server/src/data/schema.ts
@@ -187,7 +187,7 @@ export type UpdateCollaboration = Updateable<CollaborationTable>;
interface DocumentTable {
id: ColumnType<string, string, never>;
- type: ColumnType<DocumentType, DocumentType, DocumentType>;
+ type: ColumnType<DocumentType, never, never>;
workspace_id: ColumnType<string, string, never>;
revision: ColumnType<bigint, bigint, bigint>;
content: JSONColumnType<DocumentContent, string, string>;
diff --git a/apps/server/src/lib/documents.ts b/apps/server/src/lib/documents.ts
index 5ea9efd8..52db6a33 100644
--- a/apps/server/src/lib/documents.ts
+++ b/apps/server/src/lib/documents.ts
@@ -163,7 +163,6 @@ const tryUpdateDocumentFromMutation = async (
.values({
id: mutation.documentId,
workspace_id: user.workspace_id,
- type: 'rich_text',
content: JSON.stringify(content),
created_at: new Date(mutation.createdAt),
created_by: user.id,
diff --git a/packages/core/src/lib/texts.ts b/packages/core/src/lib/texts.ts
index 223dc41d..927457cc 100644
--- a/packages/core/src/lib/texts.ts
+++ b/packages/core/src/lib/texts.ts
@@ -1,5 +1,10 @@
+import { DocumentContent } from '../registry/documents';
import { Block } from '../registry/block';
+export const extractDocumentText = (id: string, content: DocumentContent) => {
+ return extractBlockTexts(id, content.blocks);
+};
+
export const extractBlockTexts = (
entryId: string,
blocks: Record<string, Block> | undefined | null
diff --git a/packages/core/src/registry/nodes/channel.ts b/packages/core/src/registry/nodes/channel.ts
index b1322413..03fe6213 100644
--- a/packages/core/src/registry/nodes/channel.ts
+++ b/packages/core/src/registry/nodes/channel.ts
@@ -61,20 +61,14 @@ export const channelModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (
- _: string,
- attributes: NodeAttributes
- ): string | null | undefined => {
+ extractNodeText: (_: string, attributes: NodeAttributes) => {
if (attributes.type !== 'channel') {
- return null;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: (): string | null | undefined => {
- return undefined;
- },
- getDocumentText: (): string | null | undefined => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/chat.ts b/packages/core/src/registry/nodes/chat.ts
index 35fdf18f..57e6bcba 100644
--- a/packages/core/src/registry/nodes/chat.ts
+++ b/packages/core/src/registry/nodes/chat.ts
@@ -46,13 +46,7 @@ export const chatModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (): string | null | undefined => {
- return undefined;
- },
- getAttributesText: (): string | null | undefined => {
- return undefined;
- },
- getDocumentText: (): string | null | undefined => {
- return undefined;
+ extractNodeText: () => {
+ return null;
},
};
diff --git a/packages/core/src/registry/nodes/core.ts b/packages/core/src/registry/nodes/core.ts
index f6c59ad1..26bdd31f 100644
--- a/packages/core/src/registry/nodes/core.ts
+++ b/packages/core/src/registry/nodes/core.ts
@@ -1,7 +1,6 @@
import { z, ZodSchema } from 'zod';
import { WorkspaceRole } from '../../types/workspaces';
-import { DocumentContent } from '../documents';
import { Node, NodeAttributes } from '.';
@@ -51,6 +50,11 @@ export interface CanReactNodeContext {
node: Node;
}
+export type NodeText = {
+ name: string | null | undefined;
+ attributes: string | null | undefined;
+};
+
export interface NodeModel {
type: string;
attributesSchema: ZodSchema;
@@ -60,16 +64,5 @@ export interface NodeModel {
canUpdateDocument: (context: CanUpdateDocumentContext) => boolean;
canDelete: (context: CanDeleteNodeContext) => boolean;
canReact: (context: CanReactNodeContext) => boolean;
- getName: (
- id: string,
- attributes: NodeAttributes
- ) => string | null | undefined;
- getAttributesText: (
- id: string,
- attributes: NodeAttributes
- ) => string | null | undefined;
- getDocumentText: (
- id: string,
- content: DocumentContent
- ) => string | null | undefined;
+ extractNodeText: (id: string, attributes: NodeAttributes) => NodeText | null;
}
diff --git a/packages/core/src/registry/nodes/database-view.ts b/packages/core/src/registry/nodes/database-view.ts
index 2012dfa6..5440ac3d 100644
--- a/packages/core/src/registry/nodes/database-view.ts
+++ b/packages/core/src/registry/nodes/database-view.ts
@@ -134,17 +134,14 @@ export const databaseViewModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (_, attributes) => {
if (attributes.type !== 'database_view') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: () => {
- return undefined;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/database.ts b/packages/core/src/registry/nodes/database.ts
index 1877e198..0f464352 100644
--- a/packages/core/src/registry/nodes/database.ts
+++ b/packages/core/src/registry/nodes/database.ts
@@ -61,17 +61,14 @@ export const databaseModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (_, attributes) => {
if (attributes.type !== 'database') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: () => {
- return undefined;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/file.ts b/packages/core/src/registry/nodes/file.ts
index 7e2409cd..6fd91afe 100644
--- a/packages/core/src/registry/nodes/file.ts
+++ b/packages/core/src/registry/nodes/file.ts
@@ -81,17 +81,14 @@ export const fileModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (_, attributes) => {
if (attributes.type !== 'file') {
- return null;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: () => {
- return undefined;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/folder.ts b/packages/core/src/registry/nodes/folder.ts
index e3503639..018336d9 100644
--- a/packages/core/src/registry/nodes/folder.ts
+++ b/packages/core/src/registry/nodes/folder.ts
@@ -59,17 +59,14 @@ export const folderModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (_, attributes) => {
if (attributes.type !== 'folder') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: () => {
- return undefined;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/message.ts b/packages/core/src/registry/nodes/message.ts
index 5b6ee042..faf9daed 100644
--- a/packages/core/src/registry/nodes/message.ts
+++ b/packages/core/src/registry/nodes/message.ts
@@ -74,26 +74,16 @@ export const messageModel: NodeModel = {
return hasNodeRole(role, 'viewer');
},
- getName: (_, attributes) => {
+ extractNodeText: (id, attributes) => {
if (attributes.type !== 'message') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: (id, attributes) => {
- if (attributes.type !== 'message') {
- return undefined;
- }
+ const attributesText = extractBlockTexts(id, attributes.content);
- const text = extractBlockTexts(id, attributes.content);
- if (!text) {
- return null;
- }
-
- return text;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: attributesText,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/page.ts b/packages/core/src/registry/nodes/page.ts
index d6b7755e..63034f23 100644
--- a/packages/core/src/registry/nodes/page.ts
+++ b/packages/core/src/registry/nodes/page.ts
@@ -70,21 +70,14 @@ export const pageModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (id, attributes) => {
if (attributes.type !== 'page') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: (id, attributes) => {
- if (attributes.type !== 'page') {
- return undefined;
- }
-
- return attributes.name;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/record.ts b/packages/core/src/registry/nodes/record.ts
index f24340ee..55514c00 100644
--- a/packages/core/src/registry/nodes/record.ts
+++ b/packages/core/src/registry/nodes/record.ts
@@ -85,21 +85,14 @@ export const recordModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (id, attributes) => {
if (attributes.type !== 'record') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: (id, attributes) => {
- if (attributes.type !== 'record') {
- return undefined;
- }
-
- return attributes.name;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};
diff --git a/packages/core/src/registry/nodes/space.ts b/packages/core/src/registry/nodes/space.ts
index 429eb66e..a40589b0 100644
--- a/packages/core/src/registry/nodes/space.ts
+++ b/packages/core/src/registry/nodes/space.ts
@@ -73,21 +73,14 @@ export const spaceModel: NodeModel = {
canReact: () => {
return false;
},
- getName: (_, attributes) => {
+ extractNodeText: (_, attributes) => {
if (attributes.type !== 'space') {
- return undefined;
+ throw new Error('Invalid node type');
}
- return attributes.name;
- },
- getAttributesText: (id, attributes) => {
- if (attributes.type !== 'space') {
- return undefined;
- }
-
- return attributes.name;
- },
- getDocumentText: () => {
- return undefined;
+ return {
+ name: attributes.name,
+ attributes: null,
+ };
},
};