Skip to content

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

Implement zod schema for nodes, apply crdt based on schema and turn on strict typescript config

Hakan Shehuebf22f0cc7b4
diff --git a/desktop/src/lib/avatars.ts b/desktop/src/lib/avatars.ts
index a781644b..6f6577e4 100644
--- a/desktop/src/lib/avatars.ts
+++ b/desktop/src/lib/avatars.ts
@@ -40,7 +40,7 @@ export const getAvatarUrl = (accountId: string, avatar: string): string => {
return `avatar://${accountId}/${avatar}`;
};
-export const getDefaultNodeAvatar = (type: IdType): string => {
+export const getDefaultNodeAvatar = (type: IdType): string | null => {
if (type === IdType.Channel) {
return '01h37jbxq11hpcnw1mdfgmm70cem';
}
diff --git a/desktop/src/lib/constants.ts b/desktop/src/lib/constants.ts
index 01e3d371..2817b9fb 100644
--- a/desktop/src/lib/constants.ts
+++ b/desktop/src/lib/constants.ts
@@ -5,16 +5,10 @@ export const NodeTypes = {
Channel: 'channel',
Chat: 'chat',
Message: 'message',
- HorizontalRule: 'horizontal_rule',
Database: 'database',
- DatabaseReplica: 'database_replica',
+ DatabaseReplica: 'databaseReplica',
Record: 'record',
Folder: 'folder',
- TableView: 'table_view',
- BoardView: 'board_view',
- CalendarView: 'calendar_view',
- Field: 'field',
- SelectOption: 'select_option',
File: 'file',
};
@@ -37,12 +31,6 @@ export const EditorNodeTypes = {
FilePlaceholder: 'filePlaceholder',
};
-export const ViewNodeTypes: string[] = [
- NodeTypes.TableView,
- NodeTypes.BoardView,
- NodeTypes.CalendarView,
-];
-
export const SortDirections = {
Ascending: 'asc',
Descending: 'desc',
diff --git a/desktop/src/lib/databases.ts b/desktop/src/lib/databases.ts
index af9b3a17..65d27347 100644
--- a/desktop/src/lib/databases.ts
+++ b/desktop/src/lib/databases.ts
@@ -1,13 +1,15 @@
import {
- FieldDataType,
- FieldNode,
- RecordNode,
- ViewFieldFilter,
- ViewFilter,
-} from '@/types/databases';
-import { isStringArray } from '@/lib/utils';
-
-export const getDefaultFieldWidth = (type: FieldDataType): number => {
+ FieldType,
+ FieldAttributes,
+ ViewFieldFilterAttributes,
+ ViewFilterAttributes,
+ ViewFieldAttributes,
+} from '@/registry';
+import { RecordNode } from '@/types/nodes';
+import { compareString, isStringArray } from '@/lib/utils';
+import { generateNodeIndex } from './nodes';
+
+export const getDefaultFieldWidth = (type: FieldType): number => {
if (!type) return 0;
switch (type.toLowerCase()) {
@@ -460,18 +462,18 @@ export const urlFieldFilterOperators: FieldFilterOperator[] = [
];
export const getFieldFilterOperators = (
- dataType: FieldDataType,
+ type: FieldType,
): FieldFilterOperator[] => {
- if (!dataType) return [];
+ if (!type) return [];
- switch (dataType) {
+ switch (type) {
case 'boolean':
return booleanFieldFilterOperators;
case 'collaborator':
return collaboratorFieldFilterOperators;
- case 'created_at':
+ case 'createdAt':
return createdAtFieldFilterOperators;
- case 'created_by':
+ case 'createdBy':
return createdByFieldFilterOperators;
case 'date':
return dateFieldFilterOperators;
@@ -479,7 +481,7 @@ export const getFieldFilterOperators = (
return emailFieldFilterOperators;
case 'file':
return fileFieldFilterOperators;
- case 'multi_select':
+ case 'multiSelect':
return multiSelectFieldFilterOperators;
case 'number':
return numberFieldFilterOperators;
@@ -498,8 +500,8 @@ export const getFieldFilterOperators = (
export const filterRecords = (
records: RecordNode[],
- filter: ViewFilter,
- field: FieldNode,
+ filter: ViewFilterAttributes,
+ field: FieldAttributes,
currentUserId: string,
): RecordNode[] => {
return records.filter((record) =>
@@ -509,22 +511,22 @@ export const filterRecords = (
const recordMatchesFilter = (
record: RecordNode,
- filter: ViewFilter,
- field: FieldNode,
+ filter: ViewFilterAttributes,
+ field: FieldAttributes,
currentUserId: string,
) => {
if (filter.type === 'group') {
return false;
}
- switch (field.dataType) {
+ switch (field.type) {
case 'boolean':
return recordMatchesBooleanFilter(record, filter, field);
case 'collaborator':
return recordMatchesCollaboratorFilter(record, filter, field);
- case 'created_at':
+ case 'createdAt':
return recordMatchesCreatedAtFilter(record, filter);
- case 'created_by':
+ case 'createdBy':
return recordMatchesCreatedByFilter(record, filter, currentUserId);
case 'date':
return recordMatchesDateFilter(record, filter, field);
@@ -532,7 +534,7 @@ const recordMatchesFilter = (
return recordMatchesEmailFilter(record, filter, field);
case 'file':
return recordMatchesFileFilter(record, filter, field);
- case 'multi_select':
+ case 'multiSelect':
return recordMatchesMultiSelectFilter(record, filter, field);
case 'number':
return recordMatchesNumberFilter(record, filter, field);
@@ -551,16 +553,23 @@ const recordMatchesFilter = (
const recordMatchesBooleanFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
-
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_true') {
- return fieldValue === true;
+ return (
+ fieldValue && fieldValue.type === 'boolean' && fieldValue.value === true
+ );
}
+
if (filter.operator === 'is_false') {
- return !fieldValue || fieldValue === false;
+ return (
+ !fieldValue ||
+ (fieldValue &&
+ fieldValue.type === 'boolean' &&
+ fieldValue.value === false)
+ );
}
return false;
@@ -568,15 +577,15 @@ const recordMatchesBooleanFilter = (
const recordMatchesCollaboratorFilter = (
record: RecordNode,
- filter: ViewFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
return false;
};
const recordMatchesCreatedAtFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
+ filter: ViewFieldFilterAttributes,
) => {
if (!filter.value) return false;
@@ -610,10 +619,10 @@ const recordMatchesCreatedAtFilter = (
const recordMatchesCreatedByFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
+ filter: ViewFieldFilterAttributes,
currentUserId: string,
) => {
- const createdBy = record.createdBy?.id;
+ const createdBy = record.createdBy;
if (!createdBy) {
return false;
}
@@ -643,10 +652,10 @@ const recordMatchesCreatedByFilter = (
const recordMatchesDateFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
}
@@ -655,11 +664,11 @@ const recordMatchesDateFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'date') {
return false;
}
- const recordDate = new Date(fieldValue);
+ const recordDate = new Date(fieldValue.value);
recordDate.setHours(0, 0, 0, 0); // Set time to midnight
if (typeof filter.value !== 'string') {
@@ -689,10 +698,10 @@ const recordMatchesDateFilter = (
const recordMatchesEmailFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -702,7 +711,7 @@ const recordMatchesEmailFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'email') {
return false;
}
@@ -717,13 +726,13 @@ const recordMatchesEmailFilter = (
switch (filter.operator) {
case 'is_equal_to':
- return fieldValue === filterValue;
+ return fieldValue.value === filterValue;
case 'is_not_equal_to':
- return fieldValue !== filterValue;
+ return fieldValue.value !== filterValue;
case 'contains':
- return fieldValue.includes(filterValue);
+ return fieldValue.value.includes(filterValue);
case 'does_not_contain':
- return !fieldValue.includes(filterValue);
+ return !fieldValue.value.includes(filterValue);
}
return false;
@@ -731,29 +740,27 @@ const recordMatchesEmailFilter = (
const recordMatchesFileFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
return false;
};
const recordMatchesMultiSelectFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValues = record.attributes[field.id] as string[];
+ const fieldValue = record.attributes.fields[field.id];
+ const selectValues =
+ fieldValue?.type === 'multiSelect' ? fieldValue.value : [];
if (filter.operator === 'is_empty') {
- return fieldValues?.length === 0;
+ return selectValues.length === 0;
}
if (filter.operator === 'is_not_empty') {
- return fieldValues?.length > 0;
- }
-
- if (!fieldValues) {
- return false;
+ return selectValues.length > 0;
}
if (!isStringArray(filter.value)) {
@@ -762,9 +769,9 @@ const recordMatchesMultiSelectFilter = (
switch (filter.operator) {
case 'is_in':
- return filter.value.some((value) => fieldValues.includes(value));
+ return filter.value.some((value) => selectValues.includes(value));
case 'is_not_in':
- return !filter.value.some((value) => fieldValues.includes(value));
+ return !filter.value.some((value) => selectValues.includes(value));
}
return false;
@@ -772,10 +779,10 @@ const recordMatchesMultiSelectFilter = (
const recordMatchesNumberFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -785,7 +792,7 @@ const recordMatchesNumberFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'number') {
return false;
}
@@ -800,17 +807,17 @@ const recordMatchesNumberFilter = (
switch (filter.operator) {
case 'is_equal_to':
- return fieldValue === filterValue;
+ return fieldValue.value === filterValue;
case 'is_not_equal_to':
- return fieldValue !== filterValue;
+ return fieldValue.value !== filterValue;
case 'is_greater_than':
- return fieldValue > filterValue;
+ return fieldValue.value > filterValue;
case 'is_less_than':
- return fieldValue < filterValue;
+ return fieldValue.value < filterValue;
case 'is_greater_than_or_equal_to':
- return fieldValue >= filterValue;
+ return fieldValue.value >= filterValue;
case 'is_less_than_or_equal_to':
- return fieldValue <= filterValue;
+ return fieldValue.value <= filterValue;
}
return false;
@@ -818,10 +825,10 @@ const recordMatchesNumberFilter = (
const recordMatchesPhoneFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -831,7 +838,7 @@ const recordMatchesPhoneFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'phone') {
return false;
}
@@ -846,13 +853,13 @@ const recordMatchesPhoneFilter = (
switch (filter.operator) {
case 'is_equal_to':
- return fieldValue === filterValue;
+ return fieldValue.value === filterValue;
case 'is_not_equal_to':
- return fieldValue !== filterValue;
+ return fieldValue.value !== filterValue;
case 'contains':
- return fieldValue.includes(filterValue);
+ return fieldValue.value.includes(filterValue);
case 'does_not_contain':
- return !fieldValue.includes(filterValue);
+ return !fieldValue.value.includes(filterValue);
}
return false;
@@ -860,10 +867,10 @@ const recordMatchesPhoneFilter = (
const recordMatchesSelectFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -873,7 +880,7 @@ const recordMatchesSelectFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'select') {
return false;
}
@@ -881,11 +888,13 @@ const recordMatchesSelectFilter = (
return true;
}
+ const selectValues = fieldValue.value;
+
switch (filter.operator) {
case 'is_in':
- return filter.value.includes(fieldValue);
+ return filter.value.some((value) => selectValues.includes(value));
case 'is_not_in':
- return !filter.value.includes(fieldValue);
+ return !filter.value.some((value) => selectValues.includes(value));
}
return false;
@@ -893,10 +902,10 @@ const recordMatchesSelectFilter = (
const recordMatchesTextFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -906,7 +915,7 @@ const recordMatchesTextFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'text') {
return false;
}
@@ -921,13 +930,13 @@ const recordMatchesTextFilter = (
switch (filter.operator) {
case 'is_equal_to':
- return fieldValue === filterValue;
+ return fieldValue.value === filterValue;
case 'is_not_equal_to':
- return fieldValue !== filterValue;
+ return fieldValue.value !== filterValue;
case 'contains':
- return fieldValue.includes(filterValue);
+ return fieldValue.value.includes(filterValue);
case 'does_not_contain':
- return !fieldValue.includes(filterValue);
+ return !fieldValue.value.includes(filterValue);
}
return false;
@@ -935,10 +944,10 @@ const recordMatchesTextFilter = (
const recordMatchesUrlFilter = (
record: RecordNode,
- filter: ViewFieldFilter,
- field: FieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: FieldAttributes,
) => {
- const fieldValue = record.attributes[field.id];
+ const fieldValue = record.attributes.fields[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -948,7 +957,7 @@ const recordMatchesUrlFilter = (
return !!fieldValue;
}
- if (!fieldValue) {
+ if (!fieldValue || fieldValue.type !== 'url') {
return false;
}
@@ -963,27 +972,98 @@ const recordMatchesUrlFilter = (
switch (filter.operator) {
case 'is_equal_to':
- return fieldValue === filterValue;
+ return fieldValue.value === filterValue;
case 'is_not_equal_to':
- return fieldValue !== filterValue;
+ return fieldValue.value !== filterValue;
case 'contains':
- return fieldValue.includes(filterValue);
+ return fieldValue.value.includes(filterValue);
case 'does_not_contain':
- return !fieldValue.includes(filterValue);
+ return !fieldValue.value.includes(filterValue);
}
return false;
};
-export const isSortableField = (field: FieldNode) => {
+export const isSortableField = (field: FieldAttributes) => {
return (
- field.dataType === 'text' ||
- field.dataType === 'number' ||
- field.dataType === 'date' ||
- field.dataType === 'created_at' ||
- field.dataType === 'email' ||
- field.dataType === 'phone' ||
- field.dataType === 'select' ||
- field.dataType === 'url'
+ field.type === 'text' ||
+ field.type === 'number' ||
+ field.type === 'date' ||
+ field.type === 'createdAt' ||
+ field.type === 'email' ||
+ field.type === 'phone' ||
+ field.type === 'select' ||
+ field.type === 'url'
+ );
+};
+
+export const generateViewFieldIndex = (
+ databaseFields: FieldAttributes[],
+ viewFields: ViewFieldAttributes[],
+ fieldId: string,
+ after: string,
+): string | null => {
+ const field = databaseFields.find((f) => f.id === fieldId);
+ if (!field) {
+ return null;
+ }
+
+ if (databaseFields.length <= 1) {
+ return null;
+ }
+
+ const mergedIndexes = databaseFields
+ .map((f) => {
+ const viewField = viewFields.find((vf) => vf.id === f.id);
+ return {
+ id: f.id,
+ databaseIndex: f.index,
+ viewIndex: viewField?.index ?? null,
+ };
+ })
+ .sort((a, b) =>
+ compareString(
+ a.viewIndex ?? a.databaseIndex,
+ b.viewIndex ?? b.databaseIndex,
+ ),
+ );
+
+ let previousIndex: string | null = null;
+ let nextIndex: string | null = null;
+ if (after === 'name') {
+ const lowestIndex = mergedIndexes[0];
+ nextIndex = lowestIndex.viewIndex ?? lowestIndex.databaseIndex;
+ } else {
+ const afterFieldArrayIndex = mergedIndexes.findIndex((f) => f.id === after);
+ if (afterFieldArrayIndex === -1) {
+ return null;
+ }
+
+ previousIndex =
+ mergedIndexes[afterFieldArrayIndex].viewIndex ??
+ mergedIndexes[afterFieldArrayIndex].databaseIndex;
+
+ if (afterFieldArrayIndex < mergedIndexes.length) {
+ nextIndex =
+ mergedIndexes[afterFieldArrayIndex + 1].viewIndex ??
+ mergedIndexes[afterFieldArrayIndex + 1].databaseIndex;
+ }
+ }
+
+ let newIndex = generateNodeIndex(previousIndex, nextIndex);
+
+ const lastDatabaseField = mergedIndexes.sort((a, b) =>
+ compareString(a.databaseIndex, b.databaseIndex),
+ )[mergedIndexes.length - 1];
+
+ const newPotentialFieldIndex = generateNodeIndex(
+ lastDatabaseField.databaseIndex,
+ null,
);
+
+ if (newPotentialFieldIndex === newIndex) {
+ newIndex = generateNodeIndex(previousIndex, newPotentialFieldIndex);
+ }
+
+ return newIndex;
};
diff --git a/desktop/src/lib/editor.ts b/desktop/src/lib/editor.ts
index 390e8e93..d9395d0e 100644
--- a/desktop/src/lib/editor.ts
+++ b/desktop/src/lib/editor.ts
@@ -2,11 +2,8 @@ import { EditorNodeTypes } from '@/lib/constants';
import { generateId, getIdTypeFromNode } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
-import { NodeBlock, NodeBlockContent } from '@/types/nodes';
import { JSONContent } from '@tiptap/core';
-import { isEqual } from 'lodash';
-import * as Y from 'yjs';
-import { diffChars } from 'diff';
+import { Block, BlockLeaf } from '@/registry';
const leafBlockTypes = new Set([
EditorNodeTypes.Paragraph,
@@ -20,9 +17,9 @@ const leafBlockTypes = new Set([
export const mapContentsToBlocks = (
parentId: string,
contents: JSONContent[],
- blocksMap: Map<string, NodeBlock>,
-): NodeBlock[] => {
- const blocks: NodeBlock[] = [];
+ blocksMap: Map<string, Block>,
+): Block[] => {
+ const blocks: Block[] = [];
mapAndPushContentsToBlocks(contents, parentId, blocks, blocksMap);
validateBlocksIndexes(blocks);
return blocks;
@@ -31,8 +28,8 @@ export const mapContentsToBlocks = (
const mapAndPushContentsToBlocks = (
contents: JSONContent[] | null | undefined,
parentId: string,
- blocks: NodeBlock[],
- blocksMap: Map<string, NodeBlock>,
+ blocks: Block[],
+ blocksMap: Map<string, Block>,
): void => {
if (!contents) {
return;
@@ -45,9 +42,13 @@ const mapAndPushContentsToBlocks = (
const mapAndPushContentToBlock = (
content: JSONContent,
parentId: string,
- blocks: NodeBlock[],
- blocksMap: Map<string, NodeBlock>,
+ blocks: Block[],
+ blocksMap: Map<string, Block>,
): void => {
+ if (!content.type) {
+ throw new Error('Invalid content type');
+ }
+
const id = getIdFromContent(content);
const index = blocksMap.get(id)?.index;
const attrs =
@@ -57,16 +58,16 @@ const mapAndPushContentToBlock = (
const isLeafBlock = leafBlockTypes.has(content.type);
const blockContent = isLeafBlock
- ? mapContentsToNodeBlockContents(content.type, content.content)
+ ? mapContentsToBlockLeafs(content.type, content.content)
: null;
blocks.push({
id: id,
- index: index,
+ index: index ?? generateNodeIndex(null, null),
attrs: attrs.length > 0 ? Object.fromEntries(attrs) : null,
parentId: parentId,
type: content.type,
- content: blockContent,
+ content: blockContent?.filter((leaf) => leaf !== null) ?? null,
});
if (!isLeafBlock && content.content) {
@@ -74,24 +75,28 @@ const mapAndPushContentToBlock = (
}
};
-const mapContentsToNodeBlockContents = (
+const mapContentsToBlockLeafs = (
type: string,
contents?: JSONContent[],
-): NodeBlockContent[] | null => {
- if (!leafBlockTypes.has(type) || contents == null) {
+): BlockLeaf[] | null => {
+ if (!leafBlockTypes.has(type) || contents == null || contents.length === 0) {
return null;
}
- const nodeBlocks: NodeBlockContent[] = [];
+ const nodeBlocks: BlockLeaf[] = [];
for (const content of contents) {
+ if (!content.type) {
+ continue;
+ }
+
nodeBlocks.push({
type: content.type,
- text: content.text,
+ text: content.text ?? '',
marks:
content.marks?.map((mark) => {
return {
type: mark.type,
- attrs: mark.attrs,
+ attrs: mark.attrs ?? null,
};
}) ?? null,
});
@@ -101,7 +106,7 @@ const mapContentsToNodeBlockContents = (
export const mapBlocksToContents = (
parentId: string,
- blocks: NodeBlock[],
+ blocks: Block[],
): JSONContent[] => {
const contents: JSONContent[] = [];
const children = blocks
@@ -115,10 +120,7 @@ export const mapBlocksToContents = (
return contents;
};
-const mapBlockToContent = (
- block: NodeBlock,
- blocks: NodeBlock[],
-): JSONContent => {
+const mapBlockToContent = (block: Block, blocks: Block[]): JSONContent => {
return {
type: block.type,
attrs: {
@@ -126,265 +128,72 @@ const mapBlockToContent = (
...block.attrs,
},
content: leafBlockTypes.has(block.type)
- ? mapNodeBlockContentsToContents(block.content)
+ ? mapBlockLeafsToContents(block.content)
: mapBlocksToContents(block.id, blocks),
};
};
-const mapNodeBlockContentsToContents = (
- nodeBlocks: NodeBlockContent[] | null,
-): JSONContent[] | null => {
- if (nodeBlocks == null) {
- return null;
+const mapBlockLeafsToContents = (
+ leafs: BlockLeaf[] | null,
+): JSONContent[] | undefined => {
+ if (leafs == null) {
+ return undefined;
}
const contents: JSONContent[] = [];
- for (const nodeBlock of nodeBlocks) {
+ for (const leaf of leafs) {
contents.push({
- type: nodeBlock.type,
- text: nodeBlock.text,
+ type: leaf.type,
+ text: leaf.text,
marks:
- nodeBlock.marks?.map((mark) => {
+ leaf.marks?.map((mark) => {
return {
type: mark.type,
- attrs: mark.attrs,
+ attrs: mark.attrs ?? undefined,
};
- }) ?? null,
+ }) ?? undefined,
});
}
return contents;
};
-const validateBlocksIndexes = (blocks: NodeBlock[]) => {
+const validateBlocksIndexes = (blocks: Block[]) => {
//group by parentId
- const groupedBlocks: { [key: string]: NodeBlock[] } = {};
+ const groupedBlocks: { [key: string]: Block[] } = {};
for (const block of blocks) {
if (!groupedBlocks[block.parentId]) {
groupedBlocks[block.parentId] = [];
}
groupedBlocks[block.parentId].push(block);
}
+
for (const parentId in groupedBlocks) {
const blocks = groupedBlocks[parentId];
- for (let i = 0; i < blocks.length; i++) {
+ for (let i = 1; i < blocks.length; i++) {
const currentIndex = blocks[i].index;
- const beforeIndex = i === 0 ? null : blocks[i - 1].index;
- // find the lowest index after the current node
- // we do this because sometimes nodes can be ordered in such a way that
- // the current node's index is higher than one of its siblings
- // after the next sibling
- // for example: 1, {current}, 4, 3
- let afterIndex = i === blocks.length - 1 ? null : blocks[i + 1].index;
- for (let j = i + 1; j < blocks.length; j++) {
- if (blocks[j].index < afterIndex) {
- afterIndex = blocks[j].index;
- break;
+ const beforeIndex = blocks[i - 1].index;
+
+ if (currentIndex <= beforeIndex) {
+ let afterIndex = i < blocks.length - 1 ? blocks[i + 1].index : null;
+ if (
+ afterIndex &&
+ afterIndex > currentIndex &&
+ afterIndex > beforeIndex
+ ) {
+ blocks[i].index = generateNodeIndex(beforeIndex, afterIndex);
+ } else {
+ blocks[i].index = generateNodeIndex(beforeIndex, null);
}
}
- // extra check to make sure that the beforeIndex is less than the afterIndex
- // because otherwise the fractional index library will throw an error
- if (afterIndex < beforeIndex) {
- afterIndex = generateNodeIndex(null, beforeIndex);
- } else if (beforeIndex === afterIndex) {
- afterIndex = generateNodeIndex(beforeIndex, null);
- }
- if (
- !currentIndex ||
- currentIndex <= beforeIndex ||
- currentIndex > afterIndex
- ) {
- blocks[i].index = generateNodeIndex(beforeIndex, afterIndex);
- }
}
}
};
const getIdFromContent = (content: JSONContent): string => {
- return content.attrs?.id ?? generateId(getIdTypeFromNode(content.type));
-};
-
-export const applyChangeToAttributesMap = (
- attributesMap: Y.Map<any>,
- blocks: NodeBlock[],
-) => {
- if (!attributesMap.has('content')) {
- attributesMap.set('content', new Y.Map());
- }
-
- const contentMap = attributesMap.get('content') as Y.Map<any>;
- const blockIds = new Set<string>();
- for (const block of blocks) {
- blockIds.add(block.id);
-
- if (!contentMap.has(block.id)) {
- contentMap.set(block.id, new Y.Map());
- }
-
- const blockMap = contentMap.get(block.id) as Y.Map<any>;
- applyBlockChangesToYDoc(blockMap, block);
- }
-
- const deletedBlockIds = Array.from(contentMap.keys()).filter(
- (id) => !blockIds.has(id),
- );
-
- for (const id of deletedBlockIds) {
- contentMap.delete(id);
+ if (!content.type) {
+ throw new Error('Invalid content type');
}
-};
-
-const applyBlockChangesToYDoc = (blockMap: Y.Map<any>, block: NodeBlock) => {
- if (blockMap.get('id') !== block.id) {
- blockMap.set('id', block.id);
- }
-
- if (blockMap.get('type') !== block.type) {
- blockMap.set('type', block.type);
- }
-
- if (blockMap.get('index') !== block.index) {
- blockMap.set('index', block.index);
- }
-
- if (blockMap.get('parentId') !== block.parentId) {
- blockMap.set('parentId', block.parentId);
- }
-
- applyBlockAttrsChangesToYDoc(blockMap, block);
- applyBlockContentChangesToYDoc(blockMap, block);
-};
-const applyBlockAttrsChangesToYDoc = (
- blockMap: Y.Map<any>,
- block: NodeBlock,
-) => {
- if (block.attrs === null) {
- if (blockMap.has('attrs')) {
- blockMap.delete('attrs');
- }
-
- return;
- }
-
- if (!blockMap.has('attrs')) {
- blockMap.set('attrs', new Y.Map());
- }
-
- const attrsMap = blockMap.get('attrs') as Y.Map<any>;
- for (const [key, value] of Object.entries(block.attrs)) {
- const existingValue = attrsMap.get(key);
- if (!isEqual(existingValue, value)) {
- attrsMap.set(key, value);
- }
- }
-};
-
-const applyBlockContentChangesToYDoc = (
- blockMap: Y.Map<any>,
- block: NodeBlock,
-) => {
- if (block.content === null || block.content.length === 0) {
- if (blockMap.has('content')) {
- blockMap.delete('content');
- }
-
- return;
- }
-
- if (!blockMap.has('content')) {
- blockMap.set('content', new Y.Array());
- }
-
- const contentArray = blockMap.get('content') as Y.Array<any>;
- for (let i = 0; i < block.content.length; i++) {
- const blockContent = block.content[i];
- if (contentArray.length > i) {
- const blockContentMap = contentArray.get(i) as Y.Map<any>;
- applyBlockContentItemChangesToYDoc(blockContentMap, blockContent);
- } else {
- const blockContentMap = new Y.Map<any>();
- contentArray.insert(i, [blockContentMap]);
- applyBlockContentItemChangesToYDoc(blockContentMap, blockContent);
- }
- }
-
- // delete any extra content items
- while (contentArray.length > block.content.length) {
- contentArray.delete(contentArray.length - 1);
- }
-};
-
-const applyBlockContentItemChangesToYDoc = (
- blockContentMap: Y.Map<any>,
- blockContent: NodeBlockContent,
-) => {
- if (blockContentMap.get('type') !== blockContent.type) {
- blockContentMap.set('type', blockContent.type);
- }
-
- applyBlockContentTextChangesToYDoc(blockContentMap, blockContent);
- applyBlockContentMarksChangesToYDoc(blockContentMap, blockContent);
-};
-
-const applyBlockContentTextChangesToYDoc = (
- blockContentMap: Y.Map<any>,
- blockContent: NodeBlockContent,
-) => {
- if (
- blockContent.text === null ||
- blockContent.text === undefined ||
- blockContent.text === ''
- ) {
- if (blockContentMap.has('text')) {
- blockContentMap.delete('text');
- }
-
- return;
- }
-
- if (!blockContentMap.has('text')) {
- blockContentMap.set('text', new Y.Text(blockContent.text));
- return;
- }
-
- const yText = blockContentMap.get('text') as Y.Text;
- const currentText = yText.toString();
- const newText = blockContent.text;
-
- if (currentText === newText) {
- return;
- }
-
- const diffs = diffChars(currentText, newText);
- let index = 0;
- for (const diff of diffs) {
- if (diff.added) {
- yText.insert(index, diff.value);
- index += diff.value.length;
- } else if (diff.removed) {
- yText.delete(index, diff.value.length);
- index -= diff.value.length;
- } else {
- index += diff.value.length;
- }
- }
-};
-
-const applyBlockContentMarksChangesToYDoc = (
- blockContentMap: Y.Map<any>,
- blockContent: NodeBlockContent,
-) => {
- if (blockContent.marks === null || blockContent.marks.length === 0) {
- if (blockContentMap.has('marks')) {
- blockContentMap.delete('marks');
- }
-
- return;
- }
-
- const existingMarks = blockContentMap.get('marks');
- if (!isEqual(existingMarks, blockContent.marks)) {
- blockContentMap.set('marks', blockContent.marks);
- }
+ return content.attrs?.id ?? generateId(getIdTypeFromNode(content.type));
};
export const editorHasContent = (block?: JSONContent) => {
diff --git a/desktop/src/lib/http-client.ts b/desktop/src/lib/http-client.ts
index 4162dfd3..814ec490 100644
--- a/desktop/src/lib/http-client.ts
+++ b/desktop/src/lib/http-client.ts
@@ -20,7 +20,7 @@ class HttpClient {
): Promise<AxiosResponse<T>> {
if (this.backoffs.has(config.serverDomain)) {
const backoff = this.backoffs.get(config.serverDomain);
- if (!backoff.canRetry()) {
+ if (!backoff?.canRetry()) {
throw new Error(`Backoff in progress for key: ${config.serverDomain}`);
}
}
@@ -35,7 +35,7 @@ class HttpClient {
// Reset backoff if successful
if (this.backoffs.has(config.serverDomain)) {
- this.backoffs.get(config.serverDomain).reset();
+ this.backoffs.get(config.serverDomain)?.reset();
}
return response;
@@ -47,7 +47,7 @@ class HttpClient {
}
const backoff = this.backoffs.get(config.serverDomain);
- backoff.increaseError();
+ backoff?.increaseError();
}
throw error;
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index ae59ce3b..66a6bb7b 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -32,9 +32,7 @@ export enum IdType {
DatabaseReplica = 'dr',
Record = 'rc',
Folder = 'fl',
- TableView = 'tv',
- BoardView = 'bv',
- CalendarView = 'cv',
+ View = 'vw',
Field = 'fi',
SelectOption = 'so',
ViewFilter = 'vf',
@@ -71,8 +69,6 @@ export const getIdTypeFromNode = (nodeType: string): IdType => {
return IdType.Channel;
case NodeTypes.Message:
return IdType.Message;
- case NodeTypes.HorizontalRule:
- return IdType.HorizontalRule;
case NodeTypes.Database:
return IdType.Database;
case NodeTypes.DatabaseReplica:
@@ -81,16 +77,6 @@ export const getIdTypeFromNode = (nodeType: string): IdType => {
return IdType.Record;
case NodeTypes.Folder:
return IdType.Folder;
- case NodeTypes.TableView:
- return IdType.TableView;
- case NodeTypes.BoardView:
- return IdType.BoardView;
- case NodeTypes.CalendarView:
- return IdType.CalendarView;
- case NodeTypes.Field:
- return IdType.Field;
- case NodeTypes.SelectOption:
- return IdType.SelectOption;
default:
return IdType.Node;
}
diff --git a/desktop/src/lib/nodes.ts b/desktop/src/lib/nodes.ts
index 2eeb83ba..90c7df49 100644
--- a/desktop/src/lib/nodes.ts
+++ b/desktop/src/lib/nodes.ts
@@ -1,22 +1,8 @@
import { SelectNode } from '@/main/data/workspace/schema';
-import { LocalNode, LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNode } from '@/types/nodes';
import { generateKeyBetween } from 'fractional-indexing-jittered';
import { NodeTypes } from '@/lib/constants';
-export const buildNodeWithChildren = (
- node: LocalNode,
- allNodes: LocalNode[],
-): LocalNodeWithChildren => {
- const children: LocalNodeWithChildren[] = allNodes
- .filter((n) => n.parentId === node.id)
- .map((n) => buildNodeWithChildren(n, allNodes));
-
- return {
- ...node,
- children: children,
- };
-};
-
export const generateNodeIndex = (
previous?: string | null,
next?: string | null,
@@ -30,7 +16,7 @@ export const generateNodeIndex = (
export const mapNode = (row: SelectNode): LocalNode => {
return {
id: row.id,
- type: row.type,
+ type: row.type as any,
index: row.index,
parentId: row.parent_id,
attributes: JSON.parse(row.attributes),
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 078f173b..a995e23d 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -95,8 +95,11 @@ app.on('ready', createWindow);
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
- eventBus.unsubscribe(subscriptionId);
- subscriptionId = null;
+ if (subscriptionId) {
+ eventBus.unsubscribe(subscriptionId);
+ subscriptionId = null;
+ }
+
if (process.platform !== 'darwin') {
app.quit();
}
@@ -151,7 +154,12 @@ ipcMain.handle(
_: unknown,
options: Electron.OpenDialogOptions,
): Promise<Electron.OpenDialogReturnValue> => {
- return dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), options);
+ const window = BrowserWindow.getFocusedWindow();
+ if (!window) {
+ throw new Error('No focused window');
+ }
+
+ return dialog.showOpenDialog(window, options);
},
);
diff --git a/desktop/src/main/crdt.ts b/desktop/src/main/crdt.ts
new file mode 100644
index 00000000..759fc924
--- /dev/null
+++ b/desktop/src/main/crdt.ts
@@ -0,0 +1,315 @@
+import { z } from 'zod';
+import * as Y from 'yjs';
+import { ZodText } from '@/registry/zod';
+import { isEqual } from 'lodash';
+import { diffChars } from 'diff';
+
+export const applyCrdt = (
+ schema: z.ZodSchema,
+ attributes: z.infer<typeof schema>,
+ attributesMap: Y.Map<any>,
+) => {
+ const parsedAttributes = schema.parse(attributes);
+
+ if (!(schema instanceof z.ZodObject)) {
+ throw new Error('Schema must be a ZodObject');
+ }
+
+ applyObjectChanges(schema, parsedAttributes, attributesMap);
+
+ const parseResult = schema.safeParse(attributesMap.toJSON());
+ if (!parseResult.success) {
+ throw new Error('Invalid attributes', parseResult.error);
+ }
+};
+
+const applyObjectChanges = (
+ schema: z.ZodObject<any, any, any, any>,
+ attributes: any,
+ yMap: Y.Map<any>,
+) => {
+ for (const [key, value] of Object.entries(attributes)) {
+ if (value === null) {
+ yMap.set(key, null);
+ continue;
+ }
+
+ const schemaField = extractType(schema.shape[key], value);
+ if (schemaField instanceof z.ZodObject) {
+ if (typeof value !== 'object') {
+ throw new Error('Value must be an object');
+ }
+
+ let nestedMap = yMap.get(key);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yMap.set(key, nestedMap);
+ }
+
+ applyObjectChanges(schemaField, value, nestedMap);
+ } else if (schemaField instanceof z.ZodRecord) {
+ if (typeof value !== 'object') {
+ throw new Error('Value must be an object');
+ }
+
+ let nestedMap = yMap.get(key);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yMap.set(key, nestedMap);
+ }
+
+ applyRecordChanges(schemaField, value, nestedMap);
+ } else if (schemaField instanceof z.ZodArray) {
+ if (!Array.isArray(value)) {
+ throw new Error('Value must be an array');
+ }
+
+ let yArray = yMap.get(key);
+ if (!(yArray instanceof Y.Array)) {
+ yArray = new Y.Array();
+ yMap.set(key, yArray);
+ }
+
+ applyArrayChanges(schemaField, value, yArray);
+ } else if (schemaField instanceof ZodText) {
+ if (typeof value !== 'string') {
+ throw new Error('Value must be a string');
+ }
+
+ let yText = yMap.get(key);
+ if (!(yText instanceof Y.Text)) {
+ yText = new Y.Text();
+ yMap.set(key, yText);
+ }
+
+ applyTextChanges(value, yText);
+ } else {
+ const currentValue = yMap.get(key);
+
+ if (!isEqual(currentValue, value)) {
+ yMap.set(key, value);
+ }
+ }
+ }
+
+ const deletedKeys = Array.from(yMap.keys()).filter(
+ (key) => !attributes.hasOwnProperty(key),
+ );
+
+ for (const key of deletedKeys) {
+ yMap.delete(key);
+ }
+};
+
+const applyArrayChanges = (
+ schemaField: z.ZodArray<any>,
+ value: Array<any>,
+ yArray: Y.Array<any>,
+) => {
+ const itemSchema = extractType(schemaField.element, value);
+ const length = value.length;
+
+ for (let i = 0; i < length; i++) {
+ const item = value[i];
+
+ if (item === null) {
+ yArray.delete(i, 1);
+ yArray.insert(i, [null]);
+ continue;
+ }
+
+ if (itemSchema instanceof z.ZodObject) {
+ if (yArray.length <= i) {
+ const nestedMap = new Y.Map();
+ yArray.insert(i, [nestedMap]);
+ }
+
+ let nestedMap = yArray.get(i);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yArray.delete(i, 1);
+ yArray.insert(i, [nestedMap]);
+ }
+
+ applyObjectChanges(itemSchema, item, nestedMap);
+ } else if (itemSchema instanceof z.ZodRecord) {
+ if (yArray.length <= i) {
+ const nestedMap = new Y.Map();
+ yArray.insert(i, [nestedMap]);
+ }
+
+ let nestedMap = yArray.get(i);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yArray.delete(i, 1);
+ yArray.insert(i, [nestedMap]);
+ }
+
+ applyRecordChanges(itemSchema, item, nestedMap);
+ } else if (itemSchema instanceof z.ZodRecord) {
+ if (yArray.length <= i) {
+ const nestedMap = new Y.Map();
+ yArray.insert(i, [nestedMap]);
+ }
+
+ let nestedMap = yArray.get(i);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yArray.delete(i, 1);
+ yArray.insert(i, [nestedMap]);
+ }
+
+ applyRecordChanges(itemSchema, item, nestedMap);
+ } else if (itemSchema instanceof ZodText) {
+ if (yArray.length <= i) {
+ const yText = new Y.Text();
+ yArray.insert(i, [yText]);
+ }
+
+ let yText = yArray.get(i);
+ if (!(yText instanceof Y.Text)) {
+ yText = new Y.Text();
+ yArray.delete(i, 1);
+ yArray.insert(i, [yText]);
+ }
+
+ applyTextChanges(item, yText);
+ } else {
+ if (yArray.length <= i) {
+ yArray.insert(i, [item]);
+ } else {
+ const currentItem = yArray.get(i);
+ if (!isEqual(currentItem, item)) {
+ yArray.delete(i);
+ yArray.insert(i, [item]);
+ }
+ }
+ }
+ }
+
+ if (yArray.length > length) {
+ yArray.delete(yArray.length, yArray.length - length);
+ }
+};
+
+const applyRecordChanges = (
+ schemaField: z.ZodRecord<any, any>,
+ record: Record<any, any>,
+ yMap: Y.Map<any>,
+) => {
+ const valueSchema = extractType(schemaField.valueSchema, record);
+ for (const [key, value] of Object.entries(record)) {
+ if (value === null) {
+ yMap.set(key, null);
+ continue;
+ }
+
+ if (valueSchema instanceof z.ZodObject) {
+ if (typeof value !== 'object') {
+ throw new Error('Value must be an object');
+ }
+
+ let nestedMap = yMap.get(key);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yMap.set(key, nestedMap);
+ }
+
+ applyObjectChanges(valueSchema, value, nestedMap);
+ } else if (valueSchema instanceof z.ZodRecord) {
+ if (typeof value !== 'object') {
+ throw new Error('Value must be an object');
+ }
+
+ let nestedMap = yMap.get(key);
+ if (!(nestedMap instanceof Y.Map)) {
+ nestedMap = new Y.Map();
+ yMap.set(key, nestedMap);
+ }
+
+ applyRecordChanges(valueSchema, value, nestedMap);
+ } else if (valueSchema instanceof z.ZodArray) {
+ if (!Array.isArray(value)) {
+ throw new Error('Value must be an array');
+ }
+
+ let yArray = yMap.get(key);
+ if (!(yArray instanceof Y.Array)) {
+ yArray = new Y.Array();
+ yMap.set(key, yArray);
+ }
+
+ applyArrayChanges(valueSchema, value, yArray);
+ } else if (valueSchema instanceof ZodText) {
+ if (typeof value !== 'string') {
+ throw new Error('Value must be a string');
+ }
+
+ let yText = yMap.get(key);
+ if (!(yText instanceof Y.Text)) {
+ yText = new Y.Text();
+ yMap.set(key, yText);
+ }
+
+ applyTextChanges(value, yText);
+ } else {
+ const currentValue = yMap.get(key);
+ if (!isEqual(currentValue, value)) {
+ yMap.set(key, value);
+ }
+ }
+ }
+
+ const deletedKeys = Array.from(yMap.keys()).filter(
+ (key) => !record.hasOwnProperty(key),
+ );
+
+ for (const key of deletedKeys) {
+ yMap.delete(key);
+ }
+};
+
+const applyTextChanges = (value: string, yText: Y.Text) => {
+ const currentText = yText.toString();
+ const newText = value ? value.toString() : '';
+
+ if (!isEqual(currentText, newText)) {
+ const diffs = diffChars(currentText, newText);
+ let index = 0;
+
+ for (const diff of diffs) {
+ if (diff.added) {
+ yText.insert(index, diff.value);
+ index += diff.value.length;
+ } else if (diff.removed) {
+ yText.delete(index, diff.value.length);
+ index -= diff.value.length;
+ } else {
+ index += diff.value.length;
+ }
+ }
+ }
+};
+
+const extractType = (
+ schema: z.ZodType<any, any, any>,
+ value: any,
+): z.ZodType<any, any, any> => {
+ if (schema instanceof z.ZodOptional) {
+ return extractType(schema.unwrap(), value);
+ }
+
+ if (schema instanceof z.ZodNullable) {
+ return extractType(schema.unwrap(), value);
+ }
+
+ if (schema instanceof z.ZodUnion) {
+ for (const option of schema.options) {
+ if (option.safeParse(value).success) {
+ return extractType(option, value);
+ }
+ }
+ }
+
+ return schema;
+};
diff --git a/desktop/src/main/data/database-manager.ts b/desktop/src/main/data/database-manager.ts
index cb90db0a..6897e7ce 100644
--- a/desktop/src/main/data/database-manager.ts
+++ b/desktop/src/main/data/database-manager.ts
@@ -34,11 +34,11 @@ class DatabaseManager {
public async getWorkspaceDatabase(
userId: string,
- ): Promise<Kysely<WorkspaceDatabaseSchema> | null> {
+ ): Promise<Kysely<WorkspaceDatabaseSchema>> {
this.waitForInit();
if (this.workspaceDatabases.has(userId)) {
- return this.workspaceDatabases.get(userId);
+ return this.workspaceDatabases.get(userId)!;
}
//try and check if it's in database but hasn't been loaded yet
@@ -49,7 +49,7 @@ class DatabaseManager {
.executeTakeFirst();
if (!workspace) {
- return null;
+ throw new Error('Workspace database not found');
}
const workspaceDatabase = await this.initWorkspaceDatabase(userId);
diff --git a/desktop/src/main/file-manager.ts b/desktop/src/main/file-manager.ts
index 3f5ed781..dbd9872a 100644
--- a/desktop/src/main/file-manager.ts
+++ b/desktop/src/main/file-manager.ts
@@ -11,9 +11,9 @@ import {
import { WorkspaceCredentials } from '@/types/workspaces';
import { databaseManager } from './data/database-manager';
import { httpClient } from '@/lib/http-client';
-import { LocalNodeAttributes } from '@/types/nodes';
import { mediator } from '@/main/mediator';
import { getWorkspaceFilesDirectoryPath } from '@/main/utils';
+import { FileAttributes } from '@/registry';
class FileManager {
public async handleFileRequest(request: Request): Promise<Response> {
@@ -130,7 +130,7 @@ class FileManager {
continue;
}
- const attributes: LocalNodeAttributes = JSON.parse(file.attributes);
+ const attributes: FileAttributes = JSON.parse(file.attributes);
const filePath = path.join(
filesDir,
`${upload.node_id}${attributes.extension}`,
@@ -226,8 +226,7 @@ class FileManager {
continue;
}
- const attributes: LocalNodeAttributes = JSON.parse(file.attributes);
-
+ const attributes: FileAttributes = JSON.parse(file.attributes);
const filePath = path.join(
filesDir,
`${download.node_id}${attributes.extension}`,
diff --git a/desktop/src/main/handlers/mutations/board-view-create.ts b/desktop/src/main/handlers/mutations/board-view-create.ts
deleted file mode 100644
index 29c3b40b..00000000
--- a/desktop/src/main/handlers/mutations/board-view-create.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { generateId, IdType } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { MutationHandler, MutationResult } from '@/operations/mutations';
-import { BoardViewCreateMutationInput } from '@/operations/mutations/board-view-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
-
-export class BoardViewCreateMutationHandler
- implements MutationHandler<BoardViewCreateMutationInput>
-{
- async handleMutation(
- input: BoardViewCreateMutationInput,
- ): Promise<MutationResult<BoardViewCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
- input.userId,
- );
-
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .selectAll()
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const id = generateId(IdType.BoardView);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.BoardView);
- attributesMap.set('parentId', input.databaseId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- attributesMap.set('groupBy', input.groupBy);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
- });
-
- return {
- output: {
- id: id,
- },
- changes: [
- {
- type: 'workspace',
- table: 'nodes',
- userId: input.userId,
- },
- ],
- };
- }
-}
diff --git a/desktop/src/main/handlers/mutations/calendar-view-create.ts b/desktop/src/main/handlers/mutations/calendar-view-create.ts
deleted file mode 100644
index b732f421..00000000
--- a/desktop/src/main/handlers/mutations/calendar-view-create.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { generateId, IdType } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { MutationHandler, MutationResult } from '@/operations/mutations';
-import { CalendarViewCreateMutationInput } from '@/operations/mutations/calendar-view-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
-
-export class CalendarViewCreateMutationHandler
- implements MutationHandler<CalendarViewCreateMutationInput>
-{
- async handleMutation(
- input: CalendarViewCreateMutationInput,
- ): Promise<MutationResult<CalendarViewCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
- input.userId,
- );
-
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .selectAll()
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const id = generateId(IdType.CalendarView);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.CalendarView);
- attributesMap.set('parentId', input.databaseId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- attributesMap.set('groupBy', input.groupBy);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
- });
-
- return {
- output: {
- id: id,
- },
- changes: [
- {
- type: 'workspace',
- table: 'nodes',
- userId: input.userId,
- },
- {
- type: 'workspace',
- table: 'changes',
- userId: input.userId,
- },
- ],
- };
- }
-}
diff --git a/desktop/src/main/handlers/mutations/channel-create.ts b/desktop/src/main/handlers/mutations/channel-create.ts
index f8e7e290..c2244f87 100644
--- a/desktop/src/main/handlers/mutations/channel-create.ts
+++ b/desktop/src/main/handlers/mutations/channel-create.ts
@@ -1,13 +1,10 @@
-import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { ChannelCreateMutationInput } from '@/operations/mutations/channel-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { ChannelAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class ChannelCreateMutationHandler
implements MutationHandler<ChannelCreateMutationInput>
@@ -19,67 +16,27 @@ export class ChannelCreateMutationHandler
input.userId,
);
- const siblings = await workspaceDatabase
+ const maxIndexResult = await workspaceDatabase
.selectFrom('nodes')
- .selectAll()
+ .select(['index'])
.where('parent_id', '=', input.spaceId)
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
+ .orderBy('index', 'desc')
+ .limit(1)
+ .executeTakeFirst();
+ const maxIndex = maxIndexResult?.index ?? null;
const id = generateId(IdType.Channel);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Channel);
- attributesMap.set('parentId', input.spaceId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
+ const attributes: ChannelAttributes = {
+ type: 'channel',
+ name: input.name,
+ parentId: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ collaborators: null,
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
+ await nodeManager.createNode(trx, input.userId, id, attributes);
});
return {
diff --git a/desktop/src/main/handlers/mutations/chat-create.ts b/desktop/src/main/handlers/mutations/chat-create.ts
index 88b5abea..a1d59ff4 100644
--- a/desktop/src/main/handlers/mutations/chat-create.ts
+++ b/desktop/src/main/handlers/mutations/chat-create.ts
@@ -4,9 +4,8 @@ import { generateId, IdType } from '@/lib/id';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { ChatCreateMutationInput } from '@/operations/mutations/chat-create';
import { sql } from 'kysely';
-import * as Y from 'yjs';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { ChatAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
interface ChatRow {
id: string;
@@ -41,56 +40,17 @@ export class ChatCreateMutationHandler
}
const id = generateId(IdType.Chat);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Chat);
- attributesMap.set('collaborators', new Y.Map());
-
- const collaboratorsMap = attributesMap.get('collaborators') as Y.Map<any>;
- collaboratorsMap.set(input.userId, NodeRole.Collaborator);
- collaboratorsMap.set(input.otherUserId, NodeRole.Collaborator);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: new Date().toISOString(),
- createdBy: input.userId,
- versionId: versionId,
+ const attributes: ChatAttributes = {
+ type: 'chat',
+ parentId: input.workspaceId,
+ collaborators: {
+ [input.userId]: NodeRole.Collaborator,
+ [input.otherUserId]: NodeRole.Collaborator,
+ },
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
+ await nodeManager.createNode(trx, input.userId, id, attributes);
});
return {
@@ -103,6 +63,11 @@ export class ChatCreateMutationHandler
table: 'nodes',
userId: input.userId,
},
+ {
+ type: 'workspace',
+ table: 'changes',
+ userId: input.userId,
+ },
],
};
}
diff --git a/desktop/src/main/handlers/mutations/database-create.ts b/desktop/src/main/handlers/mutations/database-create.ts
index c599ac54..da3b973a 100644
--- a/desktop/src/main/handlers/mutations/database-create.ts
+++ b/desktop/src/main/handlers/mutations/database-create.ts
@@ -1,13 +1,10 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { DatabaseCreateMutationInput } from '@/operations/mutations/database-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { DatabaseAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
+import { databaseManager } from '@/main/data/database-manager';
export class DatabaseCreateMutationHandler
implements MutationHandler<DatabaseCreateMutationInput>
@@ -19,155 +16,39 @@ export class DatabaseCreateMutationHandler
input.userId,
);
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where('parent_id', '=', input.spaceId)
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const createdAt = new Date().toISOString();
-
const databaseId = generateId(IdType.Database);
- const databaseVersionId = generateId(IdType.Version);
-
- const databaseDoc = new Y.Doc({
- guid: databaseId,
- });
-
- const attributesMap = databaseDoc.getMap('attributes');
- databaseDoc.transact(() => {
- attributesMap.set('type', NodeTypes.Database);
- attributesMap.set('parentId', input.spaceId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- });
-
- const databaseAttributes = JSON.stringify(attributesMap.toJSON());
- const databaseEncodedState = fromUint8Array(
- Y.encodeStateAsUpdate(databaseDoc),
- );
-
- const databaseChangeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: databaseId,
- state: databaseEncodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: databaseVersionId,
- };
-
- const tableViewId = generateId(IdType.TableView);
- const tableViewVersionId = generateId(IdType.Version);
-
- const tableViewDoc = new Y.Doc({
- guid: tableViewId,
- });
-
- const tableViewAttributesMap = tableViewDoc.getMap('attributes');
- tableViewDoc.transact(() => {
- tableViewAttributesMap.set('type', NodeTypes.TableView);
- tableViewAttributesMap.set('parentId', databaseId);
- tableViewAttributesMap.set('index', generateNodeIndex(null, null));
- tableViewAttributesMap.set('name', 'Default');
- });
-
- const tableViewAttributes = JSON.stringify(tableViewAttributesMap.toJSON());
- const tableViewEncodedState = fromUint8Array(
- Y.encodeStateAsUpdate(tableViewDoc),
- );
-
- const tableViewChangeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: tableViewId,
- state: tableViewEncodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: tableViewVersionId,
- };
-
+ const viewId = generateId(IdType.View);
const fieldId = generateId(IdType.Field);
- const fieldVersionId = generateId(IdType.Version);
-
- const fieldDoc = new Y.Doc({
- guid: fieldId,
- });
- const fieldAttributesMap = fieldDoc.getMap('attributes');
- fieldDoc.transact(() => {
- fieldAttributesMap.set('type', NodeTypes.Field);
- fieldAttributesMap.set('parentId', databaseId);
- fieldAttributesMap.set('index', generateNodeIndex(null, null));
- fieldAttributesMap.set('name', 'Comment');
- fieldAttributesMap.set('dataType', 'text');
- });
-
- const fieldAttributes = JSON.stringify(fieldAttributesMap.toJSON());
- const fieldEncodedState = fromUint8Array(Y.encodeStateAsUpdate(fieldDoc));
-
- const fieldChangeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: fieldId,
- state: fieldEncodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: fieldVersionId,
+ const attributes: DatabaseAttributes = {
+ type: 'database',
+ name: input.name,
+ parentId: input.spaceId,
+ fields: {
+ [fieldId]: {
+ id: fieldId,
+ type: 'text',
+ index: generateNodeIndex(null, null),
+ name: 'Comment',
+ },
+ },
+ views: {
+ [viewId]: {
+ id: viewId,
+ type: 'table',
+ name: 'Default',
+ fields: {},
+ filters: {},
+ sorts: {},
+ avatar: null,
+ index: generateNodeIndex(null, null),
+ groupBy: null,
+ },
+ },
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values([
- {
- id: databaseId,
- attributes: databaseAttributes,
- state: databaseEncodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: databaseVersionId,
- },
- {
- id: tableViewId,
- attributes: tableViewAttributes,
- state: tableViewEncodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: tableViewVersionId,
- },
- {
- id: fieldId,
- attributes: fieldAttributes,
- state: fieldEncodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: fieldVersionId,
- },
- ])
- .execute();
-
- await trx
- .insertInto('changes')
- .values([
- {
- data: JSON.stringify(databaseChangeData),
- created_at: createdAt,
- },
- {
- data: JSON.stringify(tableViewChangeData),
- created_at: createdAt,
- },
- {
- data: JSON.stringify(fieldChangeData),
- created_at: createdAt,
- },
- ])
- .execute();
+ await nodeManager.createNode(trx, input.userId, databaseId, attributes);
});
return {
diff --git a/desktop/src/main/handlers/mutations/document-save.ts b/desktop/src/main/handlers/mutations/document-save.ts
index 9cfacdc7..6e43c07b 100644
--- a/desktop/src/main/handlers/mutations/document-save.ts
+++ b/desktop/src/main/handlers/mutations/document-save.ts
@@ -1,8 +1,8 @@
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { DocumentSaveMutationInput } from '@/operations/mutations/document-save';
-import { applyChangeToAttributesMap, mapContentsToBlocks } from '@/lib/editor';
-import { NodeBlock } from '@/types/nodes';
-import { updateNodeAtomically } from '@/main/utils';
+import { mapContentsToBlocks } from '@/lib/editor';
+import { Block } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class DocumentSaveMutationHandler
implements MutationHandler<DocumentSaveMutationInput>
@@ -10,11 +10,15 @@ export class DocumentSaveMutationHandler
async handleMutation(
input: DocumentSaveMutationInput,
): Promise<MutationResult<DocumentSaveMutationInput>> {
- const result = await updateNodeAtomically(
+ await nodeManager.updateNode(
input.userId,
input.documentId,
- (attributesMap, attributes) => {
- const blocksMap = new Map<string, NodeBlock>();
+ (attributes) => {
+ if (attributes.type !== 'page' && attributes.type !== 'record') {
+ throw new Error('Invalid node type');
+ }
+
+ const blocksMap = new Map<string, Block>();
if (attributes.content) {
for (const [key, value] of Object.entries(attributes.content)) {
blocksMap.set(key, value);
@@ -23,22 +27,22 @@ export class DocumentSaveMutationHandler
const blocks = mapContentsToBlocks(
input.documentId,
- input.content.content,
+ input.content.content ?? [],
blocksMap,
);
- applyChangeToAttributesMap(attributesMap, blocks);
+ attributes.content = blocks.reduce(
+ (acc, block) => {
+ acc[block.id] = block;
+ return acc;
+ },
+ {} as Record<string, Block>,
+ );
+
+ return attributes;
},
);
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
-
return {
output: {
success: true,
diff --git a/desktop/src/main/handlers/mutations/email-login.ts b/desktop/src/main/handlers/mutations/email-login.ts
index d37ddcf1..bc4c7d0d 100644
--- a/desktop/src/main/handlers/mutations/email-login.ts
+++ b/desktop/src/main/handlers/mutations/email-login.ts
@@ -52,6 +52,7 @@ export class EmailLoginMutationHandler
email: data.account.email,
token: data.account.token,
server: server.domain,
+ status: 'active',
})
.execute();
diff --git a/desktop/src/main/handlers/mutations/email-register.ts b/desktop/src/main/handlers/mutations/email-register.ts
index 04df61b4..ccc6fed3 100644
--- a/desktop/src/main/handlers/mutations/email-register.ts
+++ b/desktop/src/main/handlers/mutations/email-register.ts
@@ -53,6 +53,7 @@ export class EmailRegisterMutationHandler
email: data.account.email,
token: data.account.token,
server: server.domain,
+ status: 'active',
})
.execute();
diff --git a/desktop/src/main/handlers/mutations/field-create.ts b/desktop/src/main/handlers/mutations/field-create.ts
index e2a61069..03179af6 100644
--- a/desktop/src/main/handlers/mutations/field-create.ts
+++ b/desktop/src/main/handlers/mutations/field-create.ts
@@ -1,13 +1,9 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { FieldCreateMutationInput } from '@/operations/mutations/field-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { nodeManager } from '@/main/node-manager';
export class FieldCreateMutationHandler
implements MutationHandler<FieldCreateMutationInput>
@@ -15,82 +11,35 @@ export class FieldCreateMutationHandler
async handleMutation(
input: FieldCreateMutationInput,
): Promise<MutationResult<FieldCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const fieldId = generateId(IdType.Field);
+ await nodeManager.updateNode(
input.userId,
+ input.databaseId,
+ (attributes) => {
+ if (attributes.type !== 'database') {
+ throw new Error('Invalid node type');
+ }
+
+ const maxIndex = Object.values(attributes.fields)
+ .map((field) => field.index)
+ .sort((a, b) => -compareString(a, b))[0];
+
+ const index = generateNodeIndex(maxIndex, null);
+
+ attributes.fields[fieldId] = {
+ id: fieldId,
+ type: input.fieldType,
+ name: input.name,
+ index,
+ };
+
+ return attributes;
+ },
);
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .where((eb) =>
- eb.and({
- parent_id: input.databaseId,
- type: NodeTypes.Field,
- }),
- )
- .selectAll()
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const id = generateId(IdType.Field);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Field);
- attributesMap.set('parentId', input.databaseId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- attributesMap.set('dataType', input.dataType);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
- });
-
return {
output: {
- id: id,
+ id: fieldId,
},
changes: [
{
diff --git a/desktop/src/main/handlers/mutations/file-create.ts b/desktop/src/main/handlers/mutations/file-create.ts
index f36bdb04..10d3b20c 100644
--- a/desktop/src/main/handlers/mutations/file-create.ts
+++ b/desktop/src/main/handlers/mutations/file-create.ts
@@ -1,12 +1,10 @@
-import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { generateId, IdType } from '@/lib/id';
import { FileCreateMutationInput } from '@/operations/mutations/file-create';
-import { NodeRole, NodeTypes } from '@/lib/constants';
import { fileManager } from '@/main/file-manager';
-import { LocalCreateNodeChangeData } from '@/types/sync';
-import { fromUint8Array } from 'js-base64';
+import { FileAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class FileCreateMutationHandler
implements MutationHandler<FileCreateMutationInput>
{
@@ -23,9 +21,6 @@ export class FileCreateMutationHandler
}
const id = generateId(IdType.File);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
fileManager.copyFileToWorkspace(
input.filePath,
id,
@@ -33,53 +28,18 @@ export class FileCreateMutationHandler
input.userId,
);
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.File);
- attributesMap.set('parentId', input.parentId);
- attributesMap.set('name', metadata.name);
- attributesMap.set('fileName', metadata.name);
- attributesMap.set('extension', metadata.extension);
- attributesMap.set('size', metadata.size);
- attributesMap.set('mimeType', metadata.mimeType);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
+ const attributes: FileAttributes = {
+ type: 'file',
+ parentId: input.parentId,
+ name: metadata.name,
+ fileName: metadata.name,
+ extension: metadata.extension,
+ size: metadata.size,
+ mimeType: metadata.mimeType,
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
+ await nodeManager.createNode(trx, input.userId, id, attributes);
await trx
.insertInto('uploads')
diff --git a/desktop/src/main/handlers/mutations/folder-create.ts b/desktop/src/main/handlers/mutations/folder-create.ts
index 77c0860b..0fcae96c 100644
--- a/desktop/src/main/handlers/mutations/folder-create.ts
+++ b/desktop/src/main/handlers/mutations/folder-create.ts
@@ -1,13 +1,9 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { FolderCreateMutationInput } from '@/operations/mutations/folder-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { FolderAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
+import { databaseManager } from '@/main/data/database-manager';
export class FolderCreateMutationHandler
implements MutationHandler<FolderCreateMutationInput>
@@ -19,72 +15,17 @@ export class FolderCreateMutationHandler
input.userId,
);
- let index: string | undefined = undefined;
- if (input.generateIndex) {
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where('parent_id', '=', input.parentId)
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- index = generateNodeIndex(maxIndex, null);
- }
+ const attributes: FolderAttributes = {
+ type: 'folder',
+ parentId: input.parentId,
+ name: input.name,
+ collaborators: {},
+ };
const id = generateId(IdType.Folder);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Folder);
- attributesMap.set('parentId', input.parentId);
- attributesMap.set('index', index);
- attributesMap.set('name', input.name);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
+ await nodeManager.createNode(trx, input.userId, id, attributes);
});
return {
diff --git a/desktop/src/main/handlers/mutations/index.ts b/desktop/src/main/handlers/mutations/index.ts
index 9a664a6c..66c70d2e 100644
--- a/desktop/src/main/handlers/mutations/index.ts
+++ b/desktop/src/main/handlers/mutations/index.ts
@@ -1,11 +1,9 @@
import { MutationHandler, MutationMap } from '@/operations/mutations';
import { EmailLoginMutationHandler } from '@/main/handlers/mutations/email-login';
import { EmailRegisterMutationHandler } from '@/main/handlers/mutations/email-register';
-import { BoardViewCreateMutationHandler } from '@/main/handlers/mutations/board-view-create';
-import { CalendarViewCreateMutationHandler } from '@/main/handlers/mutations/calendar-view-create';
+import { ViewCreateMutationHandler } from '@/main/handlers/mutations/view-create';
import { ChannelCreateMutationHandler } from '@/main/handlers/mutations/channel-create';
import { ChatCreateMutationHandler } from '@/main/handlers/mutations/chat-create';
-import { TableViewCreateMutationHandler } from '@/main/handlers/mutations/table-view-create';
import { DatabaseCreateMutationHandler } from '@/main/handlers/mutations/database-create';
import { FieldCreateMutationHandler } from '@/main/handlers/mutations/field-create';
import { MessageCreateMutationHandler } from '@/main/handlers/mutations/message-create';
@@ -38,6 +36,8 @@ import { SpaceUpdateMutationHandler } from '@/main/handlers/mutations/space-upda
import { AccountUpdateMutationHandler } from '@/main/handlers/mutations/account-update';
import { ServerUserNodeSyncMutationHandler } from '@/main/handlers/mutations/server-user-node-sync';
import { MarkNodeAsSeenMutationHandler } from '@/main/handlers/mutations/mark-node-as-seen';
+import { ViewUpdateMutationHandler } from '@/main/handlers/mutations/view-update';
+import { ViewDeleteMutationHandler } from '@/main/handlers/mutations/view-delete';
type MutationHandlerMap = {
[K in keyof MutationMap]: MutationHandler<MutationMap[K]['input']>;
@@ -46,11 +46,9 @@ type MutationHandlerMap = {
export const mutationHandlerMap: MutationHandlerMap = {
email_login: new EmailLoginMutationHandler(),
email_register: new EmailRegisterMutationHandler(),
- board_view_create: new BoardViewCreateMutationHandler(),
- calendar_view_create: new CalendarViewCreateMutationHandler(),
+ view_create: new ViewCreateMutationHandler(),
channel_create: new ChannelCreateMutationHandler(),
chat_create: new ChatCreateMutationHandler(),
- table_view_create: new TableViewCreateMutationHandler(),
database_create: new DatabaseCreateMutationHandler(),
field_create: new FieldCreateMutationHandler(),
message_create: new MessageCreateMutationHandler(),
@@ -83,4 +81,6 @@ export const mutationHandlerMap: MutationHandlerMap = {
account_update: new AccountUpdateMutationHandler(),
server_user_node_sync: new ServerUserNodeSyncMutationHandler(),
mark_node_as_seen: new MarkNodeAsSeenMutationHandler(),
+ view_update: new ViewUpdateMutationHandler(),
+ view_delete: new ViewDeleteMutationHandler(),
};
diff --git a/desktop/src/main/handlers/mutations/mark-node-as-seen.ts b/desktop/src/main/handlers/mutations/mark-node-as-seen.ts
index 398e722a..17a3457b 100644
--- a/desktop/src/main/handlers/mutations/mark-node-as-seen.ts
+++ b/desktop/src/main/handlers/mutations/mark-node-as-seen.ts
@@ -42,6 +42,7 @@ export class MarkNodeAsSeenMutationHandler
.values({
data: JSON.stringify(changeData),
created_at: new Date().toISOString(),
+ retry_count: 0,
})
.execute();
});
diff --git a/desktop/src/main/handlers/mutations/message-create.ts b/desktop/src/main/handlers/mutations/message-create.ts
index 23647fa5..ea8329bf 100644
--- a/desktop/src/main/handlers/mutations/message-create.ts
+++ b/desktop/src/main/handlers/mutations/message-create.ts
@@ -1,6 +1,6 @@
import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
-import { EditorNodeTypes, NodeRole, NodeTypes } from '@/lib/constants';
+import { EditorNodeTypes, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
import {
MutationChange,
@@ -8,16 +8,12 @@ import {
MutationResult,
} from '@/operations/mutations';
import { MessageCreateMutationInput } from '@/operations/mutations/message-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
-import { applyChangeToAttributesMap, mapContentsToBlocks } from '@/lib/editor';
+import { mapContentsToBlocks } from '@/lib/editor';
import { fileManager } from '@/main/file-manager';
-import {
- CreateChange,
- CreateDownload,
- CreateNode,
- CreateUpload,
-} from '@/main/data/workspace/schema';
+import { CreateDownload, CreateUpload } from '@/main/data/workspace/schema';
+import { LocalNodeAttributes } from '@/types/nodes';
+import { Block, FileAttributes, MessageAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class MessageCreateMutationHandler
implements MutationHandler<MessageCreateMutationInput>
@@ -29,31 +25,28 @@ export class MessageCreateMutationHandler
input.userId,
);
- const nodesToCreate: CreateNode[] = [];
+ const nodeAttributes: LocalNodeAttributes[] = [];
const downloadsToCreate: CreateDownload[] = [];
const uploadsToCreate: CreateUpload[] = [];
- const changesToCreate: CreateChange[] = [];
const messageId = generateId(IdType.Message);
- const messageVersionId = generateId(IdType.Version);
const createdAt = new Date().toISOString();
const blocks = mapContentsToBlocks(
messageId,
- input.content.content,
+ input.content.content ?? [],
new Map(),
);
// check if there are nested nodes (files, pages, folders etc.)
for (const block of blocks) {
if (block.type === EditorNodeTypes.FilePlaceholder) {
- const path = block.attrs.path;
+ const path = block.attrs?.path;
const metadata = fileManager.getFileMetadata(path);
if (!metadata) {
throw new Error('Invalid file');
}
const fileId = generateId(IdType.File);
- const fileVersionId = generateId(IdType.Version);
block.id = fileId;
block.type = NodeTypes.File;
@@ -81,17 +74,17 @@ export class MessageCreateMutationHandler
fileAttributesMap.set('mimeType', metadata.mimeType);
});
- const fileAttributes = JSON.stringify(fileAttributesMap.toJSON());
- const encodedFileState = fromUint8Array(Y.encodeStateAsUpdate(fileDoc));
+ const fileAttributes: FileAttributes = {
+ type: 'file',
+ parentId: messageId,
+ name: metadata.name,
+ fileName: metadata.name,
+ mimeType: metadata.mimeType,
+ size: metadata.size,
+ extension: metadata.extension,
+ };
- nodesToCreate.push({
- id: fileId,
- attributes: fileAttributes,
- state: encodedFileState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: fileVersionId,
- });
+ nodeAttributes.push(fileAttributes);
downloadsToCreate.push({
node_id: fileId,
@@ -109,50 +102,30 @@ export class MessageCreateMutationHandler
}
}
- const messageDoc = new Y.Doc({
- guid: messageId,
- });
-
- const messageAttributesMap = messageDoc.getMap('attributes');
- messageDoc.transact(() => {
- messageAttributesMap.set('type', NodeTypes.Message);
- messageAttributesMap.set('parentId', input.conversationId);
- applyChangeToAttributesMap(messageAttributesMap, blocks);
- });
-
- const messageAttributes = JSON.stringify(messageAttributesMap.toJSON());
- const encodedMessageState = fromUint8Array(
- Y.encodeStateAsUpdate(messageDoc),
- );
-
- nodesToCreate.unshift({
- id: messageId,
- attributes: messageAttributes,
- state: encodedMessageState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: messageVersionId,
- });
+ const messageAttributes: MessageAttributes = {
+ type: 'message',
+ parentId: input.conversationId,
+ content: blocks.reduce(
+ (acc, block) => {
+ acc[block.id] = block;
+ return acc;
+ },
+ {} as Record<string, Block>,
+ ),
+ reactions: {},
+ };
- for (const nodeToCreate of nodesToCreate) {
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: nodeToCreate.id,
- state: nodeToCreate.state,
- createdAt: nodeToCreate.created_at,
- createdBy: nodeToCreate.created_by,
- versionId: nodeToCreate.version_id,
- };
-
- changesToCreate.push({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- });
- }
+ nodeAttributes.unshift(messageAttributes);
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx.insertInto('nodes').values(nodesToCreate).execute();
- await trx.insertInto('changes').values(changesToCreate).execute();
+ for (const nodeAttribute of nodeAttributes) {
+ await nodeManager.createNode(
+ trx,
+ input.userId,
+ messageId,
+ nodeAttribute,
+ );
+ }
if (uploadsToCreate.length > 0) {
await trx.insertInto('uploads').values(uploadsToCreate).execute();
diff --git a/desktop/src/main/handlers/mutations/node-attribute-delete.ts b/desktop/src/main/handlers/mutations/node-attribute-delete.ts
index 0387e2c4..8da46114 100644
--- a/desktop/src/main/handlers/mutations/node-attribute-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-attribute-delete.ts
@@ -1,6 +1,7 @@
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeAttributeDeleteMutationInput } from '@/operations/mutations/node-attribute-delete';
-import { updateNodeAtomically } from '@/main/utils';
+import { nodeManager } from '@/main/node-manager';
+import { unset } from 'lodash';
export class NodeAttributeDeleteMutationHandler
implements MutationHandler<NodeAttributeDeleteMutationInput>
@@ -8,25 +9,10 @@ export class NodeAttributeDeleteMutationHandler
async handleMutation(
input: NodeAttributeDeleteMutationInput,
): Promise<MutationResult<NodeAttributeDeleteMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- if (!attributesMap.has(input.attribute)) {
- return;
- }
-
- attributesMap.delete(input.attribute);
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ unset(attributes, input.path);
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/node-attribute-set.ts b/desktop/src/main/handlers/mutations/node-attribute-set.ts
index 58830c04..af09e2f0 100644
--- a/desktop/src/main/handlers/mutations/node-attribute-set.ts
+++ b/desktop/src/main/handlers/mutations/node-attribute-set.ts
@@ -1,6 +1,7 @@
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeAttributeSetMutationInput } from '@/operations/mutations/node-attribute-set';
-import { updateNodeAtomically } from '@/main/utils';
+import { nodeManager } from '@/main/node-manager';
+import { set } from 'lodash';
export class NodeAttributeSetMutationHandler
implements MutationHandler<NodeAttributeSetMutationInput>
@@ -8,21 +9,10 @@ export class NodeAttributeSetMutationHandler
async handleMutation(
input: NodeAttributeSetMutationInput,
): Promise<MutationResult<NodeAttributeSetMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- attributesMap.set(input.attribute, input.value);
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ set(attributes, input.path, input.value);
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/node-collaborator-create.ts b/desktop/src/main/handlers/mutations/node-collaborator-create.ts
index 3a55f8e4..4243247c 100644
--- a/desktop/src/main/handlers/mutations/node-collaborator-create.ts
+++ b/desktop/src/main/handlers/mutations/node-collaborator-create.ts
@@ -1,7 +1,7 @@
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeCollaboratorCreateMutationInput } from '@/operations/mutations/node-collaborator-create';
-import * as Y from 'yjs';
-import { updateNodeAtomically } from '@/main/utils';
+import { nodeManager } from '@/main/node-manager';
+import { set } from 'lodash';
export class NodeCollaboratorCreateMutationHandler
implements MutationHandler<NodeCollaboratorCreateMutationInput>
@@ -9,30 +9,12 @@ export class NodeCollaboratorCreateMutationHandler
async handleMutation(
input: NodeCollaboratorCreateMutationInput,
): Promise<MutationResult<NodeCollaboratorCreateMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- if (!attributesMap.has('collaborators')) {
- attributesMap.set('collaborators', new Y.Map());
- }
-
- const collaboratorsMap = attributesMap.get(
- 'collaborators',
- ) as Y.Map<any>;
- input.collaboratorIds.forEach((collaboratorId) => {
- collaboratorsMap.set(collaboratorId, input.role);
- });
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ for (const collaboratorId of input.collaboratorIds) {
+ set(attributes, `collaborators.${collaboratorId}`, input.role);
+ }
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/node-collaborator-delete.ts b/desktop/src/main/handlers/mutations/node-collaborator-delete.ts
index 6235e7b0..8339ed8f 100644
--- a/desktop/src/main/handlers/mutations/node-collaborator-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-collaborator-delete.ts
@@ -1,7 +1,7 @@
-import { updateNodeAtomically } from '@/main/utils';
+import { nodeManager } from '@/main/node-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeCollaboratorDeleteMutationInput } from '@/operations/mutations/node-collaborator-delete';
-import * as Y from 'yjs';
+import { unset } from 'lodash';
export class NodeCollaboratorDeleteMutationHandler
implements MutationHandler<NodeCollaboratorDeleteMutationInput>
@@ -9,24 +9,10 @@ export class NodeCollaboratorDeleteMutationHandler
async handleMutation(
input: NodeCollaboratorDeleteMutationInput,
): Promise<MutationResult<NodeCollaboratorDeleteMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- const collaboratorsMap = attributesMap.get(
- 'collaborators',
- ) as Y.Map<any>;
- collaboratorsMap.delete(input.collaboratorId);
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ unset(attributes, `collaborators.${input.collaboratorId}`);
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/node-collaborator-update.ts b/desktop/src/main/handlers/mutations/node-collaborator-update.ts
index c839a935..2b8777f5 100644
--- a/desktop/src/main/handlers/mutations/node-collaborator-update.ts
+++ b/desktop/src/main/handlers/mutations/node-collaborator-update.ts
@@ -1,7 +1,7 @@
+import { nodeManager } from '@/main/node-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeCollaboratorUpdateMutationInput } from '@/operations/mutations/node-collaborator-update';
-import * as Y from 'yjs';
-import { updateNodeAtomically } from '@/main/utils';
+import { set } from 'lodash';
export class NodeCollaboratorUpdateMutationHandler
implements MutationHandler<NodeCollaboratorUpdateMutationInput>
@@ -9,28 +9,10 @@ export class NodeCollaboratorUpdateMutationHandler
async handleMutation(
input: NodeCollaboratorUpdateMutationInput,
): Promise<MutationResult<NodeCollaboratorUpdateMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- if (!attributesMap.has('collaborators')) {
- attributesMap.set('collaborators', new Y.Map());
- }
-
- const collaboratorsMap = attributesMap.get(
- 'collaborators',
- ) as Y.Map<any>;
- collaboratorsMap.set(input.collaboratorId, input.role);
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ set(attributes, `collaborators.${input.collaboratorId}`, input.role);
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/node-delete.ts b/desktop/src/main/handlers/mutations/node-delete.ts
index 7072bfd6..64e0345a 100644
--- a/desktop/src/main/handlers/mutations/node-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-delete.ts
@@ -67,6 +67,7 @@ export class NodeDeleteMutationHandler
.values({
data: JSON.stringify(changeData),
created_at: new Date().toISOString(),
+ retry_count: 0,
})
.execute();
});
diff --git a/desktop/src/main/handlers/mutations/node-reaction-create.ts b/desktop/src/main/handlers/mutations/node-reaction-create.ts
index c1ade04b..60d8fba0 100644
--- a/desktop/src/main/handlers/mutations/node-reaction-create.ts
+++ b/desktop/src/main/handlers/mutations/node-reaction-create.ts
@@ -1,7 +1,6 @@
-import { updateNodeAtomically } from '@/main/utils';
+import { nodeManager } from '@/main/node-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeReactionCreateMutationInput } from '@/operations/mutations/node-reaction-create';
-import * as Y from 'yjs';
export class NodeReactionCreateMutationHandler
implements MutationHandler<NodeReactionCreateMutationInput>
@@ -9,37 +8,23 @@ export class NodeReactionCreateMutationHandler
async handleMutation(
input: NodeReactionCreateMutationInput,
): Promise<MutationResult<NodeReactionCreateMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- if (!attributesMap.has('reactions')) {
- attributesMap.set('reactions', new Y.Map());
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ if (attributes.type !== 'message') {
+ throw new Error('Node is not a message');
+ }
- const reactionsMap = attributesMap.get('reactions') as Y.Map<any>;
- if (!reactionsMap.has(input.reaction)) {
- reactionsMap.set(input.reaction, new Y.Array());
- }
+ const reactions = attributes.reactions;
+ if (!reactions[input.reaction]) {
+ reactions[input.reaction] = [];
+ }
- const reactionArray = reactionsMap.get(
- input.reaction,
- ) as Y.Array<string>;
- if (reactionArray.toArray().includes(input.userId)) {
- return;
- }
+ if (reactions[input.reaction].includes(input.userId)) {
+ return attributes;
+ }
- reactionArray.push([input.userId]);
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ reactions[input.reaction].push(input.userId);
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/node-reaction-delete.ts b/desktop/src/main/handlers/mutations/node-reaction-delete.ts
index ce9a380e..43a5f014 100644
--- a/desktop/src/main/handlers/mutations/node-reaction-delete.ts
+++ b/desktop/src/main/handlers/mutations/node-reaction-delete.ts
@@ -1,7 +1,6 @@
+import { nodeManager } from '@/main/node-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { NodeReactionDeleteMutationInput } from '@/operations/mutations/node-reaction-delete';
-import * as Y from 'yjs';
-import { updateNodeAtomically } from '@/main/utils';
export class NodeReactionDeleteMutationHandler
implements MutationHandler<NodeReactionDeleteMutationInput>
@@ -9,39 +8,26 @@ export class NodeReactionDeleteMutationHandler
async handleMutation(
input: NodeReactionDeleteMutationInput,
): Promise<MutationResult<NodeReactionDeleteMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.nodeId,
- (attributesMap) => {
- if (!attributesMap.has('reactions')) {
- attributesMap.set('reactions', new Y.Map());
- }
+ await nodeManager.updateNode(input.userId, input.nodeId, (attributes) => {
+ if (attributes.type !== 'message') {
+ throw new Error('Node is not a message');
+ }
- const reactionsMap = attributesMap.get('reactions') as Y.Map<any>;
- if (!reactionsMap.has(input.reaction)) {
- reactionsMap.set(input.reaction, new Y.Array());
- }
+ const reactions = attributes.reactions;
+ if (!reactions[input.reaction]) {
+ return attributes;
+ }
- const reactionArray = reactionsMap.get(
- input.reaction,
- ) as Y.Array<string>;
+ const reactionArray = reactions[input.reaction];
- const index = reactionArray.toArray().indexOf(input.userId);
- if (index === -1) {
- return;
- }
+ const index = reactionArray.indexOf(input.userId);
+ if (index === -1) {
+ return attributes;
+ }
- reactionArray.delete(index);
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ reactionArray.splice(index, 1);
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/page-create.ts b/desktop/src/main/handlers/mutations/page-create.ts
index 4f24fa21..8fdb39c3 100644
--- a/desktop/src/main/handlers/mutations/page-create.ts
+++ b/desktop/src/main/handlers/mutations/page-create.ts
@@ -1,13 +1,9 @@
-import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { PageCreateMutationInput } from '@/operations/mutations/page-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { PageAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class PageCreateMutationHandler
implements MutationHandler<PageCreateMutationInput>
@@ -19,72 +15,16 @@ export class PageCreateMutationHandler
input.userId,
);
- let index: string | undefined = undefined;
- if (input.generateIndex) {
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where('parent_id', '=', input.parentId)
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- index = generateNodeIndex(maxIndex, null);
- }
-
const id = generateId(IdType.Page);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Page);
- attributesMap.set('parentId', input.parentId);
- attributesMap.set('index', index);
- attributesMap.set('name', input.name);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
+ const attributes: PageAttributes = {
+ type: 'page',
+ parentId: input.parentId,
+ name: input.name,
+ content: {},
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
+ await nodeManager.createNode(trx, input.userId, id, attributes);
});
return {
diff --git a/desktop/src/main/handlers/mutations/record-create.ts b/desktop/src/main/handlers/mutations/record-create.ts
index 4f53db06..b1f30800 100644
--- a/desktop/src/main/handlers/mutations/record-create.ts
+++ b/desktop/src/main/handlers/mutations/record-create.ts
@@ -1,12 +1,9 @@
-import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { RecordCreateMutationInput } from '@/operations/mutations/record-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { RecordAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class RecordCreateMutationHandler
implements MutationHandler<RecordCreateMutationInput>
@@ -18,68 +15,18 @@ export class RecordCreateMutationHandler
input.userId,
);
- const lastChild = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', '=', NodeTypes.Record),
- ]),
- )
- .orderBy('index', 'desc')
- .limit(1)
- .executeTakeFirst();
-
- const maxIndex = lastChild?.index ? lastChild.index : null;
-
const id = generateId(IdType.Record);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Record);
- attributesMap.set('parentId', input.databaseId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
+ const attributes: RecordAttributes = {
+ type: 'record',
+ parentId: input.databaseId,
+ databaseId: input.databaseId,
+ name: input.name ?? '',
+ fields: {},
+ content: {},
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
+ await nodeManager.createNode(trx, input.userId, id, attributes);
});
return {
diff --git a/desktop/src/main/handlers/mutations/select-option-create.ts b/desktop/src/main/handlers/mutations/select-option-create.ts
index b848796b..82df1929 100644
--- a/desktop/src/main/handlers/mutations/select-option-create.ts
+++ b/desktop/src/main/handlers/mutations/select-option-create.ts
@@ -1,12 +1,9 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { SelectOptionCreateMutationInput } from '@/operations/mutations/select-option-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { compareString } from '@/lib/utils';
+import { nodeManager } from '@/main/node-manager';
export class SelectOptionCreateMutationHandler
implements MutationHandler<SelectOptionCreateMutationInput>
@@ -14,74 +11,45 @@ export class SelectOptionCreateMutationHandler
async handleMutation(
input: SelectOptionCreateMutationInput,
): Promise<MutationResult<SelectOptionCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ const id = generateId(IdType.SelectOption);
+ await nodeManager.updateNode(
input.userId,
- );
-
- const lastChild = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.fieldId),
- eb('type', '=', NodeTypes.SelectOption),
- ]),
- )
- .orderBy('index', 'desc')
- .limit(1)
- .executeTakeFirst();
+ input.databaseId,
+ (attributes) => {
+ if (attributes.type !== 'database') {
+ throw new Error('Node is not a database');
+ }
- const maxIndex = lastChild?.index ? lastChild.index : null;
- const id = generateId(IdType.SelectOption);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
+ const fields = attributes.fields;
+ if (!fields[input.fieldId]) {
+ throw new Error('Field not found');
+ }
- const doc = new Y.Doc({
- guid: id,
- });
+ const field = fields[input.fieldId];
+ if (field.type !== 'select' && field.type !== 'multiSelect') {
+ throw new Error('Field is not a select');
+ }
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.SelectOption);
- attributesMap.set('parentId', input.fieldId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- attributesMap.set('color', input.color);
- });
+ if (!field.options) {
+ field.options = {};
+ }
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+ const maxIndex = Object.values(field.options)
+ .map((selectOption) => selectOption.index)
+ .sort((a, b) => -compareString(a, b))[0];
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
+ const index = generateNodeIndex(maxIndex, null);
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
+ field.options[id] = {
+ name: input.name,
id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
+ color: input.color,
+ index: index,
+ };
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
- });
+ return attributes;
+ },
+ );
return {
output: {
@@ -93,11 +61,6 @@ export class SelectOptionCreateMutationHandler
table: 'nodes',
userId: input.userId,
},
- {
- type: 'workspace',
- table: 'changes',
- userId: input.userId,
- },
],
};
}
diff --git a/desktop/src/main/handlers/mutations/server-node-sync.ts b/desktop/src/main/handlers/mutations/server-node-sync.ts
index 48046478..c8afb04f 100644
--- a/desktop/src/main/handlers/mutations/server-node-sync.ts
+++ b/desktop/src/main/handlers/mutations/server-node-sync.ts
@@ -23,10 +23,6 @@ export class ServerNodeSyncMutationHandler
)
.executeTakeFirst();
- const userId = workspace.user_id;
- const workspaceDatabase =
- await databaseManager.getWorkspaceDatabase(userId);
-
if (!workspace) {
return {
output: {
@@ -35,6 +31,10 @@ export class ServerNodeSyncMutationHandler
};
}
+ const userId = workspace.user_id;
+ const workspaceDatabase =
+ await databaseManager.getWorkspaceDatabase(userId);
+
let count = 0;
while (count++ < 10) {
const existingNode = await workspaceDatabase
diff --git a/desktop/src/main/handlers/mutations/space-create.ts b/desktop/src/main/handlers/mutations/space-create.ts
index d718d6d9..7f5ccf33 100644
--- a/desktop/src/main/handlers/mutations/space-create.ts
+++ b/desktop/src/main/handlers/mutations/space-create.ts
@@ -3,10 +3,9 @@ import { generateId, IdType } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { SpaceCreateMutationInput } from '@/operations/mutations/space-create';
-import * as Y from 'yjs';
-import { NodeRole, NodeTypes } from '@/lib/constants';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
+import { NodeRole } from '@/lib/constants';
+import { ChannelAttributes, PageAttributes, SpaceAttributes } from '@/registry';
+import { nodeManager } from '@/main/node-manager';
export class SpaceCreateMutationHandler
implements MutationHandler<SpaceCreateMutationInput>
@@ -18,143 +17,44 @@ export class SpaceCreateMutationHandler
input.userId,
);
- const createdAt = new Date().toISOString();
-
const spaceId = generateId(IdType.Space);
- const spaceVersionId = generateId(IdType.Version);
- const spaceDoc = new Y.Doc({
- guid: spaceId,
- });
-
- const spaceAttributesMap = spaceDoc.getMap('attributes');
- spaceDoc.transact(() => {
- spaceAttributesMap.set('type', NodeTypes.Space);
- spaceAttributesMap.set('name', input.name);
-
- if (input.description) {
- spaceAttributesMap.set('description', input.description);
- }
-
- const collaboratorsMap = new Y.Map<string>();
- spaceAttributesMap.set('collaborators', collaboratorsMap);
-
- collaboratorsMap.set(input.userId, NodeRole.Editor);
- });
-
- const spaceAttributes = JSON.stringify(spaceAttributesMap.toJSON());
- const spaceState = fromUint8Array(Y.encodeStateAsUpdate(spaceDoc));
-
- const spaceChangeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: spaceId,
- state: spaceState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: spaceVersionId,
+ const spaceAttributes: SpaceAttributes = {
+ type: 'space',
+ name: input.name,
+ collaborators: {
+ [input.userId]: NodeRole.Admin,
+ },
+ parentId: input.workspaceId,
+ description: input.description,
+ avatar: null,
};
const pageId = generateId(IdType.Page);
- const pageIndex = generateNodeIndex(null, null);
- const pageVersionId = generateId(IdType.Version);
- const pageDoc = new Y.Doc({
- guid: pageId,
- });
-
- const pageAttributesMap = pageDoc.getMap('attributes');
- pageDoc.transact(() => {
- pageAttributesMap.set('type', NodeTypes.Page);
- pageAttributesMap.set('name', 'Home');
- pageAttributesMap.set('parentId', spaceId);
- pageAttributesMap.set('index', pageIndex);
- });
-
- const pageAttributes = JSON.stringify(pageAttributesMap.toJSON());
- const pageState = fromUint8Array(Y.encodeStateAsUpdate(pageDoc));
-
- const pageChangeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: pageId,
- state: pageState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: pageVersionId,
+ const pageAttributes: PageAttributes = {
+ type: 'page',
+ name: 'Home',
+ parentId: spaceId,
+ content: {},
+ collaborators: {},
};
const channelId = generateId(IdType.Channel);
- const channelIndex = generateNodeIndex(pageIndex, null);
- const channelVersionId = generateId(IdType.Version);
- const channelDoc = new Y.Doc({
- guid: channelId,
- });
-
- const channelAttributesMap = channelDoc.getMap('attributes');
- channelDoc.transact(() => {
- channelAttributesMap.set('type', NodeTypes.Channel);
- channelAttributesMap.set('name', 'Discussions');
- channelAttributesMap.set('parentId', spaceId);
- channelAttributesMap.set('index', channelIndex);
- });
-
- const channelAttributes = JSON.stringify(channelAttributesMap.toJSON());
- const channelState = fromUint8Array(Y.encodeStateAsUpdate(channelDoc));
-
- const channelChangeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: channelId,
- state: channelState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: channelVersionId,
+ const channelAttributes: ChannelAttributes = {
+ type: 'channel',
+ name: 'Discussions',
+ parentId: spaceId,
+ index: generateNodeIndex(null, null),
};
await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values([
- {
- id: spaceId,
- attributes: spaceAttributes,
- state: spaceState,
- created_at: new Date().toISOString(),
- created_by: input.userId,
- version_id: spaceVersionId,
- },
- {
- id: pageId,
- attributes: pageAttributes,
- state: pageState,
- created_at: new Date().toISOString(),
- created_by: input.userId,
- version_id: pageVersionId,
- },
- {
- id: channelId,
- attributes: channelAttributes,
- state: channelState,
- created_at: new Date().toISOString(),
- created_by: input.userId,
- version_id: channelVersionId,
- },
- ])
- .execute();
-
- await trx
- .insertInto('changes')
- .values([
- {
- data: JSON.stringify(spaceChangeData),
- created_at: createdAt,
- },
- {
- data: JSON.stringify(pageChangeData),
- created_at: createdAt,
- },
- {
- data: JSON.stringify(channelChangeData),
- created_at: createdAt,
- },
- ])
- .execute();
+ await nodeManager.createNode(trx, input.userId, spaceId, spaceAttributes);
+ await nodeManager.createNode(trx, input.userId, pageId, pageAttributes);
+ await nodeManager.createNode(
+ trx,
+ input.userId,
+ channelId,
+ channelAttributes,
+ );
});
return {
diff --git a/desktop/src/main/handlers/mutations/space-update.ts b/desktop/src/main/handlers/mutations/space-update.ts
index 7901c87e..fb4bc249 100644
--- a/desktop/src/main/handlers/mutations/space-update.ts
+++ b/desktop/src/main/handlers/mutations/space-update.ts
@@ -1,6 +1,6 @@
import { MutationHandler, MutationResult } from '@/operations/mutations';
import { SpaceUpdateMutationInput } from '@/operations/mutations/space-update';
-import { updateNodeAtomically } from '@/main/utils';
+import { nodeManager } from '@/main/node-manager';
export class SpaceUpdateMutationHandler
implements MutationHandler<SpaceUpdateMutationInput>
@@ -8,31 +8,17 @@ export class SpaceUpdateMutationHandler
async handleMutation(
input: SpaceUpdateMutationInput,
): Promise<MutationResult<SpaceUpdateMutationInput>> {
- const result = await updateNodeAtomically(
- input.userId,
- input.id,
- (attributesMap) => {
- if (input.name !== attributesMap.get('name')) {
- attributesMap.set('name', input.name);
- }
+ await nodeManager.updateNode(input.userId, input.id, (attributes) => {
+ if (attributes.type !== 'space') {
+ throw new Error('Node is not a space');
+ }
- if (input.description !== attributesMap.get('description')) {
- attributesMap.set('description', input.description);
- }
+ attributes.name = input.name;
+ attributes.description = input.description;
+ attributes.avatar = input.avatar;
- if (input.avatar !== attributesMap.get('avatar')) {
- attributesMap.set('avatar', input.avatar);
- }
- },
- );
-
- if (!result) {
- return {
- output: {
- success: false,
- },
- };
- }
+ return attributes;
+ });
return {
output: {
diff --git a/desktop/src/main/handlers/mutations/table-view-create.ts b/desktop/src/main/handlers/mutations/table-view-create.ts
deleted file mode 100644
index e1f54b72..00000000
--- a/desktop/src/main/handlers/mutations/table-view-create.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import * as Y from 'yjs';
-import { databaseManager } from '@/main/data/database-manager';
-import { NodeRole, NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { generateId, IdType } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { MutationHandler, MutationResult } from '@/operations/mutations';
-import { TableViewCreateMutationInput } from '@/operations/mutations/table-view-create';
-import { fromUint8Array } from 'js-base64';
-import { LocalCreateNodeChangeData } from '@/types/sync';
-
-export class TableViewCreateMutationHandler
- implements MutationHandler<TableViewCreateMutationInput>
-{
- async handleMutation(
- input: TableViewCreateMutationInput,
- ): Promise<MutationResult<TableViewCreateMutationInput>> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
- input.userId,
- );
-
- const siblings = await workspaceDatabase
- .selectFrom('nodes')
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .selectAll()
- .execute();
-
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const id = generateId(IdType.TableView);
- const versionId = generateId(IdType.Version);
- const createdAt = new Date().toISOString();
-
- const doc = new Y.Doc({
- guid: id,
- });
-
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.TableView);
- attributesMap.set('parentId', input.databaseId);
- attributesMap.set('index', generateNodeIndex(maxIndex, null));
- attributesMap.set('name', input.name);
- });
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
-
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
- created_at: createdAt,
- created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: createdAt,
- })
- .execute();
- });
-
- return {
- output: {
- id: id,
- },
- changes: [
- {
- type: 'workspace',
- table: 'nodes',
- userId: input.userId,
- },
- {
- type: 'workspace',
- table: 'changes',
- userId: input.userId,
- },
- ],
- };
- }
-}
diff --git a/desktop/src/main/handlers/mutations/view-create.ts b/desktop/src/main/handlers/mutations/view-create.ts
new file mode 100644
index 00000000..54b64e37
--- /dev/null
+++ b/desktop/src/main/handlers/mutations/view-create.ts
@@ -0,0 +1,56 @@
+import { generateId, IdType } from '@/lib/id';
+import { MutationHandler, MutationResult } from '@/operations/mutations';
+import { ViewCreateMutationInput } from '@/operations/mutations/view-create';
+import { compareString } from '@/lib/utils';
+import { generateNodeIndex } from '@/lib/nodes';
+import { nodeManager } from '@/main/node-manager';
+
+export class ViewCreateMutationHandler
+ implements MutationHandler<ViewCreateMutationInput>
+{
+ async handleMutation(
+ input: ViewCreateMutationInput,
+ ): Promise<MutationResult<ViewCreateMutationInput>> {
+ const id = generateId(IdType.View);
+ await nodeManager.updateNode(
+ input.userId,
+ input.databaseId,
+ (attributes) => {
+ if (attributes.type !== 'database') {
+ throw new Error('Node is not a database');
+ }
+
+ const maxIndex = Object.values(attributes.views)
+ .map((view) => view.index)
+ .sort((a, b) => -compareString(a, b))[0];
+
+ attributes.views[id] = {
+ id: id,
+ type: input.viewType,
+ name: input.name,
+ avatar: null,
+ fields: {},
+ filters: {},
+ sorts: {},
+ groupBy: input.groupBy,
+ index: generateNodeIndex(maxIndex, null),
+ };
+
+ return attributes;
+ },
+ );
+
+ return {
+ output: {
+ id: id,
+ },
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/main/handlers/mutations/view-delete.ts b/desktop/src/main/handlers/mutations/view-delete.ts
new file mode 100644
index 00000000..d197b62b
--- /dev/null
+++ b/desktop/src/main/handlers/mutations/view-delete.ts
@@ -0,0 +1,37 @@
+import { MutationHandler, MutationResult } from '@/operations/mutations';
+import { nodeManager } from '@/main/node-manager';
+import { ViewDeleteMutationInput } from '@/operations/mutations/view-delete';
+
+export class ViewDeleteMutationHandler
+ implements MutationHandler<ViewDeleteMutationInput>
+{
+ async handleMutation(
+ input: ViewDeleteMutationInput,
+ ): Promise<MutationResult<ViewDeleteMutationInput>> {
+ await nodeManager.updateNode(
+ input.userId,
+ input.databaseId,
+ (attributes) => {
+ if (attributes.type !== 'database') {
+ throw new Error('Node is not a database');
+ }
+
+ delete attributes.views[input.viewId];
+ return attributes;
+ },
+ );
+
+ return {
+ output: {
+ id: input.viewId,
+ },
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/main/handlers/mutations/view-update.ts b/desktop/src/main/handlers/mutations/view-update.ts
new file mode 100644
index 00000000..f7bfccf5
--- /dev/null
+++ b/desktop/src/main/handlers/mutations/view-update.ts
@@ -0,0 +1,37 @@
+import { MutationHandler, MutationResult } from '@/operations/mutations';
+import { nodeManager } from '@/main/node-manager';
+import { ViewUpdateMutationInput } from '@/operations/mutations/view-update';
+
+export class ViewUpdateMutationHandler
+ implements MutationHandler<ViewUpdateMutationInput>
+{
+ async handleMutation(
+ input: ViewUpdateMutationInput,
+ ): Promise<MutationResult<ViewUpdateMutationInput>> {
+ await nodeManager.updateNode(
+ input.userId,
+ input.databaseId,
+ (attributes) => {
+ if (attributes.type !== 'database') {
+ throw new Error('Node is not a database');
+ }
+
+ attributes.views[input.view.id] = input.view;
+ return attributes;
+ },
+ );
+
+ return {
+ output: {
+ id: input.view.id,
+ },
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/main/handlers/queries/breadcrumb-list.ts b/desktop/src/main/handlers/queries/breadcrumb-list.ts
index efde0b86..7cf54a62 100644
--- a/desktop/src/main/handlers/queries/breadcrumb-list.ts
+++ b/desktop/src/main/handlers/queries/breadcrumb-list.ts
@@ -94,10 +94,10 @@ export class BreadcrumbListQueryHandler
): BreadcrumbNode[] => {
const breadcrumbNodes: BreadcrumbNode[] = [];
- let currentId = nodeId;
+ let currentId: string | null = nodeId;
while (currentId !== null && currentId !== undefined) {
const row = rows.find((row) => row.id === currentId);
- if (row) {
+ if (row && row.parent_id) {
breadcrumbNodes.push(this.buildBreadcrumbNode(row));
currentId = row.parent_id;
} else {
@@ -110,8 +110,9 @@ export class BreadcrumbListQueryHandler
private buildBreadcrumbNode = (row: SelectNode): BreadcrumbNode => {
const node = mapNode(row);
- const name = node.attributes.name;
- const avatar = node.attributes.avatar;
+ const attributes = node.attributes as any;
+ const name = attributes.name;
+ const avatar = attributes.avatar;
return {
id: node.id,
diff --git a/desktop/src/main/handlers/queries/chat-get.ts b/desktop/src/main/handlers/queries/chat-get.ts
index 34c9a9ac..e7e7536f 100644
--- a/desktop/src/main/handlers/queries/chat-get.ts
+++ b/desktop/src/main/handlers/queries/chat-get.ts
@@ -52,6 +52,16 @@ export class ChatGetQueryHandler implements QueryHandler<ChatGetQueryInput> {
}
const chat = await this.fetchChat(input);
+ if (!chat) {
+ return {
+ hasChanges: true,
+ result: {
+ output: null,
+ state: {},
+ },
+ };
+ }
+
const collaborators = await this.fetchCollaborators(input, chat);
if (
@@ -88,7 +98,7 @@ export class ChatGetQueryHandler implements QueryHandler<ChatGetQueryInput> {
.selectAll()
.executeTakeFirst();
- return chat;
+ return chat ?? null;
}
private async fetchCollaborators(
@@ -137,6 +147,10 @@ export class ChatGetQueryHandler implements QueryHandler<ChatGetQueryInput> {
collaborators: SelectNode[],
): ChatNode | null => {
const collaborator = mapNode(collaborators[0]);
+ if (collaborator.attributes.type !== 'user') {
+ return null;
+ }
+
return {
id: chat.id,
name: collaborator.attributes.name ?? 'Unknown',
diff --git a/desktop/src/main/handlers/queries/database-get.ts b/desktop/src/main/handlers/queries/database-get.ts
deleted file mode 100644
index 2b525916..00000000
--- a/desktop/src/main/handlers/queries/database-get.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-import { DatabaseGetQueryInput } from '@/operations/queries/database-get';
-import { databaseManager } from '@/main/data/database-manager';
-import {
- ChangeCheckResult,
- QueryHandler,
- QueryResult,
-} from '@/operations/queries';
-import { sql } from 'kysely';
-import { SelectNode } from '@/main/data/workspace/schema';
-import { mapNode } from '@/lib/nodes';
-import { NodeTypes } from '@/lib/constants';
-import {
- DatabaseNode,
- FieldDataType,
- FieldNode,
- SelectOptionNode,
-} from '@/types/databases';
-import { LocalNode } from '@/types/nodes';
-import { isEqual } from 'lodash';
-import { MutationChange } from '@/operations/mutations';
-
-export class DatabaseGetQueryHandler
- implements QueryHandler<DatabaseGetQueryInput>
-{
- public async handleQuery(
- input: DatabaseGetQueryInput,
- ): Promise<QueryResult<DatabaseGetQueryInput>> {
- const rows = await this.fetchNodes(input);
- return {
- output: this.buildDatabaseNode(rows),
- state: {
- rows,
- },
- };
- }
-
- public async checkForChanges(
- changes: MutationChange[],
- input: DatabaseGetQueryInput,
- state: Record<string, any>,
- ): Promise<ChangeCheckResult<DatabaseGetQueryInput>> {
- if (
- !changes.some(
- (change) =>
- change.type === 'workspace' &&
- change.table === 'nodes' &&
- change.userId === input.userId,
- )
- ) {
- return {
- hasChanges: false,
- };
- }
-
- const rows = await this.fetchNodes(input);
- if (isEqual(rows, state.rows)) {
- return {
- hasChanges: false,
- };
- }
-
- return {
- hasChanges: true,
- result: {
- output: this.buildDatabaseNode(rows),
- state: {
- rows,
- },
- },
- };
- }
-
- private async fetchNodes(
- input: DatabaseGetQueryInput,
- ): Promise<SelectNode[]> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
- input.userId,
- );
-
- const query = sql<SelectNode>`
- WITH database_node AS (
- SELECT *
- FROM nodes
- WHERE id = ${input.databaseId}
- ),
- field_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${input.databaseId} AND type = ${NodeTypes.Field}
- ),
- select_option_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IN
- (
- SELECT id
- FROM field_nodes
- )
- AND type = ${NodeTypes.SelectOption}
- )
- SELECT * FROM database_node
- UNION ALL
- SELECT * FROM field_nodes
- UNION ALL
- SELECT * FROM select_option_nodes
- `.compile(workspaceDatabase);
-
- const result = await workspaceDatabase.executeQuery(query);
- return result.rows;
- }
-
- private buildDatabaseNode = (rows: SelectNode[]): DatabaseNode | null => {
- const nodes = rows.map((row) => mapNode(row));
-
- const databaseLocalNode = nodes.find(
- (node) => node.type === NodeTypes.Database,
- );
- if (!databaseLocalNode) {
- return null;
- }
-
- const name = databaseLocalNode.attributes.name;
- const fieldsNodes = nodes.filter((node) => node.type === NodeTypes.Field);
- const groupedSelectOptions = nodes
- .filter((node) => node.type === NodeTypes.SelectOption)
- .reduce(
- (acc, node) => {
- if (!acc[node.parentId]) {
- acc[node.parentId] = [];
- }
- acc[node.parentId].push(node);
- return acc;
- },
- {} as Record<string, LocalNode[]>,
- );
-
- const fields: FieldNode[] = [];
- for (const fieldNode of fieldsNodes) {
- const selectOptions = groupedSelectOptions[fieldNode.id] ?? [];
- const field = this.buildFieldNode(fieldNode, selectOptions);
- if (field) {
- fields.push(field);
- }
- }
-
- return {
- id: databaseLocalNode.id,
- name: name,
- fields,
- };
- };
-
- private buildFieldNode = (
- node: LocalNode,
- selectOptions: LocalNode[],
- ): FieldNode | null => {
- const name = node.attributes.name;
- const dataType = node.attributes.dataType as FieldDataType;
-
- if (!dataType) {
- return null;
- }
-
- switch (dataType) {
- case 'boolean':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'collaborator':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'created_at':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'created_by':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'date':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'email':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'file':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'multi_select':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- options: selectOptions.map(this.buildSelectOption),
- };
- case 'number':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'phone':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'select':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- options: selectOptions.map(this.buildSelectOption),
- };
- case 'text':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'url':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- default:
- return null;
- }
- };
-
- private buildSelectOption = (node: LocalNode): SelectOptionNode => {
- const name = node.attributes.name;
- const color = node.attributes.color;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- color: color ?? 'gray',
- };
- };
-}
diff --git a/desktop/src/main/handlers/queries/database-view-list.ts b/desktop/src/main/handlers/queries/database-view-list.ts
deleted file mode 100644
index d31aec82..00000000
--- a/desktop/src/main/handlers/queries/database-view-list.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import { DatabaseViewListQueryInput } from '@/operations/queries/database-view-list';
-import { databaseManager } from '@/main/data/database-manager';
-import {
- ChangeCheckResult,
- QueryHandler,
- QueryResult,
-} from '@/operations/queries';
-import { SelectNode } from '@/main/data/workspace/schema';
-import { mapNode } from '@/lib/nodes';
-import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { LocalNode } from '@/types/nodes';
-import {
- BoardViewNode,
- CalendarViewNode,
- TableViewNode,
- ViewNode,
-} from '@/types/databases';
-import { isEqual } from 'lodash';
-import { MutationChange } from '@/operations/mutations';
-import { compareString } from '@/lib/utils';
-
-export class DatabaseViewListQueryHandler
- implements QueryHandler<DatabaseViewListQueryInput>
-{
- public async handleQuery(
- input: DatabaseViewListQueryInput,
- ): Promise<QueryResult<DatabaseViewListQueryInput>> {
- const rows = await this.fetchNodes(input);
- return {
- output: this.buildViewNodes(rows),
- state: {
- rows: rows,
- },
- };
- }
-
- public async checkForChanges(
- changes: MutationChange[],
- input: DatabaseViewListQueryInput,
- state: Record<string, any>,
- ): Promise<ChangeCheckResult<DatabaseViewListQueryInput>> {
- if (
- !changes.some(
- (change) =>
- change.type === 'workspace' &&
- change.table === 'nodes' &&
- change.userId === input.userId,
- )
- ) {
- return {
- hasChanges: false,
- };
- }
-
- const rows = await this.fetchNodes(input);
- if (isEqual(rows, state.rows)) {
- return {
- hasChanges: false,
- };
- }
-
- return {
- hasChanges: true,
- result: {
- output: this.buildViewNodes(rows),
- state: {
- rows,
- },
- },
- };
- }
-
- private async fetchNodes(
- input: DatabaseViewListQueryInput,
- ): Promise<SelectNode[]> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
- input.userId,
- );
-
- const rows = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .execute();
- return rows;
- }
-
- private buildViewNodes = (rows: SelectNode[]): ViewNode[] => {
- const nodes = rows
- .sort((a, b) => compareString(a.index, b.index))
- .map((row) => mapNode(row));
- const views: ViewNode[] = [];
- for (const node of nodes) {
- const view = this.buildViewNode(node);
- if (view) {
- views.push(view);
- }
- }
-
- return views;
- };
-
- private buildViewNode = (node: LocalNode): ViewNode | null => {
- if (node.type === NodeTypes.TableView) {
- return this.buildTableViewNode(node);
- } else if (node.type === NodeTypes.BoardView) {
- return this.buildBoardViewNode(node);
- } else if (node.type === NodeTypes.CalendarView) {
- return this.buildCalendarViewNode(node);
- }
-
- return null;
- };
-
- private buildTableViewNode = (node: LocalNode): TableViewNode => {
- const name = node.attributes.name;
- const avatar = node.attributes.avatar;
- const hiddenFields = node.attributes.hiddenFields;
- const fieldIndexes = node.attributes.fieldIndexes;
- const fieldWidths = node.attributes.fieldWidths;
- const nameWidth = node.attributes.nameWidth;
-
- const viewFilters = node.attributes.filters;
- const viewSorts = node.attributes.sorts;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- avatar,
- type: 'table_view',
- hiddenFields,
- fieldIndexes,
- fieldWidths,
- nameWidth: nameWidth,
- versionId: node.versionId,
- filters: viewFilters ?? [],
- sorts: viewSorts ?? [],
- };
- };
-
- private buildBoardViewNode = (node: LocalNode): BoardViewNode => {
- const name = node.attributes.name;
- const avatar = node.attributes.avatar;
- const groupBy = node.attributes.groupBy;
- const viewFilters = node.attributes.filters;
- const viewSorts = node.attributes.sorts;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- avatar,
- type: 'board_view',
- filters: viewFilters ?? [],
- sorts: viewSorts ?? [],
- groupBy,
- };
- };
-
- private buildCalendarViewNode = (node: LocalNode): CalendarViewNode => {
- const name = node.attributes.name;
- const avatar = node.attributes.avatar;
- const groupBy = node.attributes.groupBy;
-
- const viewFilters = node.attributes.filters;
- const viewSorts = node.attributes.sorts;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- avatar,
- type: 'calendar_view',
- filters: viewFilters ?? [],
- sorts: viewSorts ?? [],
- groupBy,
- };
- };
-}
diff --git a/desktop/src/main/handlers/queries/document-get.ts b/desktop/src/main/handlers/queries/document-get.ts
index eda7981b..499455d5 100644
--- a/desktop/src/main/handlers/queries/document-get.ts
+++ b/desktop/src/main/handlers/queries/document-get.ts
@@ -69,7 +69,7 @@ export class DocumentGetQueryHandler
private async fetchDocument(
input: DocumentGetQueryInput,
- ): Promise<SelectNode | null> {
+ ): Promise<SelectNode | undefined> {
const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
input.userId,
);
@@ -81,7 +81,9 @@ export class DocumentGetQueryHandler
.executeTakeFirst();
}
- private buildOutput(document: SelectNode | null): DocumentGetQueryOutput {
+ private buildOutput(
+ document: SelectNode | null | undefined,
+ ): DocumentGetQueryOutput {
if (!document) {
return {
content: null,
@@ -90,7 +92,14 @@ export class DocumentGetQueryHandler
}
const attributes = JSON.parse(document.attributes) as LocalNodeAttributes;
- const nodeBlocks = Object.values(attributes?.content ?? {});
+ if (attributes.type !== 'page' && attributes.type !== 'record') {
+ return {
+ content: null,
+ hash: null,
+ };
+ }
+
+ const nodeBlocks = Object.values(attributes.content ?? {});
const contents = mapBlocksToContents(document.id, nodeBlocks);
if (!contents.length) {
diff --git a/desktop/src/main/handlers/queries/file-get.ts b/desktop/src/main/handlers/queries/file-get.ts
index 9b8b2166..0f70db0e 100644
--- a/desktop/src/main/handlers/queries/file-get.ts
+++ b/desktop/src/main/handlers/queries/file-get.ts
@@ -12,12 +12,12 @@ import { FileDetails } from '@/types/files';
interface FileRow {
id: string;
attributes: string;
- parent_id: string;
+ parent_id: string | null;
type: string;
download_progress?: number | null;
created_at: string;
created_by: string;
- created_by_attributes: string;
+ created_by_attributes: string | null;
}
export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
@@ -70,7 +70,9 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
};
}
- private async fetchFile(input: FileGetQueryInput): Promise<FileRow> {
+ private async fetchFile(
+ input: FileGetQueryInput,
+ ): Promise<FileRow | undefined> {
const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
input.userId,
);
@@ -90,7 +92,7 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
'file.attributes',
'file_downloads.progress as download_progress',
'file.created_at',
- 'created_by.id as created_by',
+ 'file.created_by',
'created_by.attributes as created_by_attributes',
])
.where('file.id', '=', input.fileId)
@@ -101,7 +103,9 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
private buildFile(row: FileRow): FileDetails {
const attributes = JSON.parse(row.attributes);
- const createdByAttributes = JSON.parse(row.created_by_attributes);
+ const createdByAttributes = row.created_by_attributes
+ ? JSON.parse(row.created_by_attributes)
+ : null;
return {
id: row.id,
diff --git a/desktop/src/main/handlers/queries/file-list.ts b/desktop/src/main/handlers/queries/file-list.ts
index 20e62b13..720b2fde 100644
--- a/desktop/src/main/handlers/queries/file-list.ts
+++ b/desktop/src/main/handlers/queries/file-list.ts
@@ -14,7 +14,7 @@ import { FileNode } from '@/types/files';
interface FileRow {
id: string;
attributes: string;
- parent_id: string;
+ parent_id: string | null;
type: string;
download_progress?: number | null;
created_at: string;
diff --git a/desktop/src/main/handlers/queries/index.ts b/desktop/src/main/handlers/queries/index.ts
index 7bffb202..ada23149 100644
--- a/desktop/src/main/handlers/queries/index.ts
+++ b/desktop/src/main/handlers/queries/index.ts
@@ -1,14 +1,10 @@
import { QueryHandler, QueryMap } from '@/operations/queries';
import { AccountListQueryHandler } from '@/main/handlers/queries/accounts-list';
import { BreadcrumbListQueryHandler } from '@/main/handlers/queries/breadcrumb-list';
-import { DatabaseGetQueryHandler } from '@/main/handlers/queries/database-get';
-import { DatabaseViewListQueryHandler } from '@/main/handlers/queries/database-view-list';
-import { DocumentGetQueryHandler } from '@/main/handlers/queries/document-get';
import { MessageListQueryHandler } from '@/main/handlers/queries/message-list';
import { NodeCollaboratorListQueryHandler } from '@/main/handlers/queries/node-collaborator-list';
import { NodeCollaboratorSearchQueryHandler } from '@/main/handlers/queries/node-collaborator-search';
import { NodeGetQueryHandler } from '@/main/handlers/queries/node-get';
-import { RecordGetQueryHandler } from '@/main/handlers/queries/record-get';
import { ServerListQueryHandler } from '@/main/handlers/queries/server-list';
import { SidebarChatListQueryHandler } from '@/main/handlers/queries/sidebar-chat-list';
import { SidebarSpaceListQueryHandler } from '@/main/handlers/queries/sidebar-space-list';
@@ -19,6 +15,7 @@ import { RecordListQueryHandler } from '@/main/handlers/queries/record-list';
import { ChatGetQueryHandler } from '@/main/handlers/queries/chat-get';
import { FileListQueryHandler } from '@/main/handlers/queries/file-list';
import { FileGetQueryHandler } from '@/main/handlers/queries/file-get';
+import { DocumentGetQueryHandler } from '@/main/handlers/queries/document-get';
type QueryHandlerMap = {
[K in keyof QueryMap]: QueryHandler<QueryMap[K]['input']>;
@@ -27,14 +24,10 @@ type QueryHandlerMap = {
export const queryHandlerMap: QueryHandlerMap = {
account_list: new AccountListQueryHandler(),
breadcrumb_list: new BreadcrumbListQueryHandler(),
- database_get: new DatabaseGetQueryHandler(),
- database_view_list: new DatabaseViewListQueryHandler(),
- document_get: new DocumentGetQueryHandler(),
message_list: new MessageListQueryHandler(),
node_collaborator_list: new NodeCollaboratorListQueryHandler(),
node_collaborator_search: new NodeCollaboratorSearchQueryHandler(),
node_get: new NodeGetQueryHandler(),
- record_get: new RecordGetQueryHandler(),
record_list: new RecordListQueryHandler(),
server_list: new ServerListQueryHandler(),
sidebar_chat_list: new SidebarChatListQueryHandler(),
@@ -45,4 +38,5 @@ export const queryHandlerMap: QueryHandlerMap = {
chat_get: new ChatGetQueryHandler(),
file_list: new FileListQueryHandler(),
file_get: new FileGetQueryHandler(),
+ document_get: new DocumentGetQueryHandler(),
};
diff --git a/desktop/src/main/handlers/queries/message-list.ts b/desktop/src/main/handlers/queries/message-list.ts
index 1f543c67..ab98bbdd 100644
--- a/desktop/src/main/handlers/queries/message-list.ts
+++ b/desktop/src/main/handlers/queries/message-list.ts
@@ -128,6 +128,10 @@ export class MessageListQueryHandler
const authorMap = new Map<string, UserNode>();
for (const authorRow of authorRows) {
const authorNode = mapNode(authorRow);
+ if (authorNode.type !== 'user') {
+ continue;
+ }
+
const name = authorNode.attributes.name;
const email = authorNode.attributes.email;
const avatar = authorNode.attributes.avatar;
@@ -142,6 +146,10 @@ export class MessageListQueryHandler
for (const messageRow of messageRows) {
const messageNode = mapNode(messageRow);
+ if (messageNode.type !== 'message') {
+ continue;
+ }
+
const author = authorMap.get(messageNode.createdBy);
const reactions =
(messageNode.attributes.reactions as Record<string, string[]>) ?? {};
diff --git a/desktop/src/main/handlers/queries/node-collaborator-list.ts b/desktop/src/main/handlers/queries/node-collaborator-list.ts
index a547999b..0c6c5f75 100644
--- a/desktop/src/main/handlers/queries/node-collaborator-list.ts
+++ b/desktop/src/main/handlers/queries/node-collaborator-list.ts
@@ -139,6 +139,17 @@ export class NodeCollaboratorListQueryHandler
for (const node of nodes) {
const attributes = JSON.parse(node.attributes) as LocalNodeAttributes;
+
+ if (
+ attributes.type !== 'space' &&
+ attributes.type !== 'channel' &&
+ attributes.type !== 'chat' &&
+ attributes.type !== 'database' &&
+ attributes.type !== 'page'
+ ) {
+ continue;
+ }
+
const collaborators = attributes.collaborators;
if (!collaborators) {
continue;
@@ -216,7 +227,7 @@ export class NodeCollaboratorListQueryHandler
inheritCollaboratorMap
.get(extractedCollaborator.nodeId)
- .push(collaborator);
+ ?.push(collaborator);
}
}
@@ -230,7 +241,7 @@ export class NodeCollaboratorListQueryHandler
id: ancestor.id,
name: ancestorAttributes.name,
avatar: ancestorAttributes.avatar || null,
- collaborators: inheritCollaboratorMap.get(ancestor.id),
+ collaborators: inheritCollaboratorMap.get(ancestor.id) ?? [],
};
inherit.push(group);
diff --git a/desktop/src/main/handlers/queries/node-get.ts b/desktop/src/main/handlers/queries/node-get.ts
index 58fde4c5..d59330ad 100644
--- a/desktop/src/main/handlers/queries/node-get.ts
+++ b/desktop/src/main/handlers/queries/node-get.ts
@@ -60,7 +60,9 @@ export class NodeGetQueryHandler implements QueryHandler<NodeGetQueryInput> {
};
}
- private async fetchNode(input: NodeGetQueryInput): Promise<SelectNode> {
+ private async fetchNode(
+ input: NodeGetQueryInput,
+ ): Promise<SelectNode | undefined> {
const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
input.userId,
);
diff --git a/desktop/src/main/handlers/queries/record-get.ts b/desktop/src/main/handlers/queries/record-get.ts
deleted file mode 100644
index f651801c..00000000
--- a/desktop/src/main/handlers/queries/record-get.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { RecordGetQueryInput } from '@/operations/queries/record-get';
-import { databaseManager } from '@/main/data/database-manager';
-import {
- ChangeCheckResult,
- QueryHandler,
- QueryResult,
-} from '@/operations/queries';
-import { mapNode } from '@/lib/nodes';
-import { sql } from 'kysely';
-import { SelectNode } from '@/main/data/workspace/schema';
-import { RecordNode } from '@/types/databases';
-import { NodeTypes } from '@/lib/constants';
-import { MutationChange } from '@/operations/mutations';
-import { isEqual } from 'lodash';
-
-export class RecordGetQueryHandler
- implements QueryHandler<RecordGetQueryInput>
-{
- async handleQuery(
- input: RecordGetQueryInput,
- ): Promise<QueryResult<RecordGetQueryInput>> {
- const rows = await this.fetchNodes(input);
- return {
- output: this.buildRecord(input.recordId, rows),
- state: {
- rows,
- },
- };
- }
-
- async checkForChanges(
- changes: MutationChange[],
- input: RecordGetQueryInput,
- state: Record<string, any>,
- ): Promise<ChangeCheckResult<RecordGetQueryInput>> {
- if (
- !changes.some(
- (change) =>
- change.type === 'workspace' &&
- change.table === 'nodes' &&
- change.userId === input.userId,
- )
- ) {
- return {
- hasChanges: false,
- };
- }
-
- const rows = await this.fetchNodes(input);
- if (isEqual(rows, state.rows)) {
- return {
- hasChanges: false,
- };
- }
-
- return {
- hasChanges: true,
- result: {
- output: this.buildRecord(input.recordId, rows),
- state: {
- rows,
- },
- },
- };
- }
-
- private async fetchNodes(input: RecordGetQueryInput): Promise<SelectNode[]> {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
- input.userId,
- );
-
- const query = sql<SelectNode>`
- WITH record_node AS (
- SELECT *
- FROM nodes
- WHERE id = ${input.recordId}
- ),
- author_node AS (
- SELECT *
- FROM nodes
- WHERE id IN (SELECT DISTINCT created_by FROM record_node)
- )
- SELECT * FROM record_node
- UNION ALL
- SELECT * FROM author_node
- `.compile(workspaceDatabase);
-
- const result = await workspaceDatabase.executeQuery(query);
- return result.rows;
- }
-
- private buildRecord = (
- recordId: string,
- rows: SelectNode[],
- ): RecordNode | null => {
- const nodes = rows.map(mapNode);
- const recordNode = nodes.find((node) => node.id === recordId);
- if (!recordNode) {
- return null;
- }
-
- const recordName = recordNode.attributes.name;
- const authorNode = nodes.find((node) => node.type === NodeTypes.User);
- const author = authorNode
- ? {
- id: authorNode.id,
- name: authorNode.attributes.name,
- avatar: authorNode.attributes.avatar,
- email: authorNode.attributes.email,
- }
- : {
- id: recordNode.createdBy,
- name: 'Unknown User',
- avatar: null,
- email: '[email protected]',
- };
-
- return {
- id: recordNode.id,
- parentId: recordNode.parentId,
- name: recordName ?? null,
- index: recordNode.index,
- attributes: recordNode.attributes,
- createdAt: new Date(recordNode.createdAt),
- createdBy: author,
- versionId: recordNode.versionId,
- };
- };
-}
diff --git a/desktop/src/main/handlers/queries/record-list.ts b/desktop/src/main/handlers/queries/record-list.ts
index 640846af..469042e1 100644
--- a/desktop/src/main/handlers/queries/record-list.ts
+++ b/desktop/src/main/handlers/queries/record-list.ts
@@ -9,29 +9,26 @@ import { MutationChange } from '@/operations/mutations';
import { SelectNode } from '@/main/data/workspace/schema';
import { sql } from 'kysely';
import {
- BooleanFieldNode,
- CreatedAtFieldNode,
- DatabaseNode,
- DateFieldNode,
- EmailFieldNode,
- FieldNode,
- MultiSelectFieldNode,
- NumberFieldNode,
- PhoneFieldNode,
- RecordNode,
- SelectFieldNode,
- TextFieldNode,
- UrlFieldNode,
- ViewFieldFilter,
- ViewFilter,
- ViewSort,
-} from '@/types/databases';
+ BooleanFieldAttributes,
+ CreatedAtFieldAttributes,
+ DateFieldAttributes,
+ EmailFieldAttributes,
+ FieldAttributes,
+ MultiSelectFieldAttributes,
+ NumberFieldAttributes,
+ PhoneFieldAttributes,
+ SelectFieldAttributes,
+ TextFieldAttributes,
+ UrlFieldAttributes,
+ ViewFieldFilterAttributes,
+ ViewFilterAttributes,
+ ViewSortAttributes,
+} from '@/registry';
import { isStringArray } from '@/lib/utils';
-import { UserNode } from '@/types/users';
import { mapNode } from '@/lib/nodes';
import { NodeTypes } from '@/lib/constants';
-import { DatabaseGetQueryHandler } from '@/main/handlers/queries/database-get';
import { isEqual } from 'lodash';
+import { DatabaseNode, RecordNode } from '@/types/nodes';
export class RecordListQueryHandler
implements QueryHandler<RecordListQueryInput>
@@ -93,8 +90,12 @@ export class RecordListQueryHandler
);
const database = await this.fetchDatabase(input.userId, input.databaseId);
- const filterQuery = this.buildFiltersQuery(input.filters, database.fields);
- const orderByQuery = `ORDER BY ${input.sorts.length > 0 ? this.buildSortOrdersQuery(input.sorts, database.fields) : 'n."index" ASC'}`;
+ const filterQuery = this.buildFiltersQuery(
+ input.filters,
+ database.attributes.fields,
+ );
+
+ const orderByQuery = `ORDER BY ${input.sorts.length > 0 ? this.buildSortOrdersQuery(input.sorts, database.attributes.fields) : 'n."index" ASC'}`;
const offset = input.page * input.count;
const query = sql<SelectNode>`
WITH record_nodes AS (
@@ -126,66 +127,43 @@ export class RecordListQueryHandler
private buildRecords = (rows: SelectNode[]): RecordNode[] => {
const nodes = rows.map(mapNode);
- const recordNodes = nodes.filter((node) => node.type === NodeTypes.Record);
-
- const authorNodes = nodes.filter((node) => node.type === NodeTypes.User);
- const records: RecordNode[] = [];
- const authorMap = new Map<string, UserNode>();
-
- for (const author of authorNodes) {
- const name = author.attributes.name;
- const avatar = author.attributes.avatar;
- const email = author.attributes.email;
-
- authorMap.set(author.id, {
- id: author.id,
- name: name ?? 'Unknown User',
- email,
- avatar,
- });
- }
-
- for (const node of recordNodes) {
- const name = node.attributes.name;
- const author = authorMap.get(node.createdBy);
- const record: RecordNode = {
- id: node.id,
- parentId: node.parentId,
- name: name ?? null,
- index: node.index,
- attributes: node.attributes,
- createdAt: new Date(node.createdAt),
- createdBy: author ?? {
- id: node.createdBy,
- name: 'Unknown User',
- email: '[email protected]',
- avatar: null,
- },
- versionId: node.versionId,
- };
+ const recordNodes: RecordNode[] = [];
- records.push(record);
+ for (const node of nodes) {
+ if (node.type !== 'record') {
+ continue;
+ }
+
+ recordNodes.push(node);
}
- return records;
+ return recordNodes;
};
private async fetchDatabase(
userId: string,
databaseId: string,
): Promise<DatabaseNode> {
- const handler = new DatabaseGetQueryHandler();
- const result = await handler.handleQuery({
- type: 'database_get',
- databaseId: databaseId,
- userId: userId,
- });
- return result.output;
+ const workspaceDatabase =
+ await databaseManager.getWorkspaceDatabase(userId);
+
+ const row = await workspaceDatabase
+ .selectFrom('nodes')
+ .where('id', '=', databaseId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!row) {
+ throw new Error('Database not found');
+ }
+
+ const database = mapNode(row) as DatabaseNode;
+ return database;
}
private buildFiltersQuery = (
- filters: ViewFilter[],
- fields: FieldNode[],
+ filters: ViewFilterAttributes[],
+ fields: Record<string, FieldAttributes>,
): string => {
if (filters.length === 0) {
return '';
@@ -203,26 +181,26 @@ export class RecordListQueryHandler
};
private buildFilterQuery = (
- filter: ViewFilter,
- fields: FieldNode[],
+ filter: ViewFilterAttributes,
+ fields: Record<string, FieldAttributes>,
): string | null => {
if (filter.type === 'group') {
return null;
}
- const field = fields.find((field) => field.id === filter.fieldId);
+ const field = fields[filter.fieldId];
if (!field) {
return null;
}
- switch (field.dataType) {
+ switch (field.type) {
case 'boolean':
return this.buildBooleanFilterQuery(filter, field);
case 'collaborator':
return null;
- case 'created_at':
+ case 'createdAt':
return this.buildCreatedAtFilterQuery(filter, field);
- case 'created_by':
+ case 'createdBy':
return null;
case 'date':
return this.buildDateFilterQuery(filter, field);
@@ -230,7 +208,7 @@ export class RecordListQueryHandler
return this.buildEmailFilterQuery(filter, field);
case 'file':
return null;
- case 'multi_select':
+ case 'multiSelect':
return this.buildMultiSelectFilterQuery(filter, field);
case 'number':
return this.buildNumberFilterQuery(filter, field);
@@ -248,23 +226,23 @@ export class RecordListQueryHandler
};
buildBooleanFilterQuery = (
- filter: ViewFieldFilter,
- field: BooleanFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: BooleanFieldAttributes,
): string | null => {
if (filter.operator === 'is_true') {
- return `json_extract(n.attributes, '$.${field.id}') = true`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') = true`;
}
if (filter.operator === 'is_false') {
- return `(json_extract(n.attributes, '$.${field.id}') = false OR json_extract(n.attributes, '$.${field.id}') IS NULL)`;
+ return `(json_extract(n.attributes, '$.fields.${field.id}.value') = false OR json_extract(n.attributes, '$.fields.${field.id}.value') IS NULL)`;
}
return null;
};
private buildNumberFilterQuery = (
- filter: ViewFieldFilter,
- field: NumberFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: NumberFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
@@ -312,12 +290,12 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(n.attributes, '$.${field.id}') ${operator} ${value}`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} ${value}`;
};
private buildTextFilterQuery = (
- filter: ViewFieldFilter,
- field: TextFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: TextFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
@@ -370,17 +348,13 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildEmailFilterQuery = (
- filter: ViewFilter,
- field: EmailFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: EmailFieldAttributes,
): string | null => {
- if (filter.type === 'group') {
- return null;
- }
-
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
}
@@ -432,12 +406,12 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildPhoneFilterQuery = (
- filter: ViewFieldFilter,
- field: PhoneFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: PhoneFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
@@ -490,12 +464,12 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildUrlFilterQuery = (
- filter: ViewFieldFilter,
- field: UrlFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: UrlFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
@@ -548,12 +522,12 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildSelectFilterQuery = (
- filter: ViewFieldFilter,
- field: SelectFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: SelectFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
@@ -574,24 +548,24 @@ export class RecordListQueryHandler
const values = this.joinIds(filter.value);
switch (filter.operator) {
case 'is_in':
- return `json_extract(n.attributes, '$.${field.id}') IN (${values})`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') IN (${values})`;
case 'is_not_in':
- return `json_extract(n.attributes, '$.${field.id}') NOT IN (${values})`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') NOT IN (${values})`;
default:
return null;
}
};
private buildMultiSelectFilterQuery = (
- filter: ViewFieldFilter,
- field: MultiSelectFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: MultiSelectFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
- return `json_extract(n.attributes, '$.${field.id}') IS NULL OR json_array_length(json_extract(n.attributes, '$.${field.id}')) = 0`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') IS NULL OR json_array_length(json_extract(n.attributes, '$.fields.${field.id}.value')) = 0`;
}
if (filter.operator === 'is_not_empty') {
- return `json_extract(n.attributes, '$.${field.id}') IS NOT NULL AND json_array_length(json_extract(n.attributes, '$.${field.id}')) > 0`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') IS NOT NULL AND json_array_length(json_extract(n.attributes, '$.fields.${field.id}.value')) > 0`;
}
if (!isStringArray(filter.value)) {
@@ -605,17 +579,17 @@ export class RecordListQueryHandler
const values = this.joinIds(filter.value);
switch (filter.operator) {
case 'is_in':
- return `EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.${field.id}')) WHERE json_each.value IN (${values}))`;
+ return `EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.fields.${field.id}.value')) WHERE json_each.value IN (${values}))`;
case 'is_not_in':
- return `NOT EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.${field.id}')) WHERE json_each.value IN (${values}))`;
+ return `NOT EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.fields.${field.id}.value')) WHERE json_each.value IN (${values}))`;
default:
return null;
}
};
private buildDateFilterQuery = (
- filter: ViewFieldFilter,
- field: DateFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: DateFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return this.buildIsEmptyFilterQuery(field.id);
@@ -668,12 +642,12 @@ export class RecordListQueryHandler
return null;
}
- return `DATE(json_extract(n.attributes, '$.${field.id}')) ${operator} '${dateString}'`;
+ return `DATE(json_extract(n.attributes, '$.fields.${field.id}.value')) ${operator} '${dateString}'`;
};
private buildCreatedAtFilterQuery = (
- filter: ViewFieldFilter,
- field: CreatedAtFieldNode,
+ filter: ViewFieldFilterAttributes,
+ field: CreatedAtFieldAttributes,
): string | null => {
if (filter.operator === 'is_empty') {
return `n.created_at IS NULL`;
@@ -730,11 +704,11 @@ export class RecordListQueryHandler
};
private buildIsEmptyFilterQuery = (fieldId: string): string => {
- return `json_extract(n.attributes, '$.${fieldId}') IS NULL`;
+ return `json_extract(n.attributes, '$.fields.${fieldId}.value') IS NULL`;
};
private buildIsNotEmptyFilterQuery = (fieldId: string): string => {
- return `json_extract(n.attributes, '$.${fieldId}') IS NOT NULL`;
+ return `json_extract(n.attributes, '$.fields.${fieldId}.value') IS NOT NULL`;
};
private joinIds = (ids: string[]): string => {
@@ -742,8 +716,8 @@ export class RecordListQueryHandler
};
private buildSortOrdersQuery = (
- sorts: ViewSort[],
- fields: FieldNode[],
+ sorts: ViewSortAttributes[],
+ fields: Record<string, FieldAttributes>,
): string => {
return sorts
.map((sort) => this.buildSortOrderQuery(sort, fields))
@@ -752,22 +726,22 @@ export class RecordListQueryHandler
};
private buildSortOrderQuery = (
- sort: ViewSort,
- fields: FieldNode[],
+ sort: ViewSortAttributes,
+ fields: Record<string, FieldAttributes>,
): string | null => {
- const field = fields.find((field) => field.id === sort.fieldId);
+ const field = fields[sort.fieldId];
if (!field) {
return null;
}
- if (field.dataType === 'created_at') {
+ if (field.type === 'createdAt') {
return `n.created_at ${sort.direction}`;
}
- if (field.dataType === 'created_by') {
+ if (field.type === 'createdBy') {
return `n.created_by_id ${sort.direction}`;
}
- return `json_extract(n.attributes, '$.${field.id}') ${sort.direction}`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${sort.direction}`;
};
}
diff --git a/desktop/src/main/handlers/queries/sidebar-chat-list.ts b/desktop/src/main/handlers/queries/sidebar-chat-list.ts
index b5264ebc..c7d11e7c 100644
--- a/desktop/src/main/handlers/queries/sidebar-chat-list.ts
+++ b/desktop/src/main/handlers/queries/sidebar-chat-list.ts
@@ -163,7 +163,7 @@ export class SidebarChatListQueryHandler
.where('n.type', '=', NodeTypes.Message)
.where('n.parent_id', 'in', chatIds)
.where('un.last_seen_version_id', 'is', null)
- .select(['n.parent_id as node_id'])
+ .select(['un.node_id'])
.select((eb) => [
eb.fn.count<number>('un.node_id').as('unread_count'),
eb.fn.sum<number>('un.mentions_count').as('mentions_count'),
@@ -184,6 +184,10 @@ export class SidebarChatListQueryHandler
for (const chat of chats) {
const chatNode = mapNode(chat);
+ if (chatNode.type !== 'chat') {
+ continue;
+ }
+
if (!chatNode.attributes || !chatNode.attributes.collaborators) {
continue;
}
@@ -208,6 +212,10 @@ export class SidebarChatListQueryHandler
}
const collaboratorNode = mapNode(collaboratorRow);
+ if (collaboratorNode.type !== 'user') {
+ continue;
+ }
+
const unreadCountRow = unreadCounts.find((r) => r.node_id === chat.id);
sidebarChatNodes.push({
diff --git a/desktop/src/main/handlers/queries/sidebar-space-list.ts b/desktop/src/main/handlers/queries/sidebar-space-list.ts
index 9d340e34..a2c7d355 100644
--- a/desktop/src/main/handlers/queries/sidebar-space-list.ts
+++ b/desktop/src/main/handlers/queries/sidebar-space-list.ts
@@ -125,7 +125,7 @@ export class SidebarSpaceListQueryHandler
.where('n.type', '=', NodeTypes.Message)
.where('n.parent_id', 'in', channelIds)
.where('un.last_seen_version_id', 'is', null)
- .select(['n.parent_id as node_id'])
+ .select(['un.node_id'])
.select((eb) => [
eb.fn.count<number>('un.node_id').as('unread_count'),
eb.fn.sum<number>('un.mentions_count').as('mentions_count'),
@@ -152,7 +152,10 @@ export class SidebarSpaceListQueryHandler
.filter((n) => n.parentId === node.id)
.sort((a, b) => compareString(a.index, b.index));
- spaces.push(this.buildSpaceNode(node, children, unreadCounts));
+ const spaceNode = this.buildSpaceNode(node, children, unreadCounts);
+ if (spaceNode) {
+ spaces.push(spaceNode);
+ }
}
return spaces;
@@ -162,15 +165,25 @@ export class SidebarSpaceListQueryHandler
node: LocalNode,
children: LocalNode[],
unreadCounts: UnreadCountRow[],
- ): SidebarSpaceNode => {
+ ): SidebarSpaceNode | null => {
+ if (node.type !== 'space') {
+ return null;
+ }
+
+ const childrenNodes: SidebarNode[] = [];
+ for (const child of children) {
+ const childNode = this.buildSidearNode(child, unreadCounts);
+ if (childNode) {
+ childrenNodes.push(childNode);
+ }
+ }
+
return {
id: node.id,
type: node.type,
- name: node.attributes?.name ?? null,
- avatar: node.attributes?.avatar ?? null,
- children: children.map((child) =>
- this.buildSidearNode(child, unreadCounts),
- ),
+ name: node.attributes.name ?? null,
+ avatar: node.attributes.avatar ?? null,
+ children: childrenNodes,
unreadCount: 0,
mentionsCount: 0,
};
@@ -179,9 +192,18 @@ export class SidebarSpaceListQueryHandler
private buildSidearNode = (
node: LocalNode,
unreadCounts: UnreadCountRow[],
- ): SidebarNode => {
+ ): SidebarNode | null => {
const unreadCountRow = unreadCounts.find((r) => r.node_id === node.id);
+ if (
+ node.type !== 'channel' &&
+ node.type !== 'page' &&
+ node.type !== 'folder' &&
+ node.type !== 'database'
+ ) {
+ return null;
+ }
+
return {
id: node.id,
type: node.type,
diff --git a/desktop/src/main/handlers/queries/workspace-user-list.ts b/desktop/src/main/handlers/queries/workspace-user-list.ts
index ef157805..b2cc3dfb 100644
--- a/desktop/src/main/handlers/queries/workspace-user-list.ts
+++ b/desktop/src/main/handlers/queries/workspace-user-list.ts
@@ -8,7 +8,7 @@ import {
import { NodeTypes } from '@/lib/constants';
import { mapNode } from '@/lib/nodes';
import { SelectNode } from '@/main/data/workspace/schema';
-import { LocalNode } from '@/types/nodes';
+import { LocalNode, UserNode } from '@/types/nodes';
import { MutationChange } from '@/operations/mutations';
import { isEqual } from 'lodash';
@@ -83,7 +83,16 @@ export class WorkspaceUserListQueryHandler
return rows;
}
- private buildWorkspaceUserNodes = (rows: SelectNode[]): LocalNode[] => {
- return rows.map(mapNode);
+ private buildWorkspaceUserNodes = (rows: SelectNode[]): UserNode[] => {
+ const nodes = rows.map(mapNode);
+ const users: UserNode[] = [];
+
+ for (const node of nodes) {
+ if (node.type === NodeTypes.User) {
+ users.push(node as UserNode);
+ }
+ }
+
+ return users;
};
}
diff --git a/desktop/src/main/mediator.ts b/desktop/src/main/mediator.ts
index f4bf857d..46102e74 100644
--- a/desktop/src/main/mediator.ts
+++ b/desktop/src/main/mediator.ts
@@ -27,7 +27,9 @@ class Mediator {
public async executeMutation<T extends MutationInput>(
input: T,
): Promise<MutationMap[T['type']]['output']> {
- const handler = mutationHandlerMap[input.type] as MutationHandler<T>;
+ const handler = mutationHandlerMap[
+ input.type
+ ] as unknown as MutationHandler<T>;
const result = await handler.handleMutation(input);
if (result.changes) {
@@ -40,7 +42,7 @@ class Mediator {
public async executeQuery<T extends QueryInput>(
input: T,
): Promise<QueryMap[T['type']]['output']> {
- const handler = queryHandlerMap[input.type] as QueryHandler<T>;
+ const handler = queryHandlerMap[input.type] as unknown as QueryHandler<T>;
const result = await handler.handleQuery(input);
return result.output;
}
@@ -49,7 +51,7 @@ class Mediator {
id: string,
input: T,
): Promise<QueryMap[T['type']]['output']> {
- const handler = queryHandlerMap[input.type] as QueryHandler<T>;
+ const handler = queryHandlerMap[input.type] as unknown as QueryHandler<T>;
const result = await handler.handleQuery(input);
this.subscribedQueries.set(id, {
input,
diff --git a/desktop/src/main/node-manager.ts b/desktop/src/main/node-manager.ts
new file mode 100644
index 00000000..bda6b259
--- /dev/null
+++ b/desktop/src/main/node-manager.ts
@@ -0,0 +1,171 @@
+import * as Y from 'yjs';
+import { LocalNodeAttributes } from '@/types/nodes';
+import { fromUint8Array, toUint8Array } from 'js-base64';
+import { applyCrdt } from '@/main/crdt';
+import {
+ LocalCreateNodeChangeData,
+ LocalUpdateNodeChangeData,
+} from '@/types/sync';
+import { registryMap } from '@/registry';
+import { generateId } from '@/lib/id';
+import { IdType } from '@/lib/id';
+import { databaseManager } from '@/main/data/database-manager';
+import { hasUpdateChanges } from '@/main/utils';
+import { Transaction } from 'kysely';
+import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';
+
+class NodeManager {
+ async createNode(
+ transaction: Transaction<WorkspaceDatabaseSchema>,
+ userId: string,
+ id: string,
+ attributes: LocalNodeAttributes,
+ ) {
+ const doc = new Y.Doc({
+ guid: id,
+ });
+ const attributesMap = doc.getMap('attributes');
+
+ const registry = registryMap[attributes.type];
+ if (!registry) {
+ throw new Error('Invalid node type');
+ }
+
+ applyCrdt(registry.schema, attributes, attributesMap);
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ const createdAt = new Date().toISOString();
+ const versionId = generateId(IdType.Version);
+
+ const changeData: LocalCreateNodeChangeData = {
+ type: 'node_create',
+ id: id,
+ state: encodedState,
+ createdAt: createdAt,
+ createdBy: userId,
+ versionId: versionId,
+ };
+
+ await transaction
+ .insertInto('nodes')
+ .values({
+ id: id,
+ attributes: JSON.stringify(attributes),
+ state: encodedState,
+ created_at: createdAt,
+ created_by: userId,
+ version_id: versionId,
+ })
+ .execute();
+
+ await transaction
+ .insertInto('changes')
+ .values({
+ data: JSON.stringify(changeData),
+ created_at: createdAt,
+ retry_count: 0,
+ })
+ .execute();
+ }
+
+ async updateNode(
+ userId: string,
+ id: string,
+ updater: (attributes: LocalNodeAttributes) => LocalNodeAttributes,
+ ) {
+ const workspaceDatabase =
+ await databaseManager.getWorkspaceDatabase(userId);
+
+ let count = 0;
+ while (count++ < 20) {
+ const node = await workspaceDatabase
+ .selectFrom('nodes')
+ .select(['state', 'attributes', 'version_id'])
+ .where('id', '=', id)
+ .executeTakeFirst();
+
+ if (!node) {
+ throw new Error('Node not found');
+ }
+
+ const doc = new Y.Doc({
+ guid: id,
+ });
+ Y.applyUpdate(doc, toUint8Array(node.state));
+
+ const versionId = generateId(IdType.Version);
+ const updatedAt = new Date().toISOString();
+ const updates: string[] = [];
+
+ doc.on('update', (update) => {
+ updates.push(fromUint8Array(update));
+ });
+
+ const attributes = JSON.parse(node.attributes) as LocalNodeAttributes;
+ const updatedAttributes = updater(attributes);
+
+ const attributesMap = doc.getMap('attributes');
+ doc.transact(() => {
+ applyCrdt(
+ registryMap[updatedAttributes.type].schema,
+ updatedAttributes,
+ attributesMap,
+ );
+ });
+
+ if (updates.length === 0) {
+ return true;
+ }
+
+ const attributesJson = JSON.stringify(attributesMap.toJSON());
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ const changeData: LocalUpdateNodeChangeData = {
+ type: 'node_update',
+ id: id,
+ updatedAt: updatedAt,
+ updatedBy: userId,
+ versionId: versionId,
+ updates: updates,
+ };
+
+ const result = await workspaceDatabase
+ .transaction()
+ .execute(async (trx) => {
+ const result = await trx
+ .updateTable('nodes')
+ .set({
+ attributes: attributesJson,
+ state: encodedState,
+ updated_at: updatedAt,
+ updated_by: userId,
+ version_id: versionId,
+ })
+ .where('id', '=', id)
+ .where('version_id', '=', node.version_id)
+ .execute();
+
+ const hasChanges = hasUpdateChanges(result);
+
+ if (hasChanges) {
+ await trx
+ .insertInto('changes')
+ .values({
+ data: JSON.stringify(changeData),
+ created_at: updatedAt,
+ retry_count: 0,
+ })
+ .execute();
+ }
+
+ return hasChanges;
+ });
+
+ if (result) {
+ return true;
+ }
+ }
+ }
+}
+
+export const nodeManager = new NodeManager();
diff --git a/desktop/src/main/utils.ts b/desktop/src/main/utils.ts
index bc8bf5f1..932d7689 100644
--- a/desktop/src/main/utils.ts
+++ b/desktop/src/main/utils.ts
@@ -45,97 +45,3 @@ export const hasUpdateChanges = (result: UpdateResult[]): boolean => {
export const hasDeleteChanges = (result: DeleteResult[]): boolean => {
return result.some((r) => r.numDeletedRows && r.numDeletedRows > 0n);
};
-
-export const updateNodeAtomically = async (
- userId: string,
- nodeId: string,
- update: (attributesMap: Y.Map<any>, attributes: LocalNodeAttributes) => void,
-) => {
- const workspaceDatabase = await databaseManager.getWorkspaceDatabase(userId);
-
- let count = 0;
- while (count++ < 10) {
- const node = await workspaceDatabase
- .selectFrom('nodes')
- .select(['state', 'attributes', 'version_id'])
- .where('id', '=', nodeId)
- .executeTakeFirst();
-
- if (!node) {
- throw new Error('Node not found');
- }
-
- const doc = new Y.Doc({
- guid: nodeId,
- });
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- const versionId = generateId(IdType.Version);
- const updatedAt = new Date().toISOString();
- const updates: string[] = [];
-
- doc.on('update', (update) => {
- updates.push(fromUint8Array(update));
- });
-
- const attributes = JSON.parse(node.attributes) as LocalNodeAttributes;
- const attributesMap = doc.getMap('attributes');
-
- doc.transact(() => {
- update(attributesMap, attributes);
- });
-
- if (updates.length === 0) {
- return true;
- }
-
- const attributesJson = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const changeData: LocalUpdateNodeChangeData = {
- type: 'node_update',
- id: nodeId,
- updatedAt: updatedAt,
- updatedBy: userId,
- versionId: versionId,
- updates: updates,
- };
-
- const result = await workspaceDatabase
- .transaction()
- .execute(async (trx) => {
- const result = await trx
- .updateTable('nodes')
- .set({
- attributes: attributesJson,
- state: encodedState,
- updated_at: updatedAt,
- updated_by: userId,
- version_id: versionId,
- })
- .where('id', '=', nodeId)
- .where('version_id', '=', node.version_id)
- .execute();
-
- const hasChanges = hasUpdateChanges(result);
-
- if (hasChanges) {
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
- created_at: updatedAt,
- })
- .execute();
- }
-
- return hasChanges;
- });
-
- if (result) {
- return true;
- }
- }
-
- return false;
-};
diff --git a/desktop/src/operations/mutations/account-update.ts b/desktop/src/operations/mutations/account-update.ts
index 36fe606c..72e6d331 100644
--- a/desktop/src/operations/mutations/account-update.ts
+++ b/desktop/src/operations/mutations/account-update.ts
@@ -2,7 +2,7 @@ export type AccountUpdateMutationInput = {
type: 'account_update';
id: string;
name: string;
- avatar: string | null;
+ avatar: string | null | undefined;
};
export type AccountUpdateMutationOutput = {
diff --git a/desktop/src/operations/mutations/board-view-create.ts b/desktop/src/operations/mutations/board-view-create.ts
deleted file mode 100644
index b6071413..00000000
--- a/desktop/src/operations/mutations/board-view-create.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export type BoardViewCreateMutationInput = {
- type: 'board_view_create';
- userId: string;
- databaseId: string;
- name: string;
- groupBy: string;
-};
-
-export type BoardViewCreateMutationOutput = {
- id: string;
-};
-
-declare module '@/operations/mutations' {
- interface MutationMap {
- board_view_create: {
- input: BoardViewCreateMutationInput;
- output: BoardViewCreateMutationOutput;
- };
- }
-}
diff --git a/desktop/src/operations/mutations/calendar-view-create.ts b/desktop/src/operations/mutations/calendar-view-create.ts
deleted file mode 100644
index f0a93ec1..00000000
--- a/desktop/src/operations/mutations/calendar-view-create.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export type CalendarViewCreateMutationInput = {
- type: 'calendar_view_create';
- userId: string;
- databaseId: string;
- name: string;
- groupBy: string;
-};
-
-export type CalendarViewCreateMutationOutput = {
- id: string;
-};
-
-declare module '@/operations/mutations' {
- interface MutationMap {
- calendar_view_create: {
- input: CalendarViewCreateMutationInput;
- output: CalendarViewCreateMutationOutput;
- };
- }
-}
diff --git a/desktop/src/operations/mutations/chat-create.ts b/desktop/src/operations/mutations/chat-create.ts
index 982f9e6f..70e8bed2 100644
--- a/desktop/src/operations/mutations/chat-create.ts
+++ b/desktop/src/operations/mutations/chat-create.ts
@@ -1,5 +1,6 @@
export type ChatCreateMutationInput = {
type: 'chat_create';
+ workspaceId: string;
userId: string;
otherUserId: string;
};
diff --git a/desktop/src/operations/mutations/field-create.ts b/desktop/src/operations/mutations/field-create.ts
index f50cde03..8b49f89b 100644
--- a/desktop/src/operations/mutations/field-create.ts
+++ b/desktop/src/operations/mutations/field-create.ts
@@ -1,8 +1,10 @@
+import { FieldType } from '@/registry';
+
export type FieldCreateMutationInput = {
type: 'field_create';
databaseId: string;
name: string;
- dataType: string;
+ fieldType: FieldType;
userId: string;
};
diff --git a/desktop/src/operations/mutations/mark-node-as-seen.ts b/desktop/src/operations/mutations/mark-node-as-seen.ts
index f82a64f0..2bf2dbb5 100644
--- a/desktop/src/operations/mutations/mark-node-as-seen.ts
+++ b/desktop/src/operations/mutations/mark-node-as-seen.ts
@@ -1,5 +1,3 @@
-import { JSONContent } from '@tiptap/core';
-
export type MarkNodeAsSeenMutationInput = {
type: 'mark_node_as_seen';
userId: string;
diff --git a/desktop/src/operations/mutations/node-attribute-delete.ts b/desktop/src/operations/mutations/node-attribute-delete.ts
index 7c0ccff4..ab4d69a7 100644
--- a/desktop/src/operations/mutations/node-attribute-delete.ts
+++ b/desktop/src/operations/mutations/node-attribute-delete.ts
@@ -2,7 +2,7 @@ export type NodeAttributeDeleteMutationInput = {
type: 'node_attribute_delete';
userId: string;
nodeId: string;
- attribute: string;
+ path: string;
};
export type NodeAttributeDeleteMutationOutput = {
diff --git a/desktop/src/operations/mutations/node-attribute-set.ts b/desktop/src/operations/mutations/node-attribute-set.ts
index 34139668..553f9d3e 100644
--- a/desktop/src/operations/mutations/node-attribute-set.ts
+++ b/desktop/src/operations/mutations/node-attribute-set.ts
@@ -2,7 +2,7 @@ export type NodeAttributeSetMutationInput = {
type: 'node_attribute_set';
userId: string;
nodeId: string;
- attribute: string;
+ path: string;
value: any;
};
diff --git a/desktop/src/operations/mutations/record-create.ts b/desktop/src/operations/mutations/record-create.ts
index d60cadfe..10918b03 100644
--- a/desktop/src/operations/mutations/record-create.ts
+++ b/desktop/src/operations/mutations/record-create.ts
@@ -2,6 +2,7 @@ export type RecordCreateMutationInput = {
type: 'record_create';
userId: string;
databaseId: string;
+ name?: string;
};
export type RecordCreateMutationOutput = {
diff --git a/desktop/src/operations/mutations/select-option-create.ts b/desktop/src/operations/mutations/select-option-create.ts
index 9af9d3d0..d0ba52d8 100644
--- a/desktop/src/operations/mutations/select-option-create.ts
+++ b/desktop/src/operations/mutations/select-option-create.ts
@@ -1,6 +1,7 @@
export type SelectOptionCreateMutationInput = {
type: 'select_option_create';
userId: string;
+ databaseId: string;
fieldId: string;
name: string;
color: string;
diff --git a/desktop/src/operations/mutations/space-create.ts b/desktop/src/operations/mutations/space-create.ts
index 65acb0fb..53d1d2bd 100644
--- a/desktop/src/operations/mutations/space-create.ts
+++ b/desktop/src/operations/mutations/space-create.ts
@@ -1,6 +1,7 @@
export type SpaceCreateMutationInput = {
type: 'space_create';
userId: string;
+ workspaceId: string;
name: string;
description: string;
};
diff --git a/desktop/src/operations/mutations/space-update.ts b/desktop/src/operations/mutations/space-update.ts
index 40e456af..0bf840fd 100644
--- a/desktop/src/operations/mutations/space-update.ts
+++ b/desktop/src/operations/mutations/space-update.ts
@@ -4,7 +4,7 @@ export type SpaceUpdateMutationInput = {
id: string;
name: string;
description: string;
- avatar: string;
+ avatar?: string | null;
};
export type SpaceUpdateMutationOutput = {
diff --git a/desktop/src/operations/mutations/table-view-create.ts b/desktop/src/operations/mutations/table-view-create.ts
deleted file mode 100644
index ed5a32d1..00000000
--- a/desktop/src/operations/mutations/table-view-create.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type TableViewCreateMutationInput = {
- type: 'table_view_create';
- userId: string;
- databaseId: string;
- name: string;
-};
-
-export type TableViewCreateMutationOutput = {
- id: string;
-};
-
-declare module '@/operations/mutations' {
- interface MutationMap {
- table_view_create: {
- input: TableViewCreateMutationInput;
- output: TableViewCreateMutationOutput;
- };
- }
-}
diff --git a/desktop/src/operations/mutations/view-create.ts b/desktop/src/operations/mutations/view-create.ts
new file mode 100644
index 00000000..a776ebd5
--- /dev/null
+++ b/desktop/src/operations/mutations/view-create.ts
@@ -0,0 +1,21 @@
+export type ViewCreateMutationInput = {
+ type: 'view_create';
+ userId: string;
+ databaseId: string;
+ viewType: 'table' | 'board' | 'calendar';
+ name: string;
+ groupBy: string | null;
+};
+
+export type ViewCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/operations/mutations' {
+ interface MutationMap {
+ view_create: {
+ input: ViewCreateMutationInput;
+ output: ViewCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/operations/mutations/view-delete.ts b/desktop/src/operations/mutations/view-delete.ts
new file mode 100644
index 00000000..3493c58b
--- /dev/null
+++ b/desktop/src/operations/mutations/view-delete.ts
@@ -0,0 +1,19 @@
+export type ViewDeleteMutationInput = {
+ type: 'view_delete';
+ userId: string;
+ databaseId: string;
+ viewId: string;
+};
+
+export type ViewDeleteMutationOutput = {
+ id: string;
+};
+
+declare module '@/operations/mutations' {
+ interface MutationMap {
+ view_delete: {
+ input: ViewDeleteMutationInput;
+ output: ViewDeleteMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/operations/mutations/view-update.ts b/desktop/src/operations/mutations/view-update.ts
new file mode 100644
index 00000000..12a29ce2
--- /dev/null
+++ b/desktop/src/operations/mutations/view-update.ts
@@ -0,0 +1,21 @@
+import { ViewAttributes } from '@/registry';
+
+export type ViewUpdateMutationInput = {
+ type: 'view_update';
+ userId: string;
+ databaseId: string;
+ view: ViewAttributes;
+};
+
+export type ViewUpdateMutationOutput = {
+ id: string;
+};
+
+declare module '@/operations/mutations' {
+ interface MutationMap {
+ view_update: {
+ input: ViewUpdateMutationInput;
+ output: ViewUpdateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/operations/queries/chat-get.ts b/desktop/src/operations/queries/chat-get.ts
index 161032c5..957dd6de 100644
--- a/desktop/src/operations/queries/chat-get.ts
+++ b/desktop/src/operations/queries/chat-get.ts
@@ -10,7 +10,7 @@ declare module '@/operations/queries' {
interface QueryMap {
chat_get: {
input: ChatGetQueryInput;
- output: ChatNode;
+ output: ChatNode | null;
};
}
}
diff --git a/desktop/src/operations/queries/database-get.ts b/desktop/src/operations/queries/database-get.ts
deleted file mode 100644
index 2a9a1938..00000000
--- a/desktop/src/operations/queries/database-get.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { DatabaseNode } from '@/types/databases';
-
-export type DatabaseGetQueryInput = {
- type: 'database_get';
- databaseId: string;
- userId: string;
-};
-
-declare module '@/operations/queries' {
- interface QueryMap {
- database_get: {
- input: DatabaseGetQueryInput;
- output: DatabaseNode;
- };
- }
-}
diff --git a/desktop/src/operations/queries/database-view-list.ts b/desktop/src/operations/queries/database-view-list.ts
deleted file mode 100644
index f1caac72..00000000
--- a/desktop/src/operations/queries/database-view-list.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { ViewNode } from '@/types/databases';
-
-export type DatabaseViewListQueryInput = {
- type: 'database_view_list';
- databaseId: string;
- userId: string;
-};
-
-declare module '@/operations/queries' {
- interface QueryMap {
- database_view_list: {
- input: DatabaseViewListQueryInput;
- output: ViewNode[];
- };
- }
-}
diff --git a/desktop/src/operations/queries/file-get.ts b/desktop/src/operations/queries/file-get.ts
index 177be51a..96a63b54 100644
--- a/desktop/src/operations/queries/file-get.ts
+++ b/desktop/src/operations/queries/file-get.ts
@@ -10,7 +10,7 @@ declare module '@/operations/queries' {
interface QueryMap {
file_get: {
input: FileGetQueryInput;
- output: FileDetails;
+ output: FileDetails | null;
};
}
}
diff --git a/desktop/src/operations/queries/record-get.ts b/desktop/src/operations/queries/record-get.ts
deleted file mode 100644
index 8e167899..00000000
--- a/desktop/src/operations/queries/record-get.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { RecordNode } from '@/types/databases';
-
-export type RecordGetQueryInput = {
- type: 'record_get';
- recordId: string;
- userId: string;
-};
-
-declare module '@/operations/queries' {
- interface QueryMap {
- record_get: {
- input: RecordGetQueryInput;
- output: RecordNode;
- };
- }
-}
diff --git a/desktop/src/operations/queries/record-list.ts b/desktop/src/operations/queries/record-list.ts
index 42b97255..63010695 100644
--- a/desktop/src/operations/queries/record-list.ts
+++ b/desktop/src/operations/queries/record-list.ts
@@ -1,10 +1,11 @@
-import { RecordNode, ViewFilter, ViewSort } from '@/types/databases';
+import { RecordNode } from '@/types/nodes';
+import { ViewFilterAttributes, ViewSortAttributes } from '@/registry';
export type RecordListQueryInput = {
type: 'record_list';
databaseId: string;
- filters: ViewFilter[];
- sorts: ViewSort[];
+ filters: ViewFilterAttributes[];
+ sorts: ViewSortAttributes[];
page: number;
count: number;
userId: string;
diff --git a/desktop/src/operations/queries/workspace-user-list.ts b/desktop/src/operations/queries/workspace-user-list.ts
index b5d1b3a3..2501880d 100644
--- a/desktop/src/operations/queries/workspace-user-list.ts
+++ b/desktop/src/operations/queries/workspace-user-list.ts
@@ -1,4 +1,4 @@
-import { LocalNode } from '@/types/nodes';
+import { UserNode } from '@/types/nodes';
export type WorkspaceUserListQueryInput = {
type: 'workspace_user_list';
@@ -11,7 +11,7 @@ declare module '@/operations/queries' {
interface QueryMap {
workspace_user_list: {
input: WorkspaceUserListQueryInput;
- output: LocalNode[];
+ output: UserNode[];
};
}
}
diff --git a/desktop/src/registry/block.ts b/desktop/src/registry/block.ts
new file mode 100644
index 00000000..ea45b82c
--- /dev/null
+++ b/desktop/src/registry/block.ts
@@ -0,0 +1,28 @@
+import { ZodText } from '@/registry/zod';
+import { z } from 'zod';
+
+export const blockLeafSchema = z.object({
+ type: z.string(),
+ text: ZodText.create(),
+ marks: z
+ .array(
+ z.object({
+ type: z.string(),
+ attrs: z.record(z.any()).nullable(),
+ }),
+ )
+ .nullable(),
+});
+
+export type BlockLeaf = z.infer<typeof blockLeafSchema>;
+
+export const blockSchema = z.object({
+ id: z.string(),
+ type: z.string(),
+ parentId: z.string(),
+ content: z.array(blockLeafSchema).nullable(),
+ attrs: z.record(z.any()).nullable(),
+ index: z.string(),
+});
+
+export type Block = z.infer<typeof blockSchema>;
diff --git a/desktop/src/registry/channel.ts b/desktop/src/registry/channel.ts
new file mode 100644
index 00000000..ce4cdfb8
--- /dev/null
+++ b/desktop/src/registry/channel.ts
@@ -0,0 +1,18 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+
+export const channelAttributesSchema = z.object({
+ type: z.literal('channel'),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+ parentId: z.string(),
+ index: z.string(),
+ collaborators: z.record(z.string()).nullable().optional(),
+});
+
+export type ChannelAttributes = z.infer<typeof channelAttributesSchema>;
+
+export const ChannelRegistry: NodeRegistry = {
+ type: 'channel',
+ schema: channelAttributesSchema,
+};
diff --git a/desktop/src/registry/chat.ts b/desktop/src/registry/chat.ts
new file mode 100644
index 00000000..adf777b2
--- /dev/null
+++ b/desktop/src/registry/chat.ts
@@ -0,0 +1,15 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+
+export const chatAttributesSchema = z.object({
+ type: z.literal('chat'),
+ parentId: z.string(),
+ collaborators: z.record(z.string()),
+});
+
+export type ChatAttributes = z.infer<typeof chatAttributesSchema>;
+
+export const ChatRegistry: NodeRegistry = {
+ type: 'chat',
+ schema: chatAttributesSchema,
+};
diff --git a/desktop/src/registry/core.ts b/desktop/src/registry/core.ts
new file mode 100644
index 00000000..b046deec
--- /dev/null
+++ b/desktop/src/registry/core.ts
@@ -0,0 +1,6 @@
+import { ZodSchema } from 'zod';
+
+export interface NodeRegistry {
+ type: string;
+ schema: ZodSchema;
+}
diff --git a/desktop/src/registry/database.ts b/desktop/src/registry/database.ts
new file mode 100644
index 00000000..e3f6a618
--- /dev/null
+++ b/desktop/src/registry/database.ts
@@ -0,0 +1,84 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+import { fieldAttributesSchema } from '@/registry/fields';
+
+export const viewFieldAttributesSchema = z.object({
+ id: z.string(),
+ width: z.number().nullable().optional(),
+ display: z.boolean().nullable().optional(),
+ index: z.string().nullable().optional(),
+});
+
+export type ViewFieldAttributes = z.infer<typeof viewFieldAttributesSchema>;
+
+export const viewFieldFilterAttributesSchema = z.object({
+ id: z.string(),
+ fieldId: z.string(),
+ type: z.literal('field'),
+ operator: z.string(),
+ value: z
+ .union([z.string(), z.number(), z.boolean(), z.array(z.string())])
+ .nullable(),
+});
+
+export type ViewFieldFilterAttributes = z.infer<
+ typeof viewFieldFilterAttributesSchema
+>;
+
+export const viewGroupFilterAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('group'),
+ operator: z.enum(['and', 'or']),
+ filters: z.array(viewFieldFilterAttributesSchema),
+});
+
+export type ViewGroupFilterAttributes = z.infer<
+ typeof viewGroupFilterAttributesSchema
+>;
+
+export const viewSortAttributesSchema = z.object({
+ id: z.string(),
+ fieldId: z.string(),
+ direction: z.enum(['asc', 'desc']),
+});
+
+export type ViewSortAttributes = z.infer<typeof viewSortAttributesSchema>;
+
+export const viewFilterAttributesSchema = z.discriminatedUnion('type', [
+ viewFieldFilterAttributesSchema,
+ viewGroupFilterAttributesSchema,
+]);
+
+export type ViewFilterAttributes = z.infer<typeof viewFilterAttributesSchema>;
+
+export const viewAttributesSchema = z.object({
+ id: z.string(),
+ type: z.enum(['table', 'board', 'calendar']),
+ name: z.string(),
+ avatar: z.string().nullable(),
+ index: z.string(),
+ fields: z.record(z.string(), viewFieldAttributesSchema),
+ filters: z.record(z.string(), viewFilterAttributesSchema),
+ sorts: z.record(z.string(), viewSortAttributesSchema),
+ groupBy: z.string().nullable(),
+ nameWidth: z.number().nullable().optional(),
+});
+
+export type ViewAttributes = z.infer<typeof viewAttributesSchema>;
+
+export const databaseAttributesSchema = z.object({
+ type: z.literal('database'),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+ parentId: z.string(),
+ collaborators: z.record(z.string()).nullable().optional(),
+ fields: z.record(z.string(), fieldAttributesSchema),
+ views: z.record(z.string(), viewAttributesSchema),
+});
+
+export type DatabaseAttributes = z.infer<typeof databaseAttributesSchema>;
+
+export const DatabaseRegistry: NodeRegistry = {
+ type: 'database',
+ schema: databaseAttributesSchema,
+};
diff --git a/desktop/src/registry/fields.ts b/desktop/src/registry/fields.ts
new file mode 100644
index 00000000..176058bb
--- /dev/null
+++ b/desktop/src/registry/fields.ts
@@ -0,0 +1,347 @@
+import { z } from 'zod';
+import { ZodText } from './zod';
+
+export const selectOptionAttributesSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ color: z.string(),
+ index: z.string(),
+});
+
+export type SelectOptionAttributes = z.infer<
+ typeof selectOptionAttributesSchema
+>;
+
+export const booleanFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('boolean'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type BooleanFieldAttributes = z.infer<
+ typeof booleanFieldAttributesSchema
+>;
+
+export const booleanFieldValueSchema = z.object({
+ type: z.literal('boolean'),
+ value: z.boolean(),
+});
+
+export type BooleanFieldValue = z.infer<typeof booleanFieldValueSchema>;
+
+export const collaboratorFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('collaborator'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type CollaboratorFieldAttributes = z.infer<
+ typeof collaboratorFieldAttributesSchema
+>;
+
+export const collaboratorFieldValueSchema = z.object({
+ type: z.literal('collaborator'),
+ value: z.array(z.string()),
+});
+
+export type CollaboratorFieldValue = z.infer<
+ typeof collaboratorFieldValueSchema
+>;
+
+export const createdAtFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('createdAt'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type CreatedAtFieldAttributes = z.infer<
+ typeof createdAtFieldAttributesSchema
+>;
+
+export const createdAtFieldValueSchema = z.object({
+ type: z.literal('createdAt'),
+ value: z.string(),
+});
+
+export type CreatedAtFieldValue = z.infer<typeof createdAtFieldValueSchema>;
+
+export const createdByFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('createdBy'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type CreatedByFieldAttributes = z.infer<
+ typeof createdByFieldAttributesSchema
+>;
+
+export const createdByFieldValueSchema = z.object({
+ type: z.literal('createdBy'),
+ value: z.string(),
+});
+
+export type CreatedByFieldValue = z.infer<typeof createdByFieldValueSchema>;
+
+export const dateFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('date'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type DateFieldAttributes = z.infer<typeof dateFieldAttributesSchema>;
+
+export const dateFieldValueSchema = z.object({
+ type: z.literal('date'),
+ value: z.string(),
+});
+
+export type DateFieldValue = z.infer<typeof dateFieldValueSchema>;
+
+export const emailFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('email'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type EmailFieldAttributes = z.infer<typeof emailFieldAttributesSchema>;
+
+export const emailFieldValueSchema = z.object({
+ type: z.literal('email'),
+ value: z.string(),
+});
+
+export type EmailFieldValue = z.infer<typeof emailFieldValueSchema>;
+
+export const fileFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('file'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type FileFieldAttributes = z.infer<typeof fileFieldAttributesSchema>;
+
+export const fileFieldValueSchema = z.object({
+ type: z.literal('file'),
+ value: z.string(),
+});
+
+export type FileFieldValue = z.infer<typeof fileFieldValueSchema>;
+
+export const multiSelectFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('multiSelect'),
+ name: z.string(),
+ index: z.string(),
+ options: z.record(z.string(), selectOptionAttributesSchema).optional(),
+});
+
+export type MultiSelectFieldAttributes = z.infer<
+ typeof multiSelectFieldAttributesSchema
+>;
+
+export const multiSelectFieldValueSchema = z.object({
+ type: z.literal('multiSelect'),
+ value: z.array(z.string()),
+});
+
+export type MultiSelectFieldValue = z.infer<typeof multiSelectFieldValueSchema>;
+
+export const numberFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('number'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type NumberFieldAttributes = z.infer<typeof numberFieldAttributesSchema>;
+
+export const numberFieldValueSchema = z.object({
+ type: z.literal('number'),
+ value: z.number(),
+});
+
+export type NumberFieldValue = z.infer<typeof numberFieldValueSchema>;
+
+export const phoneFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('phone'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type PhoneFieldAttributes = z.infer<typeof phoneFieldAttributesSchema>;
+
+export const phoneFieldValueSchema = z.object({
+ type: z.literal('phone'),
+ value: z.string(),
+});
+
+export type PhoneFieldValue = z.infer<typeof phoneFieldValueSchema>;
+
+export const relationFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('relation'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type RelationFieldAttributes = z.infer<
+ typeof relationFieldAttributesSchema
+>;
+
+export const relationFieldValueSchema = z.object({
+ type: z.literal('relation'),
+ value: z.array(z.string()),
+});
+
+export type RelationFieldValue = z.infer<typeof relationFieldValueSchema>;
+
+export const rollupFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('rollup'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type RollupFieldAttributes = z.infer<typeof rollupFieldAttributesSchema>;
+
+export const rollupFieldValueSchema = z.object({
+ type: z.literal('rollup'),
+ value: z.string(),
+});
+
+export type RollupFieldValue = z.infer<typeof rollupFieldValueSchema>;
+
+export const selectFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('select'),
+ name: z.string(),
+ index: z.string(),
+ options: z.record(z.string(), selectOptionAttributesSchema).optional(),
+});
+
+export type SelectFieldAttributes = z.infer<typeof selectFieldAttributesSchema>;
+
+export const selectFieldValueSchema = z.object({
+ type: z.literal('select'),
+ value: z.string(),
+});
+
+export type SelectFieldValue = z.infer<typeof selectFieldValueSchema>;
+
+export const textFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('text'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type TextFieldAttributes = z.infer<typeof textFieldAttributesSchema>;
+
+export const textFieldValueSchema = z.object({
+ type: z.literal('text'),
+ value: ZodText.create(),
+});
+
+export type TextFieldValue = z.infer<typeof textFieldValueSchema>;
+
+export const urlFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('url'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type UrlFieldAttributes = z.infer<typeof urlFieldAttributesSchema>;
+
+export const urlFieldValueSchema = z.object({
+ type: z.literal('url'),
+ value: z.string(),
+});
+
+export const updatedAtFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('updatedAt'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type UpdatedAtFieldAttributes = z.infer<
+ typeof updatedAtFieldAttributesSchema
+>;
+
+export const updatedAtFieldValueSchema = z.object({
+ type: z.literal('updatedAt'),
+ value: z.string(),
+});
+
+export type UpdatedAtFieldValue = z.infer<typeof updatedAtFieldValueSchema>;
+
+export const updatedByFieldAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('updatedBy'),
+ name: z.string(),
+ index: z.string(),
+});
+
+export type UpdatedByFieldAttributes = z.infer<
+ typeof updatedByFieldAttributesSchema
+>;
+
+export const updatedByFieldValueSchema = z.object({
+ type: z.literal('updatedBy'),
+ value: z.string(),
+});
+
+export const fieldAttributesSchema = z.discriminatedUnion('type', [
+ booleanFieldAttributesSchema,
+ collaboratorFieldAttributesSchema,
+ createdAtFieldAttributesSchema,
+ createdByFieldAttributesSchema,
+ dateFieldAttributesSchema,
+ emailFieldAttributesSchema,
+ fileFieldAttributesSchema,
+ multiSelectFieldAttributesSchema,
+ numberFieldAttributesSchema,
+ phoneFieldAttributesSchema,
+ relationFieldAttributesSchema,
+ rollupFieldAttributesSchema,
+ selectFieldAttributesSchema,
+ textFieldAttributesSchema,
+ urlFieldAttributesSchema,
+ updatedAtFieldAttributesSchema,
+ updatedByFieldAttributesSchema,
+]);
+
+export type FieldAttributes = z.infer<typeof fieldAttributesSchema>;
+
+export const fieldValueSchema = z.discriminatedUnion('type', [
+ booleanFieldValueSchema,
+ collaboratorFieldValueSchema,
+ createdAtFieldValueSchema,
+ createdByFieldValueSchema,
+ dateFieldValueSchema,
+ emailFieldValueSchema,
+ fileFieldValueSchema,
+ multiSelectFieldValueSchema,
+ numberFieldValueSchema,
+ phoneFieldValueSchema,
+ relationFieldValueSchema,
+ rollupFieldValueSchema,
+ selectFieldValueSchema,
+ textFieldValueSchema,
+ urlFieldValueSchema,
+ updatedAtFieldValueSchema,
+ updatedByFieldValueSchema,
+]);
+
+export type FieldValue = z.infer<typeof fieldValueSchema>;
+
+export type FieldType = Extract<FieldAttributes['type'], string>;
diff --git a/desktop/src/registry/file.ts b/desktop/src/registry/file.ts
new file mode 100644
index 00000000..18cad4b5
--- /dev/null
+++ b/desktop/src/registry/file.ts
@@ -0,0 +1,19 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+
+export const fileAttributesSchema = z.object({
+ type: z.literal('file'),
+ name: z.string(),
+ parentId: z.string(),
+ mimeType: z.string(),
+ size: z.number(),
+ extension: z.string(),
+ fileName: z.string(),
+});
+
+export type FileAttributes = z.infer<typeof fileAttributesSchema>;
+
+export const FileRegistry: NodeRegistry = {
+ type: 'file',
+ schema: fileAttributesSchema,
+};
diff --git a/desktop/src/registry/folder.ts b/desktop/src/registry/folder.ts
new file mode 100644
index 00000000..99ef9ff4
--- /dev/null
+++ b/desktop/src/registry/folder.ts
@@ -0,0 +1,17 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+
+export const folderAttributesSchema = z.object({
+ type: z.literal('folder'),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+ parentId: z.string(),
+ collaborators: z.record(z.string()).nullable().optional(),
+});
+
+export type FolderAttributes = z.infer<typeof folderAttributesSchema>;
+
+export const FolderRegistry: NodeRegistry = {
+ type: 'folder',
+ schema: folderAttributesSchema,
+};
diff --git a/desktop/src/registry/index.ts b/desktop/src/registry/index.ts
new file mode 100644
index 00000000..b660d46a
--- /dev/null
+++ b/desktop/src/registry/index.ts
@@ -0,0 +1,38 @@
+import { ChannelRegistry } from '@/registry/channel';
+import { NodeRegistry } from '@/registry/core';
+import { PageRegistry } from '@/registry/page';
+import { ChatRegistry } from '@/registry/chat';
+import { SpaceRegistry } from '@/registry/space';
+import { UserRegistry } from '@/registry/user';
+import { MessageRegistry } from '@/registry/message';
+import { DatabaseRegistry } from '@/registry/database';
+import { FileRegistry } from '@/registry/file';
+import { FolderRegistry } from '@/registry/folder';
+import { RecordRegistry } from '@/registry/record';
+
+export * from '@/registry/channel';
+export * from '@/registry/core';
+export * from '@/registry/page';
+export * from '@/registry/chat';
+export * from '@/registry/space';
+export * from '@/registry/user';
+export * from '@/registry/message';
+export * from '@/registry/database';
+export * from '@/registry/file';
+export * from '@/registry/folder';
+export * from '@/registry/record';
+export * from '@/registry/block';
+export * from '@/registry/fields';
+
+export const registryMap: Record<string, NodeRegistry> = {
+ channel: ChannelRegistry,
+ chat: ChatRegistry,
+ database: DatabaseRegistry,
+ file: FileRegistry,
+ folder: FolderRegistry,
+ message: MessageRegistry,
+ page: PageRegistry,
+ record: RecordRegistry,
+ space: SpaceRegistry,
+ user: UserRegistry,
+};
diff --git a/desktop/src/registry/message.ts b/desktop/src/registry/message.ts
new file mode 100644
index 00000000..29c8f967
--- /dev/null
+++ b/desktop/src/registry/message.ts
@@ -0,0 +1,17 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+import { blockSchema } from '@/registry/block';
+
+export const messageAttributesSchema = z.object({
+ type: z.literal('message'),
+ parentId: z.string().nullable(),
+ content: z.record(z.string(), blockSchema),
+ reactions: z.record(z.array(z.string())),
+});
+
+export type MessageAttributes = z.infer<typeof messageAttributesSchema>;
+
+export const MessageRegistry: NodeRegistry = {
+ type: 'message',
+ schema: messageAttributesSchema,
+};
diff --git a/desktop/src/registry/page.ts b/desktop/src/registry/page.ts
new file mode 100644
index 00000000..c5b74613
--- /dev/null
+++ b/desktop/src/registry/page.ts
@@ -0,0 +1,19 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+import { blockSchema } from '@/registry/block';
+
+export const pageAttributesSchema = z.object({
+ type: z.literal('page'),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+ parentId: z.string(),
+ content: z.record(blockSchema),
+ collaborators: z.record(z.string()).nullable().optional(),
+});
+
+export type PageAttributes = z.infer<typeof pageAttributesSchema>;
+
+export const PageRegistry: NodeRegistry = {
+ type: 'page',
+ schema: pageAttributesSchema,
+};
diff --git a/desktop/src/registry/record.ts b/desktop/src/registry/record.ts
new file mode 100644
index 00000000..244b8735
--- /dev/null
+++ b/desktop/src/registry/record.ts
@@ -0,0 +1,20 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+import { fieldValueSchema } from '@/registry/fields';
+import { blockSchema } from '@/registry/block';
+export const recordAttributesSchema = z.object({
+ type: z.literal('record'),
+ parentId: z.string(),
+ databaseId: z.string(),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+ fields: z.record(z.string(), fieldValueSchema),
+ content: z.record(blockSchema),
+});
+
+export type RecordAttributes = z.infer<typeof recordAttributesSchema>;
+
+export const RecordRegistry: NodeRegistry = {
+ type: 'record',
+ schema: recordAttributesSchema,
+};
diff --git a/desktop/src/registry/space.ts b/desktop/src/registry/space.ts
new file mode 100644
index 00000000..c7b9957e
--- /dev/null
+++ b/desktop/src/registry/space.ts
@@ -0,0 +1,18 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+
+export const spaceAttributesSchema = z.object({
+ type: z.literal('space'),
+ name: z.string(),
+ parentId: z.string(),
+ description: z.string().nullable(),
+ avatar: z.string().nullable().optional(),
+ collaborators: z.record(z.string()),
+});
+
+export type SpaceAttributes = z.infer<typeof spaceAttributesSchema>;
+
+export const SpaceRegistry: NodeRegistry = {
+ type: 'space',
+ schema: spaceAttributesSchema,
+};
diff --git a/desktop/src/registry/user.ts b/desktop/src/registry/user.ts
new file mode 100644
index 00000000..4ed9d7d1
--- /dev/null
+++ b/desktop/src/registry/user.ts
@@ -0,0 +1,20 @@
+import { z } from 'zod';
+import { NodeRegistry } from '@/registry/core';
+import { WorkspaceRole } from '@/types/workspaces';
+
+export const userAttributesSchema = z.object({
+ type: z.literal('user'),
+ name: z.string(),
+ parentId: z.string(),
+ email: z.string().email(),
+ avatar: z.string().nullable(),
+ accountId: z.string(),
+ role: z.nativeEnum(WorkspaceRole),
+});
+
+export type UserAttributes = z.infer<typeof userAttributesSchema>;
+
+export const UserRegistry: NodeRegistry = {
+ type: 'user',
+ schema: userAttributesSchema,
+};
diff --git a/desktop/src/registry/zod.ts b/desktop/src/registry/zod.ts
new file mode 100644
index 00000000..1b87d3bb
--- /dev/null
+++ b/desktop/src/registry/zod.ts
@@ -0,0 +1,28 @@
+import {
+ ZodType,
+ ZodTypeDef,
+ ParseInput,
+ ParseReturnType,
+ INVALID,
+ OK,
+} from 'zod';
+
+export class ZodText extends ZodType<string, ZodTypeDef, string> {
+ constructor() {
+ super({
+ description: 'Text',
+ });
+ }
+
+ _parse(input: ParseInput): ParseReturnType<string> {
+ if (typeof input.data !== 'string') {
+ return INVALID;
+ }
+
+ return OK(input.data);
+ }
+
+ static create(): ZodText {
+ return new ZodText();
+ }
+}
diff --git a/desktop/src/renderer/components/accounts/login.tsx b/desktop/src/renderer/components/accounts/login.tsx
index 5caac623..d8503e79 100644
--- a/desktop/src/renderer/components/accounts/login.tsx
+++ b/desktop/src/renderer/components/accounts/login.tsx
@@ -22,7 +22,7 @@ export const Login = () => {
Use one of the following methods to login
</p>
</div>
- {isPending ? null : <LoginForm servers={data} />}
+ {isPending ? null : <LoginForm servers={data ?? []} />}
</div>
</div>
</div>
diff --git a/desktop/src/renderer/components/app.tsx b/desktop/src/renderer/components/app.tsx
index b5df56cb..724366bd 100644
--- a/desktop/src/renderer/components/app.tsx
+++ b/desktop/src/renderer/components/app.tsx
@@ -33,26 +33,26 @@ export const App = () => {
);
}
- if (accounts.length == 0) {
+ if (!accounts || accounts.length === 0) {
return <Login />;
}
const account = accounts[0];
- const server = servers.find((server) => server.domain === account.server);
+ const server = servers?.find((server) => server.domain === account?.server);
if (!server) {
return <p>Server not found.</p>;
}
- const accountWorkspaces = workspaces.filter(
- (workspace) => workspace.accountId === account.id,
+ const accountWorkspaces = workspaces?.filter(
+ (workspace) => workspace.accountId === account?.id,
);
return (
<AccountContext.Provider
value={{
...account,
- workspaces: accountWorkspaces,
+ workspaces: accountWorkspaces ?? [],
logout: () => {
setShowLogout(true);
},
@@ -64,7 +64,7 @@ export const App = () => {
<Outlet />
{showLogout && (
<AccountLogout
- id={account.id}
+ id={account?.id ?? ''}
onCancel={() => {
setShowLogout(false);
}}
@@ -75,7 +75,7 @@ export const App = () => {
)}
{showAccountSettings && (
<AccountSettingsDialog
- id={account.id}
+ id={account?.id ?? ''}
open={showAccountSettings}
onOpenChange={setShowAccountSettings}
/>
diff --git a/desktop/src/renderer/components/avatars/avatar-upload.tsx b/desktop/src/renderer/components/avatars/avatar-upload.tsx
index 24debd4b..05403795 100644
--- a/desktop/src/renderer/components/avatars/avatar-upload.tsx
+++ b/desktop/src/renderer/components/avatars/avatar-upload.tsx
@@ -17,7 +17,7 @@ export const AvatarUpload = ({ onUpload }: AvatarUploadProps) => {
const [url, setUrl] = React.useState<string | undefined>(undefined);
const handleSubmit = async (url: string) => {
- console.log(url);
+ // TODO
};
return (
diff --git a/desktop/src/renderer/components/avatars/avatar.tsx b/desktop/src/renderer/components/avatars/avatar.tsx
index 704dcd74..075759c3 100644
--- a/desktop/src/renderer/components/avatars/avatar.tsx
+++ b/desktop/src/renderer/components/avatars/avatar.tsx
@@ -13,8 +13,8 @@ import { useAccount } from '@/renderer/contexts/account';
interface AvatarProps {
id: string;
- name: string;
- avatar?: string;
+ name?: string | null;
+ avatar?: string | null;
size?: 'small' | 'medium' | 'large' | 'extra-large';
className?: string;
}
@@ -70,6 +70,10 @@ const AvatarFallback = ({ id, name, size, className }: AvatarProps) => {
};
const EmojiAvatar = ({ avatar, size, className }: AvatarProps) => {
+ if (!avatar) {
+ return null;
+ }
+
const url = getEmojiUrl(avatar);
return (
<img
@@ -81,6 +85,10 @@ const EmojiAvatar = ({ avatar, size, className }: AvatarProps) => {
};
const IconAvatar = ({ avatar, size, className }: AvatarProps) => {
+ if (!avatar) {
+ return null;
+ }
+
const url = getIconUrl(avatar);
return (
<img
@@ -93,8 +101,12 @@ const IconAvatar = ({ avatar, size, className }: AvatarProps) => {
const CustomAvatar = ({ avatar, size, className }: AvatarProps) => {
const server = useAccount();
- const url = getAvatarUrl(server.id, avatar);
+ if (!avatar) {
+ return null;
+ }
+
+ const url = getAvatarUrl(server.id, avatar);
return (
<img
src={url}
diff --git a/desktop/src/renderer/components/chats/chat-create-command.tsx b/desktop/src/renderer/components/chats/chat-create-command.tsx
index 09b60fd7..3c703ae9 100644
--- a/desktop/src/renderer/components/chats/chat-create-command.tsx
+++ b/desktop/src/renderer/components/chats/chat-create-command.tsx
@@ -44,6 +44,7 @@ export const ChatCreateCommand = () => {
type: 'chat_create',
userId: workspace.userId,
otherUserId: user.id,
+ workspaceId: workspace.id,
},
onSuccess(output) {
workspace.navigateToNode(output.id);
diff --git a/desktop/src/renderer/components/collaborators/node-collaborators.tsx b/desktop/src/renderer/components/collaborators/node-collaborators.tsx
index 49e492be..5ce1e9c7 100644
--- a/desktop/src/renderer/components/collaborators/node-collaborators.tsx
+++ b/desktop/src/renderer/components/collaborators/node-collaborators.tsx
@@ -17,7 +17,7 @@ export const NodeCollaborators = ({ nodeId }: NodeCollaboratorsProps) => {
userId: workspace.userId,
});
- if (isPending) {
+ if (isPending || !data) {
return null;
}
diff --git a/desktop/src/renderer/components/databases/boards/board-view-card.tsx b/desktop/src/renderer/components/databases/boards/board-view-card.tsx
index 574c5cbf..b24bf547 100644
--- a/desktop/src/renderer/components/databases/boards/board-view-card.tsx
+++ b/desktop/src/renderer/components/databases/boards/board-view-card.tsx
@@ -1,11 +1,8 @@
import React from 'react';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
-import {
- RecordNode,
- SelectFieldNode,
- SelectOptionNode,
-} from '@/types/databases';
+import { RecordNode } from '@/types/nodes';
+import { SelectFieldAttributes, SelectOptionAttributes } from '@/registry';
import { useDrag } from 'react-dnd';
import { cn } from '@/lib/utils';
@@ -14,8 +11,8 @@ interface BoardViewCardProps {
}
interface DragResult {
- option: SelectOptionNode;
- field: SelectFieldNode;
+ option: SelectOptionAttributes;
+ field: SelectFieldAttributes;
}
export const BoardViewCard = ({ record }: BoardViewCardProps) => {
@@ -32,9 +29,11 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
const optionId = dropResult.option.id;
const fieldId = dropResult.field.id;
- const currentOptionId = record.attributes[fieldId] as
- | string
- | undefined;
+ const currentFieldValue = record.attributes.fields[fieldId];
+ const currentOptionId =
+ currentFieldValue?.type === 'select'
+ ? currentFieldValue.value
+ : undefined;
if (currentOptionId === optionId) {
return;
@@ -44,7 +43,7 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
input: {
type: 'node_attribute_set',
nodeId: record.id,
- attribute: fieldId,
+ path: fieldId,
value: optionId,
userId: workspace.userId,
},
@@ -55,7 +54,7 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
const buttonRef = React.useRef<HTMLButtonElement>(null);
const dragRef = drag(buttonRef);
- const name = record.name;
+ const name = record.attributes.name;
const hasName = name !== null && name !== '';
return (
@@ -69,7 +68,7 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
)}
onClick={() => workspace.openModal(record.id)}
>
- {record.name ?? 'Unnamed'}
+ {name ?? 'Unnamed'}
</button>
);
};
diff --git a/desktop/src/renderer/components/databases/boards/board-view-column-header.tsx b/desktop/src/renderer/components/databases/boards/board-view-column-header.tsx
index 0d7f7fad..474059b1 100644
--- a/desktop/src/renderer/components/databases/boards/board-view-column-header.tsx
+++ b/desktop/src/renderer/components/databases/boards/board-view-column-header.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
-import { SelectOptionNode } from '@/types/databases';
+import { SelectOptionAttributes } from '@/registry';
interface BoardViewColumnHeaderProps {
- option: SelectOptionNode;
+ option: SelectOptionAttributes;
}
export const BoardViewColumnHeader = ({
diff --git a/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx b/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx
index 6391e57f..90b5b35b 100644
--- a/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx
+++ b/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx
@@ -2,31 +2,30 @@ import React from 'react';
import { useDatabase } from '@/renderer/contexts/database';
import { useInfiniteQuery } from '@/renderer/hooks/use-infinite-query';
import {
- BoardViewNode,
- SelectFieldNode,
- SelectOptionNode,
- ViewFilter,
-} from '@/types/databases';
+ SelectFieldAttributes,
+ SelectOptionAttributes,
+ ViewFilterAttributes,
+} from '@/registry';
import { BoardViewCard } from '@/renderer/components/databases/boards/board-view-card';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useView } from '@/renderer/contexts/view';
const RECORDS_PER_PAGE = 50;
interface BoardViewColumnRecordsProps {
- view: BoardViewNode;
- field: SelectFieldNode;
- option: SelectOptionNode;
+ field: SelectFieldAttributes;
+ option: SelectOptionAttributes;
}
export const BoardViewColumnRecords = ({
- view,
field,
option,
}: BoardViewColumnRecordsProps) => {
const workspace = useWorkspace();
const database = useDatabase();
+ const view = useView();
- const filters: ViewFilter[] = [
+ const filters: ViewFilterAttributes[] = [
...view.filters,
{
id: '1',
@@ -61,7 +60,7 @@ export const BoardViewColumnRecords = ({
type: 'record_list',
databaseId: database.id,
filters: filters,
- sorts: view.sorts,
+ sorts: Object.values(view.sorts),
page: page,
count: RECORDS_PER_PAGE,
userId: workspace.userId,
diff --git a/desktop/src/renderer/components/databases/boards/board-view-column.tsx b/desktop/src/renderer/components/databases/boards/board-view-column.tsx
index 946eb090..c7e839ff 100644
--- a/desktop/src/renderer/components/databases/boards/board-view-column.tsx
+++ b/desktop/src/renderer/components/databases/boards/board-view-column.tsx
@@ -1,26 +1,17 @@
import React from 'react';
import { getSelectOptionLightColorClass } from '@/lib/databases';
import { cn } from '@/lib/utils';
-import {
- BoardViewNode,
- SelectFieldNode,
- SelectOptionNode,
-} from '@/types/databases';
import { useDrop } from 'react-dnd';
+import { SelectFieldAttributes, SelectOptionAttributes } from '@/registry';
import { BoardViewColumnHeader } from '@/renderer/components/databases/boards/board-view-column-header';
import { BoardViewColumnRecords } from '@/renderer/components/databases/boards/board-view-column-records';
interface BoardViewColumnProps {
- view: BoardViewNode;
- field: SelectFieldNode;
- option: SelectOptionNode;
+ field: SelectFieldAttributes;
+ option: SelectOptionAttributes;
}
-export const BoardViewColumn = ({
- view,
- field,
- option,
-}: BoardViewColumnProps) => {
+export const BoardViewColumn = ({ field, option }: BoardViewColumnProps) => {
const [{ isDragging }, drop] = useDrop({
accept: 'board-record',
drop: () => ({
@@ -47,7 +38,7 @@ export const BoardViewColumn = ({
}}
>
<BoardViewColumnHeader option={option} />
- <BoardViewColumnRecords view={view} field={field} option={option} />
+ <BoardViewColumnRecords field={field} option={option} />
</div>
);
};
diff --git a/desktop/src/renderer/components/databases/boards/board-view.tsx b/desktop/src/renderer/components/databases/boards/board-view.tsx
index 95591aa9..ac0c5b1d 100644
--- a/desktop/src/renderer/components/databases/boards/board-view.tsx
+++ b/desktop/src/renderer/components/databases/boards/board-view.tsx
@@ -1,30 +1,27 @@
import React from 'react';
-import { BoardViewNode } from '@/types/databases';
import { ViewTabs } from '@/renderer/components/databases/view-tabs';
import { useDatabase } from '@/renderer/contexts/database';
import { BoardViewColumn } from '@/renderer/components/databases/boards/board-view-column';
import { ViewSearchBar } from '@/renderer/components/databases/search/view-search-bar';
import { ViewSortButton } from '@/renderer/components/databases/search/view-sort-button';
import { ViewFilterButton } from '@/renderer/components/databases/search/view-filter-button';
-import { ViewSearchProvider } from '@/renderer/components/databases/search/view-search-provider';
+import { useView } from '@/renderer/contexts/view';
-interface BoardViewProps {
- node: BoardViewNode;
-}
-
-export const BoardView = ({ node }: BoardViewProps) => {
+export const BoardView = () => {
const database = useDatabase();
+ const view = useView();
const groupByField = database.fields.find(
- (field) => field.id === node.groupBy,
+ (field) => field.id === view.groupBy,
);
- if (!groupByField || groupByField.dataType !== 'select') {
+ if (!groupByField || groupByField.type !== 'select') {
return null;
}
+ const selectOptions = Object.values(groupByField.options ?? {});
return (
- <ViewSearchProvider id={node.id} filters={node.filters} sorts={node.sorts}>
+ <React.Fragment>
<div className="mt-2 flex flex-row justify-between border-b">
<ViewTabs />
<div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
@@ -34,17 +31,16 @@ export const BoardView = ({ node }: BoardViewProps) => {
</div>
<ViewSearchBar />
<div className="mt-2 flex w-full min-w-full max-w-full flex-row gap-2 overflow-auto pr-5">
- {groupByField.options.map((option) => {
+ {selectOptions.map((option) => {
return (
<BoardViewColumn
key={option.id}
- view={node}
field={groupByField}
option={option}
/>
);
})}
</div>
- </ViewSearchProvider>
+ </React.Fragment>
);
};
diff --git a/desktop/src/renderer/components/databases/calendars/calendar-view-card.tsx b/desktop/src/renderer/components/databases/calendars/calendar-view-card.tsx
index 6fa4ee3d..d2d10d3f 100644
--- a/desktop/src/renderer/components/databases/calendars/calendar-view-card.tsx
+++ b/desktop/src/renderer/components/databases/calendars/calendar-view-card.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import { useWorkspace } from '@/renderer/contexts/workspace';
-import { RecordNode } from '@/types/databases';
+import { RecordNode } from '@/types/nodes';
import { cn } from '@/lib/utils';
interface CalendarViewCardProps {
@@ -10,7 +10,7 @@ interface CalendarViewCardProps {
export const CalendarViewCard = ({ record }: CalendarViewCardProps) => {
const workspace = useWorkspace();
- const name = record.name;
+ const name = record.attributes.name;
const hasName = name !== null && name !== '';
return (
@@ -23,7 +23,7 @@ export const CalendarViewCard = ({ record }: CalendarViewCardProps) => {
)}
onClick={() => workspace.openModal(record.id)}
>
- {record.name ?? 'Unnamed'}
+ {name ?? 'Unnamed'}
</button>
);
};
diff --git a/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx b/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx
index ca3ada62..a3d931bb 100644
--- a/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx
+++ b/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import { cn, isSameDay } from '@/lib/utils';
-import { RecordNode } from '@/types/databases';
+import { RecordNode } from '@/types/nodes';
import { CalendarViewCard } from '@/renderer/components/databases/calendars/calendar-view-card';
import { Plus } from 'lucide-react';
diff --git a/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx b/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx
index 2a16104d..1567285d 100644
--- a/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx
+++ b/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx
@@ -3,28 +3,33 @@ import { buttonVariants } from '@/renderer/components/ui/button';
import { cn, getDisplayedDates, toUTCDate } from '@/lib/utils';
import { DayPicker, DayProps } from 'react-day-picker';
import { CalendarViewDay } from '@/renderer/components/databases/calendars/calendar-view-day';
-import { CalendarViewNode, FieldNode, ViewFilter } from '@/types/databases';
+import {
+ ViewAttributes,
+ FieldAttributes,
+ ViewFilterAttributes,
+} from '@/registry';
import { useInfiniteQuery } from '@/renderer/hooks/use-infinite-query';
import { useDatabase } from '@/renderer/contexts/database';
import { filterRecords } from '@/lib/databases';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { useView } from '@/renderer/contexts/view';
const RECORDS_PER_PAGE = 50;
interface CalendarViewGridProps {
- view: CalendarViewNode;
- field: FieldNode;
+ field: FieldAttributes;
}
-export const CalendarViewGrid = ({ view, field }: CalendarViewGridProps) => {
+export const CalendarViewGrid = ({ field }: CalendarViewGridProps) => {
const workspace = useWorkspace();
const database = useDatabase();
+ const view = useView();
const [month, setMonth] = React.useState(new Date());
const { first, last } = getDisplayedDates(month);
- const filters: ViewFilter[] = [
+ const filters: ViewFilterAttributes[] = [
...view.filters,
{
id: 'start_date',
@@ -67,7 +72,7 @@ export const CalendarViewGrid = ({ view, field }: CalendarViewGridProps) => {
type: 'record_list',
databaseId: database.id,
filters: filters,
- sorts: view.sorts,
+ sorts: Object.values(view.sorts),
page: page,
count: RECORDS_PER_PAGE,
userId: workspace.userId,
@@ -120,7 +125,7 @@ export const CalendarViewGrid = ({ view, field }: CalendarViewGridProps) => {
<ChevronRight className="size-4" {...props} />
),
Day: (props: DayProps) => {
- const filter: ViewFilter = {
+ const filter: ViewFilterAttributes = {
id: 'calendar_filter',
type: 'field',
fieldId: field.id,
diff --git a/desktop/src/renderer/components/databases/calendars/calendar-view.tsx b/desktop/src/renderer/components/databases/calendars/calendar-view.tsx
index e6d68003..6c79aa31 100644
--- a/desktop/src/renderer/components/databases/calendars/calendar-view.tsx
+++ b/desktop/src/renderer/components/databases/calendars/calendar-view.tsx
@@ -1,22 +1,18 @@
import React from 'react';
-import { CalendarViewNode } from '@/types/databases';
import { ViewTabs } from '@/renderer/components/databases/view-tabs';
import { useDatabase } from '@/renderer/contexts/database';
import { CalendarViewGrid } from '@/renderer/components/databases/calendars/calendar-view-grid';
import { ViewSearchBar } from '@/renderer/components/databases/search/view-search-bar';
import { ViewSortButton } from '@/renderer/components/databases/search/view-sort-button';
import { ViewFilterButton } from '@/renderer/components/databases/search/view-filter-button';
-import { ViewSearchProvider } from '@/renderer/components/databases/search/view-search-provider';
+import { useView } from '@/renderer/contexts/view';
-interface CalendarViewProps {
- node: CalendarViewNode;
-}
-
-export const CalendarView = ({ node }: CalendarViewProps) => {
+export const CalendarView = () => {
const database = useDatabase();
+ const view = useView();
const groupByField = database.fields.find(
- (field) => field.id === node.groupBy,
+ (field) => field.id === view.groupBy,
);
if (!groupByField) {
@@ -24,7 +20,7 @@ export const CalendarView = ({ node }: CalendarViewProps) => {
}
return (
- <ViewSearchProvider id={node.id} filters={node.filters} sorts={node.sorts}>
+ <React.Fragment>
<div className="mt-2 flex flex-row justify-between border-b">
<ViewTabs />
<div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
@@ -34,8 +30,8 @@ export const CalendarView = ({ node }: CalendarViewProps) => {
</div>
<ViewSearchBar />
<div className="mt-2 w-full min-w-full max-w-full overflow-auto pr-5">
- <CalendarViewGrid view={node} field={groupByField} />
+ <CalendarViewGrid field={groupByField} />
</div>
- </ViewSearchProvider>
+ </React.Fragment>
);
};
diff --git a/desktop/src/renderer/components/databases/database-container.tsx b/desktop/src/renderer/components/databases/database-container.tsx
index 48180b6a..9e9b0f51 100644
--- a/desktop/src/renderer/components/databases/database-container.tsx
+++ b/desktop/src/renderer/components/databases/database-container.tsx
@@ -1,33 +1,15 @@
import React from 'react';
-import { useQuery } from '@/renderer/hooks/use-query';
import { Database } from '@/renderer/components/databases/database';
import { DatabaseViews } from '@/renderer/components/databases/database-views';
-import { useWorkspace } from '@/renderer/contexts/workspace';
interface DatabaseContainerProps {
nodeId: string;
}
export const DatabaseContainer = ({ nodeId }: DatabaseContainerProps) => {
- const workspace = useWorkspace();
-
- const { data: views, isPending: isViewsPending } = useQuery({
- type: 'database_view_list',
- databaseId: nodeId,
- userId: workspace.userId,
- });
-
- if (isViewsPending) {
- return null;
- }
-
- if (!views) {
- return null;
- }
-
return (
<Database databaseId={nodeId}>
- {views && <DatabaseViews views={views} />}
+ <DatabaseViews />
</Database>
);
};
diff --git a/desktop/src/renderer/components/databases/database-views.tsx b/desktop/src/renderer/components/databases/database-views.tsx
index a510f2c2..2c12b9c1 100644
--- a/desktop/src/renderer/components/databases/database-views.tsx
+++ b/desktop/src/renderer/components/databases/database-views.tsx
@@ -1,29 +1,28 @@
import React from 'react';
import { DatabaseViewsContext } from '@/renderer/contexts/database-views';
-import { ViewNode } from '@/types/databases';
import { View } from '@/renderer/components/databases/view';
import { ScrollArea } from '@/renderer/components/ui/scroll-area';
+import { useDatabase } from '@/renderer/contexts/database';
-interface DatabaseViewsProps {
- views: ViewNode[];
-}
-
-export const DatabaseViews = ({ views }: DatabaseViewsProps) => {
- const [activeViewId, setActiveViewId] = React.useState<string>(views[0].id);
- const activeView = views.find((view) => view.id === activeViewId);
+export const DatabaseViews = () => {
+ const database = useDatabase();
+ const [activeViewId, setActiveViewId] = React.useState<string>(
+ database.views[0].id,
+ );
+ const activeView = database.views.find((view) => view.id === activeViewId);
React.useEffect(() => {
if (!activeView) {
- setActiveViewId(views[0].id);
+ setActiveViewId(database.views[0].id);
}
- }, [views, activeViewId]);
+ }, [database.views, activeViewId]);
return (
<DatabaseViewsContext.Provider
- value={{ views, activeViewId, setActiveViewId }}
+ value={{ views: database.views, activeViewId, setActiveViewId }}
>
<ScrollArea className="group/database h-full max-h-full w-full overflow-y-auto px-10 pb-12">
- {activeView && <View node={activeView} />}
+ {activeView && <View view={activeView} />}
</ScrollArea>
</DatabaseViewsContext.Provider>
);
diff --git a/desktop/src/renderer/components/databases/database.tsx b/desktop/src/renderer/components/databases/database.tsx
index 308c2198..4f9b3d68 100644
--- a/desktop/src/renderer/components/databases/database.tsx
+++ b/desktop/src/renderer/components/databases/database.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import { DatabaseContext } from '@/renderer/contexts/database';
import { useQuery } from '@/renderer/hooks/use-query';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useMutation } from '@/renderer/hooks/use-mutation';
interface DatabaseProps {
databaseId: string;
@@ -10,26 +11,94 @@ interface DatabaseProps {
export const Database = ({ databaseId, children }: DatabaseProps) => {
const workspace = useWorkspace();
- const { data: database, isPending: isDatabasePending } = useQuery({
- type: 'database_get',
- databaseId,
+ const { data, isPending } = useQuery({
+ type: 'node_get',
+ nodeId: databaseId,
userId: workspace.userId,
});
- if (isDatabasePending) {
+ const { mutate, isPending: isMutating } = useMutation();
+
+ if (isPending || isMutating || !data) {
return null;
}
- if (!database) {
+ if (data.type !== 'database') {
return null;
}
return (
<DatabaseContext.Provider
value={{
- id: database.id,
- name: database.name,
- fields: database.fields,
+ id: data.id,
+ name: data.attributes.name,
+ fields: Object.values(data.attributes.fields),
+ views: Object.values(data.attributes.views),
+ createField: (type, name) => {
+ mutate({
+ input: {
+ type: 'field_create',
+ databaseId: data.id,
+ name,
+ fieldType: type,
+ userId: workspace.userId,
+ },
+ });
+ },
+ renameField: (id, name) => {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: data.id,
+ path: `fields.${id}.name`,
+ value: name,
+ userId: workspace.userId,
+ },
+ });
+ },
+ deleteField: (id) => {
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: data.id,
+ path: `fields.${id}`,
+ userId: workspace.userId,
+ },
+ });
+ },
+ createSelectOption: (fieldId, name, color) => {
+ mutate({
+ input: {
+ type: 'select_option_create',
+ databaseId: data.id,
+ fieldId,
+ name,
+ color,
+ userId: workspace.userId,
+ },
+ });
+ },
+ updateSelectOption: (fieldId, attributes) => {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: data.id,
+ path: `fields.${fieldId}.options.${attributes.id}`,
+ value: attributes,
+ userId: workspace.userId,
+ },
+ });
+ },
+ deleteSelectOption: (fieldId, optionId) => {
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: data.id,
+ path: `fields.${fieldId}.options.${optionId}`,
+ userId: workspace.userId,
+ },
+ });
+ },
}}
>
{children}
diff --git a/desktop/src/renderer/components/databases/fields/field-create-popover.tsx b/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
index ed8378ec..ab3e84c1 100644
--- a/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
+++ b/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
@@ -19,7 +19,7 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { useDatabase } from '@/renderer/contexts/database';
-import { FieldDataTypeSelect } from '@/renderer/components/databases/fields/field-type-select';
+import { FieldTypeSelect } from '@/renderer/components/databases/fields/field-type-select';
import { FieldAttrs } from '@/renderer/components/databases/fields/field-attrs';
import { Spinner } from '@/renderer/components/ui/spinner';
import { useMutation } from '@/renderer/hooks/use-mutation';
@@ -28,23 +28,21 @@ import { Plus } from 'lucide-react';
const formSchema = z.object({
name: z.string(),
- dataType: z.union([
- z.literal('autonumber'),
+ type: z.union([
z.literal('boolean'),
- z.literal('button'),
z.literal('collaborator'),
- z.literal('created_at'),
- z.literal('created_by'),
+ z.literal('createdAt'),
+ z.literal('createdBy'),
z.literal('date'),
z.literal('email'),
z.literal('file'),
- z.literal('multi_select'),
+ z.literal('multiSelect'),
z.literal('number'),
z.literal('phone'),
z.literal('select'),
z.literal('text'),
- z.literal('updated_at'),
- z.literal('updated_by'),
+ z.literal('updatedAt'),
+ z.literal('updatedBy'),
z.literal('url'),
]),
});
@@ -60,7 +58,7 @@ export const FieldCreatePopover = () => {
resolver: zodResolver(formSchema),
defaultValues: {
name: '',
- dataType: 'text',
+ type: 'text',
},
});
@@ -75,7 +73,7 @@ export const FieldCreatePopover = () => {
type: 'field_create',
databaseId: database.id,
name: values.name,
- dataType: values.dataType,
+ fieldType: values.type,
userId: workspace.userId,
},
onSuccess: () => {
@@ -112,13 +110,13 @@ export const FieldCreatePopover = () => {
/>
<FormField
control={form.control}
- name="dataType"
+ name="type"
render={({ field }) => (
<FormItem>
<FormLabel>Field type</FormLabel>
<FormControl>
- <FieldDataTypeSelect
- dataType={field.value}
+ <FieldTypeSelect
+ type={field.value}
onChange={field.onChange}
/>
</FormControl>
diff --git a/desktop/src/renderer/components/databases/fields/field-delete-dialog.tsx b/desktop/src/renderer/components/databases/fields/field-delete-dialog.tsx
index fbefff5a..8564b802 100644
--- a/desktop/src/renderer/components/databases/fields/field-delete-dialog.tsx
+++ b/desktop/src/renderer/components/databases/fields/field-delete-dialog.tsx
@@ -9,8 +9,7 @@ import {
AlertDialogTitle,
} from '@/renderer/components/ui/alert-dialog';
import { Button } from '@/renderer/components/ui/button';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useDatabase } from '@/renderer/contexts/database';
interface FieldDeleteDialogProps {
id: string;
@@ -23,8 +22,7 @@ export const FieldDeleteDialog = ({
open,
onOpenChange,
}: FieldDeleteDialogProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+ const database = useDatabase();
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
@@ -42,18 +40,9 @@ export const FieldDeleteDialog = ({
<AlertDialogCancel>Cancel</AlertDialogCancel>
<Button
variant="destructive"
- disabled={isPending}
onClick={async () => {
- mutate({
- input: {
- type: 'node_delete',
- nodeId: id,
- userId: workspace.userId,
- },
- onSuccess() {
- onOpenChange(false);
- },
- });
+ database.deleteField(id);
+ onOpenChange(false);
}}
>
Delete
diff --git a/desktop/src/renderer/components/databases/fields/field-icon.tsx b/desktop/src/renderer/components/databases/fields/field-icon.tsx
index e55b94a6..f0447e5b 100644
--- a/desktop/src/renderer/components/databases/fields/field-icon.tsx
+++ b/desktop/src/renderer/components/databases/fields/field-icon.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { FieldDataType } from '@/types/databases';
+import { FieldType } from '@/registry';
import {
SquareCheck,
User,
@@ -17,7 +17,7 @@ import {
} from 'lucide-react';
interface FieldIconProps {
- type?: FieldDataType;
+ type?: FieldType;
className?: string;
}
@@ -27,9 +27,9 @@ export const FieldIcon = ({ type, className }: FieldIconProps) => {
return <SquareCheck className={className} />;
case 'collaborator':
return <User className={className} />;
- case 'created_at':
+ case 'createdAt':
return <Calendar className={className} />;
- case 'created_by':
+ case 'createdBy':
return <User className={className} />;
case 'date':
return <Calendar className={className} />;
@@ -37,7 +37,7 @@ export const FieldIcon = ({ type, className }: FieldIconProps) => {
return <Mail className={className} />;
case 'file':
return <File className={className} />;
- case 'multi_select':
+ case 'multiSelect':
return <ListChecks className={className} />;
case 'number':
return <Hash className={className} />;
diff --git a/desktop/src/renderer/components/databases/fields/field-rename-input.tsx b/desktop/src/renderer/components/databases/fields/field-rename-input.tsx
index f9cc6ab1..01d5dcbe 100644
--- a/desktop/src/renderer/components/databases/fields/field-rename-input.tsx
+++ b/desktop/src/renderer/components/databases/fields/field-rename-input.tsx
@@ -1,34 +1,22 @@
import React from 'react';
-import { FieldNode } from '@/types/databases';
-import { useMutation } from '@/renderer/hooks/use-mutation';
+import { FieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useDatabase } from '@/renderer/contexts/database';
interface FieldRenameInputProps {
- field: FieldNode;
+ field: FieldAttributes;
}
export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+ const database = useDatabase();
return (
<div className="w-full p-1">
<SmartTextInput
value={field.name}
onChange={(newName) => {
- if (isPending) return;
if (newName === field.name) return;
-
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: field.id,
- attribute: 'name',
- value: newName,
- userId: workspace.userId,
- },
- });
+ database.renameField(field.id, newName);
}}
/>
</div>
diff --git a/desktop/src/renderer/components/databases/fields/field-select.tsx b/desktop/src/renderer/components/databases/fields/field-select.tsx
index 7eecadbb..f9976eca 100644
--- a/desktop/src/renderer/components/databases/fields/field-select.tsx
+++ b/desktop/src/renderer/components/databases/fields/field-select.tsx
@@ -13,13 +13,13 @@ import {
CommandItem,
CommandList,
} from '@/renderer/components/ui/command';
-import { FieldDataType, FieldNode } from '@/types/databases';
+import { FieldType, FieldAttributes } from '@/registry';
import { cn } from '@/lib/utils';
import { FieldIcon } from './field-icon';
import { Check, ChevronDown } from 'lucide-react';
interface FieldSelectProps {
- fields: FieldNode[];
+ fields: FieldAttributes[];
value: string | null;
onChange: (field: string) => void;
}
@@ -40,7 +40,7 @@ export const FieldSelect = ({ fields, value, onChange }: FieldSelectProps) => {
>
<span className="flex flex-row items-center gap-1">
<FieldIcon
- type={selectedField?.dataType as FieldDataType}
+ type={selectedField?.type as FieldType}
className="size-4"
/>
{value ? selectedField?.name : 'Select field...'}
@@ -63,7 +63,7 @@ export const FieldSelect = ({ fields, value, onChange }: FieldSelectProps) => {
}}
>
<div className="flex w-full flex-row items-center gap-2">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
<Check
className={cn(
diff --git a/desktop/src/renderer/components/databases/fields/field-type-select.tsx b/desktop/src/renderer/components/databases/fields/field-type-select.tsx
index 01827d5c..38a4bdb2 100644
--- a/desktop/src/renderer/components/databases/fields/field-type-select.tsx
+++ b/desktop/src/renderer/components/databases/fields/field-type-select.tsx
@@ -13,80 +13,77 @@ import {
CommandItem,
CommandList,
} from '@/renderer/components/ui/command';
-import { FieldDataType } from '@/types/databases';
+import { FieldType } from '@/registry';
import { cn } from '@/lib/utils';
import { FieldIcon } from './field-icon';
import { Check, ChevronsUpDown } from 'lucide-react';
interface FieldTypeOption {
name: string;
- dataType: FieldDataType;
+ type: FieldType;
}
const fieldTypes: FieldTypeOption[] = [
{
name: 'Boolean',
- dataType: 'boolean',
+ type: 'boolean',
},
{
name: 'Collaborator',
- dataType: 'collaborator',
+ type: 'collaborator',
},
{
name: 'Created Date & Time',
- dataType: 'created_at',
+ type: 'createdAt',
},
{
name: 'Created by user',
- dataType: 'created_by',
+ type: 'createdBy',
},
{
name: 'Date',
- dataType: 'date',
+ type: 'date',
},
{
name: 'Email',
- dataType: 'email',
+ type: 'email',
},
{
name: 'File',
- dataType: 'file',
+ type: 'file',
},
{
name: 'Multi Select',
- dataType: 'multi_select',
+ type: 'multiSelect',
},
{
name: 'Number',
- dataType: 'number',
+ type: 'number',
},
{
name: 'Phone',
- dataType: 'phone',
+ type: 'phone',
},
{
name: 'Select',
- dataType: 'select',
+ type: 'select',
},
{
name: 'Text',
- dataType: 'text',
+ type: 'text',
},
{
name: 'Url',
- dataType: 'url',
+ type: 'url',
},
];
-interface FieldDataTypeSelectProps {
- dataType: string | null;
- onChange: (type: FieldDataType) => void;
+interface FieldTypeSelectProps {
+ type: string | null;
+ onChange: (type: FieldType) => void;
}
-export const FieldDataTypeSelect = ({
- dataType,
- onChange,
-}: FieldDataTypeSelectProps) => {
+export const FieldTypeSelect = ({ type, onChange }: FieldTypeSelectProps) => {
const [open, setOpen] = React.useState(false);
return (
@@ -100,10 +97,9 @@ export const FieldDataTypeSelect = ({
className="w-full justify-between p-2"
>
<span className="flex flex-row items-center gap-1">
- <FieldIcon type={dataType as FieldDataType} className="size-4" />
- {dataType
- ? fieldTypes.find((fieldType) => fieldType.dataType === dataType)
- ?.name
+ <FieldIcon type={type as FieldType} className="size-4" />
+ {type
+ ? fieldTypes.find((fieldType) => fieldType.type === type)?.name
: 'Select field type...'}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
@@ -117,21 +113,19 @@ export const FieldDataTypeSelect = ({
<CommandGroup className="h-min max-h-96">
{fieldTypes.map((fieldType) => (
<CommandItem
- key={fieldType.dataType}
+ key={fieldType.type}
onSelect={() => {
- onChange(fieldType.dataType);
+ onChange(fieldType.type);
setOpen(false);
}}
>
<div className="flex w-full flex-row items-center gap-2">
- <FieldIcon type={fieldType.dataType} className="size-4" />
+ <FieldIcon type={fieldType.type} className="size-4" />
<p>{fieldType.name}</p>
<Check
className={cn(
'ml-auto size-4',
- dataType === fieldType.dataType
- ? 'opacity-100'
- : 'opacity-0',
+ type === fieldType.type ? 'opacity-100' : 'opacity-0',
)}
/>
</div>
diff --git a/desktop/src/renderer/components/databases/fields/select-field-options.tsx b/desktop/src/renderer/components/databases/fields/select-field-options.tsx
index af45aa3e..365e3174 100644
--- a/desktop/src/renderer/components/databases/fields/select-field-options.tsx
+++ b/desktop/src/renderer/components/databases/fields/select-field-options.tsx
@@ -8,15 +8,16 @@ import {
CommandList,
} from '@/renderer/components/ui/command';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
-import { MultiSelectFieldNode, SelectFieldNode } from '@/types/databases';
+import { MultiSelectFieldAttributes, SelectFieldAttributes } from '@/registry';
import { getRandomSelectOptionColor } from '@/lib/databases';
import { SelectOptionSettingsPopover } from '@/renderer/components/databases/fields/select-option-settings-popover';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { Check, Plus, X } from 'lucide-react';
+import { useDatabase } from '@/renderer/contexts/database';
interface SelectFieldOptionsProps {
- field: SelectFieldNode | MultiSelectFieldNode;
+ field: SelectFieldAttributes | MultiSelectFieldAttributes;
values: string[];
onSelect: (id: string) => void;
allowAdd: boolean;
@@ -29,13 +30,16 @@ export const SelectFieldOptions = ({
allowAdd,
}: SelectFieldOptionsProps) => {
const workspace = useWorkspace();
+ const database = useDatabase();
const { mutate, isPending } = useMutation();
+ const selectOptions = Object.values(field.options ?? {});
+
const [inputValue, setInputValue] = React.useState('');
const [color, setColor] = React.useState(getRandomSelectOptionColor());
const showNewOption =
allowAdd &&
- !field.options?.some((option) => option.name === inputValue.trim());
+ !selectOptions.some((option) => option.name === inputValue.trim());
return (
<Command className="min-h-min">
@@ -48,7 +52,7 @@ export const SelectFieldOptions = ({
<CommandEmpty>No options found.</CommandEmpty>
<CommandList>
<CommandGroup className="h-min max-h-96">
- {field.options?.map((option) => {
+ {selectOptions.map((option) => {
const isSelected = values.includes(option.id);
return (
<CommandItem
@@ -79,7 +83,10 @@ export const SelectFieldOptions = ({
e.preventDefault();
}}
>
- <SelectOptionSettingsPopover option={option} />
+ <SelectOptionSettingsPopover
+ option={option}
+ fieldId={field.id}
+ />
</div>
</CommandItem>
);
@@ -102,6 +109,7 @@ export const SelectFieldOptions = ({
mutate({
input: {
type: 'select_option_create',
+ databaseId: database.id,
fieldId: field.id,
name: inputValue.trim(),
color,
diff --git a/desktop/src/renderer/components/databases/fields/select-option-settings-popover.tsx b/desktop/src/renderer/components/databases/fields/select-option-settings-popover.tsx
index 2ba3fd2a..00bb83ba 100644
--- a/desktop/src/renderer/components/databases/fields/select-option-settings-popover.tsx
+++ b/desktop/src/renderer/components/databases/fields/select-option-settings-popover.tsx
@@ -8,22 +8,22 @@ import {
import { Separator } from '@/renderer/components/ui/separator';
import { selectOptionColors } from '@/lib/databases';
import { cn } from '@/lib/utils';
-import { SelectOptionNode } from '@/types/databases';
+import { SelectOptionAttributes } from '@/registry';
import { SelectOptionDeleteDialog } from '@/renderer/components/databases/fields/select-option-delete-dialog';
-import { useMutation } from '@/renderer/hooks/use-mutation';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useWorkspace } from '@/renderer/contexts/workspace';
import { Ellipsis, Trash2 } from 'lucide-react';
+import { useDatabase } from '@/renderer/contexts/database';
interface SelectOptionSettingsPopoverProps {
- option: SelectOptionNode;
+ fieldId: string;
+ option: SelectOptionAttributes;
}
export const SelectOptionSettingsPopover = ({
+ fieldId,
option,
}: SelectOptionSettingsPopoverProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+ const database = useDatabase();
const [openSetttingsPopover, setOpenSetttingsPopover] = React.useState(false);
const [openDeleteDialog, setOpenDeleteDialog] = React.useState(false);
@@ -43,17 +43,11 @@ export const SelectOptionSettingsPopover = ({
<SmartTextInput
value={option.name}
onChange={(newName) => {
- if (isPending) return;
if (newName === option.name) return;
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: option.id,
- attribute: 'name',
- value: newName,
- userId: workspace.userId,
- },
+ database.updateSelectOption(fieldId, {
+ ...option,
+ name: newName,
});
}}
/>
@@ -66,16 +60,9 @@ export const SelectOptionSettingsPopover = ({
key={color.value}
className="flex cursor-pointer flex-row items-center gap-2 rounded-md p-1 hover:bg-gray-100"
onClick={() => {
- if (isPending) return;
-
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: option.id,
- attribute: 'color',
- value: color.value,
- userId: workspace.userId,
- },
+ database.updateSelectOption(fieldId, {
+ ...option,
+ color: color.value,
});
}}
>
diff --git a/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx
index c9d790d3..e9c3d8c1 100644
--- a/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { BooleanFieldNode, ViewFieldFilter } from '@/types/databases';
+import { BooleanFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -13,20 +13,20 @@ import {
} from '@/renderer/components/ui/dropdown-menu';
import { Button } from '@/renderer/components/ui/button';
import { booleanFieldFilterOperators } from '@/lib/databases';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '../fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewBooleanFieldFilterProps {
- field: BooleanFieldNode;
- filter: ViewFieldFilter;
+ field: BooleanFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewBooleanFieldFilter = ({
field,
filter,
}: ViewBooleanFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
booleanFieldFilterOperators.find(
@@ -35,12 +35,12 @@ export const ViewBooleanFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={(open) => {
if (open) {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
} else {
- viewSearch.closeFieldFilter(filter.id);
+ view.closeFieldFilter(filter.id);
}
}}
>
@@ -57,7 +57,7 @@ export const ViewBooleanFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -72,7 +72,7 @@ export const ViewBooleanFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
});
@@ -87,7 +87,7 @@ export const ViewBooleanFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
diff --git a/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx b/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx
index 44a1f230..cd5d279c 100644
--- a/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx
+++ b/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx
@@ -1,5 +1,8 @@
import React from 'react';
-import { CreatedAtFieldNode, ViewFieldFilter } from '@/types/databases';
+import {
+ CreatedAtFieldAttributes,
+ ViewFieldFilterAttributes,
+} from '@/registry';
import {
Popover,
PopoverContent,
@@ -14,20 +17,20 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { dateFieldFilterOperators } from '@/lib/databases';
import { DatePicker } from '@/renderer/components/ui/date-picker';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '../fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewCreatedAtFieldFilterProps {
- field: CreatedAtFieldNode;
- filter: ViewFieldFilter;
+ field: CreatedAtFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewCreatedAtFieldFilter = ({
field,
filter,
}: ViewCreatedAtFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
dateFieldFilterOperators.find(
@@ -39,12 +42,12 @@ export const ViewCreatedAtFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -61,7 +64,7 @@ export const ViewCreatedAtFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -82,10 +85,10 @@ export const ViewCreatedAtFieldFilter = ({
? null
: dateValue?.toISOString();
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
- value: value,
+ value: value ?? null,
});
}}
>
@@ -98,7 +101,7 @@ export const ViewCreatedAtFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -108,12 +111,12 @@ export const ViewCreatedAtFieldFilter = ({
value={dateValue}
onChange={(newValue) => {
if (newValue === null || newValue === undefined) {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: null,
});
} else {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: newValue.toISOString(),
});
diff --git a/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx
index ccda4a5a..38fe662e 100644
--- a/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { DateFieldNode, ViewFieldFilter } from '@/types/databases';
+import { DateFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -14,20 +14,20 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { dateFieldFilterOperators } from '@/lib/databases';
import { DatePicker } from '@/renderer/components/ui/date-picker';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewDateFieldFilterProps {
- field: DateFieldNode;
- filter: ViewFieldFilter;
+ field: DateFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewDateFieldFilter = ({
field,
filter,
}: ViewDateFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
dateFieldFilterOperators.find(
@@ -42,12 +42,12 @@ export const ViewDateFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -64,7 +64,7 @@ export const ViewDateFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -85,10 +85,10 @@ export const ViewDateFieldFilter = ({
? null
: dateValue?.toISOString();
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
- value: value,
+ value: value ?? null,
});
}}
>
@@ -101,7 +101,7 @@ export const ViewDateFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -112,12 +112,12 @@ export const ViewDateFieldFilter = ({
value={dateValue}
onChange={(newValue) => {
if (newValue === null || newValue === undefined) {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: null,
});
} else {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: newValue.toISOString(),
});
diff --git a/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx
index c4138260..6671052d 100644
--- a/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { EmailFieldNode, ViewFieldFilter } from '@/types/databases';
+import { EmailFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -14,20 +14,20 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { emailFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewEmailFieldFilterProps {
- field: EmailFieldNode;
- filter: ViewFieldFilter;
+ field: EmailFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewEmailFieldFilter = ({
field,
filter,
}: ViewEmailFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
emailFieldFilterOperators.find(
@@ -41,12 +41,12 @@ export const ViewEmailFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -63,7 +63,7 @@ export const ViewEmailFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -84,7 +84,7 @@ export const ViewEmailFieldFilter = ({
? null
: textValue;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -100,7 +100,7 @@ export const ViewEmailFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -110,7 +110,7 @@ export const ViewEmailFieldFilter = ({
<SmartTextInput
value={textValue}
onChange={(value) => {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: value,
});
diff --git a/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx b/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx
index e32b4bb7..b6123da2 100644
--- a/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx
+++ b/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx
@@ -13,7 +13,7 @@ import {
CommandList,
} from '@/renderer/components/ui/command';
import { useDatabase } from '@/renderer/contexts/database';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
interface ViewFilterAddPopoverProps {
@@ -24,12 +24,12 @@ export const ViewFilterAddPopover = ({
children,
}: ViewFilterAddPopoverProps) => {
const database = useDatabase();
- const viewSearch = useViewSearch();
+ const view = useView();
const [open, setOpen] = React.useState(false);
const fieldsWithoutFilters = database.fields.filter(
(field) =>
- !viewSearch.filters.some(
+ !view.filters.some(
(filter) => filter.type === 'field' && filter.fieldId === field.id,
),
);
@@ -51,12 +51,12 @@ export const ViewFilterAddPopover = ({
<CommandItem
key={field.id}
onSelect={() => {
- viewSearch.initFieldFilter(field.id);
+ view.initFieldFilter(field.id);
setOpen(false);
}}
>
<div className="flex w-full flex-row items-center gap-2">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
</CommandItem>
diff --git a/desktop/src/renderer/components/databases/search/view-filter-button.tsx b/desktop/src/renderer/components/databases/search/view-filter-button.tsx
index 3b7001fc..ea230175 100644
--- a/desktop/src/renderer/components/databases/search/view-filter-button.tsx
+++ b/desktop/src/renderer/components/databases/search/view-filter-button.tsx
@@ -1,16 +1,16 @@
import React from 'react';
import { ViewFilterAddPopover } from '@/renderer/components/databases/search/view-filter-add-popover';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { Filter } from 'lucide-react';
export const ViewFilterButton = () => {
- const viewSearch = useViewSearch();
+ const view = useView();
- if (viewSearch.filters.length > 0) {
+ if (view.filters.length > 0) {
return (
<button
className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50"
- onClick={() => viewSearch.openSearchBar()}
+ onClick={() => view.openSearchBar()}
>
<Filter className="size-4" />
</button>
diff --git a/desktop/src/renderer/components/databases/search/view-filters.tsx b/desktop/src/renderer/components/databases/search/view-filters.tsx
index 8c9753ce..d123d034 100644
--- a/desktop/src/renderer/components/databases/search/view-filters.tsx
+++ b/desktop/src/renderer/components/databases/search/view-filters.tsx
@@ -11,17 +11,17 @@ import { ViewMultiSelectFieldFilter } from '@/renderer/components/databases/sear
import { ViewDateFieldFilter } from '@/renderer/components/databases/search/view-date-field-filter';
import { ViewCreatedAtFieldFilter } from '@/renderer/components/databases/search/view-created-at-field-fitler';
import { ViewFilterAddPopover } from '@/renderer/components/databases/search/view-filter-add-popover';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { Plus } from 'lucide-react';
export const ViewFilters = () => {
const database = useDatabase();
- const viewSearch = useViewSearch();
+ const view = useView();
return (
<div className="flex flex-row items-center gap-2">
- {viewSearch.filters &&
- viewSearch.filters.map((filter) => {
+ {view.filters &&
+ view.filters.map((filter) => {
if (filter.type === 'group') {
return null;
}
@@ -34,7 +34,7 @@ export const ViewFilters = () => {
return null;
}
- switch (field.dataType) {
+ switch (field.type) {
case 'boolean':
return (
<ViewBooleanFieldFilter
@@ -45,7 +45,7 @@ export const ViewFilters = () => {
);
case 'collaborator':
return null;
- case 'created_at':
+ case 'createdAt':
return (
<ViewCreatedAtFieldFilter
key={filter.id}
@@ -53,7 +53,7 @@ export const ViewFilters = () => {
filter={filter}
/>
);
- case 'created_by':
+ case 'createdBy':
return null;
case 'date':
return (
@@ -73,7 +73,7 @@ export const ViewFilters = () => {
);
case 'file':
return null;
- case 'multi_select':
+ case 'multiSelect':
return (
<ViewMultiSelectFieldFilter
key={filter.id}
diff --git a/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx
index cf83961a..4201cf4b 100644
--- a/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx
@@ -1,5 +1,8 @@
import React from 'react';
-import { MultiSelectFieldNode, ViewFieldFilter } from '@/types/databases';
+import {
+ MultiSelectFieldAttributes,
+ ViewFieldFilterAttributes,
+} from '@/registry';
import {
Popover,
PopoverContent,
@@ -15,28 +18,28 @@ import { Button } from '@/renderer/components/ui/button';
import { selectFieldFilterOperators } from '@/lib/databases';
import { SelectFieldOptions } from '@/renderer/components/databases/fields/select-field-options';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewMultiSelectFieldFilterProps {
- field: MultiSelectFieldNode;
- filter: ViewFieldFilter;
+ field: MultiSelectFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewMultiSelectFieldFilter = ({
field,
filter,
}: ViewMultiSelectFieldFilterProps) => {
- const viewSearch = useViewSearch();
-
+ const view = useView();
+ const selectOptions = Object.values(field.options ?? {});
const operator =
selectFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? selectFieldFilterOperators[0];
const selectOptionIds = (filter.value as string[]) ?? [];
- const selectedOptions = field.options.filter((option) =>
+ const selectedOptions = selectOptions.filter((option) =>
selectOptionIds.includes(option.id),
);
@@ -45,12 +48,12 @@ export const ViewMultiSelectFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -67,7 +70,7 @@ export const ViewMultiSelectFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -88,7 +91,7 @@ export const ViewMultiSelectFieldFilter = ({
? []
: selectOptionIds;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -104,7 +107,7 @@ export const ViewMultiSelectFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -137,7 +140,7 @@ export const ViewMultiSelectFieldFilter = ({
? selectOptionIds.filter((value) => value !== id)
: [...selectOptionIds, id];
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: values,
});
diff --git a/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx
index e5686130..9460ab86 100644
--- a/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { NumberFieldNode, ViewFieldFilter } from '@/types/databases';
+import { NumberFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -13,21 +13,21 @@ import {
} from '@/renderer/components/ui/dropdown-menu';
import { Button } from '@/renderer/components/ui/button';
import { SmartNumberInput } from '@/renderer/components/ui/smart-number-input';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { numberFieldFilterOperators } from '@/lib/databases';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewNumberFieldFilterProps {
- field: NumberFieldNode;
- filter: ViewFieldFilter;
+ field: NumberFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewNumberFieldFilter = ({
field,
filter,
}: ViewNumberFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
numberFieldFilterOperators.find(
@@ -41,12 +41,12 @@ export const ViewNumberFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -63,7 +63,7 @@ export const ViewNumberFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -84,7 +84,7 @@ export const ViewNumberFieldFilter = ({
? null
: numberValue;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -100,7 +100,7 @@ export const ViewNumberFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -110,7 +110,7 @@ export const ViewNumberFieldFilter = ({
<SmartNumberInput
value={numberValue ?? null}
onChange={(value) => {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: value,
});
diff --git a/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx
index 58b63a47..1a2f517e 100644
--- a/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { PhoneFieldNode, ViewFieldFilter } from '@/types/databases';
+import { PhoneFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -14,20 +14,20 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { phoneFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewPhoneFieldFilterProps {
- field: PhoneFieldNode;
- filter: ViewFieldFilter;
+ field: PhoneFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewPhoneFieldFilter = ({
field,
filter,
}: ViewPhoneFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
phoneFieldFilterOperators.find(
@@ -41,12 +41,12 @@ export const ViewPhoneFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -63,7 +63,7 @@ export const ViewPhoneFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -84,7 +84,7 @@ export const ViewPhoneFieldFilter = ({
? null
: phoneValue;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -100,7 +100,7 @@ export const ViewPhoneFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -110,7 +110,7 @@ export const ViewPhoneFieldFilter = ({
<SmartTextInput
value={phoneValue}
onChange={(value) => {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: value,
});
diff --git a/desktop/src/renderer/components/databases/search/view-search-bar.tsx b/desktop/src/renderer/components/databases/search/view-search-bar.tsx
index bf710aaf..fe4ad7ac 100644
--- a/desktop/src/renderer/components/databases/search/view-search-bar.tsx
+++ b/desktop/src/renderer/components/databases/search/view-search-bar.tsx
@@ -2,18 +2,18 @@ import React from 'react';
import { ViewSorts } from '@/renderer/components/databases/search/view-sorts';
import { ViewFilters } from '@/renderer/components/databases/search/view-filters';
import { Separator } from '@/renderer/components/ui/separator';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
export const ViewSearchBar = () => {
- const viewSearch = useViewSearch();
+ const view = useView();
- if (!viewSearch.isSearchBarOpened) {
+ if (!view.isSearchBarOpened) {
return null;
}
return (
<div className="mt-3 flex flex-row items-center gap-2">
- {viewSearch.sorts.length > 0 && (
+ {view.sorts.length > 0 && (
<React.Fragment>
<ViewSorts />
<Separator orientation="vertical" className="mx-1 h-4" />
diff --git a/desktop/src/renderer/components/databases/search/view-search-provider.tsx b/desktop/src/renderer/components/databases/search/view-search-provider.tsx
deleted file mode 100644
index 4128af76..00000000
--- a/desktop/src/renderer/components/databases/search/view-search-provider.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import React from 'react';
-import { ViewSearchContext } from '@/renderer/contexts/view-search';
-import { ViewFieldFilter, ViewFilter, ViewSort } from '@/types/databases';
-import { useDatabase } from '@/renderer/contexts/database';
-import { generateId, IdType } from '@/lib/id';
-import { getFieldFilterOperators } from '@/lib/databases';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
-
-interface ViewSearchProviderProps {
- id: string;
- filters: ViewFilter[];
- sorts: ViewSort[];
- children: React.ReactNode;
-}
-
-export const ViewSearchProvider = ({
- id,
- filters,
- sorts,
- children,
-}: ViewSearchProviderProps) => {
- const workspace = useWorkspace();
- const database = useDatabase();
- const { mutate, isPending } = useMutation();
-
- const [isSearchBarOpened, setIsSearchBarOpened] = React.useState(false);
- const [isSortsOpened, setIsSortsOpened] = React.useState(false);
- const [openedFieldFilters, setOpenedFieldFilters] = React.useState<string[]>(
- [],
- );
-
- return (
- <ViewSearchContext.Provider
- value={{
- id,
- filters: filters,
- sorts: sorts,
- isSaving: isPending,
- isSearchBarOpened: isSearchBarOpened,
- isSortsOpened: isSortsOpened,
- isFieldFilterOpened: (fieldId: string) =>
- openedFieldFilters.includes(fieldId),
- initFieldFilter: (fieldId: string) => {
- const field = database.fields.find((field) => field.id === fieldId);
- if (!field) {
- return;
- }
-
- const existingFieldFilter = filters.find(
- (filter) => filter.type === 'field' && filter.fieldId === fieldId,
- );
-
- if (existingFieldFilter) {
- if (!openedFieldFilters.includes(fieldId)) {
- setOpenedFieldFilters((prev) => [...prev, fieldId]);
- }
- return;
- }
-
- const operators = getFieldFilterOperators(field.dataType);
- const filter: ViewFieldFilter = {
- type: 'field',
- id: generateId(IdType.ViewFilter),
- fieldId,
- operator: operators[0].value,
- value: null,
- };
-
- const newFilters = [...filters, filter];
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: id,
- attribute: 'filters',
- value: newFilters,
- userId: workspace.userId,
- },
- onSuccess() {
- setOpenedFieldFilters((prev) => [...prev, filter.id]);
- setIsSearchBarOpened(true);
- },
- });
- },
- updateFilter: (filterId: string, newFilter: ViewFieldFilter) => {
- const newFilters = filters.map((filter) =>
- filter.type === 'field' && filter.id === filterId
- ? newFilter
- : filter,
- );
-
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: id,
- attribute: 'filters',
- value: newFilters,
- userId: workspace.userId,
- },
- onSuccess() {
- setIsSearchBarOpened(true);
- },
- });
- },
- removeFilter: (filterId: string) => {
- const newFilters = filters.filter((filter) => filter.id !== filterId);
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: id,
- attribute: 'filters',
- value: newFilters,
- userId: workspace.userId,
- },
- onSuccess() {
- setIsSearchBarOpened(true);
- },
- });
- },
- initFieldSort: (fieldId: string) => {
- const field = database.fields.find((field) => field.id === fieldId);
- if (!field) {
- return;
- }
-
- const existingFieldSort = sorts.find(
- (sort) => sort.fieldId === fieldId,
- );
-
- if (existingFieldSort) {
- if (!isSortsOpened) {
- setIsSortsOpened(true);
- setIsSearchBarOpened(true);
- }
- return;
- }
-
- const sort: ViewSort = {
- id: generateId(IdType.ViewFilter),
- fieldId,
- direction: 'asc',
- };
-
- const newSorts = [...sorts, sort];
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: id,
- attribute: 'sorts',
- value: newSorts,
- userId: workspace.userId,
- },
- onSuccess() {
- setIsSearchBarOpened(true);
- setIsSortsOpened(true);
- },
- });
- },
- updateSort: (sortId: string, newSort: ViewSort) => {
- const newSorts = sorts.map((sort) =>
- sort.id === sortId ? newSort : sort,
- );
-
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: id,
- attribute: 'sorts',
- value: newSorts,
- userId: workspace.userId,
- },
- onSuccess() {
- setIsSearchBarOpened(true);
- setIsSortsOpened(true);
- },
- });
- },
- removeSort: (sortId: string) => {
- const newSorts = sorts.filter((sort) => sort.id !== sortId);
-
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: id,
- attribute: 'sorts',
- value: newSorts,
- userId: workspace.userId,
- },
- onSuccess() {
- setIsSearchBarOpened(true);
- },
- });
- },
- openSearchBar: () => setIsSearchBarOpened(true),
- closeSearchBar: () => setIsSearchBarOpened(false),
- openSorts: () => setIsSortsOpened(true),
- closeSorts: () => setIsSortsOpened(false),
- openFieldFilter: (fieldId: string) =>
- setOpenedFieldFilters((prev) => [...prev, fieldId]),
- closeFieldFilter: (fieldId: string) =>
- setOpenedFieldFilters((prev) => prev.filter((id) => id !== fieldId)),
- }}
- >
- {children}
- </ViewSearchContext.Provider>
- );
-};
diff --git a/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx
index e7bc7a50..ff81c82e 100644
--- a/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { SelectFieldNode, ViewFieldFilter } from '@/types/databases';
+import { SelectFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -15,28 +15,28 @@ import { Button } from '@/renderer/components/ui/button';
import { selectFieldFilterOperators } from '@/lib/databases';
import { SelectFieldOptions } from '@/renderer/components/databases/fields/select-field-options';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '../fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewSelectFieldFilterProps {
- field: SelectFieldNode;
- filter: ViewFieldFilter;
+ field: SelectFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewSelectFieldFilter = ({
field,
filter,
}: ViewSelectFieldFilterProps) => {
- const viewSearch = useViewSearch();
-
+ const view = useView();
+ const selectOptions = Object.values(field.options ?? {});
const operator =
selectFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? selectFieldFilterOperators[0];
const selectOptionIds = (filter.value as string[]) ?? [];
- const selectedOptions = field.options.filter((option) =>
+ const selectedOptions = selectOptions.filter((option) =>
selectOptionIds.includes(option.id),
);
@@ -45,12 +45,12 @@ export const ViewSelectFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={() => {
- if (viewSearch.isFieldFilterOpened(filter.id)) {
- viewSearch.closeFieldFilter(filter.id);
+ if (view.isFieldFilterOpened(filter.id)) {
+ view.closeFieldFilter(filter.id);
} else {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
}
}}
>
@@ -67,7 +67,7 @@ export const ViewSelectFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -88,7 +88,7 @@ export const ViewSelectFieldFilter = ({
? []
: selectOptionIds;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -104,7 +104,7 @@ export const ViewSelectFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -137,7 +137,7 @@ export const ViewSelectFieldFilter = ({
? selectOptionIds.filter((optionId) => optionId !== id)
: [...selectOptionIds, id];
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: value,
});
diff --git a/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx b/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx
index 7cdfff1f..3650f251 100644
--- a/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx
+++ b/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx
@@ -14,7 +14,7 @@ import {
} from '@/renderer/components/ui/command';
import { useDatabase } from '@/renderer/contexts/database';
import { isSortableField } from '@/lib/databases';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
interface ViewSortAddPopoverProps {
@@ -23,13 +23,13 @@ interface ViewSortAddPopoverProps {
export const ViewSortAddPopover = ({ children }: ViewSortAddPopoverProps) => {
const database = useDatabase();
- const viewSearch = useViewSearch();
+ const view = useView();
const [open, setOpen] = React.useState(false);
const sortableFields = database.fields.filter(
(field) =>
isSortableField(field) &&
- !viewSearch.sorts.some((sort) => sort.fieldId === field.id),
+ !view.sorts.some((sort) => sort.fieldId === field.id),
);
if (sortableFields.length === 0) {
@@ -49,12 +49,12 @@ export const ViewSortAddPopover = ({ children }: ViewSortAddPopoverProps) => {
<CommandItem
key={field.id}
onSelect={() => {
- viewSearch.initFieldSort(field.id);
+ view.initFieldSort(field.id);
setOpen(false);
}}
>
<div className="flex w-full flex-row items-center gap-2">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
</CommandItem>
diff --git a/desktop/src/renderer/components/databases/search/view-sort-button.tsx b/desktop/src/renderer/components/databases/search/view-sort-button.tsx
index 512b04db..f102b5ca 100644
--- a/desktop/src/renderer/components/databases/search/view-sort-button.tsx
+++ b/desktop/src/renderer/components/databases/search/view-sort-button.tsx
@@ -1,16 +1,16 @@
import React from 'react';
import { ViewSortAddPopover } from '@/renderer/components/databases/search/view-sort-add-popover';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { ArrowDownAz } from 'lucide-react';
export const ViewSortButton = () => {
- const viewSearch = useViewSearch();
+ const view = useView();
- if (viewSearch.sorts.length > 0) {
+ if (view.sorts.length > 0) {
return (
<button
className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50"
- onClick={() => viewSearch.openSearchBar()}
+ onClick={() => view.openSearchBar()}
>
<ArrowDownAz className="size-4" />
</button>
diff --git a/desktop/src/renderer/components/databases/search/view-sort-row.tsx b/desktop/src/renderer/components/databases/search/view-sort-row.tsx
index 5f2ebb0c..d7196f4a 100644
--- a/desktop/src/renderer/components/databases/search/view-sort-row.tsx
+++ b/desktop/src/renderer/components/databases/search/view-sort-row.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { FieldNode, ViewSort } from '@/types/databases';
+import { FieldAttributes, ViewSortAttributes } from '@/registry';
import {
DropdownMenu,
DropdownMenuContent,
@@ -8,22 +8,22 @@ import {
} from '@/renderer/components/ui/dropdown-menu';
import { Button } from '@/renderer/components/ui/button';
import { SortDirections } from '@/lib/constants';
-import { useViewSearch } from '@/renderer/contexts/view-search';
-import { FieldIcon } from '../fields/field-icon';
+import { useView } from '@/renderer/contexts/view';
+import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewSortProps {
- sort: ViewSort;
- field: FieldNode;
+ sort: ViewSortAttributes;
+ field: FieldAttributes;
}
export const ViewSortRow = ({ sort, field }: ViewSortProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
return (
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -40,7 +40,7 @@ export const ViewSortRow = ({ sort, field }: ViewSortProps) => {
<DropdownMenuContent>
<DropdownMenuItem
onClick={() => {
- viewSearch.updateSort(sort.id, {
+ view.updateSort(sort.id, {
...sort,
direction: 'asc',
});
@@ -50,7 +50,7 @@ export const ViewSortRow = ({ sort, field }: ViewSortProps) => {
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
- viewSearch.updateSort(sort.id, {
+ view.updateSort(sort.id, {
...sort,
direction: 'desc',
});
@@ -64,7 +64,7 @@ export const ViewSortRow = ({ sort, field }: ViewSortProps) => {
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeSort(sort.id);
+ view.removeSort(sort.id);
}}
>
<Trash2 className="size-4" />
diff --git a/desktop/src/renderer/components/databases/search/view-sorts.tsx b/desktop/src/renderer/components/databases/search/view-sorts.tsx
index d94d723d..98b5eed2 100644
--- a/desktop/src/renderer/components/databases/search/view-sorts.tsx
+++ b/desktop/src/renderer/components/databases/search/view-sorts.tsx
@@ -8,21 +8,21 @@ import { Button } from '@/renderer/components/ui/button';
import { ViewSortRow } from '@/renderer/components/databases/search/view-sort-row';
import { useDatabase } from '@/renderer/contexts/database';
import { ViewSortAddPopover } from '@/renderer/components/databases/search/view-sort-add-popover';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { Plus } from 'lucide-react';
export const ViewSorts = () => {
const database = useDatabase();
- const viewSearch = useViewSearch();
+ const view = useView();
return (
<Popover
- open={viewSearch.isSortsOpened}
+ open={view.isSortsOpened}
onOpenChange={(open) => {
if (open) {
- viewSearch.openSorts();
+ view.openSorts();
} else {
- viewSearch.closeSorts();
+ view.closeSorts();
}
}}
>
@@ -33,11 +33,11 @@ export const ViewSorts = () => {
size="sm"
className="border-dashed text-xs text-muted-foreground"
>
- Sorts ({viewSearch.sorts.length})
+ Sorts ({view.sorts.length})
</Button>
</PopoverTrigger>
<PopoverContent className="flex flex-col gap-2 p-2">
- {viewSearch.sorts.map((sort) => {
+ {view.sorts.map((sort) => {
const field = database.fields.find(
(field) => field.id === sort.fieldId,
);
diff --git a/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx
index 9a01e501..ea158989 100644
--- a/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { TextFieldNode, ViewFieldFilter } from '@/types/databases';
+import { TextFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -14,20 +14,20 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { textFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { Trash2, ChevronDown } from 'lucide-react';
interface ViewTextFieldFilterProps {
- field: TextFieldNode;
- filter: ViewFieldFilter;
+ field: TextFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewTextFieldFilter = ({
field,
filter,
}: ViewTextFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
textFieldFilterOperators.find(
@@ -41,12 +41,12 @@ export const ViewTextFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={(open) => {
if (open) {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
} else {
- viewSearch.closeFieldFilter(filter.id);
+ view.closeFieldFilter(filter.id);
}
}}
>
@@ -63,7 +63,7 @@ export const ViewTextFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -84,7 +84,7 @@ export const ViewTextFieldFilter = ({
? null
: textValue;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -100,7 +100,7 @@ export const ViewTextFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -110,7 +110,7 @@ export const ViewTextFieldFilter = ({
<SmartTextInput
value={textValue}
onChange={(value) => {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: value,
});
diff --git a/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx b/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx
index 1ff5e434..14053aff 100644
--- a/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx
+++ b/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { UrlFieldNode, ViewFieldFilter } from '@/types/databases';
+import { UrlFieldAttributes, ViewFieldFilterAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -14,20 +14,20 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { urlFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ChevronDown, Trash2 } from 'lucide-react';
interface ViewUrlFieldFilterProps {
- field: UrlFieldNode;
- filter: ViewFieldFilter;
+ field: UrlFieldAttributes;
+ filter: ViewFieldFilterAttributes;
}
export const ViewUrlFieldFilter = ({
field,
filter,
}: ViewUrlFieldFilterProps) => {
- const viewSearch = useViewSearch();
+ const view = useView();
const operator =
urlFieldFilterOperators.find(
@@ -41,12 +41,12 @@ export const ViewUrlFieldFilter = ({
return (
<Popover
- open={viewSearch.isFieldFilterOpened(filter.id)}
+ open={view.isFieldFilterOpened(filter.id)}
onOpenChange={(open) => {
if (open) {
- viewSearch.openFieldFilter(filter.id);
+ view.openFieldFilter(filter.id);
} else {
- viewSearch.closeFieldFilter(filter.id);
+ view.closeFieldFilter(filter.id);
}
}}
>
@@ -63,7 +63,7 @@ export const ViewUrlFieldFilter = ({
<PopoverContent className="flex w-96 flex-col gap-2 p-2">
<div className="flex flex-row items-center gap-3 text-sm">
<div className="flex flex-row items-center gap-0.5 p-1">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
<DropdownMenu>
@@ -84,7 +84,7 @@ export const ViewUrlFieldFilter = ({
? null
: urlValue;
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
operator: operator.value,
value: value,
@@ -100,7 +100,7 @@ export const ViewUrlFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- viewSearch.removeFilter(filter.id);
+ view.removeFilter(filter.id);
}}
>
<Trash2 className="size-4" />
@@ -110,7 +110,7 @@ export const ViewUrlFieldFilter = ({
<SmartTextInput
value={urlValue}
onChange={(value) => {
- viewSearch.updateFilter(filter.id, {
+ view.updateFilter(filter.id, {
...filter,
value: value,
});
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-boolean-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-boolean-cell.tsx
index b1f35e9f..4fb86b46 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-boolean-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-boolean-cell.tsx
@@ -1,62 +1,37 @@
import React from 'react';
import { Checkbox } from '@/renderer/components/ui/checkbox';
-import { BooleanFieldNode, RecordNode } from '@/types/databases';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { BooleanFieldAttributes } from '@/registry';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewBooleanCellProps {
- record: RecordNode;
- field: BooleanFieldNode;
+ field: BooleanFieldAttributes;
}
-export const TableViewBooleanCell = ({
- record,
- field,
-}: TableViewBooleanCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
- const canEdit = true;
+export const TableViewBooleanCell = ({ field }: TableViewBooleanCellProps) => {
+ const record = useRecord();
const [input, setInput] = React.useState<boolean>(
- (record.attributes[field.id] as boolean) ?? false,
+ record.getBooleanValue(field),
);
React.useEffect(() => {
- setInput((record.attributes[field.id] as boolean) ?? false);
+ setInput(record.getBooleanValue(field));
}, [record.versionId]);
return (
<div className="flex h-full w-full flex-row items-center justify-center p-1">
<Checkbox
checked={input}
- disabled={isPending || !canEdit}
+ disabled={!record.canEdit}
onCheckedChange={(e) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (typeof e === 'boolean') {
setInput(e.valueOf());
- const checked = e.valueOf();
- if (checked) {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: checked,
- userId: workspace.userId,
- },
- });
- } else {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
- }
+ record.updateFieldValue(field, {
+ type: 'boolean',
+ value: e.valueOf(),
+ });
}
}}
/>
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-created-at-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-created-at-cell.tsx
index 73a68f2e..08831b41 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-created-at-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-created-at-cell.tsx
@@ -1,20 +1,21 @@
-import { CreatedAtFieldNode, RecordNode } from '@/types/databases';
import React from 'react';
+import { CreatedAtFieldAttributes } from '@/registry';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewCreatedAtCellProps {
- record: RecordNode;
- field: CreatedAtFieldNode;
+ field: CreatedAtFieldAttributes;
}
export const TableViewCreatedAtCell = ({
- record,
field,
}: TableViewCreatedAtCellProps) => {
+ const record = useRecord();
+
+ const createdAt = new Date(record.createdAt);
return (
<div className="h-full w-full p-1 text-sm" data-field={field.id}>
<p>
- {record.createdAt.toLocaleDateString()}{' '}
- {record.createdAt.toLocaleTimeString()}
+ {createdAt.toLocaleDateString()} {createdAt.toLocaleTimeString()}
</p>
</div>
);
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-created-by-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-created-by-cell.tsx
index 32c6823a..3d4c87fb 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-created-by-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-created-by-cell.tsx
@@ -1,28 +1,49 @@
import React from 'react';
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { CreatedByFieldNode, RecordNode } from '@/types/databases';
+import { CreatedByFieldAttributes } from '@/registry';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewCreatedByCellProps {
- field: CreatedByFieldNode;
- record: RecordNode;
+ field: CreatedByFieldAttributes;
}
export const TableViewCreatedByCell = ({
field,
- record,
}: TableViewCreatedByCellProps) => {
+ const workspace = useWorkspace();
+ const record = useRecord();
+
+ const { data } = useQuery({
+ type: 'node_get',
+ nodeId: record.createdBy,
+ userId: workspace.userId,
+ });
+
+ const createdBy =
+ data && data.attributes.type === 'user'
+ ? {
+ name: data.attributes.name,
+ avatar: data.attributes.avatar,
+ }
+ : {
+ name: 'Unknown',
+ avatar: null,
+ };
+
return (
<div
className="flex h-full w-full flex-row items-center gap-1 p-1 text-sm"
data-field={field.id}
>
<Avatar
- id={record.createdBy.id}
- name={record.createdBy.name}
- avatar={record.createdBy.avatar}
+ id={record.createdBy}
+ name={createdBy.name}
+ avatar={createdBy.avatar}
size="small"
/>
- <p>{record.createdBy.name}</p>
+ <p>{createdBy.name}</p>
</div>
);
};
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-date-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-date-cell.tsx
index cf1feef8..b864ca59 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-date-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-date-cell.tsx
@@ -1,47 +1,27 @@
import React from 'react';
-import { RecordNode, DateFieldNode } from '@/types/databases';
-import { useMutation } from '@/renderer/hooks/use-mutation';
+import { DateFieldAttributes } from '@/registry';
import { DatePicker } from '@/renderer/components/ui/date-picker';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewDateCellProps {
- record: RecordNode;
- field: DateFieldNode;
+ field: DateFieldAttributes;
}
-export const TableViewDateCell = ({
- record,
- field,
-}: TableViewDateCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
- const canEdit = true;
+export const TableViewDateCell = ({ field }: TableViewDateCellProps) => {
+ const record = useRecord();
return (
<DatePicker
- value={record.attributes[field.id]}
+ value={record.getDateValue(field)}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (newValue === null || newValue === undefined) {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue.toISOString(),
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'date',
+ value: newValue.toISOString(),
});
}
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-email-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-email-cell.tsx
index 91399af7..22b449d4 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-email-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-email-cell.tsx
@@ -1,49 +1,28 @@
import React from 'react';
-import { RecordNode, EmailFieldNode } from '@/types/databases';
+import { EmailFieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewEmailCellProps {
- record: RecordNode;
- field: EmailFieldNode;
+ field: EmailFieldAttributes;
}
-export const TableViewEmailCell = ({
- record,
- field,
-}: TableViewEmailCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const TableViewEmailCell = ({ field }: TableViewEmailCellProps) => {
+ const record = useRecord();
return (
<SmartTextInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getEmailValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'email',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-multi-select-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-multi-select-cell.tsx
index ce361f65..56de8137 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-multi-select-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-multi-select-cell.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { MultiSelectFieldNode, RecordNode } from '@/types/databases';
+import { MultiSelectFieldAttributes } from '@/registry';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
import {
Popover,
@@ -7,31 +7,28 @@ import {
PopoverContent,
} from '@/renderer/components/ui/popover';
import { SelectFieldOptions } from '@/renderer/components/databases/fields/select-field-options';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewMultiSelectCellProps {
- record: RecordNode;
- field: MultiSelectFieldNode;
+ field: MultiSelectFieldAttributes;
}
export const TableViewMultiSelectCell = ({
- record,
field,
}: TableViewMultiSelectCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+ const record = useRecord();
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState(
- (record.attributes[field.id] as string[]) ?? [],
+ record.getMultiSelectValue(field),
);
React.useEffect(() => {
- setSelectedValues((record.attributes[field.id] as string[]) ?? []);
+ setSelectedValues(record.getMultiSelectValue(field));
}, [record.versionId]);
- const selectedOptions = field.options?.filter((option) =>
+ const selectOptions = Object.values(field.options ?? {});
+ const selectedOptions = selectOptions.filter((option) =>
selectedValues.includes(option.id),
);
@@ -54,29 +51,20 @@ export const TableViewMultiSelectCell = ({
field={field}
values={selectedValues}
onSelect={(id) => {
- if (isPending) return;
+ if (!record.canEdit) return;
- if (selectedValues.includes(id)) {
- setSelectedValues(selectedValues.filter((v) => v !== id));
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ const newValues = selectedValues.includes(id)
+ ? selectedValues.filter((v) => v !== id)
+ : [...selectedValues, id];
+
+ setSelectedValues(newValues);
+
+ if (newValues.length === 0) {
+ record.removeFieldValue(field);
} else {
- const values = [...selectedValues, id];
- setSelectedValues(values);
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: values,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'multiSelect',
+ value: newValues,
});
}
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-number-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-number-cell.tsx
index 3291d437..fced089d 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-number-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-number-cell.tsx
@@ -1,54 +1,32 @@
import React from 'react';
-import { RecordNode } from '@/types/databases';
-import { NumberFieldNode } from '@/types/databases';
+import { NumberFieldAttributes } from '@/registry';
import { SmartNumberInput } from '@/renderer/components/ui/smart-number-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewNumberCellProps {
- record: RecordNode;
- field: NumberFieldNode;
+ field: NumberFieldAttributes;
}
-export const TableViewNumberCell = ({
- record,
- field,
-}: TableViewNumberCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const TableViewNumberCell = ({ field }: TableViewNumberCellProps) => {
+ const record = useRecord();
return (
<SmartNumberInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getNumberValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
- if (newValue === record.attributes[field.id]) {
+ if (newValue === record.getNumberValue(field)) {
return;
}
if (newValue === null) {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'number',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-phone-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-phone-cell.tsx
index 20e6b453..137a51e9 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-phone-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-phone-cell.tsx
@@ -1,53 +1,32 @@
import React from 'react';
-import { RecordNode, PhoneFieldNode } from '@/types/databases';
+import { PhoneFieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewPhoneCellProps {
- record: RecordNode;
- field: PhoneFieldNode;
+ field: PhoneFieldAttributes;
}
-export const TableViewPhoneCell = ({
- record,
- field,
-}: TableViewPhoneCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const TableViewPhoneCell = ({ field }: TableViewPhoneCellProps) => {
+ const record = useRecord();
return (
<SmartTextInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getPhoneValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
- if (newValue === record.attributes[field.id]) {
+ if (newValue === record.getPhoneValue(field)) {
return;
}
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'phone',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-select-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-select-cell.tsx
index 7d22b46d..732df8de 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-select-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-select-cell.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { RecordNode, SelectFieldNode } from '@/types/databases';
+import { SelectFieldAttributes } from '@/registry';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
import {
Popover,
@@ -7,31 +7,25 @@ import {
PopoverContent,
} from '@/renderer/components/ui/popover';
import { SelectFieldOptions } from '@/renderer/components/databases/fields/select-field-options';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewSelectCellProps {
- record: RecordNode;
- field: SelectFieldNode;
+ field: SelectFieldAttributes;
}
-export const TableViewSelectCell = ({
- record,
- field,
-}: TableViewSelectCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
+export const TableViewSelectCell = ({ field }: TableViewSelectCellProps) => {
+ const record = useRecord();
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(
- record.attributes[field.id] ?? '',
+ record.getSelectValue(field),
);
React.useEffect(() => {
- setSelectedValue(record.attributes[field.id] ?? '');
+ setSelectedValue(record.getSelectValue(field));
}, [record.versionId]);
- const selectedOption = field.options?.find(
+ const selectOptions = Object.values(field.options ?? {});
+ const selectedOption = selectOptions.find(
(option) => option.id === selectedValue,
);
@@ -52,36 +46,20 @@ export const TableViewSelectCell = ({
<PopoverContent className="w-80 p-1">
<SelectFieldOptions
field={field}
- values={[selectedValue]}
+ values={selectedValue ? [selectedValue] : []}
allowAdd={true}
onSelect={(id) => {
- if (isPending) {
- return;
- }
+ if (!record.canEdit) return;
if (selectedValue === id) {
setSelectedValue('');
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: id,
- userId: workspace.userId,
- },
- onSuccess() {
- setOpen(false);
- },
+ record.updateFieldValue(field, {
+ type: 'select',
+ value: id,
});
+ setOpen(false);
}
setSelectedValue(id);
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-text-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-text-cell.tsx
index 02e6a8d7..5fa55083 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-text-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-text-cell.tsx
@@ -1,53 +1,32 @@
import React from 'react';
-import { RecordNode, TextFieldNode } from '@/types/databases';
+import { TextFieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewTextCellProps {
- record: RecordNode;
- field: TextFieldNode;
+ field: TextFieldAttributes;
}
-export const TableViewTextCell = ({
- record,
- field,
-}: TableViewTextCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const TableViewTextCell = ({ field }: TableViewTextCellProps) => {
+ const record = useRecord();
return (
<SmartTextInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getTextValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
- if (newValue === record.attributes[field.id]) {
+ if (newValue === record.getTextValue(field)) {
return;
}
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'text',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/databases/tables/cells/table-view-url-cell.tsx b/desktop/src/renderer/components/databases/tables/cells/table-view-url-cell.tsx
index 78c9fae2..784095e9 100644
--- a/desktop/src/renderer/components/databases/tables/cells/table-view-url-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/cells/table-view-url-cell.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { RecordNode, UrlFieldNode } from '@/types/databases';
+import { UrlFieldAttributes } from '@/registry';
import { cn, isValidUrl } from '@/lib/utils';
import {
HoverCard,
@@ -7,55 +7,38 @@ import {
HoverCardTrigger,
} from '@/renderer/components/ui/hover-card';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
import { ExternalLink } from 'lucide-react';
+import { useRecord } from '@/renderer/contexts/record';
interface TableViewUrlCellProps {
- record: RecordNode;
- field: UrlFieldNode;
+ field: UrlFieldAttributes;
}
-export const TableViewUrlCell = ({ record, field }: TableViewUrlCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+export const TableViewUrlCell = ({ field }: TableViewUrlCellProps) => {
+ const record = useRecord();
- const canEdit = true;
- const text = record.attributes[field.id];
- const isUrl = text.length > 0 && isValidUrl(text);
+ const text = record.getUrlValue(field);
+ const isUrl = text && isValidUrl(text);
return (
<HoverCard openDelay={300}>
<HoverCardTrigger>
<SmartTextInput
value={text}
- readOnly={!canEdit || isPending}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (newValue === text) {
return;
}
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'url',
+ value: newValue,
});
}
}}
@@ -70,7 +53,7 @@ export const TableViewUrlCell = ({ record, field }: TableViewUrlCellProps) => {
>
<a
className="text-blue-500 underline hover:cursor-pointer hover:text-blue-600"
- href={text}
+ href={text ?? ''}
target="_blank"
rel="noreferrer"
>
diff --git a/desktop/src/renderer/components/databases/tables/table-view-body.tsx b/desktop/src/renderer/components/databases/tables/table-view-body.tsx
index c5e7a9b5..499bb2e9 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-body.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-body.tsx
@@ -4,7 +4,7 @@ import { TableViewRow } from '@/renderer/components/databases/tables/table-view-
import { TableViewEmptyPlaceholder } from '@/renderer/components/databases/tables/table-view-empty-placeholder';
import { TableViewLoadMoreRow } from '@/renderer/components/databases/tables/table-view-load-more-row';
import { useInfiniteQuery } from '@/renderer/hooks/use-infinite-query';
-import { useViewSearch } from '@/renderer/contexts/view-search';
+import { useView } from '@/renderer/contexts/view';
import { useWorkspace } from '@/renderer/contexts/workspace';
const RECORDS_PER_PAGE = 50;
@@ -12,15 +12,15 @@ const RECORDS_PER_PAGE = 50;
export const TableViewBody = () => {
const workspace = useWorkspace();
const database = useDatabase();
- const viewSearch = useViewSearch();
+ const view = useView();
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
useInfiniteQuery({
initialPageInput: {
type: 'record_list',
databaseId: database.id,
- filters: viewSearch.filters,
- sorts: viewSearch.sorts,
+ filters: view.filters,
+ sorts: view.sorts,
page: 0,
count: RECORDS_PER_PAGE,
userId: workspace.userId,
@@ -38,8 +38,8 @@ export const TableViewBody = () => {
return {
type: 'record_list',
databaseId: database.id,
- filters: viewSearch.filters,
- sorts: viewSearch.sorts,
+ filters: view.filters,
+ sorts: view.sorts,
page: page,
count: RECORDS_PER_PAGE,
userId: workspace.userId,
diff --git a/desktop/src/renderer/components/databases/tables/table-view-field-cell.tsx b/desktop/src/renderer/components/databases/tables/table-view-field-cell.tsx
index 3dcd8dec..f8f9cb20 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-field-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-field-cell.tsx
@@ -1,5 +1,6 @@
import React from 'react';
-import { FieldNode, RecordNode } from '@/types/databases';
+import { RecordNode } from '@/types/nodes';
+import { FieldAttributes } from '@/registry';
import { TableViewTextCell } from '@/renderer/components/databases/tables/cells/table-view-text-cell';
import { TableViewNumberCell } from '@/renderer/components/databases/tables/cells/table-view-number-cell';
import { TableViewBooleanCell } from '@/renderer/components/databases/tables/cells/table-view-boolean-cell';
@@ -14,38 +15,38 @@ import { TableViewDateCell } from '@/renderer/components/databases/tables/cells/
interface TableViewFieldCellProps {
record: RecordNode;
- field: FieldNode;
+ field: FieldAttributes;
}
export const TableViewFieldCell = ({
record,
field,
}: TableViewFieldCellProps) => {
- switch (field.dataType) {
+ switch (field.type) {
case 'text':
- return <TableViewTextCell record={record} field={field} />;
+ return <TableViewTextCell field={field} />;
case 'number':
- return <TableViewNumberCell record={record} field={field} />;
+ return <TableViewNumberCell field={field} />;
case 'boolean':
- return <TableViewBooleanCell record={record} field={field} />;
- case 'created_at':
- return <TableViewCreatedAtCell record={record} field={field} />;
- case 'created_by':
- return <TableViewCreatedByCell record={record} field={field} />;
+ return <TableViewBooleanCell field={field} />;
+ case 'createdAt':
+ return <TableViewCreatedAtCell field={field} />;
+ case 'createdBy':
+ return <TableViewCreatedByCell field={field} />;
case 'select':
- return <TableViewSelectCell record={record} field={field} />;
+ return <TableViewSelectCell field={field} />;
case 'phone':
- return <TableViewPhoneCell record={record} field={field} />;
+ return <TableViewPhoneCell field={field} />;
case 'email':
- return <TableViewEmailCell record={record} field={field} />;
+ return <TableViewEmailCell field={field} />;
case 'url':
- return <TableViewUrlCell record={record} field={field} />;
- case 'multi_select':
- return <TableViewMultiSelectCell record={record} field={field} />;
+ return <TableViewUrlCell field={field} />;
+ case 'multiSelect':
+ return <TableViewMultiSelectCell field={field} />;
case 'collaborator':
return null;
case 'date':
- return <TableViewDateCell record={record} field={field} />;
+ return <TableViewDateCell field={field} />;
case 'file':
return null;
default:
diff --git a/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx b/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx
index 0a4ec6e2..df91e420 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx
@@ -2,7 +2,6 @@ import React from 'react';
import { cn } from '@/lib/utils';
import { useDrag, useDrop } from 'react-dnd';
import { Resizable } from 're-resizable';
-import { FieldNode } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -11,31 +10,34 @@ import {
import { Separator } from '@/renderer/components/ui/separator';
import { FieldDeleteDialog } from '@/renderer/components/databases/fields/field-delete-dialog';
import { FieldRenameInput } from '@/renderer/components/databases/fields/field-rename-input';
-import { useTableView } from '@/renderer/contexts/table-view';
+import { useView } from '@/renderer/contexts/view';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { ArrowDownAz, ArrowDownZa, EyeOff, Filter, Trash2 } from 'lucide-react';
+import { ViewField } from '@/types/databases';
interface TableViewFieldHeaderProps {
- field: FieldNode;
+ viewField: ViewField;
}
-export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
- const tableView = useTableView();
+export const TableViewFieldHeader = ({
+ viewField,
+}: TableViewFieldHeaderProps) => {
+ const view = useView();
const canEditDatabase = true;
const canEditView = true;
const [showDeleteDialog, setShowDeleteDialog] = React.useState(false);
- const [, dragRef] = useDrag<FieldNode>({
+ const [, dragRef] = useDrag<ViewField>({
type: 'table-field-header',
- item: field,
+ item: viewField,
canDrag: () => canEditView,
end: (_item, monitor) => {
const dropResult = monitor.getDropResult<{ after: string }>();
if (!dropResult?.after) return;
- tableView.moveField(field.id, dropResult.after);
+ view.moveField(viewField.field.id, dropResult.after);
},
collect: (monitor) => ({
isDragging: monitor.isDragging(),
@@ -45,7 +47,7 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
const [dropMonitor, dropRef] = useDrop({
accept: 'table-field-header',
drop: () => ({
- after: field.id,
+ after: viewField.field.id,
}),
collect: (monitor) => ({
isOver: monitor.isOver(),
@@ -60,13 +62,13 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
<React.Fragment>
<Resizable
defaultSize={{
- width: `${tableView.getFieldWidth(field.id, field.dataType)}px`,
+ width: `${viewField.width}px`,
height: '2rem',
}}
minWidth={100}
maxWidth={500}
size={{
- width: `${tableView.getFieldWidth(field.id, field.dataType)}px`,
+ width: `${viewField.width}px`,
height: '2rem',
}}
enable={{
@@ -90,7 +92,7 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
}}
onResizeStop={(_e, _direction, ref) => {
const newWidth = ref.offsetWidth;
- tableView.resizeField(field.id, newWidth);
+ view.resizeField(viewField.field.id, newWidth);
}}
>
<Popover modal={true}>
@@ -104,12 +106,12 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
)}
ref={dragDropRef as any}
>
- <FieldIcon type={field.dataType} className="size-4" />
- <p>{field.name}</p>
+ <FieldIcon type={viewField.field.type} className="size-4" />
+ <p>{viewField.field.name}</p>
</div>
</PopoverTrigger>
<PopoverContent className="ml-1 flex w-72 flex-col gap-1 p-2 text-sm">
- <FieldRenameInput field={field} />
+ <FieldRenameInput field={viewField.field} />
<Separator />
{true && (
<>
@@ -153,7 +155,7 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
<div
className="flex cursor-pointer flex-row items-center gap-2 p-1 hover:bg-gray-100"
onClick={() => {
- tableView.hideField(field.id);
+ view.setFieldDisplay(viewField.field.id, false);
}}
>
<EyeOff className="size-4" />
@@ -176,7 +178,7 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
</Resizable>
{showDeleteDialog && (
<FieldDeleteDialog
- id={field.id}
+ id={viewField.field.id}
open={showDeleteDialog}
onOpenChange={setShowDeleteDialog}
/>
diff --git a/desktop/src/renderer/components/databases/tables/table-view-header.tsx b/desktop/src/renderer/components/databases/tables/table-view-header.tsx
index ca7deccb..6922f53c 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-header.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-header.tsx
@@ -1,18 +1,18 @@
import React from 'react';
-import { useTableView } from '@/renderer/contexts/table-view';
+import { useView } from '@/renderer/contexts/view';
import { TableViewNameHeader } from '@/renderer/components/databases/tables/table-view-name-header';
import { TableViewFieldHeader } from '@/renderer/components/databases/tables/table-view-field-header';
import { FieldCreatePopover } from '@/renderer/components/databases/fields/field-create-popover';
export const TableViewHeader = () => {
- const tableView = useTableView();
+ const view = useView();
return (
<div className="flex flex-row items-center gap-0.5">
<div style={{ width: '30px', minWidth: '30px' }} />
<TableViewNameHeader />
- {tableView.fields.map((field) => {
- return <TableViewFieldHeader field={field} key={field.id} />;
+ {view.fields.map((field) => {
+ return <TableViewFieldHeader viewField={field} key={field.field.id} />;
})}
<FieldCreatePopover />
</div>
diff --git a/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx b/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
index 2b6fa271..4b34cb1a 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
@@ -2,7 +2,7 @@ import React from 'react';
import isHotkey from 'is-hotkey';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { Spinner } from '@/renderer/components/ui/spinner';
-import { RecordNode } from '@/types/databases';
+import { RecordNode } from '@/types/nodes';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { Maximize2 } from 'lucide-react';
@@ -56,14 +56,14 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
const { mutate, isPending } = useMutation();
const canEdit = true;
- const hasName = record.name && record.name.length > 0;
+ const hasName = record.attributes.name && record.attributes.name.length > 0;
const handleSave = (newName: string) => {
mutate({
input: {
type: 'node_attribute_set',
nodeId: record.id,
- attribute: 'name',
+ path: 'name',
value: newName,
userId: workspace.userId,
},
@@ -77,7 +77,7 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
<div className="group relative flex h-full w-full items-center">
{isEditing ? (
<NameEditor
- initialValue={record.name ?? ''}
+ initialValue={record.attributes.name ?? ''}
onSave={handleSave}
onCancel={() => setIsEditing(false)}
/>
@@ -88,7 +88,7 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
className="flex h-full w-full cursor-pointer flex-row items-center gap-1 p-1 text-sm"
>
{hasName ? (
- record.name
+ record.attributes.name
) : (
<span className="text-muted-foreground">Unnamed</span>
)}
diff --git a/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx b/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx
index cdf0ff48..71146860 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx
@@ -7,13 +7,13 @@ import {
} from '@/renderer/components/ui/popover';
import { Separator } from '@/renderer/components/ui/separator';
import { Input } from '@/renderer/components/ui/input';
-import { useTableView } from '@/renderer/contexts/table-view';
+import { useView } from '@/renderer/contexts/view';
import { useDrop } from 'react-dnd';
import { cn } from '@/lib/utils';
import { ArrowDownAz, ArrowDownZa, Filter, Type } from 'lucide-react';
export const TableViewNameHeader = () => {
- const tableView = useTableView();
+ const view = useView();
const canEditView = true;
@@ -31,12 +31,12 @@ export const TableViewNameHeader = () => {
return (
<Resizable
defaultSize={{
- width: `${tableView.getNameWidth()}px`,
+ width: `${view.nameWidth}px`,
height: '2rem',
}}
minWidth={100}
maxWidth={500}
- size={{ width: `${tableView.getNameWidth()}px`, height: '2rem' }}
+ size={{ width: `${view.nameWidth}px`, height: '2rem' }}
enable={{
bottom: false,
bottomLeft: false,
@@ -58,7 +58,7 @@ export const TableViewNameHeader = () => {
}}
onResizeStop={(e, direction, ref) => {
const newWidth = ref.offsetWidth;
- tableView.resizeName(newWidth);
+ view.resizeName(newWidth);
}}
>
<Popover modal={true}>
diff --git a/desktop/src/renderer/components/databases/tables/table-view-row.tsx b/desktop/src/renderer/components/databases/tables/table-view-row.tsx
index fac47995..ce5b318f 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-row.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-row.tsx
@@ -1,8 +1,9 @@
import React from 'react';
import { TableViewNameCell } from '@/renderer/components/databases/tables/table-view-name-cell';
import { TableViewFieldCell } from '@/renderer/components/databases/tables/table-view-field-cell';
-import { RecordNode } from '@/types/databases';
-import { useTableView } from '@/renderer/contexts/table-view';
+import { RecordNode } from '@/types/nodes';
+import { useView } from '@/renderer/contexts/view';
+import { RecordProvider } from '../../records/record-provider';
interface TableViewRowProps {
index: number;
@@ -10,35 +11,36 @@ interface TableViewRowProps {
}
export const TableViewRow = ({ index, record }: TableViewRowProps) => {
- const tableView = useTableView();
+ const view = useView();
return (
- <div className="animate-fade-in flex flex-row items-center gap-0.5 border-b">
- <span
- className="flex cursor-pointer items-center justify-center text-sm text-muted-foreground"
- style={{ width: '30px', minWidth: '30px' }}
- >
- {index + 1}
- </span>
- <div
- className="h-8 border-r"
- style={{ width: `${tableView.getNameWidth()}px`, minWidth: '300px' }}
- >
- <TableViewNameCell record={record} />
+ <RecordProvider record={record}>
+ <div className="animate-fade-in flex flex-row items-center gap-0.5 border-b">
+ <span
+ className="flex cursor-pointer items-center justify-center text-sm text-muted-foreground"
+ style={{ width: '30px', minWidth: '30px' }}
+ >
+ {index + 1}
+ </span>
+ <div
+ className="h-8 border-r"
+ style={{ width: `${view.nameWidth}px`, minWidth: '300px' }}
+ >
+ <TableViewNameCell record={record} />
+ </div>
+ {view.fields.map((field) => {
+ return (
+ <div
+ key={`row-${record.id}-${field.field.id}`}
+ className="h-8 border-r"
+ style={{ width: `${field.width}px` }}
+ >
+ <TableViewFieldCell record={record} field={field.field} />
+ </div>
+ );
+ })}
+ <div className="w-8" />
</div>
- {tableView.fields.map((field) => {
- const width = tableView.getFieldWidth(field.id, field.dataType);
- return (
- <div
- key={`row-${record.id}-${field.id}`}
- className="h-8 border-r"
- style={{ width: width }}
- >
- <TableViewFieldCell record={record} field={field} />
- </div>
- );
- })}
- <div className="w-8" />
- </div>
+ </RecordProvider>
);
};
diff --git a/desktop/src/renderer/components/databases/tables/table-view-settings-popover.tsx b/desktop/src/renderer/components/databases/tables/table-view-settings-popover.tsx
index 70c3b31a..45e365f8 100644
--- a/desktop/src/renderer/components/databases/tables/table-view-settings-popover.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view-settings-popover.tsx
@@ -4,7 +4,7 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-import { useTableView } from '@/renderer/contexts/table-view';
+import { useView } from '@/renderer/contexts/view';
import { Separator } from '@/renderer/components/ui/separator';
import { useDatabase } from '@/renderer/contexts/database';
import { cn } from '@/lib/utils';
@@ -26,8 +26,9 @@ import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
export const TableViewSettingsPopover = () => {
const workspace = useWorkspace();
- const tableView = useTableView();
const database = useDatabase();
+ const view = useView();
+
const { mutate, isPending } = useMutation();
const [open, setOpen] = React.useState(false);
@@ -51,13 +52,13 @@ export const TableViewSettingsPopover = () => {
<AvatarPopover
onPick={(avatar) => {
if (isPending) return;
- if (avatar === tableView.avatar) return;
+ if (avatar === view.avatar) return;
mutate({
input: {
type: 'node_attribute_set',
- nodeId: tableView.id,
- attribute: 'avatar',
+ nodeId: view.id,
+ path: 'avatar',
value: avatar,
userId: workspace.userId,
},
@@ -66,24 +67,24 @@ export const TableViewSettingsPopover = () => {
>
<Button type="button" variant="outline" size="icon">
<Avatar
- id={tableView.id}
- name={tableView.name}
- avatar={tableView.avatar}
+ id={view.id}
+ name={view.name}
+ avatar={view.avatar}
className="h-6 w-6"
/>
</Button>
</AvatarPopover>
<SmartTextInput
- value={tableView.name}
+ value={view.name}
onChange={(newName) => {
if (isPending) return;
- if (newName === tableView.name) return;
+ if (newName === view.name) return;
mutate({
input: {
type: 'node_attribute_set',
- nodeId: tableView.id,
- attribute: 'name',
+ nodeId: view.id,
+ path: 'name',
value: newName,
userId: workspace.userId,
},
@@ -95,7 +96,9 @@ export const TableViewSettingsPopover = () => {
<div className="flex flex-col gap-2 text-sm">
<p className="my-1 font-semibold">Fields</p>
{database.fields.map((field) => {
- const isHidden = tableView.isHiddenField(field.id);
+ const isHidden = !!view.fields.find(
+ (f) => f.field.id === field.id,
+ );
return (
<div
@@ -106,7 +109,7 @@ export const TableViewSettingsPopover = () => {
)}
>
<div className="flex flex-row items-center gap-2">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<div>{field.name}</div>
</div>
<div className="flex flex-row items-center gap-2">
@@ -119,11 +122,7 @@ export const TableViewSettingsPopover = () => {
onClick={() => {
if (!canEditView) return;
- if (isHidden) {
- tableView.showField(field.id);
- } else {
- tableView.hideField(field.id);
- }
+ view.setFieldDisplay(field.id, !isHidden);
}}
>
{isHidden ? (
@@ -196,7 +195,7 @@ export const TableViewSettingsPopover = () => {
)}
{openDelete && (
<ViewDeleteDialog
- id={tableView.id}
+ id={view.id}
open={openDelete}
onOpenChange={setOpenDelete}
/>
diff --git a/desktop/src/renderer/components/databases/tables/table-view.tsx b/desktop/src/renderer/components/databases/tables/table-view.tsx
index c21dfd3c..f6a09350 100644
--- a/desktop/src/renderer/components/databases/tables/table-view.tsx
+++ b/desktop/src/renderer/components/databases/tables/table-view.tsx
@@ -2,231 +2,29 @@ import React from 'react';
import { TableViewHeader } from '@/renderer/components/databases/tables/table-view-header';
import { TableViewBody } from '@/renderer/components/databases/tables/table-view-body';
import { TableViewRecordCreateRow } from '@/renderer/components/databases/tables/table-view-record-create-row';
-import { TableViewContext } from '@/renderer/contexts/table-view';
-import { useDatabase } from '@/renderer/contexts/database';
-import { compareString } from '@/lib/utils';
-import { FieldDataType, TableViewNode } from '@/types/databases';
import { ViewTabs } from '@/renderer/components/databases/view-tabs';
import { TableViewSettingsPopover } from '@/renderer/components/databases/tables/table-view-settings-popover';
-import { getDefaultFieldWidth, getDefaultNameWidth } from '@/lib/databases';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@/renderer/hooks/use-mutation';
import { ViewSearchBar } from '@/renderer/components/databases/search/view-search-bar';
import { ViewFilterButton } from '@/renderer/components/databases/search/view-filter-button';
import { ViewSortButton } from '@/renderer/components/databases/search/view-sort-button';
-import { ViewSearchProvider } from '@/renderer/components/databases/search/view-search-provider';
-import { useWorkspace } from '@/renderer/contexts/workspace';
-
-interface TableViewProps {
- node: TableViewNode;
-}
-
-export const TableView = ({ node }: TableViewProps) => {
- const workspace = useWorkspace();
- const database = useDatabase();
- const { mutate } = useMutation();
-
- const [hiddenFields, setHiddenFields] = React.useState<string[]>(
- node.hiddenFields ?? [],
- );
- const [fieldIndexes, setFieldIndexes] = React.useState<
- Record<string, string>
- >(node.fieldIndexes ?? {});
- const [fieldWidths, setFieldWidths] = React.useState<Record<string, number>>(
- node.fieldWidths ?? {},
- );
- const [nameWidth, setNameWidth] = React.useState<number>(
- node.nameWidth ?? getDefaultNameWidth(),
- );
-
- React.useEffect(() => {
- setHiddenFields(node.hiddenFields ?? []);
- setFieldIndexes(node.fieldIndexes ?? {});
- setFieldWidths(node.fieldWidths ?? {});
- setNameWidth(node.nameWidth ?? getDefaultNameWidth());
- }, [node.hiddenFields, node.fieldIndexes, node.fieldWidths, node.nameWidth]);
-
- const fields = React.useMemo(() => {
- return database.fields
- .filter((field) => !hiddenFields.includes(field.id))
- .sort((a, b) =>
- compareString(
- fieldIndexes[a.id] ?? a.index,
- fieldIndexes[b.id] ?? b.index,
- ),
- );
- }, [database.fields, hiddenFields, fieldIndexes]);
+export const TableView = () => {
return (
- <TableViewContext.Provider
- value={{
- id: node.id,
- name: node.name,
- avatar: node.avatar,
- fields,
- hideField: (id: string) => {
- if (hiddenFields.includes(id)) {
- return;
- }
-
- const newHiddenFields = [...hiddenFields, id];
- setHiddenFields(newHiddenFields);
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: node.id,
- attribute: 'hiddenFields',
- value: newHiddenFields,
- userId: workspace.userId,
- },
- });
- },
- showField: (id: string) => {
- if (!hiddenFields.includes(id)) {
- return;
- }
-
- const newHiddenFields = hiddenFields.filter((f) => f !== id);
- setHiddenFields(newHiddenFields);
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: node.id,
- attribute: 'hiddenFields',
- value: newHiddenFields,
- userId: workspace.userId,
- },
- });
- },
- isHiddenField: (id: string) => hiddenFields.includes(id),
- getNameWidth: () => nameWidth,
- resizeName: (width: number) => {
- setNameWidth(width);
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: node.id,
- attribute: 'nameWidth',
- value: width,
- userId: workspace.userId,
- },
- });
- },
- getFieldWidth: (id: string, type: FieldDataType) => {
- return fieldWidths[id] ?? getDefaultFieldWidth(type);
- },
- resizeField: (id, width) => {
- setFieldWidths({ ...fieldWidths, [id]: width });
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: node.id,
- attribute: 'fieldWidths',
- value: { ...fieldWidths, [id]: width },
- userId: workspace.userId,
- },
- });
- },
- moveField: (id, after) => {
- const field = database.fields.find((f) => f.id === id);
- if (!field) {
- return;
- }
-
- if (database.fields.length <= 1) {
- return;
- }
-
- const mergedIndexes = database.fields
- .map((f) => {
- return {
- id: f.id,
- databaseIndex: f.index,
- viewIndex: fieldIndexes[f.id],
- };
- })
- .sort((a, b) =>
- compareString(
- a.viewIndex ?? a.databaseIndex,
- b.viewIndex ?? b.databaseIndex,
- ),
- );
-
- let previousIndex: string | null = null;
- let nextIndex: string | null = null;
- if (after === 'name') {
- const lowestIndex = mergedIndexes[0];
- nextIndex = lowestIndex.viewIndex ?? lowestIndex.databaseIndex;
- } else {
- const afterFieldArrayIndex = mergedIndexes.findIndex(
- (f) => f.id === after,
- );
- if (afterFieldArrayIndex === -1) {
- return;
- }
-
- previousIndex =
- mergedIndexes[afterFieldArrayIndex].viewIndex ??
- mergedIndexes[afterFieldArrayIndex].databaseIndex;
-
- if (afterFieldArrayIndex < mergedIndexes.length) {
- nextIndex =
- mergedIndexes[afterFieldArrayIndex + 1].viewIndex ??
- mergedIndexes[afterFieldArrayIndex + 1].databaseIndex;
- }
- }
-
- let newIndex = generateNodeIndex(previousIndex, nextIndex);
-
- const lastDatabaseField = mergedIndexes.sort((a, b) =>
- compareString(a.databaseIndex, b.databaseIndex),
- )[mergedIndexes.length - 1];
-
- const newPotentialFieldIndex = generateNodeIndex(
- lastDatabaseField.databaseIndex,
- null,
- );
-
- if (newPotentialFieldIndex === newIndex) {
- newIndex = generateNodeIndex(previousIndex, newPotentialFieldIndex);
- }
-
- setFieldIndexes({
- ...fieldIndexes,
- [id]: newIndex,
- });
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: node.id,
- attribute: 'fieldIndexes',
- value: { ...fieldIndexes, [id]: newIndex },
- userId: workspace.userId,
- },
- });
- },
- }}
- >
- <ViewSearchProvider
- id={node.id}
- filters={node.filters}
- sorts={node.sorts}
- >
- <div className="mt-2 flex flex-row justify-between border-b">
- <ViewTabs />
- <div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
- <TableViewSettingsPopover />
- <ViewSortButton />
- <ViewFilterButton />
- </div>
- </div>
- <ViewSearchBar />
- <div className="mt-2 w-full min-w-full max-w-full overflow-auto pr-5">
- <TableViewHeader />
- <TableViewBody />
- <TableViewRecordCreateRow />
+ <React.Fragment>
+ <div className="mt-2 flex flex-row justify-between border-b">
+ <ViewTabs />
+ <div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
+ <TableViewSettingsPopover />
+ <ViewSortButton />
+ <ViewFilterButton />
</div>
- </ViewSearchProvider>
- </TableViewContext.Provider>
+ </div>
+ <ViewSearchBar />
+ <div className="mt-2 w-full min-w-full max-w-full overflow-auto pr-5">
+ <TableViewHeader />
+ <TableViewBody />
+ <TableViewRecordCreateRow />
+ </div>
+ </React.Fragment>
);
};
diff --git a/desktop/src/renderer/components/databases/view-create-dialog.tsx b/desktop/src/renderer/components/databases/view-create-dialog.tsx
index 6da95e92..0e01de26 100644
--- a/desktop/src/renderer/components/databases/view-create-dialog.tsx
+++ b/desktop/src/renderer/components/databases/view-create-dialog.tsx
@@ -31,31 +31,31 @@ import { Calendar, Columns, Table } from 'lucide-react';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
- type: z.enum(['TABLE', 'BOARD', 'CALENDAR']),
+ type: z.enum(['table', 'board', 'calendar']),
groupBy: z.string().optional(),
});
interface ViewTypeOption {
name: string;
icon: React.FC;
- type: 'TABLE' | 'BOARD' | 'CALENDAR';
+ type: 'table' | 'board' | 'calendar';
}
const viewTypes: ViewTypeOption[] = [
{
name: 'Table',
icon: Table,
- type: 'TABLE',
+ type: 'table',
},
{
name: 'Board',
icon: Columns,
- type: 'BOARD',
+ type: 'board',
},
{
name: 'Calendar',
icon: Calendar,
- type: 'CALENDAR',
+ type: 'calendar',
},
];
@@ -76,7 +76,7 @@ export const ViewCreateDialog = ({
resolver: zodResolver(formSchema),
defaultValues: {
name: '',
- type: 'TABLE',
+ type: 'table',
},
});
const type = form.watch('type');
@@ -91,20 +91,7 @@ export const ViewCreateDialog = ({
return;
}
- if (values.type === 'TABLE') {
- mutate({
- input: {
- type: 'table_view_create',
- databaseId: database.id,
- name: values.name,
- userId: workspace.userId,
- },
- onSuccess() {
- form.reset();
- onOpenChange(false);
- },
- });
- } else if (values.type === 'BOARD') {
+ if (values.type === 'board') {
if (!values.groupBy) {
toast({
title: 'Failed to create board view',
@@ -114,21 +101,7 @@ export const ViewCreateDialog = ({
});
return;
}
-
- mutate({
- input: {
- type: 'board_view_create',
- databaseId: database.id,
- name: values.name,
- groupBy: values.groupBy,
- userId: workspace.userId,
- },
- onSuccess() {
- form.reset();
- onOpenChange(false);
- },
- });
- } else if (values.type === 'CALENDAR') {
+ } else if (values.type === 'calendar') {
if (!values.groupBy) {
toast({
title: 'Failed to create calendar view',
@@ -138,21 +111,22 @@ export const ViewCreateDialog = ({
});
return;
}
-
- mutate({
- input: {
- type: 'calendar_view_create',
- databaseId: database.id,
- name: values.name,
- groupBy: values.groupBy,
- userId: workspace.userId,
- },
- onSuccess() {
- form.reset();
- onOpenChange(false);
- },
- });
}
+
+ mutate({
+ input: {
+ type: 'view_create',
+ viewType: values.type,
+ databaseId: database.id,
+ name: values.name,
+ userId: workspace.userId,
+ groupBy: values.groupBy ?? null,
+ },
+ onSuccess() {
+ form.reset();
+ onOpenChange(false);
+ },
+ });
};
return (
@@ -208,7 +182,7 @@ export const ViewCreateDialog = ({
</div>
)}
/>
- {type === 'BOARD' && (
+ {type === 'board' && (
<FormField
control={form.control}
name="groupBy"
@@ -218,9 +192,9 @@ export const ViewCreateDialog = ({
<FormControl>
<FieldSelect
fields={database.fields.filter(
- (field) => field.dataType === 'select',
+ (field) => field.type === 'select',
)}
- value={field.value}
+ value={field.value ?? null}
onChange={field.onChange}
/>
</FormControl>
@@ -229,7 +203,7 @@ export const ViewCreateDialog = ({
)}
/>
)}
- {type === 'CALENDAR' && (
+ {type === 'calendar' && (
<FormField
control={form.control}
name="groupBy"
@@ -240,10 +214,10 @@ export const ViewCreateDialog = ({
<FieldSelect
fields={database.fields.filter(
(field) =>
- field.dataType === 'date' ||
- field.dataType === 'created_at',
+ field.type === 'date' ||
+ field.type === 'createdAt',
)}
- value={field.value}
+ value={field.value ?? null}
onChange={field.onChange}
/>
</FormControl>
diff --git a/desktop/src/renderer/components/databases/view-delete-dialog.tsx b/desktop/src/renderer/components/databases/view-delete-dialog.tsx
index 442a408e..33d12f83 100644
--- a/desktop/src/renderer/components/databases/view-delete-dialog.tsx
+++ b/desktop/src/renderer/components/databases/view-delete-dialog.tsx
@@ -11,6 +11,7 @@ import {
import { Button } from '@/renderer/components/ui/button';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useDatabase } from '@/renderer/contexts/database';
interface ViewDeleteDialogProps {
id: string;
@@ -24,6 +25,7 @@ export const ViewDeleteDialog = ({
onOpenChange,
}: ViewDeleteDialogProps) => {
const workspace = useWorkspace();
+ const database = useDatabase();
const { mutate, isPending } = useMutation();
return (
@@ -46,8 +48,9 @@ export const ViewDeleteDialog = ({
onClick={() => {
mutate({
input: {
- type: 'node_delete',
- nodeId: id,
+ type: 'view_delete',
+ viewId: id,
+ databaseId: database.id,
userId: workspace.userId,
},
onSuccess() {
diff --git a/desktop/src/renderer/components/databases/view-tab.tsx b/desktop/src/renderer/components/databases/view-tab.tsx
index fe825429..feec1293 100644
--- a/desktop/src/renderer/components/databases/view-tab.tsx
+++ b/desktop/src/renderer/components/databases/view-tab.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { cn } from '@/lib/utils';
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { ViewNode } from '@/types/databases';
+import { ViewAttributes } from '@/registry/database';
interface ViewTabProps {
- view: ViewNode;
+ view: ViewAttributes;
isActive: boolean;
onClick: () => void;
}
diff --git a/desktop/src/renderer/components/databases/view.tsx b/desktop/src/renderer/components/databases/view.tsx
index df8d08c5..dc713d4c 100644
--- a/desktop/src/renderer/components/databases/view.tsx
+++ b/desktop/src/renderer/components/databases/view.tsx
@@ -1,25 +1,344 @@
import React from 'react';
-import { ViewNode } from '@/types/databases';
+import { match } from 'ts-pattern';
+import {
+ ViewAttributes,
+ ViewFieldFilterAttributes,
+ ViewFilterAttributes,
+ ViewSortAttributes,
+} from '@/registry/database';
import { TableView } from '@/renderer/components/databases/tables/table-view';
import { BoardView } from '@/renderer/components/databases/boards/board-view';
import { CalendarView } from '@/renderer/components/databases/calendars/calendar-view';
+import { ViewContext } from '@/renderer/contexts/view';
+import { useDatabase } from '@/renderer/contexts/database';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { compareString } from '@/lib/utils';
+import {
+ generateViewFieldIndex,
+ getDefaultFieldWidth,
+ getDefaultNameWidth,
+ getFieldFilterOperators,
+} from '@/lib/databases';
+import { ViewField } from '@/types/databases';
+import { useMutation } from '@/renderer/hooks/use-mutation';
interface ViewProps {
- node: ViewNode;
+ view: ViewAttributes;
}
-export const View = ({ node }: ViewProps) => {
- if (node.type === 'table_view') {
- return <TableView node={node} />;
- }
+export const View = ({ view }: ViewProps) => {
+ const workspace = useWorkspace();
+ const database = useDatabase();
+ const { mutate, isPending } = useMutation();
- if (node.type === 'board_view') {
- return <BoardView node={node} />;
- }
+ const fields: ViewField[] = React.useMemo(() => {
+ return database.fields
+ .map((field) => {
+ const viewField = view.fields[field.id];
- if (node.type === 'calendar_view') {
- return <CalendarView node={node} />;
- }
+ return {
+ field,
+ display: viewField?.display ?? true,
+ index: viewField?.index ?? field.index,
+ width: viewField?.width ?? getDefaultFieldWidth(field.type),
+ };
+ })
+ .filter((field) => field.display)
+ .sort((a, b) => compareString(a.index, b.index));
+ }, [database.fields, view.fields]);
- return null;
+ const [isSearchBarOpened, setIsSearchBarOpened] = React.useState(false);
+ const [isSortsOpened, setIsSortsOpened] = React.useState(false);
+ const [openedFieldFilters, setOpenedFieldFilters] = React.useState<string[]>(
+ [],
+ );
+
+ return (
+ <ViewContext.Provider
+ value={{
+ id: view.id,
+ name: view.name,
+ avatar: view.avatar,
+ fields,
+ filters: Object.values(view.filters),
+ sorts: Object.values(view.sorts),
+ groupBy: view.groupBy,
+ nameWidth: view.nameWidth ?? getDefaultNameWidth(),
+ isSearchBarOpened,
+ isSortsOpened,
+ setFieldDisplay: (id: string, display: boolean) => {
+ const viewField = view.fields[id];
+ if (viewField && viewField.display === display) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ if (!viewCopy.fields[id]) {
+ viewCopy.fields[id] = {
+ id: id,
+ display: display,
+ };
+ } else {
+ viewCopy.fields[id].display = display;
+ }
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ });
+ },
+ resizeField: (id: string, width: number) => {
+ const viewField = view.fields[id];
+ if (viewField && viewField.width === width) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ if (!viewCopy.fields[id]) {
+ viewCopy.fields[id] = {
+ id: id,
+ width: width,
+ };
+ } else {
+ viewCopy.fields[id].width = width;
+ }
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ });
+ },
+ resizeName: (width: number) => {
+ if (view.nameWidth === width) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ viewCopy.nameWidth = width;
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ });
+ },
+ moveField: (id: string, after: string) => {
+ const newIndex = generateViewFieldIndex(
+ database.fields,
+ Object.values(view.fields),
+ id,
+ after,
+ );
+ if (newIndex === null) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ if (!viewCopy.fields[id]) {
+ viewCopy.fields[id] = {
+ id: id,
+ index: newIndex,
+ };
+ } else {
+ viewCopy.fields[id].index = newIndex;
+ }
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ });
+ },
+ isFieldFilterOpened: (fieldId: string) =>
+ openedFieldFilters.includes(fieldId),
+ initFieldFilter: (fieldId: string) => {
+ if (view.filters[fieldId]) {
+ setOpenedFieldFilters((prev) => [...prev, fieldId]);
+ return;
+ }
+
+ const field = database.fields.find((f) => f.id === fieldId);
+ if (!field) {
+ return;
+ }
+
+ const operators = getFieldFilterOperators(field.type);
+ const filter: ViewFieldFilterAttributes = {
+ type: 'field',
+ id: fieldId,
+ fieldId,
+ operator: operators[0].value,
+ value: null,
+ };
+
+ const viewCopy = { ...view };
+ viewCopy.filters[fieldId] = filter;
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ onSuccess() {
+ setOpenedFieldFilters((prev) => [...prev, fieldId]);
+ setIsSearchBarOpened(true);
+ },
+ });
+ },
+ updateFilter: (id: string, filter: ViewFilterAttributes) => {
+ if (!view.filters[id]) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ viewCopy.filters[id] = filter;
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ },
+ });
+ },
+ removeFilter: (id: string) => {
+ if (!view.filters[id]) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ delete viewCopy.filters[id];
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ },
+ });
+ },
+ initFieldSort: (fieldId: string) => {
+ if (view.sorts[fieldId]) {
+ return;
+ }
+
+ const field = database.fields.find((f) => f.id === fieldId);
+ if (!field) {
+ return;
+ }
+
+ const sort: ViewSortAttributes = {
+ id: fieldId,
+ fieldId,
+ direction: 'asc',
+ };
+
+ const viewCopy = { ...view };
+ viewCopy.sorts[fieldId] = sort;
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ setIsSortsOpened(true);
+ },
+ });
+ },
+ updateSort: (id: string, sort: ViewSortAttributes) => {
+ if (!view.sorts[id]) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ viewCopy.sorts[id] = sort;
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ setIsSortsOpened(true);
+ },
+ });
+ },
+ removeSort: (id: string) => {
+ if (!view.sorts[id]) {
+ return;
+ }
+
+ const viewCopy = { ...view };
+ delete viewCopy.sorts[id];
+
+ mutate({
+ input: {
+ type: 'view_update',
+ userId: workspace.userId,
+ databaseId: database.id,
+ view: viewCopy,
+ },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ },
+ });
+ },
+ openSearchBar: () => {
+ setIsSearchBarOpened(true);
+ },
+ closeSearchBar: () => {
+ setIsSearchBarOpened(false);
+ },
+ openSorts: () => {
+ setIsSortsOpened(true);
+ },
+ closeSorts: () => {
+ setIsSortsOpened(false);
+ },
+ openFieldFilter: (fieldId: string) => {
+ setOpenedFieldFilters((prev) => [...prev, fieldId]);
+ },
+ closeFieldFilter: (fieldId: string) => {
+ setOpenedFieldFilters((prev) => prev.filter((id) => id !== fieldId));
+ },
+ }}
+ >
+ {match(view.type)
+ .with('table', () => <TableView />)
+ .with('board', () => <BoardView />)
+ .with('calendar', () => <CalendarView />)
+ .exhaustive()}
+ </ViewContext.Provider>
+ );
};
diff --git a/desktop/src/renderer/components/documents/document-editor.tsx b/desktop/src/renderer/components/documents/document-editor.tsx
index 797e8603..dfff079b 100644
--- a/desktop/src/renderer/components/documents/document-editor.tsx
+++ b/desktop/src/renderer/components/documents/document-editor.tsx
@@ -168,6 +168,10 @@ export const DocumentEditor = ({
);
React.useEffect(() => {
+ if (!editor) {
+ return;
+ }
+
if (hasPendingChanges.current) {
return;
}
diff --git a/desktop/src/renderer/components/documents/document.tsx b/desktop/src/renderer/components/documents/document.tsx
index bb803963..eb7f663f 100644
--- a/desktop/src/renderer/components/documents/document.tsx
+++ b/desktop/src/renderer/components/documents/document.tsx
@@ -15,7 +15,7 @@ export const Document = ({ nodeId }: DocumentProps) => {
userId: workspace.userId,
});
- if (isPending || !data || !data.hash) {
+ if (isPending || !data || !data.hash || data.content === null) {
return null;
}
diff --git a/desktop/src/renderer/components/files/file-download.tsx b/desktop/src/renderer/components/files/file-download.tsx
index da78923b..596e10ca 100644
--- a/desktop/src/renderer/components/files/file-download.tsx
+++ b/desktop/src/renderer/components/files/file-download.tsx
@@ -6,7 +6,7 @@ import { Download } from 'lucide-react';
interface FileDownloadProps {
id: string;
- downloadProgress: number | null;
+ downloadProgress: number | null | undefined;
}
export const FileDownload = ({ id, downloadProgress }: FileDownloadProps) => {
diff --git a/desktop/src/renderer/components/messages/message-create.tsx b/desktop/src/renderer/components/messages/message-create.tsx
index 2d1d83a7..8a6709b8 100644
--- a/desktop/src/renderer/components/messages/message-create.tsx
+++ b/desktop/src/renderer/components/messages/message-create.tsx
@@ -68,8 +68,12 @@ export const MessageCreate = React.forwardRef<
}
const messageContent = content;
+ if (!messageContent) {
+ return;
+ }
+
if (replyTo) {
- messageContent.content.unshift({
+ messageContent.unshift({
type: 'messageReference',
attrs: {
id: replyTo.id,
diff --git a/desktop/src/renderer/components/messages/message-editor.tsx b/desktop/src/renderer/components/messages/message-editor.tsx
index 99c319f8..38be117e 100644
--- a/desktop/src/renderer/components/messages/message-editor.tsx
+++ b/desktop/src/renderer/components/messages/message-editor.tsx
@@ -145,6 +145,8 @@ export const MessageEditor = React.forwardRef<
'Something went wrong adding file to the message. Please try again!',
variant: 'destructive',
});
+
+ return;
}
editor.chain().focus().addFilePlaceholder(fileMetadata).run();
diff --git a/desktop/src/renderer/components/messages/message.tsx b/desktop/src/renderer/components/messages/message.tsx
index 504c08ba..dcb590f6 100644
--- a/desktop/src/renderer/components/messages/message.tsx
+++ b/desktop/src/renderer/components/messages/message.tsx
@@ -18,13 +18,13 @@ import { MessagesSquare, Reply } from 'lucide-react';
interface MessageProps {
message: MessageNode;
- previousMessage?: MessageNode;
+ previousMessage?: MessageNode | null;
onReply: (replyTo: MessageNode | null) => void;
}
const shouldDisplayUserInfo = (
message: MessageNode,
- previousMessage?: MessageNode,
+ previousMessage?: MessageNode | null,
) => {
if (!previousMessage) {
return true;
diff --git a/desktop/src/renderer/components/records/record-attributes.tsx b/desktop/src/renderer/components/records/record-attributes.tsx
index 284b7a8f..a8b577b0 100644
--- a/desktop/src/renderer/components/records/record-attributes.tsx
+++ b/desktop/src/renderer/components/records/record-attributes.tsx
@@ -1,19 +1,15 @@
import React from 'react';
-import { RecordNode } from '@/types/databases';
import { RecordName } from '@/renderer/components/records/record-name';
import { useDatabase } from '@/renderer/contexts/database';
import { RecordField } from '@/renderer/components/records/record-field';
import { RecordFieldValue } from '@/renderer/components/records/record-field-value';
-interface RecordAttributesProps {
- record: RecordNode;
-}
-
-export const RecordAttributes = ({ record }: RecordAttributesProps) => {
+export const RecordAttributes = () => {
const database = useDatabase();
+
return (
<div className="flex flex-col gap-2">
- <RecordName record={record} />
+ <RecordName />
<div className="flex flex-row gap-2">
<div className="flex w-60 flex-col gap-2">
{database.fields.map((field) => (
@@ -22,13 +18,7 @@ export const RecordAttributes = ({ record }: RecordAttributesProps) => {
</div>
<div className="flex flex-1 flex-col gap-2">
{database.fields.map((field) => {
- return (
- <RecordFieldValue
- key={`value-${field.id}`}
- field={field}
- record={record}
- />
- );
+ return <RecordFieldValue key={`value-${field.id}`} field={field} />;
})}
</div>
</div>
diff --git a/desktop/src/renderer/components/records/record-container.tsx b/desktop/src/renderer/components/records/record-container.tsx
index 3a2d8258..64f05a8d 100644
--- a/desktop/src/renderer/components/records/record-container.tsx
+++ b/desktop/src/renderer/components/records/record-container.tsx
@@ -6,6 +6,7 @@ import { ScrollArea } from '@/renderer/components/ui/scroll-area';
import { Document } from '@/renderer/components/documents/document';
import { Separator } from '@/renderer/components/ui/separator';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { RecordProvider } from '@/renderer/components/records/record-provider';
interface RecordContainerProps {
nodeId: string;
@@ -14,24 +15,26 @@ interface RecordContainerProps {
export const RecordContainer = ({ nodeId }: RecordContainerProps) => {
const workspace = useWorkspace();
- const { data: record, isPending: isRecordPending } = useQuery({
- type: 'record_get',
- recordId: nodeId,
+ const { data, isPending } = useQuery({
+ type: 'node_get',
+ nodeId,
userId: workspace.userId,
});
- if (isRecordPending) {
+ if (isPending) {
return null;
}
- if (!record) {
+ if (!data || data.type !== 'record') {
return null;
}
return (
- <Database databaseId={record.parentId}>
+ <Database databaseId={data.attributes.databaseId}>
<ScrollArea className="h-full max-h-full w-full overflow-y-auto px-10 pb-12">
- <RecordAttributes record={record} />
+ <RecordProvider record={data}>
+ <RecordAttributes />
+ </RecordProvider>
<Separator className="my-4 w-full" />
<Document nodeId={nodeId} />
</ScrollArea>
diff --git a/desktop/src/renderer/components/records/record-field-value.tsx b/desktop/src/renderer/components/records/record-field-value.tsx
index 566fa5a5..0bcf59b8 100644
--- a/desktop/src/renderer/components/records/record-field-value.tsx
+++ b/desktop/src/renderer/components/records/record-field-value.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { FieldNode, RecordNode } from '@/types/databases';
+import { FieldAttributes } from '@/registry';
import { RecordTextValue } from '@/renderer/components/records/values/record-text-value';
import { RecordNumberValue } from '@/renderer/components/records/values/record-number-value';
import { RecordBooleanValue } from '@/renderer/components/records/values/record-boolean-value';
@@ -12,31 +12,30 @@ import { RecordUrlValue } from '@/renderer/components/records/values/record-url-
import { RecordMultiSelectValue } from '@/renderer/components/records/values/record-multi-select-value';
interface RecordFieldValueProps {
- record: RecordNode;
- field: FieldNode;
+ field: FieldAttributes;
}
-export const RecordFieldValue = ({ record, field }: RecordFieldValueProps) => {
- switch (field.dataType) {
+export const RecordFieldValue = ({ field }: RecordFieldValueProps) => {
+ switch (field.type) {
case 'text':
- return <RecordTextValue record={record} field={field} />;
+ return <RecordTextValue field={field} />;
case 'number':
- return <RecordNumberValue record={record} field={field} />;
+ return <RecordNumberValue field={field} />;
case 'boolean':
- return <RecordBooleanValue record={record} field={field} />;
- case 'created_at':
- return <RecordCreatedAtValue record={record} field={field} />;
- case 'created_by':
- return <RecordCreatedByValue record={record} field={field} />;
+ return <RecordBooleanValue field={field} />;
+ case 'createdAt':
+ return <RecordCreatedAtValue field={field} />;
+ case 'createdBy':
+ return <RecordCreatedByValue field={field} />;
case 'select':
- return <RecordSelectValue record={record} field={field} />;
+ return <RecordSelectValue field={field} />;
case 'phone':
- return <RecordPhoneValue record={record} field={field} />;
+ return <RecordPhoneValue field={field} />;
case 'email':
- return <RecordEmailValue record={record} field={field} />;
+ return <RecordEmailValue field={field} />;
case 'url':
- return <RecordUrlValue record={record} field={field} />;
- case 'multi_select':
- return <RecordMultiSelectValue record={record} field={field} />;
+ return <RecordUrlValue field={field} />;
+ case 'multiSelect':
+ return <RecordMultiSelectValue field={field} />;
}
};
diff --git a/desktop/src/renderer/components/records/record-field.tsx b/desktop/src/renderer/components/records/record-field.tsx
index 653d0b43..0b961e12 100644
--- a/desktop/src/renderer/components/records/record-field.tsx
+++ b/desktop/src/renderer/components/records/record-field.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { FieldNode } from '@/types/databases';
+import { FieldAttributes } from '@/registry';
import {
Popover,
PopoverContent,
@@ -12,7 +12,7 @@ import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { Trash2 } from 'lucide-react';
interface RecordFieldProps {
- field: FieldNode;
+ field: FieldAttributes;
}
export const RecordField = ({ field }: RecordFieldProps) => {
@@ -24,7 +24,7 @@ export const RecordField = ({ field }: RecordFieldProps) => {
<Popover modal={true}>
<PopoverTrigger asChild>
<div className="flex h-8 w-full cursor-pointer flex-row items-center gap-1 p-1 text-sm hover:bg-gray-50">
- <FieldIcon type={field.dataType} className="size-4" />
+ <FieldIcon type={field.type} className="size-4" />
<p>{field.name}</p>
</div>
</PopoverTrigger>
diff --git a/desktop/src/renderer/components/records/record-name.tsx b/desktop/src/renderer/components/records/record-name.tsx
index b36dedd2..af87421c 100644
--- a/desktop/src/renderer/components/records/record-name.tsx
+++ b/desktop/src/renderer/components/records/record-name.tsx
@@ -1,15 +1,12 @@
import React from 'react';
-import { RecordNode } from '@/types/databases';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
-interface RecordNameProps {
- record: RecordNode;
-}
-
-export const RecordName = ({ record }: RecordNameProps) => {
+export const RecordName = () => {
const workspace = useWorkspace();
+ const record = useRecord();
const { mutate, isPending } = useMutation();
return (
@@ -28,7 +25,7 @@ export const RecordName = ({ record }: RecordNameProps) => {
input: {
type: 'node_attribute_set',
nodeId: record.id,
- attribute: 'name',
+ path: 'name',
value: value,
userId: workspace.userId,
},
diff --git a/desktop/src/renderer/components/records/record-provider.tsx b/desktop/src/renderer/components/records/record-provider.tsx
new file mode 100644
index 00000000..186ab30f
--- /dev/null
+++ b/desktop/src/renderer/components/records/record-provider.tsx
@@ -0,0 +1,189 @@
+import React from 'react';
+import { RecordContext } from '@/renderer/contexts/record';
+import { RecordNode } from '@/types/nodes';
+import { useDatabase } from '@/renderer/contexts/database';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useMutation } from '@/renderer/hooks/use-mutation';
+
+export const RecordProvider = ({
+ record,
+ children,
+}: {
+ record: RecordNode;
+ children: React.ReactNode;
+}) => {
+ const workspace = useWorkspace();
+ const database = useDatabase();
+
+ const { mutate } = useMutation();
+
+ return (
+ <RecordContext.Provider
+ value={{
+ id: record.id,
+ name: record.attributes.name,
+ avatar: record.attributes.avatar,
+ fields: record.attributes.fields,
+ createdBy: record.createdBy,
+ createdAt: record.createdAt,
+ updatedBy: record.updatedBy,
+ updatedAt: record.updatedAt,
+ canEdit: true,
+ updateFieldValue: (field, value) => {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ path: `fields.${field.id}`,
+ value,
+ userId: workspace.userId,
+ },
+ });
+ },
+ removeFieldValue: (field) => {
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ path: `fields.${field.id}`,
+ userId: workspace.userId,
+ },
+ });
+ },
+ getBooleanValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'boolean') {
+ return fieldValue.value;
+ }
+ }
+
+ return false;
+ },
+ getCollaboratorValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'collaborator') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getDateValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'date') {
+ return new Date(fieldValue.value);
+ }
+ }
+
+ return null;
+ },
+ getEmailValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'email') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getFileValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'file') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getMultiSelectValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'multiSelect') {
+ return fieldValue.value;
+ }
+ }
+
+ return [];
+ },
+ getNumberValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'number') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getPhoneValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'phone') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getRelationValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'relation') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getRollupValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'rollup') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getSelectValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'select') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getTextValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'text') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ getUrlValue: (field) => {
+ if (field.id in record.attributes.fields) {
+ const fieldValue = record.attributes.fields[field.id];
+ if (fieldValue.type === 'url') {
+ return fieldValue.value;
+ }
+ }
+
+ return null;
+ },
+ versionId: record.versionId,
+ }}
+ >
+ {children}
+ </RecordContext.Provider>
+ );
+};
diff --git a/desktop/src/renderer/components/records/values/record-boolean-value.tsx b/desktop/src/renderer/components/records/values/record-boolean-value.tsx
index 8bf9f141..df882972 100644
--- a/desktop/src/renderer/components/records/values/record-boolean-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-boolean-value.tsx
@@ -1,62 +1,41 @@
import React from 'react';
import { Checkbox } from '@/renderer/components/ui/checkbox';
-import { BooleanFieldNode, RecordNode } from '@/types/databases';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { BooleanFieldAttributes } from '@/registry';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordBooleanValueProps {
- record: RecordNode;
- field: BooleanFieldNode;
+ field: BooleanFieldAttributes;
}
-export const RecordBooleanValue = ({
- record,
- field,
-}: RecordBooleanValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const RecordBooleanValue = ({ field }: RecordBooleanValueProps) => {
+ const record = useRecord();
const [input, setInput] = React.useState<boolean>(
- (record.attributes[field.id] as boolean) ?? false,
+ record.getBooleanValue(field),
);
React.useEffect(() => {
- setInput((record.attributes[field.id] as boolean) ?? false);
+ setInput(record.getBooleanValue(field));
}, [record.versionId]);
return (
<div className="flex h-full w-full flex-row items-center justify-start p-1">
<Checkbox
checked={input}
- disabled={isPending || !canEdit}
+ disabled={!record.canEdit}
onCheckedChange={(e) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (typeof e === 'boolean') {
setInput(e.valueOf());
const checked = e.valueOf();
if (checked) {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: checked,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'boolean',
+ value: checked,
});
} else {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
}
}
}}
diff --git a/desktop/src/renderer/components/records/values/record-created-at-value.tsx b/desktop/src/renderer/components/records/values/record-created-at-value.tsx
index 220929fb..c790c9ae 100644
--- a/desktop/src/renderer/components/records/values/record-created-at-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-created-at-value.tsx
@@ -1,20 +1,19 @@
import React from 'react';
-import { CreatedAtFieldNode, RecordNode } from '@/types/databases';
+import { CreatedAtFieldAttributes } from '@/registry';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordCreatedAtValueProps {
- record: RecordNode;
- field: CreatedAtFieldNode;
+ field: CreatedAtFieldAttributes;
}
-export const RecordCreatedAtValue = ({
- record,
- field,
-}: RecordCreatedAtValueProps) => {
+export const RecordCreatedAtValue = ({ field }: RecordCreatedAtValueProps) => {
+ const record = useRecord();
+ const createdAt = new Date(record.createdAt);
+
return (
<div className="h-full w-full p-1 text-sm" data-field={field.id}>
<p>
- {record.createdAt.toLocaleDateString()}{' '}
- {record.createdAt.toLocaleTimeString()}
+ {createdAt.toLocaleDateString()} {createdAt.toLocaleTimeString()}
</p>
</div>
);
diff --git a/desktop/src/renderer/components/records/values/record-created-by-value.tsx b/desktop/src/renderer/components/records/values/record-created-by-value.tsx
index 33952047..e07a7292 100644
--- a/desktop/src/renderer/components/records/values/record-created-by-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-created-by-value.tsx
@@ -1,28 +1,45 @@
import React from 'react';
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { CreatedByFieldNode, RecordNode } from '@/types/databases';
-
+import { CreatedByFieldAttributes } from '@/registry';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordCreatedByValueProps {
- field: CreatedByFieldNode;
- record: RecordNode;
+ field: CreatedByFieldAttributes;
}
-export const RecordCreatedByValue = ({
- field,
- record,
-}: RecordCreatedByValueProps) => {
+export const RecordCreatedByValue = ({ field }: RecordCreatedByValueProps) => {
+ const workspace = useWorkspace();
+ const record = useRecord();
+ const { data } = useQuery({
+ type: 'node_get',
+ nodeId: record.createdBy,
+ userId: workspace.userId,
+ });
+
+ const createdBy =
+ data && data.attributes.type === 'user'
+ ? {
+ name: data.attributes.name,
+ avatar: data.attributes.avatar,
+ }
+ : {
+ name: 'Unknown',
+ avatar: null,
+ };
+
return (
<div
className="flex h-full w-full flex-row items-center gap-1 p-1 text-sm"
data-field={field.id}
>
<Avatar
- id={record.createdBy.id}
- name={record.createdBy.name}
- avatar={record.createdBy.avatar}
+ id={record.createdBy}
+ name={createdBy.name}
+ avatar={createdBy.avatar}
size="small"
/>
- <p>{record.createdBy.name}</p>
+ <p>{createdBy.name}</p>
</div>
);
};
diff --git a/desktop/src/renderer/components/records/values/record-email-value.tsx b/desktop/src/renderer/components/records/values/record-email-value.tsx
index ecadef62..84308177 100644
--- a/desktop/src/renderer/components/records/values/record-email-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-email-value.tsx
@@ -1,46 +1,28 @@
import React from 'react';
-import { RecordNode, EmailFieldNode } from '@/types/databases';
+import { EmailFieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordEmailValueProps {
- record: RecordNode;
- field: EmailFieldNode;
+ field: EmailFieldAttributes;
}
-export const RecordEmailValue = ({ record, field }: RecordEmailValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const RecordEmailValue = ({ field }: RecordEmailValueProps) => {
+ const record = useRecord();
return (
<SmartTextInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getEmailValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'email',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/records/values/record-multi-select-value.tsx b/desktop/src/renderer/components/records/values/record-multi-select-value.tsx
index 5ba9069c..ddd048d9 100644
--- a/desktop/src/renderer/components/records/values/record-multi-select-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-multi-select-value.tsx
@@ -1,37 +1,34 @@
import React from 'react';
-import { MultiSelectFieldNode, RecordNode } from '@/types/databases';
-import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
+import { MultiSelectFieldAttributes } from '@/registry';
import {
Popover,
PopoverTrigger,
PopoverContent,
} from '@/renderer/components/ui/popover';
import { SelectFieldOptions } from '@/renderer/components/databases/fields/select-field-options';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordMultiSelectValueProps {
- record: RecordNode;
- field: MultiSelectFieldNode;
+ field: MultiSelectFieldAttributes;
}
export const RecordMultiSelectValue = ({
- record,
field,
}: RecordMultiSelectValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+ const record = useRecord();
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState(
- (record.attributes[field.id] as string[]) ?? [],
+ record.getMultiSelectValue(field),
);
React.useEffect(() => {
- setSelectedValues((record.attributes[field.id] as string[]) ?? []);
+ setSelectedValues(record.getMultiSelectValue(field));
}, [record.versionId]);
- const selectedOptions = field.options?.filter((option) =>
+ const selectOptions = Object.values(field.options ?? {});
+ const selectedOptions = selectOptions.filter((option) =>
selectedValues.includes(option.id),
);
@@ -54,30 +51,20 @@ export const RecordMultiSelectValue = ({
field={field}
values={selectedValues}
onSelect={(id) => {
- if (isPending) return;
+ if (!record.canEdit) return;
- if (selectedValues.includes(id)) {
- const values = selectedValues.filter((v) => v !== id);
- setSelectedValues(values);
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ const newValues = selectedValues.includes(id)
+ ? selectedValues.filter((v) => v !== id)
+ : [...selectedValues, id];
+
+ setSelectedValues(newValues);
+
+ if (newValues.length === 0) {
+ record.removeFieldValue(field);
} else {
- const values = [...selectedValues, id];
- setSelectedValues(values);
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: values,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'multiSelect',
+ value: newValues,
});
}
}}
diff --git a/desktop/src/renderer/components/records/values/record-number-value.tsx b/desktop/src/renderer/components/records/values/record-number-value.tsx
index ae0eaae7..f6486e82 100644
--- a/desktop/src/renderer/components/records/values/record-number-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-number-value.tsx
@@ -1,54 +1,32 @@
import React from 'react';
-import { RecordNode } from '@/types/databases';
-import { NumberFieldNode } from '@/types/databases';
+import { NumberFieldAttributes } from '@/registry';
import { SmartNumberInput } from '@/renderer/components/ui/smart-number-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordNumberValueProps {
- record: RecordNode;
- field: NumberFieldNode;
+ field: NumberFieldAttributes;
}
-export const RecordNumberValue = ({
- record,
- field,
-}: RecordNumberValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const RecordNumberValue = ({ field }: RecordNumberValueProps) => {
+ const record = useRecord();
return (
<SmartNumberInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getNumberValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
- if (newValue === record.attributes[field.id]) {
+ if (newValue === record.getNumberValue(field)) {
return;
}
if (newValue === null) {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'number',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/records/values/record-phone-value.tsx b/desktop/src/renderer/components/records/values/record-phone-value.tsx
index 58ca788c..0d10dbdf 100644
--- a/desktop/src/renderer/components/records/values/record-phone-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-phone-value.tsx
@@ -1,50 +1,32 @@
import React from 'react';
-import { RecordNode, PhoneFieldNode } from '@/types/databases';
+import { PhoneFieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordPhoneValueProps {
- record: RecordNode;
- field: PhoneFieldNode;
+ field: PhoneFieldAttributes;
}
-export const RecordPhoneValue = ({ record, field }: RecordPhoneValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const RecordPhoneValue = ({ field }: RecordPhoneValueProps) => {
+ const record = useRecord();
return (
<SmartTextInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getPhoneValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
- if (newValue === record.attributes[field.id]) {
+ if (newValue === record.getPhoneValue(field)) {
return;
}
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'phone',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/records/values/record-select-value.tsx b/desktop/src/renderer/components/records/values/record-select-value.tsx
index 404c4f13..7112f3bd 100644
--- a/desktop/src/renderer/components/records/values/record-select-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-select-value.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { RecordNode, SelectFieldNode } from '@/types/databases';
+import { SelectFieldAttributes } from '@/registry';
import { SelectOptionBadge } from '@/renderer/components/databases/fields/select-option-badge';
import {
Popover,
@@ -7,33 +7,25 @@ import {
PopoverContent,
} from '@/renderer/components/ui/popover';
import { SelectFieldOptions } from '@/renderer/components/databases/fields/select-field-options';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordSelectValueProps {
- record: RecordNode;
- field: SelectFieldNode;
+ field: SelectFieldAttributes;
}
-export const RecordSelectValue = ({
- record,
- field,
-}: RecordSelectValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+export const RecordSelectValue = ({ field }: RecordSelectValueProps) => {
+ const record = useRecord();
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(
- record.attributes[field.id] ?? '',
+ record.getSelectValue(field),
);
React.useEffect(() => {
- setSelectedValue(record.attributes[field.id] ?? '');
+ setSelectedValue(record.getSelectValue(field));
}, [record.versionId]);
- const selectedOption = field.options?.find(
- (option) => option.id === selectedValue,
- );
+ const selectedOption = field.options?.[selectedValue ?? ''];
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -52,37 +44,21 @@ export const RecordSelectValue = ({
<PopoverContent className="w-80 p-1">
<SelectFieldOptions
field={field}
- values={[selectedValue]}
+ values={[selectedValue ?? '']}
onSelect={(id) => {
- if (isPending) {
- return;
- }
+ if (!record.canEdit) return;
+
+ setSelectedValue(id);
+ setOpen(false);
if (selectedValue === id) {
- setSelectedValue('');
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: id,
- userId: workspace.userId,
- },
- onSuccess() {
- setOpen(false);
- },
+ record.updateFieldValue(field, {
+ type: 'select',
+ value: id,
});
}
- setSelectedValue(id);
}}
allowAdd={true}
/>
diff --git a/desktop/src/renderer/components/records/values/record-text-value.tsx b/desktop/src/renderer/components/records/values/record-text-value.tsx
index 7f54cf35..5d84e826 100644
--- a/desktop/src/renderer/components/records/values/record-text-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-text-value.tsx
@@ -1,50 +1,32 @@
import React from 'react';
-import { RecordNode, TextFieldNode } from '@/types/databases';
+import { TextFieldAttributes } from '@/registry';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordTextValueProps {
- record: RecordNode;
- field: TextFieldNode;
+ field: TextFieldAttributes;
}
-export const RecordTextValue = ({ record, field }: RecordTextValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
-
- const canEdit = true;
+export const RecordTextValue = ({ field }: RecordTextValueProps) => {
+ const record = useRecord();
return (
<SmartTextInput
- value={record.attributes[field.id]}
- readOnly={!canEdit || isPending}
+ value={record.getTextValue(field)}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
- if (newValue === record.attributes[field.id]) {
+ if (newValue === record.getTextValue(field)) {
return;
}
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'text',
+ value: newValue,
});
}
}}
diff --git a/desktop/src/renderer/components/records/values/record-url-value.tsx b/desktop/src/renderer/components/records/values/record-url-value.tsx
index c2ee920d..c6b9a6ff 100644
--- a/desktop/src/renderer/components/records/values/record-url-value.tsx
+++ b/desktop/src/renderer/components/records/values/record-url-value.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { RecordNode, UrlFieldNode } from '@/types/databases';
+import { UrlFieldAttributes } from '@/registry';
import { cn, isValidUrl } from '@/lib/utils';
import {
HoverCard,
@@ -7,55 +7,38 @@ import {
HoverCardTrigger,
} from '@/renderer/components/ui/hover-card';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useMutation } from '@/renderer/hooks/use-mutation';
-import { useWorkspace } from '@/renderer/contexts/workspace';
import { ExternalLink } from 'lucide-react';
+import { useRecord } from '@/renderer/contexts/record';
interface RecordUrlValueProps {
- record: RecordNode;
- field: UrlFieldNode;
+ field: UrlFieldAttributes;
}
-export const RecordUrlValue = ({ record, field }: RecordUrlValueProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+export const RecordUrlValue = ({ field }: RecordUrlValueProps) => {
+ const record = useRecord();
- const canEdit = true;
- const text = record.attributes[field.id];
- const isUrl = text.length > 0 && isValidUrl(text);
+ const text = record.getUrlValue(field);
+ const isUrl = text && isValidUrl(text);
return (
<HoverCard openDelay={300}>
<HoverCardTrigger>
<SmartTextInput
value={text}
- readOnly={!canEdit || isPending}
+ readOnly={!record.canEdit}
onChange={(newValue) => {
- if (isPending) return;
- if (!canEdit) return;
+ if (!record.canEdit) return;
if (newValue === text) {
return;
}
if (newValue === null || newValue === '') {
- mutate({
- input: {
- type: 'node_attribute_delete',
- nodeId: record.id,
- attribute: field.id,
- userId: workspace.userId,
- },
- });
+ record.removeFieldValue(field);
} else {
- mutate({
- input: {
- type: 'node_attribute_set',
- nodeId: record.id,
- attribute: field.id,
- value: newValue,
- userId: workspace.userId,
- },
+ record.updateFieldValue(field, {
+ type: 'url',
+ value: newValue,
});
}
}}
@@ -70,7 +53,7 @@ export const RecordUrlValue = ({ record, field }: RecordUrlValueProps) => {
>
<a
className="text-blue-500 underline hover:cursor-pointer hover:text-blue-600"
- href={text}
+ href={text ?? ''}
target="_blank"
rel="noreferrer"
>
diff --git a/desktop/src/renderer/components/spaces/space-create-dialog.tsx b/desktop/src/renderer/components/spaces/space-create-dialog.tsx
index a588c862..b440c395 100644
--- a/desktop/src/renderer/components/spaces/space-create-dialog.tsx
+++ b/desktop/src/renderer/components/spaces/space-create-dialog.tsx
@@ -70,6 +70,7 @@ export const SpaceCreateDialog = ({
name: values.name,
description: values.description,
userId: workspace.userId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/desktop/src/renderer/components/spaces/space-settings-dialog.tsx b/desktop/src/renderer/components/spaces/space-settings-dialog.tsx
index f7513da8..cf612944 100644
--- a/desktop/src/renderer/components/spaces/space-settings-dialog.tsx
+++ b/desktop/src/renderer/components/spaces/space-settings-dialog.tsx
@@ -21,7 +21,7 @@ import { NodeCollaborators } from '@/renderer/components/collaborators/node-coll
interface SpaceSettingsDialogProps {
id: string;
name: string;
- avatar: string;
+ avatar?: string | null;
open: boolean;
onOpenChange: (open: boolean) => void;
defaultTab?: string;
diff --git a/desktop/src/renderer/components/spaces/space-update-form.tsx b/desktop/src/renderer/components/spaces/space-update-form.tsx
index 6e60e7c5..1a224047 100644
--- a/desktop/src/renderer/components/spaces/space-update-form.tsx
+++ b/desktop/src/renderer/components/spaces/space-update-form.tsx
@@ -28,7 +28,7 @@ interface SpaceUpdateFormProps {
const formSchema = z.object({
name: z.string(),
description: z.string(),
- avatar: z.string(),
+ avatar: z.string().nullable().optional(),
});
export const SpaceUpdateForm = ({ id }: SpaceUpdateFormProps) => {
@@ -52,11 +52,11 @@ export const SpaceUpdateForm = ({ id }: SpaceUpdateFormProps) => {
});
React.useEffect(() => {
- if (data) {
+ if (data && data.attributes.type === 'space') {
form.reset({
name: data.attributes.name,
- description: data.attributes.description,
- avatar: data.attributes.avatar,
+ description: data.attributes.description ?? '',
+ avatar: data.attributes.avatar ?? null,
});
}
}, [isLoadingSpace, data]);
diff --git a/desktop/src/renderer/components/workspaces/containers/breadcrumb-item-popover.tsx b/desktop/src/renderer/components/workspaces/containers/breadcrumb-item-popover.tsx
index 4a40ef6d..95348f7d 100644
--- a/desktop/src/renderer/components/workspaces/containers/breadcrumb-item-popover.tsx
+++ b/desktop/src/renderer/components/workspaces/containers/breadcrumb-item-popover.tsx
@@ -36,7 +36,7 @@ export const BreadcrumbItemPopover = ({
input: {
type: 'node_attribute_set',
nodeId: node.id,
- attribute: 'avatar',
+ path: 'avatar',
value: avatar,
userId: workspace.userId,
},
@@ -63,7 +63,7 @@ export const BreadcrumbItemPopover = ({
input: {
type: 'node_attribute_set',
nodeId: node.id,
- attribute: 'name',
+ path: 'name',
value: newName,
userId: workspace.userId,
},
diff --git a/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx b/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx
index 3cbc5b3b..e70a3d36 100644
--- a/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx
+++ b/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx
@@ -30,7 +30,7 @@ export const Breadcrumb = ({ nodeId }: BreadcrumbProps) => {
userId: workspace.userId,
});
- if (isPending) {
+ if (isPending || !data) {
return null;
}
diff --git a/desktop/src/renderer/components/workspaces/sidebars/sidebar-chats.tsx b/desktop/src/renderer/components/workspaces/sidebars/sidebar-chats.tsx
index 4907b534..2d1ada5e 100644
--- a/desktop/src/renderer/components/workspaces/sidebars/sidebar-chats.tsx
+++ b/desktop/src/renderer/components/workspaces/sidebars/sidebar-chats.tsx
@@ -16,7 +16,7 @@ import { useParams } from 'react-router-dom';
export const SidebarChats = () => {
const workspace = useWorkspace();
- const { nodeId } = useParams<{ nodeId?: string | null }>();
+ const { nodeId } = useParams<{ nodeId?: string }>();
const { data } = useQuery({
type: 'sidebar_chat_list',
diff --git a/desktop/src/renderer/components/workspaces/sidebars/sidebar-space-item.tsx b/desktop/src/renderer/components/workspaces/sidebars/sidebar-space-item.tsx
index a5eeb5ec..05880c9a 100644
--- a/desktop/src/renderer/components/workspaces/sidebars/sidebar-space-item.tsx
+++ b/desktop/src/renderer/components/workspaces/sidebars/sidebar-space-item.tsx
@@ -52,7 +52,7 @@ interface SidebarSpaceNodeProps {
export const SidebarSpaceItem = ({ node }: SidebarSpaceNodeProps) => {
const workspace = useWorkspace();
- const { nodeId } = useParams<{ nodeId?: string | null }>();
+ const { nodeId } = useParams<{ nodeId?: string }>();
const [openCreatePage, setOpenCreatePage] = React.useState(false);
const [openCreateChannel, setOpenCreateChannel] = React.useState(false);
@@ -75,7 +75,7 @@ export const SidebarSpaceItem = ({ node }: SidebarSpaceNodeProps) => {
<SidebarMenuItem>
<CollapsibleTrigger asChild>
<SidebarMenuButton
- tooltip={node.name}
+ tooltip={node.name ?? ''}
className="group/space-button"
>
<Avatar
diff --git a/desktop/src/renderer/components/workspaces/workspace-create.tsx b/desktop/src/renderer/components/workspaces/workspace-create.tsx
index 0e122a37..324d1674 100644
--- a/desktop/src/renderer/components/workspaces/workspace-create.tsx
+++ b/desktop/src/renderer/components/workspaces/workspace-create.tsx
@@ -30,7 +30,7 @@ export const WorkspaceCreate = () => {
name: values.name,
description: values.description,
accountId: account.id,
- avatar: values.avatar,
+ avatar: values.avatar ?? null,
},
onSuccess(output) {
navigate(`/${output.id}`);
diff --git a/desktop/src/renderer/components/workspaces/workspace-update.tsx b/desktop/src/renderer/components/workspaces/workspace-update.tsx
index 57f1f4f0..61aea8cf 100644
--- a/desktop/src/renderer/components/workspaces/workspace-update.tsx
+++ b/desktop/src/renderer/components/workspaces/workspace-update.tsx
@@ -12,8 +12,8 @@ export const WorkspaceUpdate = () => {
<WorkspaceForm
values={{
name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
+ description: workspace.description ?? '',
+ avatar: workspace.avatar ?? null,
}}
onSubmit={(values) => {
mutate({
@@ -23,7 +23,7 @@ export const WorkspaceUpdate = () => {
accountId: workspace.accountId,
name: values.name,
description: values.description,
- avatar: values.avatar,
+ avatar: values.avatar ?? null,
},
onSuccess() {
toast({
diff --git a/desktop/src/renderer/components/workspaces/workspace-users.tsx b/desktop/src/renderer/components/workspaces/workspace-users.tsx
index e49961ed..9c4174dc 100644
--- a/desktop/src/renderer/components/workspaces/workspace-users.tsx
+++ b/desktop/src/renderer/components/workspaces/workspace-users.tsx
@@ -62,9 +62,8 @@ export const WorkspaceUsers = () => {
const email: string = user.attributes.email ?? ' ';
const avatar: string | null | undefined = user.attributes.avatar;
const role: WorkspaceRole = user.attributes.role;
- const accountId: string = user.attributes.accountId;
- if (!accountId || !role) {
+ if (!role) {
return null;
}
@@ -72,7 +71,9 @@ export const WorkspaceUsers = () => {
<div key={user.id} className="flex items-center space-x-3">
<Avatar id={user.id} name={name} avatar={avatar} />
<div className="flex-grow">
- <p className="text-sm font-medium leading-none">{name}</p>
+ <p className="text-sm font-medium leading-none">
+ {user.attributes.name}
+ </p>
<p className="text-sm text-muted-foreground">{email}</p>
</div>
<WorkspaceUserRoleDropdown userId={user.id} value={role} />
diff --git a/desktop/src/renderer/contexts/database-views.ts b/desktop/src/renderer/contexts/database-views.ts
index eacdfd91..830d0af7 100644
--- a/desktop/src/renderer/contexts/database-views.ts
+++ b/desktop/src/renderer/contexts/database-views.ts
@@ -1,8 +1,8 @@
-import { ViewNode } from '@/types/databases';
+import { ViewAttributes } from '@/registry';
import { createContext, useContext } from 'react';
interface DatabaseViewsContext {
- views: ViewNode[];
+ views: ViewAttributes[];
activeViewId: string;
setActiveViewId: (viewId: string) => void;
}
diff --git a/desktop/src/renderer/contexts/database.ts b/desktop/src/renderer/contexts/database.ts
index a400c7eb..153df2a1 100644
--- a/desktop/src/renderer/contexts/database.ts
+++ b/desktop/src/renderer/contexts/database.ts
@@ -1,10 +1,25 @@
-import { FieldNode } from '@/types/databases';
import { createContext, useContext } from 'react';
+import {
+ ViewAttributes,
+ FieldAttributes,
+ FieldType,
+ SelectOptionAttributes,
+} from '@/registry';
interface DatabaseContext {
id: string;
name: string;
- fields: FieldNode[];
+ fields: FieldAttributes[];
+ views: ViewAttributes[];
+ createField: (type: FieldType, name: string) => void;
+ renameField: (id: string, name: string) => void;
+ deleteField: (id: string) => void;
+ createSelectOption: (fieldId: string, name: string, color: string) => void;
+ updateSelectOption: (
+ fieldId: string,
+ attributes: SelectOptionAttributes,
+ ) => void;
+ deleteSelectOption: (fieldId: string, optionId: string) => void;
}
export const DatabaseContext = createContext<DatabaseContext>(
diff --git a/desktop/src/renderer/contexts/record.ts b/desktop/src/renderer/contexts/record.ts
new file mode 100644
index 00000000..afed8a81
--- /dev/null
+++ b/desktop/src/renderer/contexts/record.ts
@@ -0,0 +1,50 @@
+import {
+ BooleanFieldAttributes,
+ CollaboratorFieldAttributes,
+ DateFieldAttributes,
+ EmailFieldAttributes,
+ FieldAttributes,
+ FieldValue,
+ FileFieldAttributes,
+ MultiSelectFieldAttributes,
+ NumberFieldAttributes,
+ PhoneFieldAttributes,
+ RelationFieldAttributes,
+ RollupFieldAttributes,
+ SelectFieldAttributes,
+ TextFieldAttributes,
+ UrlFieldAttributes,
+} from '@/registry';
+import { createContext, useContext } from 'react';
+
+interface RecordContext {
+ id: string;
+ name: string;
+ avatar?: string | null;
+ fields: Record<string, FieldValue>;
+ createdBy: string;
+ createdAt: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ versionId: string;
+ canEdit: boolean;
+ updateFieldValue: (field: FieldAttributes, value: FieldValue) => void;
+ removeFieldValue: (field: FieldAttributes) => void;
+ getBooleanValue: (field: BooleanFieldAttributes) => boolean;
+ getCollaboratorValue: (field: CollaboratorFieldAttributes) => string[] | null;
+ getDateValue: (field: DateFieldAttributes) => Date | null;
+ getEmailValue: (field: EmailFieldAttributes) => string | null;
+ getFileValue: (field: FileFieldAttributes) => string | null;
+ getMultiSelectValue: (field: MultiSelectFieldAttributes) => string[];
+ getNumberValue: (field: NumberFieldAttributes) => number | null;
+ getPhoneValue: (field: PhoneFieldAttributes) => string | null;
+ getRelationValue: (field: RelationFieldAttributes) => string[] | null;
+ getRollupValue: (field: RollupFieldAttributes) => string | null;
+ getSelectValue: (field: SelectFieldAttributes) => string | null;
+ getTextValue: (field: TextFieldAttributes) => string | null;
+ getUrlValue: (field: UrlFieldAttributes) => string | null;
+}
+
+export const RecordContext = createContext<RecordContext>({} as RecordContext);
+
+export const useRecord = () => useContext(RecordContext);
diff --git a/desktop/src/renderer/contexts/table-view.ts b/desktop/src/renderer/contexts/table-view.ts
deleted file mode 100644
index 9698c9d0..00000000
--- a/desktop/src/renderer/contexts/table-view.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { FieldNode, FieldDataType } from '@/types/databases';
-import { createContext, useContext } from 'react';
-
-interface TableViewContext {
- id: string;
- name: string;
- avatar: string | null;
- fields: FieldNode[];
- hideField: (id: string) => void;
- showField: (id: string) => void;
- isHiddenField: (id: string) => boolean;
- getNameWidth: () => number;
- resizeName: (width: number) => void;
- getFieldWidth: (id: string, type: FieldDataType) => number;
- resizeField: (id: string, width: number) => void;
- moveField: (id: string, after: string) => void;
-}
-
-export const TableViewContext = createContext<TableViewContext>(
- {} as TableViewContext,
-);
-
-export const useTableView = () => useContext(TableViewContext);
diff --git a/desktop/src/renderer/contexts/view-search.ts b/desktop/src/renderer/contexts/view-search.ts
deleted file mode 100644
index f7d5d472..00000000
--- a/desktop/src/renderer/contexts/view-search.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { ViewFilter, ViewSort } from '@/types/databases';
-import { createContext, useContext } from 'react';
-
-interface ViewSearchContext {
- id: string;
- filters: ViewFilter[];
- sorts: ViewSort[];
- isSaving: boolean;
- isSearchBarOpened: boolean;
- isSortsOpened: boolean;
- isFieldFilterOpened: (fieldId: string) => boolean;
- initFieldFilter: (fieldId: string) => void;
- updateFilter: (id: string, filter: ViewFilter) => void;
- removeFilter: (id: string) => void;
- initFieldSort: (fieldId: string) => void;
- updateSort: (id: string, sort: ViewSort) => void;
- removeSort: (id: string) => void;
- openSearchBar: () => void;
- closeSearchBar: () => void;
- openSorts: () => void;
- closeSorts: () => void;
- openFieldFilter: (fieldId: string) => void;
- closeFieldFilter: (fieldId: string) => void;
-}
-
-export const ViewSearchContext = createContext<ViewSearchContext>(
- {} as ViewSearchContext,
-);
-
-export const useViewSearch = () => useContext(ViewSearchContext);
diff --git a/desktop/src/renderer/contexts/view.ts b/desktop/src/renderer/contexts/view.ts
new file mode 100644
index 00000000..25d29924
--- /dev/null
+++ b/desktop/src/renderer/contexts/view.ts
@@ -0,0 +1,37 @@
+import { ViewFilterAttributes, ViewSortAttributes } from '@/registry';
+import { ViewField } from '@/types/databases';
+import { createContext, useContext } from 'react';
+
+interface ViewContext {
+ id: string;
+ name: string;
+ avatar: string | null;
+ fields: ViewField[];
+ filters: ViewFilterAttributes[];
+ sorts: ViewSortAttributes[];
+ groupBy: string | null;
+ nameWidth: number;
+ isSearchBarOpened: boolean;
+ isSortsOpened: boolean;
+ setFieldDisplay: (id: string, display: boolean) => void;
+ resizeField: (id: string, width: number) => void;
+ resizeName: (width: number) => void;
+ moveField: (id: string, after: string) => void;
+ isFieldFilterOpened: (fieldId: string) => boolean;
+ initFieldFilter: (fieldId: string) => void;
+ updateFilter: (id: string, filter: ViewFilterAttributes) => void;
+ removeFilter: (id: string) => void;
+ initFieldSort: (fieldId: string) => void;
+ updateSort: (id: string, sort: ViewSortAttributes) => void;
+ removeSort: (id: string) => void;
+ openSearchBar: () => void;
+ closeSearchBar: () => void;
+ openSorts: () => void;
+ closeSorts: () => void;
+ openFieldFilter: (fieldId: string) => void;
+ closeFieldFilter: (fieldId: string) => void;
+}
+
+export const ViewContext = createContext<ViewContext>({} as ViewContext);
+
+export const useView = () => useContext(ViewContext);
diff --git a/desktop/src/renderer/editor/renderers/file.tsx b/desktop/src/renderer/editor/renderers/file.tsx
index 4c8404f1..b54ee396 100644
--- a/desktop/src/renderer/editor/renderers/file.tsx
+++ b/desktop/src/renderer/editor/renderers/file.tsx
@@ -8,7 +8,7 @@ interface FileRendererProps {
}
export const FileRenderer = ({ node }: FileRendererProps) => {
- const id = node.attrs.id;
+ const id = node.attrs?.id;
if (!id) {
return null;
}
diff --git a/desktop/src/renderer/editor/renderers/message-reference.tsx b/desktop/src/renderer/editor/renderers/message-reference.tsx
index 48e7cec1..55e2bd04 100644
--- a/desktop/src/renderer/editor/renderers/message-reference.tsx
+++ b/desktop/src/renderer/editor/renderers/message-reference.tsx
@@ -13,7 +13,7 @@ export const MessageReferenceRenderer = ({
}: MessageReferenceRendererProps) => {
return (
<div className="items-top flex flex-col gap-2 border-l-4 p-2 text-sm text-foreground">
- <p className="font-medium">{node.attrs.name}</p>
+ <p className="font-medium">{node.attrs?.name ?? 'Unknown'}</p>
<NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
</div>
);
diff --git a/desktop/src/renderer/editor/renderers/node.tsx b/desktop/src/renderer/editor/renderers/node.tsx
index e43e000b..d589a499 100644
--- a/desktop/src/renderer/editor/renderers/node.tsx
+++ b/desktop/src/renderer/editor/renderers/node.tsx
@@ -75,7 +75,7 @@ export const NodeRenderer = ({
<MessageReferenceRenderer node={node} keyPrefix={keyPrefix} />
))
.with('file', () => <FileRenderer node={node} keyPrefix={keyPrefix} />)
- .otherwise(null)}
+ .otherwise(() => null)}
</MarkRenderer>
);
};
diff --git a/desktop/src/renderer/editor/views/folder.tsx b/desktop/src/renderer/editor/views/folder.tsx
index 63c13ead..f467f8cf 100644
--- a/desktop/src/renderer/editor/views/folder.tsx
+++ b/desktop/src/renderer/editor/views/folder.tsx
@@ -19,7 +19,11 @@ export const FolderNodeView = ({ node }: NodeViewProps) => {
return null;
}
- const name = data?.attributes.name ?? 'Unnamed';
+ if (data?.attributes.type !== 'folder') {
+ return null;
+ }
+
+ const name = data.attributes.name ?? 'Unnamed';
const avatar = data?.attributes.avatar;
return (
diff --git a/desktop/src/renderer/editor/views/page.tsx b/desktop/src/renderer/editor/views/page.tsx
index a8c3f96b..d2d02ded 100644
--- a/desktop/src/renderer/editor/views/page.tsx
+++ b/desktop/src/renderer/editor/views/page.tsx
@@ -19,8 +19,12 @@ export const PageNodeView = ({ node }: NodeViewProps) => {
return null;
}
- const name = data?.attributes.name ?? 'Unnamed';
- const avatar = data?.attributes.avatar;
+ if (data?.attributes.type !== 'page') {
+ return null;
+ }
+
+ const name = data.attributes.name ?? 'Unnamed';
+ const avatar = data.attributes.avatar;
return (
<NodeViewWrapper
diff --git a/desktop/src/types/chats.ts b/desktop/src/types/chats.ts
index d801fc95..d17bd603 100644
--- a/desktop/src/types/chats.ts
+++ b/desktop/src/types/chats.ts
@@ -1,5 +1,5 @@
export type ChatNode = {
id: string;
name: string;
- avatar: string;
+ avatar: string | null;
};
diff --git a/desktop/src/types/databases.ts b/desktop/src/types/databases.ts
index eead6995..edfbbea2 100644
--- a/desktop/src/types/databases.ts
+++ b/desktop/src/types/databases.ts
@@ -1,206 +1,8 @@
-import { UserNode } from '@/types/users';
+import { FieldAttributes, ViewFieldAttributes } from '@/registry';
-export type DatabaseNode = {
- id: string;
- name: string;
- fields: FieldNode[];
-};
-
-export type ViewNode = TableViewNode | BoardViewNode | CalendarViewNode;
-
-export type TableViewNode = {
- id: string;
- name: string;
- avatar: string | null;
- type: 'table_view';
- hiddenFields: string[];
- fieldIndexes: Record<string, string>;
- fieldWidths: Record<string, number>;
- nameWidth: number;
- versionId: string;
- filters: ViewFilter[];
- sorts: ViewSort[];
-};
-
-export type BoardViewNode = {
- id: string;
- name: string;
- avatar: string | null;
- type: 'board_view';
- filters: ViewFilter[];
- sorts: ViewSort[];
- groupBy: string | null;
-};
-
-export type CalendarViewNode = {
- id: string;
- name: string;
- avatar: string | null;
- type: 'calendar_view';
- filters: ViewFilter[];
- sorts: ViewSort[];
- groupBy: string | null;
-};
-
-export type FieldDataType =
- | 'boolean'
- | 'collaborator'
- | 'created_at'
- | 'created_by'
- | 'date'
- | 'email'
- | 'file'
- | 'multi_select'
- | 'number'
- | 'phone'
- | 'select'
- | 'text'
- | 'url';
-
-export type FieldNode =
- | BooleanFieldNode
- | CollaboratorFieldNode
- | CreatedAtFieldNode
- | CreatedByFieldNode
- | DateFieldNode
- | EmailFieldNode
- | FileFieldNode
- | MultiSelectFieldNode
- | NumberFieldNode
- | PhoneFieldNode
- | SelectFieldNode
- | TextFieldNode
- | UrlFieldNode;
-
-export type BooleanFieldNode = {
- id: string;
- dataType: 'boolean';
- name: string;
- index: string;
-};
-
-export type CollaboratorFieldNode = {
- id: string;
- dataType: 'collaborator';
- name: string;
- index: string;
-};
-
-export type CreatedAtFieldNode = {
- id: string;
- dataType: 'created_at';
- name: string;
- index: string;
-};
-
-export type CreatedByFieldNode = {
- id: string;
- dataType: 'created_by';
- name: string;
- index: string;
-};
-
-export type DateFieldNode = {
- id: string;
- dataType: 'date';
- name: string;
+export type ViewField = {
+ field: FieldAttributes;
+ display: boolean;
index: string;
-};
-
-export type EmailFieldNode = {
- id: string;
- dataType: 'email';
- name: string;
- index: string;
-};
-
-export type FileFieldNode = {
- id: string;
- dataType: 'file';
- name: string;
- index: string;
-};
-
-export type MultiSelectFieldNode = {
- id: string;
- dataType: 'multi_select';
- name: string;
- index: string;
- options: SelectOptionNode[];
-};
-
-export type NumberFieldNode = {
- id: string;
- dataType: 'number';
- name: string;
- index: string;
-};
-
-export type PhoneFieldNode = {
- id: string;
- dataType: 'phone';
- name: string;
- index: string;
-};
-
-export type SelectFieldNode = {
- id: string;
- dataType: 'select';
- name: string;
- index: string;
- options: SelectOptionNode[];
-};
-
-export type TextFieldNode = {
- id: string;
- dataType: 'text';
- name: string;
- index: string;
-};
-export type UrlFieldNode = {
- id: string;
- dataType: 'url';
- name: string;
- index: string;
-};
-
-export type SelectOptionNode = {
- id: string;
- name: string;
- color: string;
-};
-
-export type RecordNode = {
- id: string;
- name: string | null;
- parentId: string;
- index: string;
- createdAt: Date;
- createdBy: UserNode;
- versionId: string;
-
- attributes: any;
-};
-
-export type ViewFieldFilter = {
- id: string;
- type: 'field';
- fieldId: string;
- operator: string;
- value: string | number | boolean | string[] | number[] | null;
-};
-
-export type ViewGroupFilter = {
- id: string;
- type: 'group';
- operator: 'and' | 'or';
- filters: ViewFieldFilter[];
-};
-
-export type ViewFilter = ViewFieldFilter | ViewGroupFilter;
-
-export type ViewSort = {
- id: string;
- fieldId: string;
- direction: 'asc' | 'desc';
+ width: number;
};
diff --git a/desktop/src/types/nodes.ts b/desktop/src/types/nodes.ts
index 2d49e61c..4e81cbc4 100644
--- a/desktop/src/types/nodes.ts
+++ b/desktop/src/types/nodes.ts
@@ -1,9 +1,20 @@
-export type LocalNode = {
+import {
+ ChannelAttributes,
+ ChatAttributes,
+ DatabaseAttributes,
+ FileAttributes,
+ FolderAttributes,
+ MessageAttributes,
+ PageAttributes,
+ RecordAttributes,
+ SpaceAttributes,
+ UserAttributes,
+} from '@/registry';
+
+type LocalNodeBase = {
id: string;
parentId: string | null;
- type: string;
index: string | null;
- attributes: LocalNodeAttributes;
state: string;
createdAt: string;
createdBy: string;
@@ -15,44 +26,86 @@ export type LocalNode = {
serverVersionId: string | null;
};
-export type LocalNodeAttributes = {
- type: string;
- parentId?: string | null;
- index?: string | null;
- content?: Record<string, NodeBlock> | null;
- [key: string]: any;
+export type ChannelNode = LocalNodeBase & {
+ type: 'channel';
+ attributes: ChannelAttributes;
};
-export type NodeBlock = {
- id: string;
- type: string;
- index: string;
- parentId: string;
- content: NodeBlockContent[] | null;
- attrs: Record<string, any> | null;
+export type ChatNode = LocalNodeBase & {
+ type: 'chat';
+ attributes: ChatAttributes;
};
-export type NodeBlockContent = {
- type: string;
- text?: string | null;
- marks?: NodeBlocContentkMark[];
+export type DatabaseNode = LocalNodeBase & {
+ type: 'database';
+ attributes: DatabaseAttributes;
};
-export type NodeBlocContentkMark = {
- type: string;
- attrs: Record<string, any>;
+export type FileNode = LocalNodeBase & {
+ type: 'file';
+ attributes: FileAttributes;
+};
+
+export type FolderNode = LocalNodeBase & {
+ type: 'folder';
+ attributes: FolderAttributes;
+};
+
+export type MessageNode = LocalNodeBase & {
+ type: 'message';
+ attributes: MessageAttributes;
+};
+
+export type PageNode = LocalNodeBase & {
+ type: 'page';
+ attributes: PageAttributes;
};
-export type LocalNodeWithChildren = LocalNode & {
- children: LocalNodeWithChildren[];
+export type RecordNode = LocalNodeBase & {
+ type: 'record';
+ attributes: RecordAttributes;
};
+export type SpaceNode = LocalNodeBase & {
+ type: 'space';
+ attributes: SpaceAttributes;
+};
+
+export type UserNode = LocalNodeBase & {
+ type: 'user';
+ attributes: UserAttributes;
+};
+
+export type LocalNode =
+ | ChannelNode
+ | ChatNode
+ | DatabaseNode
+ | FileNode
+ | FolderNode
+ | MessageNode
+ | PageNode
+ | RecordNode
+ | SpaceNode
+ | UserNode;
+
+export type LocalNodeAttributes =
+ | UserAttributes
+ | SpaceAttributes
+ | DatabaseAttributes
+ | ChannelAttributes
+ | ChatAttributes
+ | FileAttributes
+ | FolderAttributes
+ | MessageAttributes
+ | PageAttributes
+ | RecordAttributes;
+
export type ServerNode = {
id: string;
parentId: string | null;
type: string;
index: string | null;
- attributes: ServerNodeAttributes;
+ attributes: LocalNodeAttributes;
state: string;
createdAt: string;
createdBy: string;
@@ -63,19 +116,6 @@ export type ServerNode = {
serverUpdatedAt: string | null;
};
-export type ServerNodeAttributes = {
- type: string;
- parentId?: string | null;
- index?: string | null;
- content?: NodeBlockContent[] | null;
- [key: string]: any;
-};
-
-export type NodeInsertInput = {
- id: string;
- attributes: LocalNodeAttributes;
-};
-
export type NodeCollaboratorsWrapper = {
direct: NodeCollaborator[];
inherit: InheritNodeCollaboratorsGroup[];
diff --git a/desktop/src/types/spaces.ts b/desktop/src/types/spaces.ts
new file mode 100644
index 00000000..c2e9cb6d
--- /dev/null
+++ b/desktop/src/types/spaces.ts
@@ -0,0 +1,5 @@
+export type SpaceAttributes = {
+ type: 'space';
+ name: string;
+ description?: string | null;
+};
diff --git a/desktop/src/types/users.ts b/desktop/src/types/users.ts
index 01aa5c05..9e4119e4 100644
--- a/desktop/src/types/users.ts
+++ b/desktop/src/types/users.ts
@@ -4,3 +4,10 @@ export type UserNode = {
email: string;
avatar: string | null;
};
+
+export type UserAttributes = {
+ type: 'user';
+ name: string;
+ email: string;
+ avatar: string | null;
+};
diff --git a/desktop/src/types/workspaces.ts b/desktop/src/types/workspaces.ts
index 37396b83..2d6c5fac 100644
--- a/desktop/src/types/workspaces.ts
+++ b/desktop/src/types/workspaces.ts
@@ -45,7 +45,7 @@ export type WorkspaceUserRoleUpdateOutput = {
export type SidebarNode = {
id: string;
type: string;
- name: string | null;
+ name: string;
avatar: string | null;
unreadCount: number;
mentionsCount: number;
diff --git a/desktop/tsconfig.json b/desktop/tsconfig.json
index 11a3d90b..b455319b 100644
--- a/desktop/tsconfig.json
+++ b/desktop/tsconfig.json
@@ -6,6 +6,7 @@
"skipLibCheck": true,
"esModuleInterop": true,
"noImplicitAny": true,
+ "strict": true,
"sourceMap": true,
"baseUrl": ".",
"outDir": "dist",