Skip to content

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

Save node attributes in a separate table + refactoring

Hakan Shehu2b0d73cbbfcd
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 68f53145..b3af3090 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -66,7 +66,6 @@
"kysely": "^0.27.4",
"lodash": "^4.17.21",
"lowlight": "^3.1.0",
- "node-sql-parser": "^5.3.1",
"re-resizable": "^6.9.17",
"react": "^18.3.1",
"react-dnd": "^16.0.1",
@@ -3491,12 +3490,6 @@
"undici-types": "~6.11.1"
}
},
- "node_modules/@types/pegjs": {
- "version": "0.10.6",
- "resolved": "https://registry.npmjs.org/@types/pegjs/-/pegjs-0.10.6.tgz",
- "integrity": "sha512-eLYXDbZWXh2uxf+w8sXS8d6KSoXTswfps6fvCUuVAGN8eRpfe7h9eSRydxiSJvo9Bf+GzifsDOr9TMQlmJdmkw==",
- "license": "MIT"
- },
"node_modules/@types/prop-types": {
"version": "15.7.12",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.12.tgz",
@@ -4316,15 +4309,6 @@
"prebuild-install": "^7.1.1"
}
},
- "node_modules/big-integer": {
- "version": "1.6.52",
- "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",
- "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
- "license": "Unlicense",
- "engines": {
- "node": ">=0.6"
- }
- },
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -9792,19 +9776,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/node-sql-parser": {
- "version": "5.3.1",
- "resolved": "https://registry.npmjs.org/node-sql-parser/-/node-sql-parser-5.3.1.tgz",
- "integrity": "sha512-WBDgG1lMy3y67DroHKn/hjqPXs2vGDrQPVCFyHE0kXsFncPKdiiMV4H78+XuXeKSFnGYgLnsQ7xyJHH2qDCgXQ==",
- "license": "Apache-2.0",
- "dependencies": {
- "@types/pegjs": "^0.10.0",
- "big-integer": "^1.6.48"
- },
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/nopt": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/nopt/-/nopt-6.0.0.tgz",
diff --git a/desktop/package.json b/desktop/package.json
index b6c37f14..7e9c6b83 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -106,7 +106,6 @@
"kysely": "^0.27.4",
"lodash": "^4.17.21",
"lowlight": "^3.1.0",
- "node-sql-parser": "^5.3.1",
"re-resizable": "^6.9.17",
"react": "^18.3.1",
"react-dnd": "^16.0.1",
diff --git a/desktop/src/components/channels/channel-create-dialog.tsx b/desktop/src/components/channels/channel-create-dialog.tsx
index e7e59c98..0b55ac77 100644
--- a/desktop/src/components/channels/channel-create-dialog.tsx
+++ b/desktop/src/components/channels/channel-create-dialog.tsx
@@ -22,11 +22,7 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
-import { compareString } from '@/lib/utils';
+import { useChannelCreateMutation } from '@/mutations/use-channel-create-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -44,6 +40,8 @@ export const ChannelCreateDialog = ({
onOpenChange,
}: ChannelCreateDialogProps) => {
const workspace = useWorkspace();
+ const { mutate, isPending } = useChannelCreateMutation();
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -51,57 +49,29 @@ export const ChannelCreateDialog = ({
},
});
- const { mutate, isPending } = useMutation({
- mutationFn: async (values: z.infer<typeof formSchema>) => {
- const siblingsQuery = workspace.schema
- .selectFrom('nodes')
- .where('parent_id', '=', spaceId)
- .selectAll()
- .compile();
-
- const result = await workspace.query(siblingsQuery);
- const siblings = result.rows;
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const index = generateNodeIndex(maxIndex, null);
- const query = workspace.schema
- .insertInto('nodes')
- .values({
- id: NeuronId.generate(NeuronId.Type.Channel),
- type: NodeTypes.Channel,
- parent_id: spaceId,
- index,
- attrs: JSON.stringify({
- name: values.name,
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- await workspace.mutate(query);
- },
- });
-
const handleCancel = () => {
form.reset();
onOpenChange(false);
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(values, {
- onSuccess: () => {
- onOpenChange(false);
- form.reset();
+ if (isPending) {
+ return;
+ }
+
+ mutate(
+ {
+ spaceId,
+ name: values.name,
+ },
+ {
+ onSuccess: (id) => {
+ onOpenChange(false);
+ form.reset();
+ workspace.navigateToNode(id);
+ },
},
- });
+ );
};
return (
@@ -134,7 +104,11 @@ export const ChannelCreateDialog = ({
/>
</div>
<DialogFooter>
- <Button variant="outline" onClick={handleCancel}>
+ <Button
+ variant="outline"
+ disabled={isPending}
+ onClick={handleCancel}
+ >
Cancel
</Button>
<Button type="submit" disabled={isPending}>
diff --git a/desktop/src/components/channels/channel-sidebar-node.tsx b/desktop/src/components/channels/channel-sidebar-node.tsx
deleted file mode 100644
index 7b87f0bb..00000000
--- a/desktop/src/components/channels/channel-sidebar-node.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import React from 'react';
-import { LocalNode } from '@/types/nodes';
-import { cn } from '@/lib/utils';
-import { Avatar } from '@/components/ui/avatar';
-import { Icon } from '@/components/ui/icon';
-import { useWorkspace } from '@/contexts/workspace';
-
-interface ChannelSidebarNodeProps {
- node: LocalNode;
-}
-
-export const ChannelSidebarNode = ({ node }: ChannelSidebarNodeProps) => {
- const workspace = useWorkspace();
- const isActive = false;
- const isUnread = false;
- const directCount = 0;
-
- const avatar = node.attrs.avatar;
- const name = node.attrs.name ?? 'Unnamed';
- return (
- <div
- key={node.id}
- className={cn(
- 'flex cursor-pointer items-center rounded-md p-1 text-sm text-foreground/80 hover:bg-gray-100',
- isActive && 'bg-gray-100',
- )}
- onClick={() => {
- workspace.navigateToNode(node.id);
- }}
- >
- <Avatar id={node.id} avatar={avatar} name={name} size="small" />
- <span
- className={cn(
- 'line-clamp-1 w-full flex-grow pl-2 text-left',
- isUnread && 'font-bold',
- )}
- >
- {name}
- </span>
- {directCount > 0 && (
- <span className="mr-1 rounded-md bg-red-500 px-1 py-0.5 text-xs text-white">
- {directCount}
- </span>
- )}
- {directCount == 0 && isUnread && (
- <Icon
- name="checkbox-blank-circle-fill"
- className="mr-2 h-3 w-3 p-0.5 text-red-500"
- />
- )}
- </div>
- );
-};
diff --git a/desktop/src/components/databases/database-container-node.tsx b/desktop/src/components/databases/database-container-node.tsx
index f2f029d0..3d604ee8 100644
--- a/desktop/src/components/databases/database-container-node.tsx
+++ b/desktop/src/components/databases/database-container-node.tsx
@@ -1,85 +1,31 @@
import React from 'react';
import { LocalNode } from '@/types/nodes';
-import { useQuery } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { sql } from 'kysely';
-import { SelectNode } from '@/data/schemas/workspace';
-import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
import { DatabaseContext } from '@/contexts/database';
import { DatabaseViews } from './database-views';
import { ScrollArea } from '@/components/ui/scroll-area';
-import { mapField } from '@/lib/databases';
+import { useDatabaseQuery } from '@/queries/use-database-query';
interface DatabaseContainerNodeProps {
node: LocalNode;
}
export const DatabaseContainerNode = ({ node }: DatabaseContainerNodeProps) => {
- const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- queryKey: ['database', node.id],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- WITH field_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${node.id} AND type = ${NodeTypes.Field}
- ),
- view_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${node.id} AND type IN (${sql.join(ViewNodeTypes)})
- ),
- select_option_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IN
- (
- SELECT id
- FROM field_nodes
- )
- AND type = ${NodeTypes.SelectOption}
- )
- SELECT * FROM field_nodes
- UNION ALL
- SELECT * FROM view_nodes
- UNION ALL
- SELECT * FROM select_option_nodes;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- });
+ const { data, isPending } = useDatabaseQuery(node.id);
if (isPending) {
return null;
}
- const rows = data?.rows ?? [];
- const fieldNodes = rows
- .filter((row) => row.type === NodeTypes.Field)
- .map((row) => {
- const selectOptionRows =
- rows.filter(
- (selectOptionRow) =>
- selectOptionRow.type === NodeTypes.SelectOption &&
- selectOptionRow.parent_id === row.id,
- ) ?? [];
- return mapField(row, selectOptionRows);
- });
-
- const viewNodes = rows
- .filter((row) => ViewNodeTypes.includes(row.type))
- .map((row) => mapNode(row));
+ if (!data) {
+ return null;
+ }
return (
- <DatabaseContext.Provider value={{ id: node.id, fields: fieldNodes }}>
+ <DatabaseContext.Provider
+ value={{ id: node.id, name: data?.name, fields: data?.fields }}
+ >
<ScrollArea className="h-full max-h-full w-full overflow-y-auto px-10 pb-12">
- <DatabaseViews key={node.id} views={viewNodes} />
+ <DatabaseViews key={node.id} views={data.views} />
</ScrollArea>
</DatabaseContext.Provider>
);
diff --git a/desktop/src/components/databases/database-create-dialog.tsx b/desktop/src/components/databases/database-create-dialog.tsx
index b822e225..cb79bc2c 100644
--- a/desktop/src/components/databases/database-create-dialog.tsx
+++ b/desktop/src/components/databases/database-create-dialog.tsx
@@ -22,11 +22,7 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
-import { compareString } from '@/lib/utils';
+import { useDatabaseCreateMutation } from '@/mutations/use-database-create-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -44,6 +40,8 @@ export const DatabaseCreateDialog = ({
onOpenChange,
}: DatabaseCreateDialogProps) => {
const workspace = useWorkspace();
+ const { mutate, isPending } = useDatabaseCreateMutation();
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -51,87 +49,22 @@ export const DatabaseCreateDialog = ({
},
});
- const { mutate, isPending } = useMutation({
- mutationFn: async (values: z.infer<typeof formSchema>) => {
- const siblingsQuery = workspace.schema
- .selectFrom('nodes')
- .where('parent_id', '=', spaceId)
- .selectAll()
- .compile();
-
- const result = await workspace.query(siblingsQuery);
- const siblings = result.rows;
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const index = generateNodeIndex(maxIndex, null);
- const databaseId = NeuronId.generate(NeuronId.Type.Database);
- const query = workspace.schema
- .insertInto('nodes')
- .values([
- {
- id: databaseId,
- type: NodeTypes.Database,
- parent_id: spaceId,
- index,
- attrs: JSON.stringify({
- name: values.name,
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- id: NeuronId.generate(NeuronId.Type.TableView),
- type: NodeTypes.TableView,
- parent_id: databaseId,
- index: generateNodeIndex(null, null),
- attrs: JSON.stringify({
- name: 'Default',
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- id: NeuronId.generate(NeuronId.Type.Field),
- type: NodeTypes.Field,
- parent_id: databaseId,
- index: generateNodeIndex(null, null),
- attrs: JSON.stringify({
- name: 'Title',
- type: 'text',
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
-
- await workspace.mutate(query);
- },
- });
-
const handleCancel = () => {
form.reset();
onOpenChange(false);
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(values, {
- onSuccess: () => {
- onOpenChange(false);
- form.reset();
+ mutate(
+ { spaceId, name: values.name },
+ {
+ onSuccess: (id) => {
+ onOpenChange(false);
+ form.reset();
+ workspace.navigateToNode(id);
+ },
},
- });
+ );
};
return (
diff --git a/desktop/src/components/databases/database-sidebar-node.tsx b/desktop/src/components/databases/database-sidebar-node.tsx
deleted file mode 100644
index c5d707f1..00000000
--- a/desktop/src/components/databases/database-sidebar-node.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import React from 'react';
-import { LocalNode } from '@/types/nodes';
-import { cn } from '@/lib/utils';
-import { Avatar } from '@/components/ui/avatar';
-import { Icon } from '@/components/ui/icon';
-import { useWorkspace } from '@/contexts/workspace';
-
-interface DatabaseSidebarNodeProps {
- node: LocalNode;
-}
-
-export const DatabaseSidebarNode = ({ node }: DatabaseSidebarNodeProps) => {
- const workspace = useWorkspace();
- const isActive = false;
- const isUnread = false;
-
- const avatar = node.attrs.avatar;
- const name = node.attrs.name ?? 'Unnamed';
- return (
- <div
- key={node.id}
- className={cn(
- 'flex cursor-pointer items-center rounded-md p-1 text-sm text-foreground/80 hover:bg-gray-100',
- isActive && 'bg-gray-100',
- )}
- onClick={() => {
- workspace.navigateToNode(node.id);
- }}
- >
- <Avatar id={node.id} avatar={avatar} name={name} size="small" />
- <span
- className={cn(
- 'line-clamp-1 w-full flex-grow pl-2 text-left',
- isUnread && 'font-bold',
- )}
- >
- {name}
- </span>
- {isUnread && (
- <Icon
- name="checkbox-blank-circle-fill"
- className="mr-2 h-3 w-3 p-0.5 text-red-500"
- />
- )}
- </div>
- );
-};
diff --git a/desktop/src/components/databases/database-views.tsx b/desktop/src/components/databases/database-views.tsx
index bf942a42..c3c4dd3a 100644
--- a/desktop/src/components/databases/database-views.tsx
+++ b/desktop/src/components/databases/database-views.tsx
@@ -1,19 +1,15 @@
import React from 'react';
-import { LocalNode } from '@/types/nodes';
import { ViewTab } from '@/components/databases/view-tab';
import { ViewActions } from '@/components/databases/view-actions';
-import { match } from 'ts-pattern';
-import { NodeTypes } from '@/lib/constants';
-import { TableView } from '@/components/databases/tables/table-view';
-import { BoardView } from '@/components/databases/boards/board-view';
-import { CalendarView } from '@/components/databases/calendars/calendar-view';
+import { ViewNode } from '@/types/databases';
+import { View } from '@/components/databases/view';
interface DatabaseViewsProps {
- views: LocalNode[];
+ views: ViewNode[];
}
export const DatabaseViews = ({ views }: DatabaseViewsProps) => {
- const [selectedView, setSelectedView] = React.useState<LocalNode | null>(
+ const [selectedView, setSelectedView] = React.useState<ViewNode | null>(
views.length > 0 ? views[0] : null,
);
@@ -32,13 +28,7 @@ export const DatabaseViews = ({ views }: DatabaseViewsProps) => {
</div>
<ViewActions />
</div>
- {match(selectedView?.type)
- .with(NodeTypes.TableView, () => <TableView node={selectedView} />)
- .with(NodeTypes.BoardView, () => <BoardView node={selectedView} />)
- .with(NodeTypes.CalendarView, () => (
- <CalendarView node={selectedView} />
- ))
- .otherwise(() => null)}
+ {selectedView && <View node={selectedView} />}
</div>
);
};
diff --git a/desktop/src/components/databases/fields/field-create-popover.tsx b/desktop/src/components/databases/fields/field-create-popover.tsx
index bfe25052..2d2fbbce 100644
--- a/desktop/src/components/databases/fields/field-create-popover.tsx
+++ b/desktop/src/components/databases/fields/field-create-popover.tsx
@@ -19,20 +19,15 @@ import {
PopoverTrigger,
} from '@/components/ui/popover';
import { useDatabase } from '@/contexts/database';
-import { FieldTypeSelect } from './field-type-select';
-import { FieldAttrs } from './field-attrs';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { compareString } from '@/lib/utils';
-import { generateNodeIndex } from '@/lib/nodes';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
+import { FieldDataTypeSelect } from '@/components/databases/fields/field-type-select';
+import { FieldAttrs } from '@/components/databases/fields/field-attrs';
import { Spinner } from '@/components/ui/spinner';
import { Icon } from '@/components/ui/icon';
+import { useFieldCreateMutation } from '@/mutations/use-field-create-mutation';
const formSchema = z.object({
name: z.string(),
- type: z.union([
+ dataType: z.union([
z.literal('autonumber'),
z.literal('boolean'),
z.literal('button'),
@@ -55,59 +50,17 @@ const formSchema = z.object({
export const FieldCreatePopover = () => {
const [open, setOpen] = React.useState(false);
- const workspace = useWorkspace();
const database = useDatabase();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
name: '',
- type: 'text',
+ dataType: 'text',
},
});
- const { mutate, isPending } = useMutation({
- mutationFn: async (values: z.infer<typeof formSchema>) => {
- const lastFieldQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and({
- parent_id: database.id,
- type: NodeTypes.Field,
- }),
- )
- .selectAll()
- .orderBy('index', 'desc')
- .limit(1)
- .compile();
-
- const result = await workspace.query(lastFieldQuery);
- const lastChild =
- result.rows && result.rows.length > 0 ? result.rows[0] : null;
- const maxIndex = lastChild?.index ? lastChild.index : null;
-
- const index = generateNodeIndex(maxIndex, null);
- const query = workspace.schema
- .insertInto('nodes')
- .values({
- id: NeuronId.generate(NeuronId.Type.Field),
- type: NodeTypes.Field,
- parent_id: database.id,
- index,
- attrs: JSON.stringify({
- name: values.name,
- type: values.type,
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- await workspace.mutate(query);
- },
- });
+ const { mutate, isPending } = useFieldCreateMutation();
const handleCancelClick = () => {
setOpen(false);
@@ -115,12 +68,19 @@ export const FieldCreatePopover = () => {
};
const handleSubmit = (values: z.infer<typeof formSchema>) => {
- mutate(values, {
- onSuccess: () => {
- setOpen(false);
- form.reset();
+ mutate(
+ {
+ databaseId: database.id,
+ name: values.name,
+ dataType: values.dataType,
+ },
+ {
+ onSuccess: () => {
+ setOpen(false);
+ form.reset();
+ },
},
- });
+ );
};
return (
@@ -150,13 +110,13 @@ export const FieldCreatePopover = () => {
/>
<FormField
control={form.control}
- name="type"
+ name="dataType"
render={({ field }) => (
<FormItem>
<FormLabel>Field type</FormLabel>
<FormControl>
- <FieldTypeSelect
- type={field.value}
+ <FieldDataTypeSelect
+ dataType={field.value}
onChange={field.onChange}
/>
</FormControl>
diff --git a/desktop/src/components/databases/fields/field-delete-dialog.tsx b/desktop/src/components/databases/fields/field-delete-dialog.tsx
index 998f8e28..8a2644cd 100644
--- a/desktop/src/components/databases/fields/field-delete-dialog.tsx
+++ b/desktop/src/components/databases/fields/field-delete-dialog.tsx
@@ -9,8 +9,7 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
+import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
interface FieldDeleteDialogProps {
id: string;
@@ -23,16 +22,7 @@ export const FieldDeleteDialog = ({
open,
onOpenChange,
}: FieldDeleteDialogProps) => {
- const { mutate, isPending } = useMutation({
- mutationFn: async (fieldId: string) => {
- const mutation = workspace.schema
- .deleteFrom('nodes')
- .where('id', '=', fieldId)
- .compile();
- await workspace.mutate(mutation);
- },
- });
- const workspace = useWorkspace();
+ const { mutate, isPending } = useNodeDeleteMutation();
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
diff --git a/desktop/src/components/databases/fields/field-rename-input.tsx b/desktop/src/components/databases/fields/field-rename-input.tsx
index 92debdc5..dac2b9b1 100644
--- a/desktop/src/components/databases/fields/field-rename-input.tsx
+++ b/desktop/src/components/databases/fields/field-rename-input.tsx
@@ -1,35 +1,17 @@
import React from 'react';
import isHotkey from 'is-hotkey';
import { Input } from '@/components/ui/input';
-import { Field } from '@/types/databases';
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
-import { NeuronId } from '@/lib/id';
-import { sql } from 'kysely';
+import { FieldNode } from '@/types/databases';
+import { useNodeUpdateNameMutation } from '@/mutations/use-node-update-name-mutation';
interface FieldRenameInputProps {
- field: Field;
+ field: FieldNode;
}
export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
- const workspace = useWorkspace();
+ const { mutate, isPending } = useNodeUpdateNameMutation();
const [name, setName] = React.useState(field.name);
- const { mutate, isPending } = useMutation({
- mutationFn: async (newName: string) => {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(attrs, '$.name', ${newName}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${field.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- },
- });
-
return (
<div className="w-full p-1">
<Input
@@ -39,12 +21,12 @@ export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
}}
onBlur={() => {
if (name !== field.name && !isPending) {
- mutate(name);
+ mutate({ id: field.id, name });
}
}}
onKeyDown={(e) => {
if (isHotkey('enter', e) && name !== field.name && !isPending) {
- mutate(name);
+ mutate({ id: field.id, name });
}
}}
/>
diff --git a/desktop/src/components/databases/fields/field-type-select.tsx b/desktop/src/components/databases/fields/field-type-select.tsx
index 54d69da0..f05f30c3 100644
--- a/desktop/src/components/databases/fields/field-type-select.tsx
+++ b/desktop/src/components/databases/fields/field-type-select.tsx
@@ -15,75 +15,78 @@ import {
} from '@/components/ui/command';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon } from '@/lib/databases';
-import { FieldType } from '@/types/databases';
+import { FieldDataType } from '@/types/databases';
import { cn } from '@/lib/utils';
interface FieldTypeOption {
name: string;
- type: FieldType;
+ dataType: FieldDataType;
}
const fieldTypes: FieldTypeOption[] = [
{
name: 'Boolean',
- type: 'boolean',
+ dataType: 'boolean',
},
{
name: 'Collaborator',
- type: 'collaborator',
+ dataType: 'collaborator',
},
{
name: 'Created Date & Time',
- type: 'created_at',
+ dataType: 'created_at',
},
{
name: 'Created by user',
- type: 'created_by',
+ dataType: 'created_by',
},
{
name: 'Date',
- type: 'date',
+ dataType: 'date',
},
{
name: 'Email',
- type: 'email',
+ dataType: 'email',
},
{
name: 'File',
- type: 'file',
+ dataType: 'file',
},
{
name: 'Multi Select',
- type: 'multi_select',
+ dataType: 'multi_select',
},
{
name: 'Number',
- type: 'number',
+ dataType: 'number',
},
{
name: 'Phone',
- type: 'phone',
+ dataType: 'phone',
},
{
name: 'Select',
- type: 'select',
+ dataType: 'select',
},
{
name: 'Text',
- type: 'text',
+ dataType: 'text',
},
{
name: 'Url',
- type: 'url',
+ dataType: 'url',
},
];
-interface FieldTypeSelectProps {
- type: string | null;
- onChange: (type: FieldType) => void;
+interface FieldDataTypeSelectProps {
+ dataType: string | null;
+ onChange: (type: FieldDataType) => void;
}
-export const FieldTypeSelect = ({ type, onChange }: FieldTypeSelectProps) => {
+export const FieldDataTypeSelect = ({
+ dataType,
+ onChange,
+}: FieldDataTypeSelectProps) => {
const [open, setOpen] = React.useState(false);
return (
@@ -96,9 +99,10 @@ export const FieldTypeSelect = ({ type, onChange }: FieldTypeSelectProps) => {
className="w-full justify-between p-2"
>
<span className="flex flex-row items-center gap-1">
- <Icon name={getFieldIcon(type as FieldType)} />
- {type
- ? fieldTypes.find((fieldType) => fieldType.type === type)?.name
+ <Icon name={getFieldIcon(dataType as FieldDataType)} />
+ {dataType
+ ? fieldTypes.find((fieldType) => fieldType.dataType === dataType)
+ ?.name
: 'Select field type...'}
</span>
<Icon
@@ -115,20 +119,22 @@ export const FieldTypeSelect = ({ type, onChange }: FieldTypeSelectProps) => {
<CommandGroup className="h-min max-h-96">
{fieldTypes.map((fieldType) => (
<CommandItem
- key={fieldType.type}
+ key={fieldType.dataType}
onSelect={() => {
- onChange(fieldType.type);
+ onChange(fieldType.dataType);
setOpen(false);
}}
>
<div className="flex w-full flex-row items-center gap-2">
- <Icon name={getFieldIcon(fieldType.type)} />
+ <Icon name={getFieldIcon(fieldType.dataType)} />
<p>{fieldType.name}</p>
<Icon
name="check-line"
className={cn(
'ml-auto h-4 w-4',
- type === fieldType.type ? 'opacity-100' : 'opacity-0',
+ dataType === fieldType.dataType
+ ? 'opacity-100'
+ : 'opacity-0',
)}
/>
</div>
diff --git a/desktop/src/components/databases/fields/select-field-options.tsx b/desktop/src/components/databases/fields/select-field-options.tsx
index 1e34e325..95d79edb 100644
--- a/desktop/src/components/databases/fields/select-field-options.tsx
+++ b/desktop/src/components/databases/fields/select-field-options.tsx
@@ -9,76 +9,23 @@ import {
} from '@/components/ui/command';
import { SelectOptionBadge } from '@/components/databases/fields/select-option-badge';
import { Icon } from '@/components/ui/icon';
-import { MultiSelectField, SelectField } from '@/types/databases';
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
-import { generateNodeIndex } from '@/lib/nodes';
+import { MultiSelectFieldNode, SelectFieldNode } from '@/types/databases';
import { getRandomSelectOptionColor } from '@/lib/databases';
import { SelectOptionSettingsPopover } from '@/components/databases/fields/select-option-settings-popover';
+import { useSelectOptionCreateMutation } from '@/mutations/use-select-option-create-mutation';
interface SelectFieldOptionsProps {
- field: SelectField | MultiSelectField;
+ field: SelectFieldNode | MultiSelectFieldNode;
values: string[];
onSelect: (id: string) => void;
}
-interface CreateSelectOptionInput {
- name: string;
- color: string;
-}
-
export const SelectFieldOptions = ({
field,
values,
onSelect,
}: SelectFieldOptionsProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (input: CreateSelectOptionInput) => {
- const lastChildQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and({
- parent_id: field.id,
- type: NodeTypes.SelectOption,
- }),
- )
- .selectAll()
- .orderBy('index', 'desc')
- .limit(1)
- .compile();
-
- const result = await workspace.query(lastChildQuery);
- const lastChild =
- result.rows && result.rows.length > 0 ? result.rows[0] : null;
- const maxIndex = lastChild?.index ? lastChild.index : null;
-
- const index = generateNodeIndex(maxIndex, null);
- const id = NeuronId.generate(NeuronId.Type.SelectOption);
- const query = workspace.schema
- .insertInto('nodes')
- .values({
- id,
- type: NodeTypes.SelectOption,
- parent_id: field.id,
- index,
- attrs: JSON.stringify({
- name: input.name,
- color: input.color,
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- await workspace.mutate(query);
- return id;
- },
- });
+ const { mutate, isPending } = useSelectOptionCreateMutation();
const [inputValue, setInputValue] = React.useState('');
const [color, setColor] = React.useState(getRandomSelectOptionColor());
@@ -159,6 +106,7 @@ export const SelectFieldOptions = ({
mutate(
{
+ fieldId: field.id,
name: inputValue.trim(),
color,
},
diff --git a/desktop/src/components/databases/fields/select-option-delete-dialog.tsx b/desktop/src/components/databases/fields/select-option-delete-dialog.tsx
index 21ffcba7..683cbac9 100644
--- a/desktop/src/components/databases/fields/select-option-delete-dialog.tsx
+++ b/desktop/src/components/databases/fields/select-option-delete-dialog.tsx
@@ -9,8 +9,7 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
+import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
interface SelectOptionDeleteDialogProps {
id: string;
@@ -23,16 +22,7 @@ export const SelectOptionDeleteDialog = ({
open,
onOpenChange,
}: SelectOptionDeleteDialogProps) => {
- const { mutate, isPending } = useMutation({
- mutationFn: async (fieldId: string) => {
- const mutation = workspace.schema
- .deleteFrom('nodes')
- .where('id', '=', fieldId)
- .compile();
- await workspace.mutate(mutation);
- },
- });
- const workspace = useWorkspace();
+ const { mutate, isPending } = useNodeDeleteMutation();
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
diff --git a/desktop/src/components/databases/fields/select-option-settings-popover.tsx b/desktop/src/components/databases/fields/select-option-settings-popover.tsx
index 9b6e810b..83d2d1c8 100644
--- a/desktop/src/components/databases/fields/select-option-settings-popover.tsx
+++ b/desktop/src/components/databases/fields/select-option-settings-popover.tsx
@@ -11,15 +11,13 @@ import {
import { Separator } from '@/components/ui/separator';
import { selectOptionColors } from '@/lib/databases';
import { cn } from '@/lib/utils';
-import { SelectOption } from '@/types/databases';
+import { SelectOptionNode } from '@/types/databases';
import { SelectOptionDeleteDialog } from '@/components/databases/fields/select-option-delete-dialog';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-import { sql } from 'kysely';
+import { useNodeUpdateNameMutation } from '@/mutations/use-node-update-name-mutation';
+import { useUpdateSelectOptionColorMutation } from '@/mutations/use-update-select-option-color-mutation';
interface SelectOptionSettingsPopoverProps {
- option: SelectOption;
+ option: SelectOptionNode;
}
interface UpdateSelectOptionInput {
@@ -30,26 +28,8 @@ interface UpdateSelectOptionInput {
export const SelectOptionSettingsPopover = ({
option,
}: SelectOptionSettingsPopoverProps) => {
- const workspace = useWorkspace();
-
- const { mutate, isPending } = useMutation({
- mutationFn: async (input: UpdateSelectOptionInput) => {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(
- coalesce(attrs, '{}'),
- '$.name', ${input.name},
- '$.color', ${input.color}
- ),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${option.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- },
- });
+ const nameMutation = useNodeUpdateNameMutation();
+ const colorMutation = useUpdateSelectOptionColorMutation();
const [name, setName] = React.useState(option.name);
const [openSetttingsPopover, setOpenSetttingsPopover] = React.useState(false);
@@ -73,19 +53,19 @@ export const SelectOptionSettingsPopover = ({
setName(e.target.value);
}}
onBlur={() => {
- if (name !== option.name && !isPending) {
- mutate({
+ if (name !== option.name && !nameMutation.isPending) {
+ nameMutation.mutate({
+ id: option.id,
name,
- color: option.color,
});
}
}}
onKeyDown={(e) => {
if (isHotkey('enter', e)) {
- if (name !== option.name && !isPending) {
- mutate({
+ if (name !== option.name && !nameMutation.isPending) {
+ nameMutation.mutate({
+ id: option.id,
name,
- color: option.color,
});
}
e.preventDefault();
@@ -101,10 +81,15 @@ 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={() => {
- mutate({
- name,
- color: color.value,
- });
+ if (
+ color.value !== option.color &&
+ !colorMutation.isPending
+ ) {
+ colorMutation.mutate({
+ id: option.id,
+ color: color.value,
+ });
+ }
}}
>
<span className={cn('h-4 w-4 rounded-md', color.class)} />
diff --git a/desktop/src/components/databases/tables/cells/table-view-boolean-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-boolean-cell.tsx
index 3dbbfe8f..ca695312 100644
--- a/desktop/src/components/databases/tables/cells/table-view-boolean-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-boolean-cell.tsx
@@ -1,65 +1,30 @@
import React from 'react';
-
import { Checkbox } from '@/components/ui/checkbox';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { BooleanField, RecordNode } from '@/types/databases';
-import { sql } from 'kysely';
-
-const getBooleanValue = (record: RecordNode, field: BooleanField): boolean => {
- const attrs = record.attrs;
-
- if (!attrs) {
+import { BooleanFieldNode, RecordNode } from '@/types/databases';
+import { useUpdateBooleanFieldValueMutation } from '@/mutations/use-update-boolean-field-value-mutation';
+
+const getBooleanValue = (
+ record: RecordNode,
+ field: BooleanFieldNode,
+): boolean => {
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ if (!attribute) {
return false;
}
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'number') {
- return fieldValue === 1;
- }
-
- return false;
+ return attribute.numberValue === 1;
};
interface TableViewBooleanCellProps {
record: RecordNode;
- field: BooleanField;
+ field: BooleanFieldNode;
}
export const TableViewBooleanCell = ({
record,
field,
}: TableViewBooleanCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: boolean) => {
- if (newValue) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${sql.ref(field.id)}', 1),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
+ const { mutate, isPending } = useUpdateBooleanFieldValueMutation();
const canEdit = true;
@@ -82,7 +47,11 @@ export const TableViewBooleanCell = ({
if (typeof e === 'boolean') {
setInput(e.valueOf());
- mutate(e.valueOf());
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ value: e.valueOf(),
+ });
}
}}
/>
diff --git a/desktop/src/components/databases/tables/cells/table-view-created-at-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-created-at-cell.tsx
index e898d74b..73a68f2e 100644
--- a/desktop/src/components/databases/tables/cells/table-view-created-at-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-created-at-cell.tsx
@@ -1,9 +1,9 @@
-import { CreatedAtField, RecordNode } from '@/types/databases';
+import { CreatedAtFieldNode, RecordNode } from '@/types/databases';
import React from 'react';
interface TableViewCreatedAtCellProps {
record: RecordNode;
- field: CreatedAtField;
+ field: CreatedAtFieldNode;
}
export const TableViewCreatedAtCell = ({
diff --git a/desktop/src/components/databases/tables/cells/table-view-created-by-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-created-by-cell.tsx
index 686a32a2..a075c5c9 100644
--- a/desktop/src/components/databases/tables/cells/table-view-created-by-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-created-by-cell.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { Avatar } from '@/components/ui/avatar';
-import { CreatedByField, RecordNode } from '@/types/databases';
+import { CreatedByFieldNode, RecordNode } from '@/types/databases';
interface TableViewCreatedByCellProps {
- field: CreatedByField;
+ field: CreatedByFieldNode;
record: RecordNode;
}
diff --git a/desktop/src/components/databases/tables/cells/table-view-email-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-email-cell.tsx
index 6e42f9a7..d172c0f3 100644
--- a/desktop/src/components/databases/tables/cells/table-view-email-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-email-cell.tsx
@@ -1,65 +1,23 @@
import React from 'react';
import isHotkey from 'is-hotkey';
+import { RecordNode, EmailFieldNode } from '@/types/databases';
+import { useUpdateEmailFieldValueMutation } from '@/mutations/use-update-email-field-value-mutation';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { RecordNode, EmailField } from '@/types/databases';
-import { sql } from 'kysely';
-
-const getEmailValue = (record: RecordNode, field: EmailField): string => {
- const attrs = record.attrs;
-
- if (!attrs) {
- return '';
- }
-
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'string') {
- return fieldValue;
- }
-
- return '';
+const getEmailValue = (record: RecordNode, field: EmailFieldNode): string => {
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ return attribute?.textValue ?? '';
};
interface TableViewEmailCellProps {
record: RecordNode;
- field: EmailField;
+ field: EmailFieldNode;
}
export const TableViewEmailCell = ({
record,
field,
}: TableViewEmailCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: string) => {
- if (newValue.length > 0) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${field.id}', ${newValue}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
+ const { mutate, isPending } = useUpdateEmailFieldValueMutation();
const canEdit = true;
@@ -73,7 +31,11 @@ export const TableViewEmailCell = ({
const saveIfChanged = (current: string, previous: string | null) => {
if (current.length && current !== previous) {
- mutate(current);
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ value: current,
+ });
}
};
diff --git a/desktop/src/components/databases/tables/cells/table-view-multi-select-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-multi-select-cell.tsx
index c7369246..905ecf10 100644
--- a/desktop/src/components/databases/tables/cells/table-view-multi-select-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-multi-select-cell.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { MultiSelectField, RecordNode } from '@/types/databases';
+import { MultiSelectFieldNode, RecordNode } from '@/types/databases';
import { SelectOptionBadge } from '@/components/databases/fields/select-option-badge';
import {
Popover,
@@ -7,66 +7,30 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { sql } from 'kysely';
+import { useUpdateMultiSelectFieldValueMutation } from '@/mutations/use-update-multi-select-field-value-mutation';
const getMultiSelectValues = (
record: RecordNode,
- field: MultiSelectField,
+ field: MultiSelectFieldNode,
): string[] => {
- const attrs = record.attrs;
- if (!attrs) {
- return [];
- }
-
- const fieldValue = attrs[field.id];
- return Array.isArray(fieldValue) ? fieldValue : [];
+ const attributes = record.attributes.filter((attr) => attr.type === field.id);
+ return attributes.map((attr) => attr.foreignNodeId);
};
interface TableViewMultiSelectCellProps {
record: RecordNode;
- field: MultiSelectField;
+ field: MultiSelectFieldNode;
}
export const TableViewMultiSelectCell = ({
record,
field,
}: TableViewMultiSelectCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValues: string[]) => {
- if (newValues.length > 0) {
- const values = JSON.stringify(newValues);
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${sql.ref(field.id)}', ${sql.raw(values)}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
-
+ const { mutate, isPending } = useUpdateMultiSelectFieldValueMutation();
const [open, setOpen] = React.useState(false);
- const values = getMultiSelectValues(record, field);
- const [selectedValues, setSelectedValues] = React.useState(values);
+ const [selectedValues, setSelectedValues] = React.useState(
+ getMultiSelectValues(record, field),
+ );
React.useEffect(() => {
setSelectedValues(getMultiSelectValues(record, field));
@@ -97,19 +61,23 @@ export const TableViewMultiSelectCell = ({
onSelect={(id) => {
if (isPending) return;
- let newValues: string[];
if (selectedValues.includes(id)) {
- newValues = selectedValues.filter((v) => v !== id);
+ setSelectedValues(selectedValues.filter((v) => v !== id));
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ selectOptionId: id,
+ add: false,
+ });
} else {
- newValues = [...selectedValues, id];
+ setSelectedValues([...selectedValues, id]);
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ selectOptionId: id,
+ add: true,
+ });
}
-
- setSelectedValues(newValues);
- mutate(newValues, {
- onSuccess: () => {
- setOpen(false);
- },
- });
}}
/>
</PopoverContent>
diff --git a/desktop/src/components/databases/tables/cells/table-view-number-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-number-cell.tsx
index e42bebdc..00f121dc 100644
--- a/desktop/src/components/databases/tables/cells/table-view-number-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-number-cell.tsx
@@ -1,70 +1,27 @@
import React from 'react';
import isHotkey from 'is-hotkey';
-import { useEffect, useRef, useState } from 'react';
-
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
import { RecordNode } from '@/types/databases';
-import { NeuronId } from '@/lib/id';
-import { NumberField } from '@/types/databases';
-import { sql } from 'kysely';
+import { NumberFieldNode } from '@/types/databases';
+import { useUpdateNumberFieldValueMutation } from '@/mutations/use-update-number-field-value-mutation';
const getNumberValue = (
record: RecordNode,
- field: NumberField,
+ field: NumberFieldNode,
): number | null => {
- const attrs = record.attrs;
-
- if (!attrs) {
- return null;
- }
-
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'number') {
- return fieldValue;
- }
-
- return null;
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ return attribute?.numberValue ?? null;
};
interface TableViewNumberCellProps {
record: RecordNode;
- field: NumberField;
+ field: NumberFieldNode;
}
export const TableViewNumberCell = ({
record,
field,
}: TableViewNumberCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: number | null) => {
- if (newValue !== null) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${field.id}', ${newValue}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
+ const { mutate, isPending } = useUpdateNumberFieldValueMutation();
const canEdit = true;
@@ -72,13 +29,17 @@ export const TableViewNumberCell = ({
getNumberValue(record, field)?.toString() ?? '',
);
- useEffect(() => {
+ React.useEffect(() => {
setInput(getNumberValue(record, field)?.toString() ?? '');
}, [record.versionId]);
const saveIfChanged = (current: number | null, previous: number | null) => {
if (current !== previous) {
- mutate(current);
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ value: current,
+ });
}
};
diff --git a/desktop/src/components/databases/tables/cells/table-view-phone-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-phone-cell.tsx
index 1659bf27..95436b7f 100644
--- a/desktop/src/components/databases/tables/cells/table-view-phone-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-phone-cell.tsx
@@ -1,65 +1,23 @@
import React from 'react';
import isHotkey from 'is-hotkey';
+import { RecordNode, PhoneFieldNode } from '@/types/databases';
+import { useUpdatePhoneFieldValueMutation } from '@/mutations/use-update-phone-field-value-mutation';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { RecordNode, PhoneField } from '@/types/databases';
-import { sql } from 'kysely';
-
-const getPhoneValue = (record: RecordNode, field: PhoneField): string => {
- const attrs = record.attrs;
-
- if (!attrs) {
- return '';
- }
-
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'string') {
- return fieldValue;
- }
-
- return '';
+const getPhoneValue = (record: RecordNode, field: PhoneFieldNode): string => {
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ return attribute?.textValue ?? '';
};
interface TableViewPhoneCellProps {
record: RecordNode;
- field: PhoneField;
+ field: PhoneFieldNode;
}
export const TableViewPhoneCell = ({
record,
field,
}: TableViewPhoneCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: string) => {
- if (newValue.length > 0) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${field.id}', ${newValue}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
+ const { mutate, isPending } = useUpdatePhoneFieldValueMutation();
const canEdit = true;
@@ -73,7 +31,11 @@ export const TableViewPhoneCell = ({
const saveIfChanged = (current: string, previous: string | null) => {
if (current.length && current !== previous) {
- mutate(current);
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ value: current,
+ });
}
};
diff --git a/desktop/src/components/databases/tables/cells/table-view-select-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-select-cell.tsx
index 4525f4fd..f993eb51 100644
--- a/desktop/src/components/databases/tables/cells/table-view-select-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-select-cell.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { RecordNode, SelectField } from '@/types/databases';
+import { RecordNode, SelectFieldNode } from '@/types/databases';
import { SelectOptionBadge } from '@/components/databases/fields/select-option-badge';
import {
Popover,
@@ -7,71 +7,30 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { sql } from 'kysely';
+import { useUpdateSelectFieldValueMutation } from '@/mutations/use-update-select-field-value-mutation';
const getSelectValue = (
record: RecordNode,
- field: SelectField,
+ field: SelectFieldNode,
): string | null => {
- const attrs = record.attrs;
-
- if (!attrs) {
- return null;
- }
-
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'string') {
- return fieldValue;
- }
-
- return null;
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ return attribute?.foreignNodeId ?? null;
};
interface TableViewSelectCellProps {
record: RecordNode;
- field: SelectField;
+ field: SelectFieldNode;
}
export const TableViewSelectCell = ({
record,
field,
}: TableViewSelectCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: string | null) => {
- if (newValue !== null && newValue.length > 0) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${field.id}', ${newValue}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
-
+ const { mutate, isPending } = useUpdateSelectFieldValueMutation();
const [open, setOpen] = React.useState(false);
- const value = getSelectValue(record, field);
- const [selectedValue, setSelectedValue] = React.useState(value);
+ const [selectedValue, setSelectedValue] = React.useState(
+ getSelectValue(record, field) ?? '',
+ );
React.useEffect(() => {
setSelectedValue(getSelectValue(record, field) ?? '');
@@ -106,18 +65,27 @@ export const TableViewSelectCell = ({
if (selectedValue === id) {
setSelectedValue('');
- mutate(null, {
- onSuccess: () => {
- setOpen(false);
- },
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ selectOptionId: id,
+ add: false,
});
} else {
setSelectedValue(id);
- mutate(id, {
- onSuccess: () => {
- setOpen(false);
+ mutate(
+ {
+ recordId: record.id,
+ fieldId: field.id,
+ selectOptionId: id,
+ add: true,
},
- });
+ {
+ onSuccess: () => {
+ setOpen(false);
+ },
+ },
+ );
}
}}
/>
diff --git a/desktop/src/components/databases/tables/cells/table-view-text-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-text-cell.tsx
index cacba255..764f0265 100644
--- a/desktop/src/components/databases/tables/cells/table-view-text-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-text-cell.tsx
@@ -1,65 +1,23 @@
import React from 'react';
import isHotkey from 'is-hotkey';
+import { RecordNode, TextFieldNode } from '@/types/databases';
+import { useUpdateTextFieldValueMutation } from '@/mutations/use-update-text-field-value-mutation';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { RecordNode, TextField } from '@/types/databases';
-import { sql } from 'kysely';
-
-const getTextValue = (record: RecordNode, field: TextField): string => {
- const attrs = record.attrs;
-
- if (!attrs) {
- return '';
- }
-
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'string') {
- return fieldValue;
- }
-
- return '';
+const getTextValue = (record: RecordNode, field: TextFieldNode): string => {
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ return attribute?.textValue ?? '';
};
interface TableViewTextCellProps {
record: RecordNode;
- field: TextField;
+ field: TextFieldNode;
}
export const TableViewTextCell = ({
record,
field,
}: TableViewTextCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: string) => {
- if (newValue.length > 0) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${field.id}', ${newValue}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
+ const { mutate, isPending } = useUpdateTextFieldValueMutation();
const canEdit = true;
@@ -73,7 +31,11 @@ export const TableViewTextCell = ({
const saveIfChanged = (current: string, previous: string | null) => {
if (current.length && current !== previous) {
- mutate(current);
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ value: current,
+ });
}
};
diff --git a/desktop/src/components/databases/tables/cells/table-view-url-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-url-cell.tsx
index 01166d7b..e30d946d 100644
--- a/desktop/src/components/databases/tables/cells/table-view-url-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-url-cell.tsx
@@ -1,11 +1,6 @@
import React from 'react';
import isHotkey from 'is-hotkey';
-
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { RecordNode, UrlField } from '@/types/databases';
-import { sql } from 'kysely';
+import { RecordNode, UrlFieldNode } from '@/types/databases';
import { cn, isValidUrl } from '@/lib/utils';
import {
HoverCard,
@@ -13,26 +8,16 @@ import {
HoverCardTrigger,
} from '@/components/ui/hover-card';
import { Icon } from '@/components/ui/icon';
+import { useUpdateUrlFieldValueMutation } from '@/mutations/use-update-url-field-value-mutation';
-const getUrlValue = (record: RecordNode, field: UrlField): string => {
- const attrs = record.attrs;
-
- if (!attrs) {
- return '';
- }
-
- const fieldValue = attrs[field.id];
-
- if (typeof fieldValue === 'string') {
- return fieldValue;
- }
-
- return '';
+const getUrlValue = (record: RecordNode, field: UrlFieldNode): string => {
+ const attribute = record.attributes.find((attr) => attr.type === field.id);
+ return attribute?.textValue ?? '';
};
interface TableViewUrlCellProps {
record: RecordNode;
- field: UrlField;
+ field: UrlFieldNode;
className?: string;
}
@@ -41,34 +26,7 @@ export const TableViewUrlCell = ({
field,
className,
}: TableViewUrlCellProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (newValue: string) => {
- if (newValue.length > 0) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.${field.id}', ${newValue}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.${sql.ref(field.id)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
+ const { mutate, isPending } = useUpdateUrlFieldValueMutation();
const canEdit = true;
@@ -82,7 +40,11 @@ export const TableViewUrlCell = ({
const saveIfChanged = (current: string, previous: string | null) => {
if (current.length && current !== previous) {
- mutate(current);
+ mutate({
+ recordId: record.id,
+ fieldId: field.id,
+ value: current,
+ });
}
};
diff --git a/desktop/src/components/databases/tables/table-view-body.tsx b/desktop/src/components/databases/tables/table-view-body.tsx
index e42a2699..3331b515 100644
--- a/desktop/src/components/databases/tables/table-view-body.tsx
+++ b/desktop/src/components/databases/tables/table-view-body.tsx
@@ -1,75 +1,17 @@
import React from 'react';
import { useDatabase } from '@/contexts/database';
-import { useWorkspace } from '@/contexts/workspace';
-import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
import { TableViewRow } from '@/components/databases/tables/table-view-row';
import { TableViewEmptyPlaceholder } from '@/components/databases/tables/table-view-empty-placeholder';
-import { QueryResult, sql } from 'kysely';
-import { SelectNode } from '@/data/schemas/workspace';
-import { buildRecords } from '@/lib/databases';
import { TableViewLoadMoreRow } from './table-view-load-more-row';
-
-const RECORDS_PER_PAGE = 50;
+import { useRecordsQuery } from '@/queries/use-records-query';
export const TableViewBody = () => {
- const workspace = useWorkspace();
const database = useDatabase();
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useInfiniteQuery({
- queryKey: ['table-body', database.id],
- initialPageParam: 0,
- getNextPageParam: (lastPage: QueryResult<SelectNode>, pages) => {
- if (lastPage && lastPage.rows) {
- const recordsCount = lastPage.rows.filter(
- (row) => row.type === NodeTypes.Record,
- ).length;
-
- if (recordsCount >= RECORDS_PER_PAGE) {
- return pages.length;
- }
- }
- return undefined;
- },
- queryFn: async ({ queryKey, pageParam }) => {
- const offset = pageParam * RECORDS_PER_PAGE;
- const query = sql<SelectNode>`
- WITH record_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${database.id} AND type = ${NodeTypes.Record}
- ORDER BY ${sql.ref('index')} ASC
- LIMIT ${sql.lit(RECORDS_PER_PAGE)}
- OFFSET ${sql.lit(offset)}
- ),
- author_nodes AS (
- SELECT *
- FROM nodes
- WHERE id IN (SELECT DISTINCT created_by FROM record_nodes)
- )
- SELECT * FROM record_nodes
- UNION ALL
- SELECT * FROM author_nodes;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- page: pageParam,
- query,
- });
- },
- });
-
- const pages = data?.pages ?? [];
- const allNodes =
- pages
- .map((page) => page.rows)
- .flat()
- .map((row) => mapNode(row)) ?? [];
+ useRecordsQuery(database.id);
- const records = buildRecords(allNodes);
+ const records = data ?? [];
return (
<div className="border-t">
{records.length === 0 && <TableViewEmptyPlaceholder />}
diff --git a/desktop/src/components/databases/tables/table-view-field-cell.tsx b/desktop/src/components/databases/tables/table-view-field-cell.tsx
index 756b50b9..ff011253 100644
--- a/desktop/src/components/databases/tables/table-view-field-cell.tsx
+++ b/desktop/src/components/databases/tables/table-view-field-cell.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Field, RecordNode } from '@/types/databases';
+import { FieldNode, RecordNode } from '@/types/databases';
import { TableViewTextCell } from '@/components/databases/tables/cells/table-view-text-cell';
import { TableViewNumberCell } from '@/components/databases/tables/cells/table-view-number-cell';
import { TableViewBooleanCell } from '@/components/databases/tables/cells/table-view-boolean-cell';
@@ -13,14 +13,14 @@ import { TableViewMultiSelectCell } from '@/components/databases/tables/cells/ta
interface TableViewFieldCellProps {
record: RecordNode;
- field: Field;
+ field: FieldNode;
}
export const TableViewFieldCell = ({
record,
field,
}: TableViewFieldCellProps) => {
- switch (field.type) {
+ switch (field.dataType) {
case 'text':
return <TableViewTextCell record={record} field={field} />;
case 'number':
diff --git a/desktop/src/components/databases/tables/table-view-field-header.tsx b/desktop/src/components/databases/tables/table-view-field-header.tsx
index a463ef0f..751d2f40 100644
--- a/desktop/src/components/databases/tables/table-view-field-header.tsx
+++ b/desktop/src/components/databases/tables/table-view-field-header.tsx
@@ -4,7 +4,7 @@ import { cn } from '@/lib/utils';
import { getFieldIcon } from '@/lib/databases';
import { useDrag, useDrop } from 'react-dnd';
import { Resizable } from 're-resizable';
-import { Field } from '@/types/databases';
+import { FieldNode } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -16,7 +16,7 @@ import { FieldRenameInput } from '@/components/databases/fields/field-rename-inp
import { useTableView } from '@/contexts/table-view';
interface TableViewFieldHeaderProps {
- field: Field;
+ field: FieldNode;
}
export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
@@ -27,7 +27,7 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
const [showDeleteDialog, setShowDeleteDialog] = React.useState(false);
- const [, dragRef] = useDrag<Field>({
+ const [, dragRef] = useDrag<FieldNode>({
type: 'table-field-header',
item: field,
canDrag: () => canEditView,
@@ -60,13 +60,13 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
<React.Fragment>
<Resizable
defaultSize={{
- width: `${tableView.getFieldWidth(field.id, field.type)}px`,
+ width: `${tableView.getFieldWidth(field.id, field.dataType)}px`,
height: '2rem',
}}
minWidth={100}
maxWidth={500}
size={{
- width: `${tableView.getFieldWidth(field.id, field.type)}px`,
+ width: `${tableView.getFieldWidth(field.id, field.dataType)}px`,
height: '2rem',
}}
enable={{
@@ -104,7 +104,7 @@ export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {
)}
ref={dragDropRef as any}
>
- <Icon name={getFieldIcon(field.type)} />
+ <Icon name={getFieldIcon(field.dataType)} />
<p>{field.name}</p>
</div>
</PopoverTrigger>
diff --git a/desktop/src/components/databases/tables/table-view-name-cell.tsx b/desktop/src/components/databases/tables/table-view-name-cell.tsx
index 2afd2577..d76fa124 100644
--- a/desktop/src/components/databases/tables/table-view-name-cell.tsx
+++ b/desktop/src/components/databases/tables/table-view-name-cell.tsx
@@ -2,11 +2,9 @@ import React from 'react';
import isHotkey from 'is-hotkey';
import { Icon } from '@/components/ui/icon';
import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
-import { NeuronId } from '@/lib/id';
import { Spinner } from '@/components/ui/spinner';
import { RecordNode } from '@/types/databases';
-import { sql } from 'kysely';
+import { useNodeUpdateNameMutation } from '@/mutations/use-node-update-name-mutation';
interface NameEditorProps {
initialValue: string;
@@ -55,25 +53,12 @@ interface TableViewNameCellProps {
export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
const workspace = useWorkspace();
const [isEditing, setIsEditing] = React.useState(false);
- const [name, setName] = React.useState(record.attrs?.name);
+ const [name, setName] = React.useState(record.name);
- const { mutate, isPending } = useMutation({
- mutationFn: async (newName: string) => {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.name', ${newName}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${record.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- },
- });
+ const { mutate, isPending } = useNodeUpdateNameMutation();
React.useEffect(() => {
- setName(record.attrs?.name);
+ setName(record.name);
}, [record.versionId]);
const canEdit = true;
@@ -81,18 +66,21 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
const handleSave = (newName: string) => {
setName(newName);
- mutate(newName, {
- onSuccess: () => {
- setIsEditing(false);
+ mutate(
+ { id: record.id, name: newName },
+ {
+ onSuccess: () => {
+ setIsEditing(false);
+ },
},
- });
+ );
};
return (
<div className="group relative flex h-full w-full items-center">
{isEditing ? (
<NameEditor
- initialValue={name}
+ initialValue={name ?? ''}
onSave={handleSave}
onCancel={() => setIsEditing(false)}
/>
diff --git a/desktop/src/components/databases/tables/table-view-record-create-row.tsx b/desktop/src/components/databases/tables/table-view-record-create-row.tsx
index 98c183f1..d16e7007 100644
--- a/desktop/src/components/databases/tables/table-view-record-create-row.tsx
+++ b/desktop/src/components/databases/tables/table-view-record-create-row.tsx
@@ -1,50 +1,11 @@
import React from 'react';
import { Icon } from '@/components/ui/icon';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
import { useDatabase } from '@/contexts/database';
-import { generateNodeIndex } from '@/lib/nodes';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
+import { useRecordCreateMutation } from '@/mutations/use-record-create-mutation';
export const TableViewRecordCreateRow = () => {
- const workspace = useWorkspace();
const database = useDatabase();
-
- const { mutate, isPending } = useMutation({
- mutationFn: async () => {
- const lastChildQuery = workspace.schema
- .selectFrom('nodes')
- .where('parent_id', '=', database.id)
- .selectAll()
- .orderBy('index', 'desc')
- .limit(1)
- .compile();
-
- const result = await workspace.query(lastChildQuery);
- const lastChild =
- result.rows && result.rows.length > 0 ? result.rows[0] : null;
- const maxIndex = lastChild?.index ? lastChild.index : null;
-
- const index = generateNodeIndex(maxIndex, null);
- const query = workspace.schema
- .insertInto('nodes')
- .values({
- id: NeuronId.generate(NeuronId.Type.Record),
- type: NodeTypes.Record,
- parent_id: database.id,
- index,
- attrs: null,
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- await workspace.mutate(query);
- },
- });
+ const { mutate, isPending } = useRecordCreateMutation();
return (
<button
@@ -52,7 +13,9 @@ export const TableViewRecordCreateRow = () => {
disabled={isPending}
className="animate-fade-in flex h-8 w-full cursor-pointer flex-row items-center gap-1 border-b pl-2 text-muted-foreground hover:bg-gray-50"
onClick={() => {
- mutate();
+ mutate({
+ databaseId: database.id,
+ });
}}
>
<Icon name="add-line" />
diff --git a/desktop/src/components/databases/tables/table-view-row.tsx b/desktop/src/components/databases/tables/table-view-row.tsx
index 8da43929..7f6b07f7 100644
--- a/desktop/src/components/databases/tables/table-view-row.tsx
+++ b/desktop/src/components/databases/tables/table-view-row.tsx
@@ -27,7 +27,7 @@ export const TableViewRow = ({ index, record }: TableViewRowProps) => {
<TableViewNameCell record={record} />
</div>
{tableView.fields.map((field) => {
- const width = tableView.getFieldWidth(field.id, field.type);
+ const width = tableView.getFieldWidth(field.id, field.dataType);
return (
<div
key={`row-${record.id}-${field.id}`}
diff --git a/desktop/src/components/databases/tables/table-view.tsx b/desktop/src/components/databases/tables/table-view.tsx
index c5fb4dd5..1744a0db 100644
--- a/desktop/src/components/databases/tables/table-view.tsx
+++ b/desktop/src/components/databases/tables/table-view.tsx
@@ -1,146 +1,53 @@
import React from 'react';
-import { LocalNode } from '@/types/nodes';
import { TableViewHeader } from '@/components/databases/tables/table-view-header';
import { TableViewBody } from '@/components/databases/tables/table-view-body';
import { TableViewRecordCreateRow } from '@/components/databases/tables/table-view-record-create-row';
import { TableViewContext } from '@/contexts/table-view';
import { useDatabase } from '@/contexts/database';
import { compareString } from '@/lib/utils';
-import { FieldType } from '@/types/databases';
+import { FieldDataType, TableViewNode } from '@/types/databases';
import { getDefaultFieldWidth, getDefaultNameWidth } from '@/lib/databases';
-import { useMutation } from '@tanstack/react-query';
-import { sql } from 'kysely';
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
+import { useUpdateViewFieldIndexMutation } from '@/mutations/use-update-view-field-index-mutation';
+import { useUpdateViewNameWidthMutation } from '@/mutations/use-update-view-name-width-mutation';
+import { useUpdateViewFieldWidthMutation } from '@/mutations/use-update-view-field-width-mutation';
+import { useUpdateViewHiddenFieldMutation } from '@/mutations/use-update-hidden-field-mutation';
interface TableViewProps {
- node: LocalNode;
-}
-
-interface UpdateHiddenFieldInput {
- fieldId: string;
- hide: boolean;
-}
-
-interface UpdateFieldIndexesInput {
- fieldId: string;
- index: string;
-}
-
-interface UpdateFieldWidthsInput {
- fieldId: string;
- width: number;
+ node: TableViewNode;
}
export const TableView = ({ node }: TableViewProps) => {
- const workspace = useWorkspace();
const database = useDatabase();
- const attrs = node.attrs ?? {};
- const [hiddenFields, setHiddenFields] = React.useState<
- Record<string, number>
- >(attrs.hiddenFields ?? []);
+ const updateHiddenFieldMutation = useUpdateViewHiddenFieldMutation();
+ const updateNameWidthMutation = useUpdateViewNameWidthMutation();
+ const updateFieldWidthMutation = useUpdateViewFieldWidthMutation();
+ const updateFieldIndexMutation = useUpdateViewFieldIndexMutation();
+
+ const [hiddenFields, setHiddenFields] = React.useState<string[]>(
+ node.hiddenFields ?? [],
+ );
const [fieldIndexes, setFieldIndexes] = React.useState<
Record<string, string>
- >(attrs.fieldIndexes ?? {});
+ >(node.fieldIndexes ?? {});
const [fieldWidths, setFieldWidths] = React.useState<Record<string, number>>(
- attrs.fieldWidths ?? {},
+ node.fieldWidths ?? {},
);
const [nameWidth, setNameWidth] = React.useState<number>(
- attrs.nameWidth ?? getDefaultNameWidth(),
+ node.nameWidth ?? getDefaultNameWidth(),
);
- const updateHiddenFieldMutation = useMutation({
- mutationFn: async (input: UpdateHiddenFieldInput) => {
- const { fieldId, hide } = input;
-
- if (hide) {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.hiddenFields.${sql.ref(fieldId)}', 1),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${node.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- } else {
- const query = sql`
- UPDATE nodes
- SET attrs = json_remove(attrs, '$.hiddenFields.${sql.ref(fieldId)}'),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${node.id} AND attrs IS NOT NULL
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }
- },
- });
-
- const updateFieldIndexesMutation = useMutation({
- mutationFn: async (input: UpdateFieldIndexesInput) => {
- const { fieldId, index } = input;
-
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.fieldIndexes.${sql.ref(fieldId)}', ${index}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${node.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- },
- });
-
- const updateFieldWidthsMutation = useMutation({
- mutationFn: async (input: UpdateFieldWidthsInput) => {
- const { fieldId, width } = input;
-
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.fieldWidths.${sql.ref(fieldId)}', ${width}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${node.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- },
- });
-
- const updateNameWidthMutation = useMutation({
- mutationFn: async (width: number) => {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(coalesce(attrs, '{}'), '$.nameWidth', ${width}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${node.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- },
- });
-
React.useEffect(() => {
- const attrs = node.attrs ?? {};
- setHiddenFields(attrs.hiddenFields ?? []);
- setFieldIndexes(attrs.fieldIndexes ?? {});
- setFieldWidths(attrs.fieldWidths ?? {});
- setNameWidth(attrs.nameWidth ?? getDefaultNameWidth());
+ setHiddenFields(node.hiddenFields ?? []);
+ setFieldIndexes(node.fieldIndexes ?? {});
+ setFieldWidths(node.fieldWidths ?? {});
+ setNameWidth(node.nameWidth ?? getDefaultNameWidth());
}, [node.versionId]);
const fields = React.useMemo(() => {
return database.fields
- .filter((field) => !hiddenFields[field.id])
+ .filter((field) => !hiddenFields.includes(field.id))
.sort((a, b) =>
compareString(
fieldIndexes[a.id] ?? a.index,
@@ -155,34 +62,45 @@ export const TableView = ({ node }: TableViewProps) => {
id: node.id,
fields,
hideField: (id: string) => {
- if (hiddenFields[id]) {
+ if (hiddenFields.includes(id)) {
return;
}
- setHiddenFields({ ...hiddenFields, [id]: 1 });
- updateHiddenFieldMutation.mutate({ fieldId: id, hide: true });
+ setHiddenFields([...hiddenFields, id]);
+ updateHiddenFieldMutation.mutate({
+ viewId: node.id,
+ fieldId: id,
+ hide: true,
+ });
},
showField: (id: string) => {
- if (!hiddenFields[id]) {
+ if (!hiddenFields.includes(id)) {
return;
}
- const newHiddenFields = { ...hiddenFields };
- delete newHiddenFields[id];
+ const newHiddenFields = hiddenFields.filter((f) => f !== id);
setHiddenFields(newHiddenFields);
- updateHiddenFieldMutation.mutate({ fieldId: id, hide: false });
+ updateHiddenFieldMutation.mutate({
+ viewId: node.id,
+ fieldId: id,
+ hide: false,
+ });
},
getNameWidth: () => nameWidth,
resizeName: (width: number) => {
setNameWidth(width);
- updateNameWidthMutation.mutate(width);
+ updateNameWidthMutation.mutate({ viewId: node.id, width });
},
- getFieldWidth: (id: string, type: FieldType) => {
+ getFieldWidth: (id: string, type: FieldDataType) => {
return fieldWidths[id] ?? getDefaultFieldWidth(type);
},
resizeField: (id, width) => {
setFieldWidths({ ...fieldWidths, [id]: width });
- updateFieldWidthsMutation.mutate({ fieldId: id, width });
+ updateFieldWidthMutation.mutate({
+ viewId: node.id,
+ fieldId: id,
+ width,
+ });
},
moveField: (id, after) => {
const field = database.fields.find((f) => f.id === id);
@@ -252,7 +170,11 @@ export const TableView = ({ node }: TableViewProps) => {
...fieldIndexes,
[id]: newIndex,
});
- updateFieldIndexesMutation.mutate({ fieldId: id, index: newIndex });
+ updateFieldIndexMutation.mutate({
+ viewId: node.id,
+ fieldId: id,
+ index: newIndex,
+ });
},
}}
>
diff --git a/desktop/src/components/databases/view-tab.tsx b/desktop/src/components/databases/view-tab.tsx
index b7a80a8c..9eb069d9 100644
--- a/desktop/src/components/databases/view-tab.tsx
+++ b/desktop/src/components/databases/view-tab.tsx
@@ -1,16 +1,15 @@
import React from 'react';
import { cn } from '@/lib/utils';
-import { LocalNode } from '@/types/nodes';
import { Avatar } from '@/components/ui/avatar';
+import { ViewNode } from '@/types/databases';
interface ViewTabProps {
- view: LocalNode;
+ view: ViewNode;
isActive: boolean;
onClick: () => void;
}
export const ViewTab = ({ view, isActive, onClick }: ViewTabProps) => {
- const name = view.attrs?.name ?? 'Unnamed View';
return (
<div
role="presentation"
@@ -21,8 +20,8 @@ export const ViewTab = ({ view, isActive, onClick }: ViewTabProps) => {
onClick={() => onClick()}
onKeyDown={() => onClick()}
>
- <Avatar id={view.id} name={name} size="small" />
- {name}
+ <Avatar id={view.id} name={view.name} size="small" />
+ {view.name}
</div>
);
};
diff --git a/desktop/src/components/databases/view.tsx b/desktop/src/components/databases/view.tsx
new file mode 100644
index 00000000..6ca97769
--- /dev/null
+++ b/desktop/src/components/databases/view.tsx
@@ -0,0 +1,15 @@
+import React from 'react';
+import { ViewNode } from '@/types/databases';
+import { TableView } from '@/components/databases/tables/table-view';
+
+interface ViewProps {
+ node: ViewNode;
+}
+
+export const View = ({ node }: ViewProps) => {
+ if (node.type === 'table_view') {
+ return <TableView node={node} />;
+ }
+
+ return null;
+};
diff --git a/desktop/src/components/documents/document-editor.tsx b/desktop/src/components/documents/document-editor.tsx
index dbf04d4c..44fb83ae 100644
--- a/desktop/src/components/documents/document-editor.tsx
+++ b/desktop/src/components/documents/document-editor.tsx
@@ -20,7 +20,9 @@ import {
PageNode,
TextNode,
ParagraphNode,
- HeadingNode,
+ Heading1Node,
+ Heading2Node,
+ Heading3Node,
BlockquoteNode,
BulletListNode,
CodeBlockNode,
@@ -47,13 +49,13 @@ import {
} from '@/editor/extensions';
import { EditorBubbleMenu } from '@/editor/menu/bubble-menu';
-import { LocalNode } from '@/types/nodes';
+import { LocalNode, LocalNodeWithAttributes } from '@/types/nodes';
import { useWorkspace } from '@/contexts/workspace';
import { EditorObserver } from '@/editor/observer';
interface DocumentEditorProps {
node: LocalNode;
- nodes: Map<string, LocalNode>;
+ nodes: Map<string, LocalNodeWithAttributes>;
}
export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {
@@ -71,7 +73,9 @@ export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {
PageNode,
TextNode,
ParagraphNode,
- HeadingNode,
+ Heading1Node,
+ Heading2Node,
+ Heading3Node,
BlockquoteNode,
BulletListNode,
CodeBlockNode,
diff --git a/desktop/src/components/documents/document.tsx b/desktop/src/components/documents/document.tsx
index f64d2718..a9e96714 100644
--- a/desktop/src/components/documents/document.tsx
+++ b/desktop/src/components/documents/document.tsx
@@ -1,51 +1,18 @@
import React from 'react';
import { LocalNode } from '@/types/nodes';
import { DocumentEditor } from './document-editor';
-import { useQuery } from '@tanstack/react-query';
-import { sql } from 'kysely';
-import { SelectNode } from '@/data/schemas/workspace';
-import { useWorkspace } from '@/contexts/workspace';
-import { mapNode } from '@/lib/nodes';
-import { NodeTypes } from '@/lib/constants';
+import { useDocumentQuery } from '@/queries/use-document-query';
interface DocumentProps {
node: LocalNode;
}
export const Document = ({ node }: DocumentProps) => {
- const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- queryKey: ['document', 'nodes', node.id],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- WITH RECURSIVE document_hierarchy AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${node.id}
-
- UNION ALL
-
- SELECT child.*
- FROM nodes child
- INNER JOIN document_hierarchy parent ON child.parent_id = parent.id
- WHERE parent.type NOT IN (${NodeTypes.Page})
- )
- SELECT *
- FROM document_hierarchy;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- query,
- key: queryKey,
- });
- },
- });
+ const { data, isPending } = useDocumentQuery(node.id);
if (isPending) {
return null;
}
- const rows = data.rows;
- const nodes = new Map(rows.map((row) => [row.id, mapNode(row)]));
- return <DocumentEditor key={node.id} node={node} nodes={nodes} />;
+ return <DocumentEditor key={node.id} node={node} nodes={data} />;
};
diff --git a/desktop/src/components/messages/message-create.tsx b/desktop/src/components/messages/message-create.tsx
index df4209d0..a509a143 100644
--- a/desktop/src/components/messages/message-create.tsx
+++ b/desktop/src/components/messages/message-create.tsx
@@ -1,44 +1,20 @@
import React from 'react';
import { MessageEditor } from '@/components/messages/message-editor';
-import { JSONContent } from '@tiptap/core';
-import { useMutation } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { buildMessageCreateNodes } from '@/lib/messages';
-import { CreateNode } from '@/data/schemas/workspace';
+import { useMessageCreateMutation } from '@/mutations/use-message-create-mutation';
interface MessageCreateProps {
conversationId: string;
}
export const MessageCreate = ({ conversationId }: MessageCreateProps) => {
- const workspace = useWorkspace();
- const { mutate, isPending } = useMutation({
- mutationFn: async (content: JSONContent) => {
- const nodesToCreate: CreateNode[] = [];
-
- buildMessageCreateNodes(
- nodesToCreate,
- workspace.userId,
- workspace.id,
- conversationId,
- content,
- );
-
- const query = workspace.schema
- .insertInto('nodes')
- .values(nodesToCreate)
- .compile();
-
- await workspace.mutate(query);
- },
- });
+ const { mutate, isPending } = useMessageCreateMutation();
return (
<div className="container mt-1 px-10">
<div className="flex flex-col">
<MessageEditor
conversationId={conversationId}
- onSubmit={mutate}
+ onSubmit={(content) => mutate({ conversationId, content })}
loading={isPending}
canEdit={true}
canSubmit={true}
diff --git a/desktop/src/components/messages/message-delete-button.tsx b/desktop/src/components/messages/message-delete-button.tsx
index c089be45..756bc27e 100644
--- a/desktop/src/components/messages/message-delete-button.tsx
+++ b/desktop/src/components/messages/message-delete-button.tsx
@@ -10,8 +10,7 @@ import {
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
+import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
interface MessageDeleteButtonProps {
id: string;
@@ -19,17 +18,7 @@ interface MessageDeleteButtonProps {
export const MessageDeleteButton = ({ id }: MessageDeleteButtonProps) => {
const [showDeleteModal, setShowDeleteModal] = React.useState(false);
- const { mutate, isPending } = useMutation({
- mutationFn: async (messageId: string) => {
- const mutation = workspace.schema
- .deleteFrom('nodes')
- .where('id', '=', messageId)
- .compile();
-
- await workspace.mutate(mutation);
- },
- });
- const workspace = useWorkspace();
+ const { mutate, isPending } = useNodeDeleteMutation();
return (
<React.Fragment>
diff --git a/desktop/src/components/messages/message-list.tsx b/desktop/src/components/messages/message-list.tsx
index f4a74f7f..2f4f3f44 100644
--- a/desktop/src/components/messages/message-list.tsx
+++ b/desktop/src/components/messages/message-list.tsx
@@ -1,15 +1,7 @@
import React from 'react';
import { InView } from 'react-intersection-observer';
import { Message } from '@/components/messages/message';
-import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
-import { SelectNode } from '@/data/schemas/workspace';
-import { QueryResult, sql } from 'kysely';
-import { NodeTypes } from '@/lib/constants';
-import { useWorkspace } from '@/contexts/workspace';
-import { mapNode } from '@/lib/nodes';
-import { buildMessages } from '@/lib/messages';
-
-const MESSAGES_PER_PAGE = 50;
+import { useMessagesQuery } from '@/queries/use-messages-query';
interface MessageListProps {
conversationId: string;
@@ -20,82 +12,20 @@ export const MessageList = ({
conversationId,
onLastMessageIdChange,
}: MessageListProps) => {
- const workspace = useWorkspace();
const lastMessageId = React.useRef<string | null>(null);
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useInfiniteQuery({
- queryKey: ['conversation', conversationId],
- initialPageParam: 0,
- getNextPageParam: (lastPage: QueryResult<SelectNode>, pages) => {
- if (lastPage && lastPage.rows) {
- const messageCount = lastPage.rows.filter(
- (row) => row.type === NodeTypes.Message,
- ).length;
-
- if (messageCount >= MESSAGES_PER_PAGE) {
- return pages.length;
- }
- }
- return undefined;
- },
- queryFn: async ({ queryKey, pageParam }) => {
- const offset = pageParam * MESSAGES_PER_PAGE;
- const query = sql<SelectNode>`
- WITH message_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${conversationId} AND type = ${NodeTypes.Message}
- ORDER BY id DESC
- LIMIT ${sql.lit(MESSAGES_PER_PAGE)}
- OFFSET ${sql.lit(offset)}
- ),
- descendant_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IN (SELECT id FROM message_nodes)
- UNION ALL
- SELECT child.*
- FROM nodes child
- INNER JOIN descendant_nodes parent ON child.parent_id = parent.id
- ),
- author_nodes AS (
- SELECT *
- FROM nodes
- WHERE id IN (SELECT DISTINCT created_by FROM message_nodes)
- )
- SELECT * FROM message_nodes
- UNION ALL
- SELECT * FROM descendant_nodes
- UNION ALL
- SELECT * FROM author_nodes;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- page: pageParam,
- query,
- });
- },
- });
-
- const pages = data?.pages ?? [];
- const allNodes =
- pages
- .map((page) => page.rows)
- .flat()
- .map((row) => mapNode(row)) ?? [];
- const messages = buildMessages(allNodes);
+ useMessagesQuery(conversationId);
React.useEffect(() => {
- if (messages.length > 0) {
- const lastMessage = messages[messages.length - 1];
+ if (data?.length > 0) {
+ const lastMessage = data[data.length - 1];
if (lastMessage.id !== lastMessageId.current) {
lastMessageId.current = lastMessage.id;
onLastMessageIdChange(lastMessageId.current);
}
}
- }, [messages]);
+ }, [data]);
if (isPending) {
return null;
@@ -111,8 +41,8 @@ export const MessageList = ({
}
}}
></InView>
- {messages.map((message, index) => {
- const previousMessage = index > 0 ? messages[index - 1] : null;
+ {data.map((message, index) => {
+ const previousMessage = index > 0 ? data[index - 1] : null;
const currentMessageDate = new Date(message.createdAt);
const previousMessageDate = previousMessage
diff --git a/desktop/src/components/messages/message.tsx b/desktop/src/components/messages/message.tsx
index 3803c533..4e38cda9 100644
--- a/desktop/src/components/messages/message.tsx
+++ b/desktop/src/components/messages/message.tsx
@@ -19,13 +19,6 @@ interface MessageProps {
}
export const Message = ({ message, previousMessage }: MessageProps) => {
- const author = message.author ?? {
- id: message.createdBy,
- attrs: {
- name: 'Deleted user',
- },
- };
-
const shouldDisplayUserInfo = () => {
if (!previousMessage) {
return true;
@@ -38,14 +31,14 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
return true;
}
- return !previousMessage || previousMessage.createdBy !== message.createdBy;
+ return !previousMessage || previousMessage.author.id !== message.author.id;
};
const canEdit = true;
const canDelete = true;
const canReplyInThread = true;
- if (!message.children || message.children.length === 0) {
+ if (!message.content || message.content.length === 0) {
return null;
}
@@ -59,14 +52,18 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
>
<div className="mr-2 w-10 pt-1">
{shouldDisplayUserInfo() && (
- <Avatar id={author.id} name={author.attrs.name} size="medium" />
+ <Avatar
+ id={message.author.id}
+ name={message.author.name}
+ size="medium"
+ />
)}
</div>
<div className="relative w-full">
{shouldDisplayUserInfo() && (
<p className="font-medium">
- {author.attrs.name}
+ {message.author.name}
<Tooltip>
<TooltipTrigger asChild>
<span className="ml-2 text-xs text-muted-foreground">
@@ -122,7 +119,9 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
</ul>
{/*{data.messageReference && <MessageReference />}*/}
<div className="text-foreground">
- <NodeRenderer node={message} keyPrefix={message.id} />
+ {message.content.map((node) => (
+ <NodeRenderer key={node.id} node={node} keyPrefix={node.id} />
+ ))}
</div>
{/*<MessageReactions*/}
{/* message={message}*/}
diff --git a/desktop/src/components/pages/page-create-dialog.tsx b/desktop/src/components/pages/page-create-dialog.tsx
index 47449326..3a4cba5c 100644
--- a/desktop/src/components/pages/page-create-dialog.tsx
+++ b/desktop/src/components/pages/page-create-dialog.tsx
@@ -22,11 +22,7 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
-import { compareString } from '@/lib/utils';
+import { usePageCreateMutation } from '@/mutations/use-page-create-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -44,6 +40,8 @@ export const PageCreateDialog = ({
onOpenChange,
}: PageCreateDialogProps) => {
const workspace = useWorkspace();
+ const { mutate, isPending } = usePageCreateMutation();
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -51,57 +49,22 @@ export const PageCreateDialog = ({
},
});
- const { mutate, isPending } = useMutation({
- mutationFn: async (values: z.infer<typeof formSchema>) => {
- const siblingsQuery = workspace.schema
- .selectFrom('nodes')
- .where('parent_id', '=', spaceId)
- .selectAll()
- .compile();
-
- const result = await workspace.query(siblingsQuery);
- const siblings = result.rows;
- const maxIndex =
- siblings.length > 0
- ? siblings.sort((a, b) => compareString(a.index, b.index))[
- siblings.length - 1
- ].index
- : null;
-
- const index = generateNodeIndex(maxIndex, null);
- const query = workspace.schema
- .insertInto('nodes')
- .values({
- id: NeuronId.generate(NeuronId.Type.Page),
- type: NodeTypes.Page,
- parent_id: spaceId,
- index,
- attrs: JSON.stringify({
- name: values.name,
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- await workspace.mutate(query);
- },
- });
-
const handleCancel = () => {
form.reset();
onOpenChange(false);
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(values, {
- onSuccess: () => {
- onOpenChange(false);
- form.reset();
+ mutate(
+ { spaceId, name: values.name },
+ {
+ onSuccess: (id) => {
+ onOpenChange(false);
+ form.reset();
+ workspace.navigateToNode(id);
+ },
},
- });
+ );
};
return (
diff --git a/desktop/src/components/root.tsx b/desktop/src/components/root.tsx
index 8b1bbbe5..ba0f48cf 100644
--- a/desktop/src/components/root.tsx
+++ b/desktop/src/components/root.tsx
@@ -7,7 +7,7 @@ import { WorkspaceCreate } from '@/components/workspaces/workspace-create';
import { Workspace } from '@/components/workspaces/workspace';
import { WorkspaceRedirect } from '@/components/workspaces/workspace-redirect';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
-import { Container } from '@/components/workspaces/container';
+import { Container } from '@/components/workspaces/containers/container';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { eventBus } from '@/lib/event-bus';
import { DndProvider } from 'react-dnd';
diff --git a/desktop/src/components/spaces/space-create-dialog.tsx b/desktop/src/components/spaces/space-create-dialog.tsx
index 75f90ac8..2adf4194 100644
--- a/desktop/src/components/spaces/space-create-dialog.tsx
+++ b/desktop/src/components/spaces/space-create-dialog.tsx
@@ -1,5 +1,4 @@
import React from 'react';
-import { useWorkspace } from '@/contexts/workspace';
import {
Dialog,
DialogContent,
@@ -23,10 +22,7 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
-import { NeuronId } from '@/lib/id';
-import { NodeTypes } from '@/lib/constants';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
+import { useSpaceCreateMutation } from '@/mutations/use-space-create-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -42,7 +38,8 @@ export const SpaceCreateDialog = ({
open,
onOpenChange,
}: SpaceCreateDialogProps) => {
- const workspace = useWorkspace();
+ const { mutate, isPending } = useSpaceCreateMutation();
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -51,74 +48,21 @@ export const SpaceCreateDialog = ({
},
});
- const { mutate, isPending } = useMutation({
- mutationFn: async (values: z.infer<typeof formSchema>) => {
- const spaceId = NeuronId.generate(NeuronId.Type.Space);
- const firstIndex = generateNodeIndex(null, null);
- const secondIndex = generateNodeIndex(firstIndex, null);
- const query = workspace
- .schema
- .insertInto('nodes')
- .values([
- {
- id: spaceId,
- type: NodeTypes.Space,
- parent_id: null,
- index: generateNodeIndex(null, null),
- attrs: JSON.stringify({
- name: values.name,
- description: values.description,
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- id: NeuronId.generate(NeuronId.Type.Page),
- type: NodeTypes.Page,
- parent_id: spaceId,
- index: firstIndex,
- attrs: JSON.stringify({
- name: 'Home',
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- id: NeuronId.generate(NeuronId.Type.Channel),
- type: NodeTypes.Channel,
- parent_id: spaceId,
- index: secondIndex,
- attrs: JSON.stringify({
- name: 'Discussions',
- }),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
-
- await workspace.mutate(query);
- },
- });
-
const handleCancel = () => {
form.reset();
onOpenChange(false);
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(values, {
- onSuccess: () => {
- onOpenChange(false);
- form.reset();
+ mutate(
+ { name: values.name, description: values.description },
+ {
+ onSuccess: () => {
+ onOpenChange(false);
+ form.reset();
+ },
},
- });
+ );
};
return (
diff --git a/desktop/src/components/workspaces/container-header.tsx b/desktop/src/components/workspaces/container-header.tsx
deleted file mode 100644
index 572ee15a..00000000
--- a/desktop/src/components/workspaces/container-header.tsx
+++ /dev/null
@@ -1,246 +0,0 @@
-import React from 'react';
-import { LocalNode } from '@/types/nodes';
-import { Avatar } from '@/components/ui/avatar';
-import {
- Breadcrumb,
- BreadcrumbEllipsis,
- BreadcrumbItem,
- BreadcrumbList,
- BreadcrumbSeparator,
-} from '@/components/ui/breadcrumb';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu';
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from '@/components/ui/popover';
-import { NodeTypes } from '@/lib/constants';
-import { useWorkspace } from '@/contexts/workspace';
-import { cn } from '@/lib/utils';
-import { Input } from '@/components/ui/input';
-import { debounce } from 'lodash';
-import { sql } from 'kysely';
-import { mapNode } from '@/lib/nodes';
-import { useQuery } from '@tanstack/react-query';
-import { SelectNode } from '@/data/schemas/workspace';
-import { NeuronId } from '@/lib/id';
-
-const buildBreadcrumbNodes = (node: LocalNode, rows: SelectNode[]) => {
- const breadcrumbNodes: LocalNode[] = [];
- let parentId = node.parentId;
- while (parentId !== null && parentId !== undefined) {
- const row = rows.find((row) => row.id === parentId);
- if (row) {
- breadcrumbNodes.push(mapNode(row));
- parentId = row.parent_id;
- } else {
- parentId = null;
- }
- }
- return breadcrumbNodes.reverse();
-};
-
-interface BreadcrumbNodeProps {
- node: LocalNode;
- className?: string;
-}
-
-const BreadcrumbNode = ({ node, className }: BreadcrumbNodeProps) => {
- const name = node.attrs.name ?? 'Untitled';
- const avatar = node.attrs.avatar;
-
- return (
- <div className={cn('flex items-center space-x-1', className)}>
- {avatar && (
- <Avatar size="small" id={node.id} name={name} avatar={avatar} />
- )}
- <span>{name}</span>
- </div>
- );
-};
-
-interface BreadcrumbNodeEditorProps {
- node: LocalNode;
-}
-
-export const BreadcrumbNodeEditor = ({ node }: BreadcrumbNodeEditorProps) => {
- const workspace = useWorkspace();
- const [name, setName] = React.useState(node.attrs.name ?? '');
-
- const handleNameChange = React.useMemo(
- () =>
- debounce(async (newName: string) => {
- const query = sql`
- UPDATE nodes
- SET attrs = json_set(attrs, '$.name', ${newName}),
- updated_at = ${new Date().toISOString()},
- updated_by = ${workspace.userId},
- version_id = ${NeuronId.generate(NeuronId.Type.Version)}
- WHERE id = ${node.id}
- `.compile(workspace.schema);
-
- await workspace.mutate(query);
- }, 500),
- [node.id],
- );
-
- return (
- <div>
- <Input
- placeholder="Name"
- value={name}
- onChange={async (e) => {
- const newName = e.target.value;
- setName(newName);
- await handleNameChange(newName);
- }}
- />
- </div>
- );
-};
-
-interface ContainerHeaderProps {
- node: LocalNode;
-}
-
-export const ContainerHeader = ({ node }: ContainerHeaderProps) => {
- const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- queryKey: ['breadcrumb', node.id],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- WITH RECURSIVE breadcrumb AS (
- SELECT *
- FROM nodes
- WHERE id = ${node.parentId}
- UNION ALL
- SELECT n.*
- FROM nodes n
- INNER JOIN breadcrumb b ON n.id = b.parent_id
- )
- SELECT * FROM breadcrumb;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- });
-
- if (isPending) {
- return null;
- }
-
- const breadcrumbNodes: LocalNode[] = buildBreadcrumbNodes(node, data.rows);
- const showEllipsis = breadcrumbNodes.length > 2;
- const firstNodes = showEllipsis
- ? breadcrumbNodes.slice(0, 1)
- : breadcrumbNodes;
- const ellipsisNodes = showEllipsis ? breadcrumbNodes.slice(1, -1) : [];
- const lastNodes = showEllipsis ? breadcrumbNodes.slice(-1) : [];
-
- const isClickable = (node: LocalNode) => node.type !== NodeTypes.Space;
-
- return (
- <Breadcrumb className="mx-1 flex h-12 justify-between p-2 text-foreground/80">
- <BreadcrumbList>
- {firstNodes.map((breadcrumbNode) => {
- return (
- <React.Fragment key={breadcrumbNode.id}>
- <BreadcrumbItem
- onClick={() => {
- if (isClickable(breadcrumbNode)) {
- workspace.navigateToNode(breadcrumbNode.id);
- }
- }}
- >
- <BreadcrumbNode
- node={breadcrumbNode}
- className={
- isClickable(breadcrumbNode)
- ? 'hover:cursor-pointer hover:text-foreground'
- : ''
- }
- />
- </BreadcrumbItem>
- <BreadcrumbSeparator />
- </React.Fragment>
- );
- })}
- {showEllipsis && (
- <BreadcrumbItem>
- <DropdownMenu>
- <DropdownMenuTrigger className="flex items-center gap-1">
- <BreadcrumbEllipsis className="h-4 w-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {ellipsisNodes.map((breadcrumbNode) => {
- return (
- <DropdownMenuItem
- key={breadcrumbNode.id}
- onClick={() => {
- if (isClickable(breadcrumbNode)) {
- workspace.navigateToNode(breadcrumbNode.id);
- }
- }}
- >
- <BreadcrumbNode
- node={breadcrumbNode}
- className={
- isClickable(breadcrumbNode)
- ? 'hover:cursor-pointer hover:text-foreground'
- : ''
- }
- />
- </DropdownMenuItem>
- );
- })}
- </DropdownMenuContent>
- </DropdownMenu>
- </BreadcrumbItem>
- )}
- {showEllipsis &&
- lastNodes.length > 0 &&
- lastNodes.map((breadcrumbNode) => {
- return (
- <React.Fragment key={breadcrumbNode.id}>
- <BreadcrumbItem
- onClick={() => {
- if (isClickable(breadcrumbNode)) {
- workspace.navigateToNode(breadcrumbNode.id);
- }
- }}
- >
- <BreadcrumbNode
- node={breadcrumbNode}
- className={
- isClickable(breadcrumbNode)
- ? 'hover:cursor-pointer hover:text-foreground'
- : ''
- }
- />
- </BreadcrumbItem>
- <BreadcrumbSeparator />
- </React.Fragment>
- );
- })}
- <BreadcrumbItem className="hover:cursor-pointer hover:text-foreground">
- <Popover>
- <PopoverTrigger>
- <BreadcrumbNode node={node} />
- </PopoverTrigger>
- <PopoverContent>
- <BreadcrumbNodeEditor node={node} />
- </PopoverContent>
- </Popover>
- </BreadcrumbItem>
- </BreadcrumbList>
- </Breadcrumb>
- );
-};
diff --git a/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx b/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
new file mode 100644
index 00000000..32ace43d
--- /dev/null
+++ b/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import { Input } from '@/components/ui/input';
+import { debounce } from 'lodash';
+import { BreadcrumbNode } from '@/types/workspaces';
+import { useNodeUpdateNameMutation } from '@/mutations/use-node-update-name-mutation';
+
+interface BreadcrumbItemEditorProps {
+ node: BreadcrumbNode;
+}
+
+export const BreadcrumbItemEditor = ({ node }: BreadcrumbItemEditorProps) => {
+ const [name, setName] = React.useState(node.name ?? '');
+ const { mutate } = useNodeUpdateNameMutation();
+
+ const handleNameChange = React.useMemo(
+ () =>
+ debounce(async (newName: string) => {
+ mutate({
+ id: node.id,
+ name: newName,
+ });
+ }, 500),
+ [node.id],
+ );
+
+ return (
+ <div>
+ <Input
+ placeholder="Name"
+ value={name}
+ onChange={async (e) => {
+ const newName = e.target.value;
+ setName(newName);
+ await handleNameChange(newName);
+ }}
+ />
+ </div>
+ );
+};
diff --git a/desktop/src/components/workspaces/containers/breadcrumb-item.tsx b/desktop/src/components/workspaces/containers/breadcrumb-item.tsx
new file mode 100644
index 00000000..580e2155
--- /dev/null
+++ b/desktop/src/components/workspaces/containers/breadcrumb-item.tsx
@@ -0,0 +1,25 @@
+import React from 'react';
+import { cn } from '@/lib/utils';
+import { Avatar } from '@/components/ui/avatar';
+import { BreadcrumbNode } from '@/types/workspaces';
+
+interface BreadcrumbNodeProps {
+ node: BreadcrumbNode;
+ className?: string;
+}
+
+export const BreadcrumbItem = ({ node, className }: BreadcrumbNodeProps) => {
+ return (
+ <div className={cn('flex items-center space-x-1', className)}>
+ {node.avatar && (
+ <Avatar
+ size="small"
+ id={node.id}
+ name={node.name}
+ avatar={node.avatar}
+ />
+ )}
+ <span>{node.name ?? 'Unnamed'}</span>
+ </div>
+ );
+};
diff --git a/desktop/src/components/workspaces/containers/breadcrumb.tsx b/desktop/src/components/workspaces/containers/breadcrumb.tsx
new file mode 100644
index 00000000..74d793ba
--- /dev/null
+++ b/desktop/src/components/workspaces/containers/breadcrumb.tsx
@@ -0,0 +1,116 @@
+import React from 'react';
+import { LocalNode } from '@/types/nodes';
+import {
+ Breadcrumb as BreadcrumbWrapper,
+ BreadcrumbEllipsis,
+ BreadcrumbItem as BreadcrumbItemWrapper,
+ BreadcrumbList,
+ BreadcrumbSeparator,
+} from '@/components/ui/breadcrumb';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import { NodeTypes } from '@/lib/constants';
+import { useWorkspace } from '@/contexts/workspace';
+import { BreadcrumbItem } from '@/components/workspaces/containers/breadcrumb-item';
+import { BreadcrumbItemEditor } from '@/components/workspaces/containers/breadcrumb-item-editor';
+import { useBreadcrumbQuery } from '@/queries/use-breadcrumb-query';
+
+interface BreadcrumbProps {
+ node: LocalNode;
+}
+
+export const Breadcrumb = ({ node }: BreadcrumbProps) => {
+ const workspace = useWorkspace();
+ const { data, isPending } = useBreadcrumbQuery(node.id);
+
+ if (isPending) {
+ return null;
+ }
+
+ const showEllipsis = data.length > 2;
+ const visibleNodes = showEllipsis ? [data[0], data[data.length - 1]] : data;
+ const ellipsisNodes = showEllipsis ? data.slice(1, -1) : [];
+
+ const isClickable = (type: string) => type !== NodeTypes.Space;
+
+ return (
+ <BreadcrumbWrapper className="mx-1 flex h-12 justify-between p-2 text-foreground/80">
+ <BreadcrumbList>
+ {visibleNodes.map((breadcrumbNode, index) => (
+ <React.Fragment key={breadcrumbNode.id}>
+ {index > 0 && <BreadcrumbSeparator />}
+ <BreadcrumbItemWrapper
+ onClick={() => {
+ if (isClickable(breadcrumbNode.type)) {
+ workspace.navigateToNode(breadcrumbNode.id);
+ }
+ }}
+ >
+ {breadcrumbNode.id === node.id ? (
+ <Popover>
+ <PopoverTrigger>
+ <BreadcrumbItem node={breadcrumbNode} />
+ </PopoverTrigger>
+ <PopoverContent>
+ <BreadcrumbItemEditor node={breadcrumbNode} />
+ </PopoverContent>
+ </Popover>
+ ) : (
+ <BreadcrumbItem
+ node={breadcrumbNode}
+ className={
+ isClickable(breadcrumbNode.type)
+ ? 'hover:cursor-pointer hover:text-foreground'
+ : ''
+ }
+ />
+ )}
+ </BreadcrumbItemWrapper>
+ {showEllipsis && index === 0 && (
+ <React.Fragment>
+ <BreadcrumbSeparator />
+ <BreadcrumbItemWrapper>
+ <DropdownMenu>
+ <DropdownMenuTrigger className="flex items-center gap-1">
+ <BreadcrumbEllipsis className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {ellipsisNodes.map((ellipsisNode) => (
+ <DropdownMenuItem
+ key={ellipsisNode.id}
+ onClick={() => {
+ if (isClickable(ellipsisNode.type)) {
+ workspace.navigateToNode(ellipsisNode.id);
+ }
+ }}
+ >
+ <BreadcrumbItem
+ node={ellipsisNode}
+ className={
+ isClickable(ellipsisNode.type)
+ ? 'hover:cursor-pointer hover:text-foreground'
+ : ''
+ }
+ />
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </BreadcrumbItemWrapper>
+ </React.Fragment>
+ )}
+ </React.Fragment>
+ ))}
+ </BreadcrumbList>
+ </BreadcrumbWrapper>
+ );
+};
diff --git a/desktop/src/components/workspaces/containers/container-header.tsx b/desktop/src/components/workspaces/containers/container-header.tsx
new file mode 100644
index 00000000..3c99870f
--- /dev/null
+++ b/desktop/src/components/workspaces/containers/container-header.tsx
@@ -0,0 +1,11 @@
+import React from 'react';
+import { LocalNode } from '@/types/nodes';
+import { Breadcrumb } from '@/components/workspaces/containers/breadcrumb';
+
+interface ContainerHeaderProps {
+ node: LocalNode;
+}
+
+export const ContainerHeader = ({ node }: ContainerHeaderProps) => {
+ return <Breadcrumb node={node} />;
+};
diff --git a/desktop/src/components/workspaces/container.tsx b/desktop/src/components/workspaces/containers/container.tsx
similarity index 98%
rename from desktop/src/components/workspaces/container.tsx
rename to desktop/src/components/workspaces/containers/container.tsx
index e8add563..27c135fe 100644
--- a/desktop/src/components/workspaces/container.tsx
+++ b/desktop/src/components/workspaces/containers/container.tsx
@@ -4,7 +4,7 @@ import { useParams } from 'react-router-dom';
import { NodeTypes } from '@/lib/constants';
import { PageContainerNode } from '@/components/pages/page-container-node';
import { ChannelContainerNode } from '@/components/channels/channel-container-node';
-import { ContainerHeader } from '@/components/workspaces/container-header';
+import { ContainerHeader } from '@/components/workspaces/containers/container-header';
import { Spinner } from '@/components/ui/spinner';
import { mapNode } from '@/lib/nodes';
import { useQuery } from '@tanstack/react-query';
diff --git a/desktop/src/components/workspaces/sidebar-node-children.tsx b/desktop/src/components/workspaces/sidebar-node-children.tsx
deleted file mode 100644
index 847ff284..00000000
--- a/desktop/src/components/workspaces/sidebar-node-children.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import React from 'react';
-import { LocalNode } from '@/types/nodes';
-import { SidebarNode } from '@/components/workspaces/sidebar-node';
-import { useSidebar } from '@/contexts/sidebar';
-import { compareString } from '@/lib/utils';
-
-interface SidebarNodeChildrenProps {
- node: LocalNode;
-}
-
-export const SidebarNodeChildren = ({ node }: SidebarNodeChildrenProps) => {
- const sidebar = useSidebar();
- const children: LocalNode[] = sidebar.nodes
- .filter((n) => n.parentId === node.id)
- .sort((a, b) => compareString(a.index, b.index));
-
- return (
- <React.Fragment>
- {children.map((child) => (
- <SidebarNode key={child.id} node={child} />
- ))}
- </React.Fragment>
- );
-};
diff --git a/desktop/src/components/workspaces/sidebar-node.tsx b/desktop/src/components/workspaces/sidebar-node.tsx
deleted file mode 100644
index f369578c..00000000
--- a/desktop/src/components/workspaces/sidebar-node.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import React from 'react';
-import { LocalNode } from '@/types/nodes';
-import { match } from 'ts-pattern';
-import { SpaceSidebarNode } from '@/components/spaces/space-sidebar-node';
-import { NodeTypes } from '@/lib/constants';
-import { ChannelSidebarNode } from '@/components/channels/channel-sidebar-node';
-import { PageSidebarNode } from '@/components/pages/page-sidebar-node';
-import { DatabaseSidebarNode } from '@/components/databases/database-sidebar-node';
-
-interface SidebarNodeProps {
- node: LocalNode;
-}
-
-export const SidebarNode = ({ node }: SidebarNodeProps): React.ReactNode => {
- return match(node.type)
- .with(NodeTypes.Space, () => <SpaceSidebarNode node={node} />)
- .with(NodeTypes.Channel, () => <ChannelSidebarNode node={node} />)
- .with(NodeTypes.Page, () => <PageSidebarNode node={node} />)
- .with(NodeTypes.Database, () => <DatabaseSidebarNode node={node} />)
- .otherwise(null);
-};
diff --git a/desktop/src/components/workspaces/sidebar.tsx b/desktop/src/components/workspaces/sidebar.tsx
deleted file mode 100644
index 155a8e48..00000000
--- a/desktop/src/components/workspaces/sidebar.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import React from 'react';
-import { SidebarHeader } from '@/components/workspaces/sidebar-header';
-import { SidebarSpaces } from '@/components/workspaces/sidebar-spaces';
-import { LocalNode } from '@/types/nodes';
-import { SidebarContext } from '@/contexts/sidebar';
-import { Spinner } from '@/components/ui/spinner';
-import { mapNode } from '@/lib/nodes';
-import { useQuery } from '@tanstack/react-query';
-import { useWorkspace } from '@/contexts/workspace';
-import { Icon } from '@/components/ui/icon';
-import { SpacebarChats } from '@/components/workspaces/spacebar-chats';
-
-export const Sidebar = () => {
- const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- queryKey: ['sidebar', workspace.id],
- queryFn: async ({ queryKey }) => {
- const query = workspace.schema
- .selectFrom('nodes')
- .selectAll()
- .where((qb) =>
- qb.or([
- qb.eb('type', '=', 'space'),
- qb.eb(
- 'parent_id',
- 'in',
- qb.selectFrom('nodes').select('id').where('type', '=', 'space'),
- ),
- ]),
- )
- .compile();
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- });
-
- if (isPending) {
- return <Spinner />;
- }
-
- const nodes: LocalNode[] = data?.rows.map((row) => mapNode(row)) ?? [];
- return (
- <SidebarContext.Provider
- value={{
- nodes: nodes,
- }}
- >
- <div className="h-full max-h-screen w-full border-r border-gray-200">
- <SidebarHeader />
- <div className="relative mt-2 max-h-full flex-grow overflow-hidden px-2">
- <div className="flex cursor-pointer items-center rounded-md p-1 text-sm text-foreground/80 hover:bg-gray-100">
- <Icon name="search-line" className="mr-2 h-4 w-4" />
- <span>Search</span>
- </div>
- <div className="flex cursor-pointer items-center rounded-md p-1 text-sm text-foreground/80 hover:bg-gray-100">
- <Icon name="inbox-line" className="mr-2 h-4 w-4" />
- <span>Inbox</span>
- </div>
- <SpacebarChats />
- <SidebarSpaces />
- </div>
- </div>
- </SidebarContext.Provider>
- );
-};
diff --git a/desktop/src/components/workspaces/spacebar-chats.tsx b/desktop/src/components/workspaces/sidebars/sidebar-chats.tsx
similarity index 61%
rename from desktop/src/components/workspaces/spacebar-chats.tsx
rename to desktop/src/components/workspaces/sidebars/sidebar-chats.tsx
index 6d6aac54..4008b079 100644
--- a/desktop/src/components/workspaces/spacebar-chats.tsx
+++ b/desktop/src/components/workspaces/sidebars/sidebar-chats.tsx
@@ -1,6 +1,11 @@
import React from 'react';
+import { SidebarChatNode } from '@/types/workspaces';
-export const SpacebarChats = () => {
+interface SidebarChatsProps {
+ chats: SidebarChatNode[];
+}
+
+export const SidebarChats = ({ chats }: SidebarChatsProps) => {
return (
<div className="pt-2 first:pt-0">
<div className="flex items-center justify-between p-1 pb-2 text-xs text-muted-foreground">
diff --git a/desktop/src/components/workspaces/sidebar-header.tsx b/desktop/src/components/workspaces/sidebars/sidebar-header.tsx
similarity index 100%
rename from desktop/src/components/workspaces/sidebar-header.tsx
rename to desktop/src/components/workspaces/sidebars/sidebar-header.tsx
diff --git a/desktop/src/components/pages/page-sidebar-node.tsx b/desktop/src/components/workspaces/sidebars/sidebar-item.tsx
similarity index 77%
rename from desktop/src/components/pages/page-sidebar-node.tsx
rename to desktop/src/components/workspaces/sidebars/sidebar-item.tsx
index e906bc16..ca1d339a 100644
--- a/desktop/src/components/pages/page-sidebar-node.tsx
+++ b/desktop/src/components/workspaces/sidebars/sidebar-item.tsx
@@ -1,22 +1,20 @@
import React from 'react';
-import { LocalNode } from '@/types/nodes';
+import { useWorkspace } from '@/contexts/workspace';
+import { SidebarNode } from '@/types/workspaces';
import { cn } from '@/lib/utils';
import { Avatar } from '@/components/ui/avatar';
import { Icon } from '@/components/ui/icon';
-import { useWorkspace } from '@/contexts/workspace';
-interface PageSidebarNodeProps {
- node: LocalNode;
+interface SidebarItemProps {
+ node: SidebarNode;
}
-export const PageSidebarNode = ({ node }: PageSidebarNodeProps) => {
+export const SidebarItem = ({ node }: SidebarItemProps): React.ReactNode => {
const workspace = useWorkspace();
const isActive = false;
const isUnread = false;
const directCount = 0;
- const avatar = node.attrs.avatar;
- const name = node.attrs.name ?? 'Unnamed';
return (
<div
key={node.id}
@@ -28,14 +26,14 @@ export const PageSidebarNode = ({ node }: PageSidebarNodeProps) => {
workspace.navigateToNode(node.id);
}}
>
- <Avatar id={node.id} avatar={avatar} name={name} size="small" />
+ <Avatar id={node.id} avatar={node.avatar} name={node.name} size="small" />
<span
className={cn(
'line-clamp-1 w-full flex-grow pl-2 text-left',
isUnread && 'font-bold',
)}
>
- {name}
+ {node.name ?? 'Unnamed'}
</span>
{directCount > 0 && (
<span className="mr-1 rounded-md bg-red-500 px-1 py-0.5 text-xs text-white">
diff --git a/desktop/src/components/spaces/space-sidebar-node.tsx b/desktop/src/components/workspaces/sidebars/sidebar-space-item.tsx
similarity index 88%
rename from desktop/src/components/spaces/space-sidebar-node.tsx
rename to desktop/src/components/workspaces/sidebars/sidebar-space-item.tsx
index b20815f8..9f022b00 100644
--- a/desktop/src/components/spaces/space-sidebar-node.tsx
+++ b/desktop/src/components/workspaces/sidebars/sidebar-space-item.tsx
@@ -1,9 +1,7 @@
import React from 'react';
-import { LocalNode } from '@/types/nodes';
import { cn } from '@/lib/utils';
import { Avatar } from '@/components/ui/avatar';
import { Icon } from '@/components/ui/icon';
-import { SidebarNodeChildren } from '@/components/workspaces/sidebar-node-children';
import {
DropdownMenu,
DropdownMenuContent,
@@ -17,17 +15,19 @@ import { NodeTypes } from '@/lib/constants';
import { ChannelCreateDialog } from '@/components/channels/channel-create-dialog';
import { PageCreateDialog } from '@/components/pages/page-create-dialog';
import { DatabaseCreateDialog } from '@/components/databases/database-create-dialog';
+import { SidebarSpaceNode } from '@/types/workspaces';
+import { SidebarItem } from '@/components/workspaces/sidebars/sidebar-item';
interface SettingsState {
open: boolean;
tab?: string;
}
-interface SpaceSidebarNodeProps {
- node: LocalNode;
+interface SidebarSpaceNodeProps {
+ node: SidebarSpaceNode;
}
-export const SpaceSidebarNode = ({ node }: SpaceSidebarNodeProps) => {
+export const SidebarSpaceItem = ({ node }: SidebarSpaceNodeProps) => {
const [isOpen, setIsOpen] = React.useState(true);
const [openCreatePage, setOpenCreatePage] = React.useState(false);
const [openCreateChannel, setOpenCreateChannel] = React.useState(false);
@@ -38,8 +38,7 @@ export const SpaceSidebarNode = ({ node }: SpaceSidebarNodeProps) => {
});
const isActive = false;
- const avatar = node.attrs.avatar;
- const name = node.attrs.name ?? 'Unnamed';
+
return (
<React.Fragment>
<div
@@ -49,12 +48,17 @@ export const SpaceSidebarNode = ({ node }: SpaceSidebarNodeProps) => {
isActive && 'bg-gray-100',
)}
>
- <Avatar id={node.id} avatar={avatar} name={name} size="small" />
+ <Avatar
+ id={node.id}
+ avatar={node.avatar}
+ name={node.name}
+ size="small"
+ />
<span
className="line-clamp-1 w-full flex-grow pl-2 text-left"
onClick={() => setIsOpen(!isOpen)}
>
- {name}
+ {node.name ?? 'Unnamed'}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -63,7 +67,7 @@ export const SpaceSidebarNode = ({ node }: SpaceSidebarNodeProps) => {
</span>
</DropdownMenuTrigger>
<DropdownMenuContent className="ml-1 w-72">
- <DropdownMenuLabel>{name}</DropdownMenuLabel>
+ <DropdownMenuLabel>{node.name ?? 'Unnamed'}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => setOpenCreatePage(true)}>
<div className="flex flex-row items-center gap-2">
@@ -114,7 +118,9 @@ export const SpaceSidebarNode = ({ node }: SpaceSidebarNodeProps) => {
</div>
{isOpen && (
<div className="pl-4">
- <SidebarNodeChildren node={node} />
+ {node.children.map((child) => (
+ <SidebarItem key={child.id} node={child} />
+ ))}
</div>
)}
{openCreateChannel && (
diff --git a/desktop/src/components/workspaces/sidebar-spaces.tsx b/desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx
similarity index 57%
rename from desktop/src/components/workspaces/sidebar-spaces.tsx
rename to desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx
index 0b878d9b..151cfa41 100644
--- a/desktop/src/components/workspaces/sidebar-spaces.tsx
+++ b/desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx
@@ -1,12 +1,13 @@
import React from 'react';
import { SpaceCreateButton } from '@/components/spaces/space-create-button';
-import { SidebarNode } from '@/components/workspaces/sidebar-node';
-import { useSidebar } from '@/contexts/sidebar';
+import { SidebarSpaceNode } from '@/types/workspaces';
+import { SidebarSpaceItem } from '@/components/workspaces/sidebars/sidebar-space-item';
-export const SidebarSpaces = () => {
- const sidebar = useSidebar();
- const spaces = sidebar.nodes.filter((node) => node.type === 'space');
+interface SidebarSpacesProps {
+ spaces: SidebarSpaceNode[];
+}
+export const SidebarSpaces = ({ spaces }: SidebarSpacesProps) => {
return (
<div className="pt-2 first:pt-0">
<div className="flex items-center justify-between p-1 pb-2 text-xs text-muted-foreground">
@@ -15,7 +16,7 @@ export const SidebarSpaces = () => {
</div>
<div className="flex flex-col gap-0.5">
{spaces.map((space) => (
- <SidebarNode node={space} key={space.id} />
+ <SidebarSpaceItem node={space} key={space.id} />
))}
</div>
</div>
diff --git a/desktop/src/components/workspaces/sidebars/sidebar.tsx b/desktop/src/components/workspaces/sidebars/sidebar.tsx
new file mode 100644
index 00000000..148694ad
--- /dev/null
+++ b/desktop/src/components/workspaces/sidebars/sidebar.tsx
@@ -0,0 +1,33 @@
+import React from 'react';
+import { SidebarHeader } from '@/components/workspaces/sidebars/sidebar-header';
+import { SidebarSpaces } from '@/components/workspaces/sidebars/sidebar-spaces';
+import { SidebarChats } from '@/components/workspaces/sidebars/sidebar-chats';
+import { Spinner } from '@/components/ui/spinner';
+import { Icon } from '@/components/ui/icon';
+import { useSidebarQuery } from '@/queries/use-sidebar-query';
+
+export const Sidebar = () => {
+ const { data, isPending } = useSidebarQuery();
+
+ if (isPending) {
+ return <Spinner />;
+ }
+
+ return (
+ <div className="h-full max-h-screen w-full border-r border-gray-200">
+ <SidebarHeader />
+ <div className="relative mt-2 max-h-full flex-grow overflow-hidden px-2">
+ <div className="flex cursor-pointer items-center rounded-md p-1 text-sm text-foreground/80 hover:bg-gray-100">
+ <Icon name="search-line" className="mr-2 h-4 w-4" />
+ <span>Search</span>
+ </div>
+ <div className="flex cursor-pointer items-center rounded-md p-1 text-sm text-foreground/80 hover:bg-gray-100">
+ <Icon name="inbox-line" className="mr-2 h-4 w-4" />
+ <span>Inbox</span>
+ </div>
+ <SidebarChats chats={data?.chats ?? []} />
+ <SidebarSpaces spaces={data?.spaces ?? []} />
+ </div>
+ </div>
+ );
+};
diff --git a/desktop/src/components/workspaces/workspace.tsx b/desktop/src/components/workspaces/workspace.tsx
index 62f0beef..80230382 100644
--- a/desktop/src/components/workspaces/workspace.tsx
+++ b/desktop/src/components/workspaces/workspace.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Sidebar } from '@/components/workspaces/sidebar';
+import { Sidebar } from '@/components/workspaces/sidebars/sidebar';
import { WorkspaceContext } from '@/contexts/workspace';
import { Outlet, useNavigate, useParams } from 'react-router-dom';
import {
@@ -153,7 +153,7 @@ export const Workspace = () => {
<div className="w-96">
<Sidebar />
</div>
- <main className="min-w-128 h-full w-full flex-grow overflow-hidden bg-white">
+ <main className="h-full w-full min-w-128 flex-grow overflow-hidden bg-white">
<Outlet />
</main>
</div>
diff --git a/desktop/src/contexts/database.ts b/desktop/src/contexts/database.ts
index 825ef5b7..a400c7eb 100644
--- a/desktop/src/contexts/database.ts
+++ b/desktop/src/contexts/database.ts
@@ -1,9 +1,10 @@
-import { Field } from '@/types/databases';
+import { FieldNode } from '@/types/databases';
import { createContext, useContext } from 'react';
interface DatabaseContext {
id: string;
- fields: Field[];
+ name: string;
+ fields: FieldNode[];
}
export const DatabaseContext = createContext<DatabaseContext>(
diff --git a/desktop/src/contexts/sidebar.ts b/desktop/src/contexts/sidebar.ts
deleted file mode 100644
index b9112ba4..00000000
--- a/desktop/src/contexts/sidebar.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { createContext, useContext } from 'react';
-import { LocalNode } from '@/types/nodes';
-
-interface SidebarContext {
- nodes: LocalNode[];
-}
-
-export const SidebarContext = createContext<SidebarContext>(
- {} as SidebarContext,
-);
-
-export const useSidebar = () => useContext(SidebarContext);
diff --git a/desktop/src/contexts/table-view.ts b/desktop/src/contexts/table-view.ts
index 53d35bbd..ffd0f7a8 100644
--- a/desktop/src/contexts/table-view.ts
+++ b/desktop/src/contexts/table-view.ts
@@ -1,14 +1,14 @@
-import { Field, FieldType } from '@/types/databases';
+import { FieldNode, FieldDataType } from '@/types/databases';
import { createContext, useContext } from 'react';
interface TableViewContext {
id: string;
- fields: Field[];
+ fields: FieldNode[];
hideField: (id: string) => void;
showField: (id: string) => void;
getNameWidth: () => number;
resizeName: (width: number) => void;
- getFieldWidth: (id: string, type: FieldType) => number;
+ getFieldWidth: (id: string, type: FieldDataType) => number;
resizeField: (id: string, width: number) => void;
moveField: (id: string, after: string) => void;
}
diff --git a/desktop/src/data/migrations/app.ts b/desktop/src/data/migrations/app.ts
index d4413f3f..50e20608 100644
--- a/desktop/src/data/migrations/app.ts
+++ b/desktop/src/data/migrations/app.ts
@@ -40,6 +40,6 @@ const createWorkspacesTable: Migration = {
};
export const appDatabaseMigrations: Record<string, Migration> = {
- '202408011709_create_accounts_table': createAccountsTable,
- '202408011712_create_workspaces_table': createWorkspacesTable,
+ '00001_create_accounts_table': createAccountsTable,
+ '00002_create_workspaces_table': createWorkspacesTable,
};
diff --git a/desktop/src/data/migrations/workspace.ts b/desktop/src/data/migrations/workspace.ts
index a9f58deb..f60a02ec 100644
--- a/desktop/src/data/migrations/workspace.ts
+++ b/desktop/src/data/migrations/workspace.ts
@@ -10,7 +10,6 @@ const createNodesTable: Migration = {
)
.addColumn('type', 'text', (col) => col.notNull())
.addColumn('index', 'text')
- .addColumn('attrs', 'text')
.addColumn('content', 'text')
.addColumn('created_at', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
@@ -27,6 +26,51 @@ const createNodesTable: Migration = {
},
};
+const createNodesParentIdAndTypeIndex: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE INDEX IF NOT EXISTS "nodes_parent_id_type_index" ON "nodes" ("parent_id", "type");
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`DROP INDEX IF EXISTS "nodes_parent_id_type_index"`.execute(db);
+ },
+};
+
+const createNodeAttributesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('node_attributes')
+ .addColumn('node_id', 'text', (col) =>
+ col.references('nodes.id').onDelete('cascade'),
+ )
+ .addColumn('type', 'text', (col) => col.notNull())
+ .addColumn('key', 'text', (col) => col.notNull())
+ .addColumn('text_value', 'text')
+ .addColumn('number_value', 'real')
+ .addColumn('foreign_node_id', 'text', (col) =>
+ col.references('nodes.id').onDelete('cascade'),
+ )
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('created_by', 'text', (col) => col.notNull())
+ .addColumn('updated_by', 'text')
+ .addColumn('version_id', 'text', (col) => col.notNull())
+ .addColumn('server_created_at', 'text')
+ .addColumn('server_updated_at', 'text')
+ .addColumn('server_version_id', 'text')
+ .addPrimaryKeyConstraint('node_attributes_pkey', [
+ 'node_id',
+ 'type',
+ 'key',
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('node_attributes').execute();
+ },
+};
+
const createMutationsTable: Migration = {
up: async (db) => {
await db.schema
@@ -61,7 +105,6 @@ const createNodesInsertTrigger: Migration = {
'parent_id', NEW.'parent_id',
'type', NEW.'type',
'index', NEW.'index',
- 'attrs', NEW.'attrs',
'content', NEW.'content',
'created_at', NEW.'created_at',
'updated_at', NEW.'updated_at',
@@ -99,7 +142,6 @@ const createNodesUpdateTrigger: Migration = {
'parent_id', OLD.'parent_id',
'type', OLD.'type',
'index', OLD.'index',
- 'attrs', OLD.'attrs',
'content', OLD.'content',
'created_at', OLD.'created_at',
'updated_at', OLD.'updated_at',
@@ -115,7 +157,6 @@ const createNodesUpdateTrigger: Migration = {
'parent_id', NEW.'parent_id',
'type', NEW.'type',
'index', NEW.'index',
- 'attrs', NEW.'attrs',
'content', NEW.'content',
'created_at', NEW.'created_at',
'updated_at', NEW.'updated_at',
@@ -152,7 +193,6 @@ const createDeleteNodesTrigger: Migration = {
'parent_id', OLD.'parent_id',
'type', OLD.'type',
'index', OLD.'index',
- 'attrs', OLD.'attrs',
'content', OLD.'content',
'created_at', OLD.'created_at',
'updated_at', OLD.'updated_at',
@@ -173,10 +213,146 @@ const createDeleteNodesTrigger: Migration = {
},
};
+const createNodeAttributesInsertTrigger: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE TRIGGER after_insert_node_attributes
+ AFTER INSERT ON node_attributes
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO mutations ('action', 'table', 'after', 'created_at')
+ VALUES (
+ 'insert',
+ 'node_attributes',
+ json_object(
+ 'node_id', NEW.'node_id',
+ 'type', NEW.'type',
+ 'key', NEW.'key',
+ 'text_value', NEW.'text_value',
+ 'number_value', NEW.'number_value',
+ 'foreign_node_id', NEW.'foreign_node_id',
+ 'created_at', NEW.'created_at',
+ 'updated_at', NEW.'updated_at',
+ 'created_by', NEW.'created_by',
+ 'updated_by', NEW.'updated_by',
+ 'version_id', NEW.'version_id',
+ 'server_created_at', NEW.'server_created_at',
+ 'server_updated_at', NEW.'server_updated_at',
+ 'server_version_id', NEW.'server_version_id'
+ ),
+ datetime('now')
+ );
+ END;
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`DROP TRIGGER after_insert_node_attributes`.execute(db);
+ },
+};
+
+const createNodeAttributesUpdateTrigger: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE TRIGGER after_update_node_attributes
+ AFTER UPDATE ON node_attributes
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO mutations ('action', 'table', 'before', 'after', 'created_at')
+ VALUES (
+ 'update',
+ 'node_attributes',
+ json_object(
+ 'node_id', OLD.'node_id',
+ 'type', OLD.'type',
+ 'key', OLD.'key',
+ 'text_value', OLD.'text_value',
+ 'number_value', OLD.'number_value',
+ 'foreign_node_id', OLD.'foreign_node_id',
+ 'created_at', OLD.'created_at',
+ 'updated_at', OLD.'updated_at',
+ 'created_by', OLD.'created_by',
+ 'updated_by', OLD.'updated_by',
+ 'version_id', OLD.'version_id',
+ 'server_created_at', OLD.'server_created_at',
+ 'server_updated_at', OLD.'server_updated_at',
+ 'server_version_id', OLD.'server_version_id'
+ ),
+ json_object(
+ 'node_id', NEW.'node_id',
+ 'type', NEW.'type',
+ 'key', NEW.'key',
+ 'text_value', NEW.'text_value',
+ 'number_value', NEW.'number_value',
+ 'foreign_node_id', NEW.'foreign_node_id',
+ 'created_at', NEW.'created_at',
+ 'updated_at', NEW.'updated_at',
+ 'created_by', NEW.'created_by',
+ 'updated_by', NEW.'updated_by',
+ 'version_id', NEW.'version_id',
+ 'server_created_at', NEW.'server_created_at',
+ 'server_updated_at', NEW.'server_updated_at',
+ 'server_version_id', NEW.'server_version_id'
+ ),
+ datetime('now')
+ );
+ END;
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`DROP TRIGGER after_update_node_attributes`.execute(db);
+ },
+};
+
+const createNodeAttributesDeleteTrigger: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE TRIGGER after_delete_node_attributes
+ AFTER DELETE ON node_attributes
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO mutations ('action', 'table', 'before', 'created_at')
+ VALUES (
+ 'delete',
+ 'node_attributes',
+ json_object(
+ 'node_id', OLD.'node_id',
+ 'type', OLD.'type',
+ 'key', OLD.'key',
+ 'text_value', OLD.'text_value',
+ 'number_value', OLD.'number_value',
+ 'foreign_node_id', OLD.'foreign_node_id',
+ 'created_at', OLD.'created_at',
+ 'updated_at', OLD.'updated_at',
+ 'created_by', OLD.'created_by',
+ 'updated_by', OLD.'updated_by',
+ 'version_id', OLD.'version_id',
+ 'server_created_at', OLD.'server_created_at',
+ 'server_updated_at', OLD.'server_updated_at',
+ 'server_version_id', OLD.'server_version_id'
+ ),
+ datetime('now')
+ );
+ END;
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`DROP TRIGGER after_delete_node_attributes`.execute(db);
+ },
+};
+
export const workspaceDatabaseMigrations: Record<string, Migration> = {
- '202408011756_create_nodes_table': createNodesTable,
- '202408011757_create_mutations_table': createMutationsTable,
- '202408011758_create_node_insert_trigger': createNodesInsertTrigger,
- '202408011759_create_node_update_trigger': createNodesUpdateTrigger,
- '202408011760_create_node_delete_trigger': createDeleteNodesTrigger,
+ '00001_create_nodes_table': createNodesTable,
+ '00002_create_nodes_parent_id_and_type_index':
+ createNodesParentIdAndTypeIndex,
+ '00003_create_node_attributes_table': createNodeAttributesTable,
+ '00004_create_mutations_table': createMutationsTable,
+ '00005_create_node_insert_trigger': createNodesInsertTrigger,
+ '00006_create_node_update_trigger': createNodesUpdateTrigger,
+ '00007_create_node_delete_trigger': createDeleteNodesTrigger,
+ '00008_create_node_attributes_insert_trigger':
+ createNodeAttributesInsertTrigger,
+ '00009_create_node_attributes_update_trigger':
+ createNodeAttributesUpdateTrigger,
+ '00010_create_node_attributes_delete_trigger':
+ createNodeAttributesDeleteTrigger,
};
diff --git a/desktop/src/data/schemas/workspace.ts b/desktop/src/data/schemas/workspace.ts
index a52140a9..c9f35959 100644
--- a/desktop/src/data/schemas/workspace.ts
+++ b/desktop/src/data/schemas/workspace.ts
@@ -2,24 +2,47 @@ import { ColumnType, Insertable, Selectable, Updateable } from 'kysely';
interface NodeTable {
id: ColumnType<string, string, never>;
- parent_id?: ColumnType<string | null, string | null, string | null>;
+ parent_id: ColumnType<string, string, string>;
type: ColumnType<string, string, string>;
index: ColumnType<string | null, string | null, string | null>;
- attrs: ColumnType<string | null, string | null, string | null>;
content: ColumnType<string | null, string | null, string | null>;
created_at: ColumnType<string, string, never>;
- updated_at?: ColumnType<string | null, string | null, string | null>;
+ updated_at: ColumnType<string | null, string | null, string | null>;
created_by: ColumnType<string, string, never>;
- updated_by?: ColumnType<string | null, string | null, string | null>;
+ updated_by: ColumnType<string | null, string | null, string | null>;
version_id: ColumnType<string, string, string>;
- server_created_at?: ColumnType<string | null, string | null, string | null>;
- server_updated_at?: ColumnType<string | null, string | null, string | null>;
- server_version_id?: ColumnType<string | null, string | null, string | null>;
+ server_created_at: ColumnType<string | null, string | null, string | null>;
+ server_updated_at: ColumnType<string | null, string | null, string | null>;
+ server_version_id: ColumnType<string | null, string | null, string | null>;
}
export type SelectNode = Selectable<NodeTable>;
export type CreateNode = Insertable<NodeTable>;
export type UpdateNode = Updateable<NodeTable>;
+export type SelectNodeWithAttributes = SelectNode & {
+ attributes: string;
+};
+
+interface NodeAttributeTable {
+ node_id: ColumnType<string, string, never>;
+ type: ColumnType<string, string, never>;
+ key: ColumnType<string, string, never>;
+ text_value: ColumnType<string | null, string | null, string | null>;
+ number_value: ColumnType<number | null, number | null, number | null>;
+ foreign_node_id: ColumnType<string | null, string | null, string | null>;
+ created_at: ColumnType<string, string, never>;
+ updated_at: ColumnType<string | null, string | null, string | null>;
+ created_by: ColumnType<string, string, never>;
+ updated_by: ColumnType<string | null, string | null, string | null>;
+ version_id: ColumnType<string, string, string>;
+ server_created_at: ColumnType<string | null, string | null, string | null>;
+ server_updated_at: ColumnType<string | null, string | null, string | null>;
+ server_version_id: ColumnType<string | null, string | null, string | null>;
+}
+
+export type SelectNodeAttribute = Selectable<NodeAttributeTable>;
+export type CreateNodeAttribute = Insertable<NodeAttributeTable>;
+export type UpdateNodeAttribute = Updateable<NodeAttributeTable>;
interface MutationTable {
id: ColumnType<number, never, never>;
@@ -36,5 +59,6 @@ export type UpdateMutation = Updateable<MutationTable>;
export interface WorkspaceDatabaseSchema {
nodes: NodeTable;
+ node_attributes: NodeAttributeTable;
mutations: MutationTable;
}
diff --git a/desktop/src/data/utils.ts b/desktop/src/data/utils.ts
index 2a7acf15..1cb96f4c 100644
--- a/desktop/src/data/utils.ts
+++ b/desktop/src/data/utils.ts
@@ -1,11 +1,7 @@
import SQLite from 'better-sqlite3';
-import { Parser, AST, Select } from 'node-sql-parser';
import { QueryResult } from 'kysely';
import { isEqual } from 'lodash';
-const parser = new Parser();
-const parseOptions = { database: 'Sqlite' };
-
export const buildSqlite = (filename: string): SQLite.Database => {
const database = new SQLite(filename);
database.pragma('journal_mode = WAL');
@@ -13,61 +9,10 @@ export const buildSqlite = (filename: string): SQLite.Database => {
};
export const extractTablesFromSql = (sql: string): string[] => {
- const tables: string[] = [];
- const ast = parser.astify(sql, parseOptions);
- if (Array.isArray(ast)) {
- ast.forEach((astItem) => {
- tables.push(...extractTablesFromAst(astItem));
- });
- } else {
- tables.push(...extractTablesFromAst(ast));
- }
-
- return tables;
-};
-
-const extractTablesFromAst = (ast: AST): string[] => {
- const tables: string[] = [];
- if (ast.type === 'select') {
- const selectAst = ast as Select;
- selectAst.from.forEach((from) => {
- const astFrom = from as any;
- if (astFrom.table) {
- tables.push(astFrom.table);
- }
- });
-
- if (selectAst.with && selectAst.with.length > 0) {
- selectAst.with.forEach((withItem) => {
- const fromArray = withItem?.stmt?.ast?.from;
- fromArray?.forEach((from) => {
- const astFrom = from as any;
- if (astFrom.table) {
- tables.push(astFrom.table);
- }
- });
- });
- }
- }
- if (ast.type === 'insert') {
- tables.push(ast.table[0].table);
- } else if (ast.type === 'update' && ast.table) {
- ast.table.forEach((from) => {
- const astFrom = from as any;
- if (astFrom.table) {
- tables.push(astFrom.table);
- }
- });
- } else if (ast.type === 'delete') {
- ast.from.forEach((from) => {
- const astFrom = from as any;
- if (astFrom.table) {
- tables.push(astFrom.table);
- }
- });
- }
-
- return tables;
+ // A regex to match table names from SELECT, JOIN, UPDATE, INSERT, DELETE
+ const regex = /\b(?:FROM|JOIN|INTO|UPDATE|TABLE)\s+["]?([a-zA-Z0-9_]+)["]?/gi;
+ const matches = [...sql.matchAll(regex)].map((match) => match[1]);
+ return matches;
};
export const resultHasChanged = <R>(
diff --git a/desktop/src/data/workspace-manager.ts b/desktop/src/data/workspace-manager.ts
index 6942651c..6e9ff03e 100644
--- a/desktop/src/data/workspace-manager.ts
+++ b/desktop/src/data/workspace-manager.ts
@@ -8,7 +8,10 @@ import {
SqliteDialect,
} from 'kysely';
import { Workspace, WorkspaceSyncData } from '@/types/workspaces';
-import { WorkspaceDatabaseSchema } from '@/data/schemas/workspace';
+import {
+ SelectNodeAttribute,
+ WorkspaceDatabaseSchema,
+} from '@/data/schemas/workspace';
import { workspaceDatabaseMigrations } from '@/data/migrations/workspace';
import {
buildSqlite,
@@ -20,7 +23,7 @@ import { ServerMutation } from '@/types/mutations';
import { eventBus } from '@/lib/event-bus';
import { AxiosInstance } from 'axios';
import { debounce, isEqual } from 'lodash';
-import { ServerNode } from '@/types/nodes';
+import { ServerNode, ServerNodeAttribute } from '@/types/nodes';
import { SelectNode } from '@/data/schemas/workspace';
export class WorkspaceManager {
@@ -210,23 +213,54 @@ export class WorkspaceManager {
public async executeServerMutation(mutation: ServerMutation): Promise<void> {
if (mutation.table === 'nodes') {
- if (mutation.action === 'insert' && mutation.after) {
- await this.syncNodeFromServer(mutation.after);
- } else if (mutation.action === 'update' && mutation.after) {
- await this.syncNodeFromServer(mutation.after);
- } else if (mutation.action === 'delete' && mutation.before) {
- await this.database
- .deleteFrom('nodes')
- .where('id', '=', mutation.before.id)
- .execute();
-
- this.debouncedNotifyQuerySubscribers(['nodes']);
- }
+ await this.executeNodeServerMutation(mutation);
+ } else if (mutation.table === 'node_attributes') {
+ await this.executeNodeAttributeServerMutation(mutation);
}
//other cases in the future
}
+ private async executeNodeServerMutation(
+ mutation: ServerMutation,
+ ): Promise<void> {
+ if (mutation.action === 'insert' && mutation.after) {
+ await this.syncNodeFromServer(mutation.after);
+ } else if (mutation.action === 'update' && mutation.after) {
+ await this.syncNodeFromServer(mutation.after);
+ } else if (mutation.action === 'delete' && mutation.before) {
+ await this.database
+ .deleteFrom('nodes')
+ .where('id', '=', mutation.before.id)
+ .execute();
+
+ this.debouncedNotifyQuerySubscribers(['nodes']);
+ }
+ }
+
+ private async executeNodeAttributeServerMutation(
+ mutation: ServerMutation,
+ ): Promise<void> {
+ if (mutation.action === 'insert' && mutation.after) {
+ await this.syncNodeAttributeFromServer(mutation.after);
+ } else if (mutation.action === 'update' && mutation.after) {
+ await this.syncNodeAttributeFromServer(mutation.after);
+ } else if (mutation.action === 'delete' && mutation.before) {
+ await this.database
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', mutation.before.nodeId),
+ eb('type', '=', mutation.before.type),
+ eb('key', '=', mutation.before.key),
+ ]),
+ )
+ .execute();
+
+ this.debouncedNotifyQuerySubscribers(['node_attributes']);
+ }
+ }
+
public isSynced(): boolean {
return this.workspace.synced;
}
@@ -248,6 +282,10 @@ export class WorkspaceManager {
await this.syncNodeFromServer(node);
}
+ for (const nodeAttribute of data.nodeAttributes) {
+ await this.syncNodeAttributeFromServer(nodeAttribute);
+ }
+
this.workspace.synced = true;
return true;
}
@@ -268,7 +306,6 @@ export class WorkspaceManager {
parent_id: node.parentId,
index: node.index,
content: node.content ? JSON.stringify(node.content) : null,
- attrs: node.attrs ? JSON.stringify(node.attrs) : null,
created_at: node.createdAt,
created_by: node.createdBy,
updated_by: node.updatedBy,
@@ -292,7 +329,6 @@ export class WorkspaceManager {
parent_id: node.parentId,
index: node.index,
content: node.content ? JSON.stringify(node.content) : null,
- attrs: node.attrs ? JSON.stringify(node.attrs) : null,
updated_at: node.updatedAt,
updated_by: node.updatedBy,
version_id: node.versionId,
@@ -307,6 +343,78 @@ export class WorkspaceManager {
}
}
+ private async syncNodeAttributeFromServer(
+ nodeAttribute: ServerNodeAttribute,
+ ): Promise<void> {
+ const existingNodeAttribute = await this.database
+ .selectFrom('node_attributes')
+ .selectAll()
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttribute.nodeId),
+ eb('type', '=', nodeAttribute.type),
+ eb('key', '=', nodeAttribute.key),
+ ]),
+ )
+ .executeTakeFirst();
+
+ if (!existingNodeAttribute) {
+ await this.database
+ .insertInto('node_attributes')
+ .values({
+ node_id: nodeAttribute.nodeId,
+ type: nodeAttribute.type,
+ key: nodeAttribute.key,
+ text_value: nodeAttribute.textValue,
+ number_value: nodeAttribute.numberValue,
+ foreign_node_id: nodeAttribute.foreignNodeId,
+ created_at: nodeAttribute.createdAt,
+ created_by: nodeAttribute.createdBy,
+ updated_by: nodeAttribute.updatedBy,
+ updated_at: nodeAttribute.updatedAt,
+ version_id: nodeAttribute.versionId,
+ server_created_at: nodeAttribute.serverCreatedAt,
+ server_updated_at: nodeAttribute.serverUpdatedAt,
+ server_version_id: nodeAttribute.versionId,
+ })
+ .execute();
+
+ this.debouncedNotifyQuerySubscribers(['node_attributes']);
+ return;
+ }
+
+ if (
+ this.shouldUpdateNodeAttributeFromServer(
+ existingNodeAttribute,
+ nodeAttribute,
+ )
+ ) {
+ await this.database
+ .updateTable('node_attributes')
+ .set({
+ text_value: nodeAttribute.textValue,
+ number_value: nodeAttribute.numberValue,
+ foreign_node_id: nodeAttribute.foreignNodeId,
+ updated_at: nodeAttribute.updatedAt,
+ updated_by: nodeAttribute.updatedBy,
+ version_id: nodeAttribute.versionId,
+ server_created_at: nodeAttribute.serverCreatedAt,
+ server_updated_at: nodeAttribute.serverUpdatedAt,
+ server_version_id: nodeAttribute.versionId,
+ })
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttribute.nodeId),
+ eb('type', '=', nodeAttribute.type),
+ eb('key', '=', nodeAttribute.key),
+ ]),
+ )
+ .execute();
+
+ this.debouncedNotifyQuerySubscribers(['node_attributes']);
+ }
+ }
+
public shouldUpdateNodeFromServer(
localNode: SelectNode,
serverNode: ServerNode,
@@ -331,6 +439,32 @@ export class WorkspaceManager {
return true;
}
+ private shouldUpdateNodeAttributeFromServer(
+ localNodeAttribute: SelectNodeAttribute,
+ serverNodeAttribute: ServerNodeAttribute,
+ ): boolean {
+ if (
+ localNodeAttribute.server_version_id === serverNodeAttribute.versionId
+ ) {
+ return false;
+ }
+
+ if (localNodeAttribute.updated_at) {
+ if (!serverNodeAttribute.updatedAt) {
+ return false;
+ }
+
+ const localUpdatedAt = new Date(localNodeAttribute.updated_at);
+ const serverUpdatedAt = new Date(serverNodeAttribute.updatedAt);
+
+ if (localUpdatedAt > serverUpdatedAt) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
private async migrate(): Promise<void> {
const migrator = new Migrator({
db: this.database,
diff --git a/desktop/src/editor/classes.tsx b/desktop/src/editor/classes.tsx
index 5fe754f6..57091457 100644
--- a/desktop/src/editor/classes.tsx
+++ b/desktop/src/editor/classes.tsx
@@ -1,9 +1,7 @@
export const defaultClasses = {
- heading: {
- 1: 'mb-1 mt-4 font-heading text-4xl font-bold',
- 2: 'mb-px mt-3 font-heading text-2xl font-semibold tracking-tight',
- 3: 'mb-px mt-2 font-heading text-xl font-semibold tracking-tight',
- },
+ heading1: 'mb-1 mt-4 font-heading text-4xl font-bold',
+ heading2: 'mb-px mt-3 font-heading text-2xl font-semibold tracking-tight',
+ heading3: 'mb-px mt-2 font-heading text-xl font-semibold tracking-tight',
paragraph: 'm-0 px-0 py-1',
bulletList: 'm-0 ps-6 list-disc [&_ul]:list-[circle] [&_ul_ul]:list-[square]',
orderedList: 'm-0 ps-6 list-decimal',
diff --git a/desktop/src/editor/commands/heading1.tsx b/desktop/src/editor/commands/heading1.tsx
index b7950537..c2057235 100644
--- a/desktop/src/editor/commands/heading1.tsx
+++ b/desktop/src/editor/commands/heading1.tsx
@@ -8,11 +8,6 @@ export const Heading1Command: EditorCommand = {
icon: 'h-1',
disabled: false,
handler: ({ editor, range }) => {
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .setNode('heading', { level: 1 })
- .run();
+ editor.chain().focus().deleteRange(range).setNode('heading1').run();
},
};
diff --git a/desktop/src/editor/commands/heading2.tsx b/desktop/src/editor/commands/heading2.tsx
index 3b09690c..b0e4e9ec 100644
--- a/desktop/src/editor/commands/heading2.tsx
+++ b/desktop/src/editor/commands/heading2.tsx
@@ -8,11 +8,6 @@ export const Heading2Command: EditorCommand = {
icon: 'h-2',
disabled: false,
handler: ({ editor, range }) => {
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .setNode('heading', { level: 2 })
- .run();
+ editor.chain().focus().deleteRange(range).setNode('heading2').run();
},
};
diff --git a/desktop/src/editor/commands/heading3.tsx b/desktop/src/editor/commands/heading3.tsx
index 875e0de7..566ef883 100644
--- a/desktop/src/editor/commands/heading3.tsx
+++ b/desktop/src/editor/commands/heading3.tsx
@@ -8,11 +8,6 @@ export const Heading3Command: EditorCommand = {
icon: 'h-3',
disabled: false,
handler: ({ editor, range }) => {
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .setNode('heading', { level: 3 })
- .run();
+ editor.chain().focus().deleteRange(range).setNode('heading3').run();
},
};
diff --git a/desktop/src/editor/extensions/heading.tsx b/desktop/src/editor/extensions/heading.tsx
deleted file mode 100644
index a0d92d18..00000000
--- a/desktop/src/editor/extensions/heading.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { mergeAttributes } from '@tiptap/core';
-import Heading from '@tiptap/extension-heading';
-
-import { defaultClasses } from '@/editor/classes';
-
-type Levels = 1 | 2 | 3;
-
-export const HeadingNode = Heading.configure({
- levels: [1, 2, 3],
-}).extend({
- renderHTML({ node, HTMLAttributes }) {
- const hasLevel = this.options.levels.includes(node.attrs.level);
- const level: Levels = hasLevel ? node.attrs.level : this.options.levels[0];
-
- return [
- `h${level}`,
- mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
- class: `${defaultClasses.heading[level]}`,
- }),
- 0,
- ];
- },
-});
diff --git a/desktop/src/editor/extensions/heading1.tsx b/desktop/src/editor/extensions/heading1.tsx
new file mode 100644
index 00000000..43d044c1
--- /dev/null
+++ b/desktop/src/editor/extensions/heading1.tsx
@@ -0,0 +1,84 @@
+import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core';
+import { defaultClasses } from '@/editor/classes';
+
+export interface Heading1Options {
+ HTMLAttributes: Record<string, any>;
+}
+
+declare module '@tiptap/core' {
+ interface Commands<ReturnType> {
+ heading1: {
+ /**
+ * Set a heading1 node
+ */
+ setHeading1: () => ReturnType;
+ /**
+ * Toggle a heading1 node
+ */
+ toggleHeading1: () => ReturnType;
+ };
+ }
+}
+
+/**
+ * This extension allows you to create h1 headings.
+ */
+export const Heading1Node = Node.create<Heading1Options>({
+ name: 'heading1',
+
+ addOptions() {
+ return {
+ HTMLAttributes: {},
+ };
+ },
+
+ content: 'inline*',
+
+ group: 'block',
+
+ defining: true,
+
+ parseHTML() {
+ return [{ tag: 'h1' }];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return [
+ 'h1',
+ mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
+ class: defaultClasses.heading1,
+ }),
+ 0,
+ ];
+ },
+
+ addCommands() {
+ return {
+ setHeading1:
+ () =>
+ ({ commands }) => {
+ return commands.setNode(this.name);
+ },
+ toggleHeading1:
+ () =>
+ ({ commands }) => {
+ return commands.toggleNode(this.name, 'paragraph');
+ },
+ };
+ },
+
+ addKeyboardShortcuts() {
+ return {
+ 'Mod-Alt-1': () => this.editor.commands.toggleHeading1(),
+ };
+ },
+
+ addInputRules() {
+ return [
+ textblockTypeInputRule({
+ find: /^#\s$/,
+ type: this.type,
+ }),
+ ];
+ },
+});
diff --git a/desktop/src/editor/extensions/heading2.tsx b/desktop/src/editor/extensions/heading2.tsx
new file mode 100644
index 00000000..9e4364cd
--- /dev/null
+++ b/desktop/src/editor/extensions/heading2.tsx
@@ -0,0 +1,84 @@
+import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core';
+import { defaultClasses } from '@/editor/classes';
+
+export interface Heading2Options {
+ HTMLAttributes: Record<string, any>;
+}
+
+declare module '@tiptap/core' {
+ interface Commands<ReturnType> {
+ heading2: {
+ /**
+ * Set a heading2 node
+ */
+ setHeading2: () => ReturnType;
+ /**
+ * Toggle a heading2 node
+ */
+ toggleHeading2: () => ReturnType;
+ };
+ }
+}
+
+/**
+ * This extension allows you to create h2 headings.
+ */
+export const Heading2Node = Node.create<Heading2Options>({
+ name: 'heading2',
+
+ addOptions() {
+ return {
+ HTMLAttributes: {},
+ };
+ },
+
+ content: 'inline*',
+
+ group: 'block',
+
+ defining: true,
+
+ parseHTML() {
+ return [{ tag: 'h2' }];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return [
+ 'h2',
+ mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
+ class: defaultClasses.heading2,
+ }),
+ 0,
+ ];
+ },
+
+ addCommands() {
+ return {
+ setHeading2:
+ () =>
+ ({ commands }) => {
+ return commands.setNode(this.name);
+ },
+ toggleHeading2:
+ () =>
+ ({ commands }) => {
+ return commands.toggleNode(this.name, 'paragraph');
+ },
+ };
+ },
+
+ addKeyboardShortcuts() {
+ return {
+ 'Mod-Alt-2': () => this.editor.commands.toggleHeading2(),
+ };
+ },
+
+ addInputRules() {
+ return [
+ textblockTypeInputRule({
+ find: /^##\s$/,
+ type: this.type,
+ }),
+ ];
+ },
+});
diff --git a/desktop/src/editor/extensions/heading3.tsx b/desktop/src/editor/extensions/heading3.tsx
new file mode 100644
index 00000000..81430ae6
--- /dev/null
+++ b/desktop/src/editor/extensions/heading3.tsx
@@ -0,0 +1,84 @@
+import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core';
+import { defaultClasses } from '@/editor/classes';
+
+export interface Heading3Options {
+ HTMLAttributes: Record<string, any>;
+}
+
+declare module '@tiptap/core' {
+ interface Commands<ReturnType> {
+ heading3: {
+ /**
+ * Set a heading3 node
+ */
+ setHeading3: () => ReturnType;
+ /**
+ * Toggle a heading3 node
+ */
+ toggleHeading3: () => ReturnType;
+ };
+ }
+}
+
+/**
+ * This extension allows you to create h3 headings.
+ */
+export const Heading3Node = Node.create<Heading3Options>({
+ name: 'heading3',
+
+ addOptions() {
+ return {
+ HTMLAttributes: {},
+ };
+ },
+
+ content: 'inline*',
+
+ group: 'block',
+
+ defining: true,
+
+ parseHTML() {
+ return [{ tag: 'h3' }];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return [
+ 'h3',
+ mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
+ class: defaultClasses.heading3,
+ }),
+ 0,
+ ];
+ },
+
+ addCommands() {
+ return {
+ setHeading3:
+ () =>
+ ({ commands }) => {
+ return commands.setNode(this.name);
+ },
+ toggleHeading3:
+ () =>
+ ({ commands }) => {
+ return commands.toggleNode(this.name, 'paragraph');
+ },
+ };
+ },
+
+ addKeyboardShortcuts() {
+ return {
+ 'Mod-Alt-3': () => this.editor.commands.toggleHeading3(),
+ };
+ },
+
+ addInputRules() {
+ return [
+ textblockTypeInputRule({
+ find: /^###\s$/,
+ type: this.type,
+ }),
+ ];
+ },
+});
diff --git a/desktop/src/editor/extensions/id.tsx b/desktop/src/editor/extensions/id.tsx
index 6785a41b..d5775785 100644
--- a/desktop/src/editor/extensions/id.tsx
+++ b/desktop/src/editor/extensions/id.tsx
@@ -5,7 +5,9 @@ import { NodeTypes } from '@/lib/constants';
const types = [
NodeTypes.Paragraph,
- NodeTypes.Heading,
+ NodeTypes.Heading1,
+ NodeTypes.Heading2,
+ NodeTypes.Heading3,
NodeTypes.Blockquote,
NodeTypes.BulletList,
NodeTypes.ListItem,
diff --git a/desktop/src/editor/extensions/index.tsx b/desktop/src/editor/extensions/index.tsx
index 23a5bdf1..234aed38 100644
--- a/desktop/src/editor/extensions/index.tsx
+++ b/desktop/src/editor/extensions/index.tsx
@@ -15,7 +15,9 @@ import { CommanderExtension } from '@/editor/extensions/commander';
import { DeleteControlExtension } from '@/editor/extensions/delete-control';
import { DividerNode } from '@/editor/extensions/divider';
import { DropcursorExtension } from '@/editor/extensions/dropcursor';
-import { HeadingNode } from '@/editor/extensions/heading';
+import { Heading1Node } from '@/editor/extensions/heading1';
+import { Heading2Node } from '@/editor/extensions/heading2';
+import { Heading3Node } from '@/editor/extensions/heading3';
import { HighlightMark } from '@/editor/extensions/highlight';
import { LinkMark } from '@/editor/extensions/link';
import { ListItemNode } from '@/editor/extensions/list-item';
@@ -43,7 +45,9 @@ export {
DeleteControlExtension,
DividerNode,
DocumentNode,
- HeadingNode,
+ Heading1Node,
+ Heading2Node,
+ Heading3Node,
HighlightMark,
ItalicMark,
LinkMark,
diff --git a/desktop/src/editor/mappers.ts b/desktop/src/editor/mappers.ts
new file mode 100644
index 00000000..f6304e12
--- /dev/null
+++ b/desktop/src/editor/mappers.ts
@@ -0,0 +1,677 @@
+import { AttributeTypes, EditorNodeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { EditorNode } from '@/types/editor';
+import { LocalNodeWithAttributes, NodeBlock } from '@/types/nodes';
+import { JSONContent } from '@tiptap/core';
+
+export const mapContentsToEditorNodes = (
+ contents: JSONContent[],
+ parentId: string,
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): EditorNode[] => {
+ const editorNodes: EditorNode[] = [];
+ mapAndPushContentsToNodes(contents, parentId, editorNodes, nodesMap);
+ validateNodesIndexes(editorNodes);
+ return editorNodes;
+};
+
+const mapAndPushContentsToNodes = (
+ contents: JSONContent[] | null | undefined,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ if (!contents) {
+ return;
+ }
+
+ contents.map((content) => {
+ mapAndPushContentToNode(content, parentId, editorNodes, nodesMap);
+ });
+};
+
+export const mapNodesToContents = (
+ parentId: string,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent[] => {
+ const contents: JSONContent[] = [];
+ const children = nodes
+ .filter((node) => node.parentId === parentId)
+ .sort((a, b) => compareString(a.index, b.index));
+
+ for (const child of children) {
+ contents.push(mapNodeToContent(child, nodes));
+ }
+ return contents;
+};
+
+const validateNodesIndexes = (editorNodes: EditorNode[]) => {
+ //group by parentId
+ const groupedNodes: { [key: string]: EditorNode[] } = {};
+ for (const node of editorNodes) {
+ if (!groupedNodes[node.parentId]) {
+ groupedNodes[node.parentId] = [];
+ }
+
+ groupedNodes[node.parentId].push(node);
+ }
+
+ for (const parentId in groupedNodes) {
+ const nodes = groupedNodes[parentId];
+
+ for (let i = 0; i < nodes.length; i++) {
+ const currentIndex = nodes[i].index;
+ const beforeIndex = i === 0 ? null : nodes[i - 1].index;
+
+ // find the lowest index after the current node
+ // we do this because sometimes nodes can be ordered in such a way that
+ // the current node's index is higher than one of its siblings
+ // after the next sibling
+ // for example: 1, {current}, 4, 3
+ let afterIndex = i === nodes.length - 1 ? null : nodes[i + 1].index;
+ for (let j = i + 1; j < nodes.length; j++) {
+ if (nodes[j].index < afterIndex) {
+ afterIndex = nodes[j].index;
+ break;
+ }
+ }
+
+ // extra check to make sure that the beforeIndex is less than the afterIndex
+ // because otherwise the fractional index library will throw an error
+ if (afterIndex < beforeIndex) {
+ afterIndex = generateNodeIndex(null, beforeIndex);
+ } else if (beforeIndex === afterIndex) {
+ afterIndex = generateNodeIndex(beforeIndex, null);
+ }
+
+ if (
+ !currentIndex ||
+ currentIndex <= beforeIndex ||
+ currentIndex > afterIndex
+ ) {
+ nodes[i].index = generateNodeIndex(beforeIndex, afterIndex);
+ }
+ }
+ }
+};
+
+const mapAndPushContentToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ switch (content.type) {
+ case EditorNodeTypes.Paragraph:
+ mapParagraphToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.Heading1:
+ mapHeading1ToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.Heading2:
+ mapHeading2ToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.Heading3:
+ mapHeading3ToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.BulletList:
+ mapBulletListToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.OrderedList:
+ mapOrderedListToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.ListItem:
+ mapListItemToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.Blockquote:
+ mapBlockquoteToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.CodeBlock:
+ mapCodeBlockToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.HorizontalRule:
+ mapHorizontalRuleToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.TaskList:
+ mapTaskListToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.TaskItem:
+ mapTaskItemToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ case EditorNodeTypes.Page:
+ mapPageToNode(content, parentId, editorNodes, nodesMap);
+ break;
+ }
+};
+
+const mapNodeToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ switch (node.type) {
+ case NodeTypes.Paragraph:
+ return mapParagraphToContent(node);
+ case NodeTypes.Heading1:
+ return mapHeading1ToContent(node);
+ case NodeTypes.Heading2:
+ return mapHeading2ToContent(node);
+ case NodeTypes.Heading3:
+ return mapHeading3ToContent(node);
+ case NodeTypes.BulletList:
+ return mapBulletListToContent(node, nodes);
+ case NodeTypes.OrderedList:
+ return mapOrderedListToContent(node, nodes);
+ case NodeTypes.ListItem:
+ return mapListItemToContent(node, nodes);
+ case NodeTypes.Blockquote:
+ return mapBlockquoteToContent(node, nodes);
+ case NodeTypes.CodeBlock:
+ return mapCodeBlockToContent(node);
+ case NodeTypes.HorizontalRule:
+ return mapHorizontalRuleToContent(node);
+ case NodeTypes.TaskList:
+ return mapTaskListToContent(node, nodes);
+ case NodeTypes.TaskItem:
+ return mapTaskItemToContent(node, nodes);
+ case NodeTypes.Page:
+ return mapPageToContent(node);
+ }
+};
+
+const mapParagraphToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.Paragraph,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: mapContentsToNodeBlocks(content.content),
+ });
+};
+
+const mapParagraphToContent = (node: LocalNodeWithAttributes): JSONContent => {
+ return {
+ type: EditorNodeTypes.Paragraph,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodeBlocksToContents(node.content),
+ };
+};
+
+const mapHeading1ToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.Heading1,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: mapContentsToNodeBlocks(content.content),
+ });
+};
+
+const mapHeading1ToContent = (node: LocalNodeWithAttributes): JSONContent => {
+ return {
+ type: EditorNodeTypes.Heading1,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodeBlocksToContents(node.content),
+ };
+};
+
+const mapHeading2ToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.Heading2,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: mapContentsToNodeBlocks(content.content),
+ });
+};
+
+const mapHeading2ToContent = (node: LocalNodeWithAttributes): JSONContent => {
+ return {
+ type: EditorNodeTypes.Heading2,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodeBlocksToContents(node.content),
+ };
+};
+
+const mapHeading3ToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.Heading3,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: mapContentsToNodeBlocks(content.content),
+ });
+};
+
+const mapHeading3ToContent = (node: LocalNodeWithAttributes): JSONContent => {
+ return {
+ type: EditorNodeTypes.Heading3,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodeBlocksToContents(node.content),
+ };
+};
+
+const mapBulletListToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.BulletList,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+
+ mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
+};
+
+const mapBulletListToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ return {
+ type: EditorNodeTypes.BulletList,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodesToContents(node.id, nodes),
+ };
+};
+
+const mapOrderedListToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.OrderedList,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+
+ mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
+};
+
+const mapOrderedListToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ return {
+ type: EditorNodeTypes.OrderedList,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodesToContents(node.id, nodes),
+ };
+};
+
+const mapListItemToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.ListItem,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+
+ mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
+};
+
+const mapListItemToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ return {
+ type: EditorNodeTypes.ListItem,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodesToContents(node.id, nodes),
+ };
+};
+
+const mapBlockquoteToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.Blockquote,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+
+ mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
+};
+
+const mapBlockquoteToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ return {
+ type: EditorNodeTypes.Blockquote,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodesToContents(node.id, nodes),
+ };
+};
+
+const mapCodeBlockToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+
+ const language = content.attrs?.language;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.CodeBlock,
+ parentId: parentId,
+ index: index,
+ attributes: [
+ {
+ nodeId: id,
+ type: AttributeTypes.Language,
+ key: AttributeTypes.Language,
+ numberValue: null,
+ textValue: language,
+ foreignNodeId: null,
+ },
+ ],
+ content: mapContentsToNodeBlocks(content.content),
+ });
+};
+
+const mapCodeBlockToContent = (node: LocalNodeWithAttributes): JSONContent => {
+ const language = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Language,
+ )?.textValue;
+
+ return {
+ type: EditorNodeTypes.CodeBlock,
+ attrs: {
+ id: node.id,
+ language: language,
+ },
+ content: mapNodeBlocksToContents(node.content),
+ };
+};
+
+const mapHorizontalRuleToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.HorizontalRule,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+};
+
+const mapHorizontalRuleToContent = (
+ node: LocalNodeWithAttributes,
+): JSONContent => {
+ return {
+ type: EditorNodeTypes.HorizontalRule,
+ attrs: {
+ id: node.id,
+ },
+ content: null,
+ };
+};
+
+const mapTaskListToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.TaskList,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+
+ mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
+};
+
+const mapTaskListToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ return {
+ type: EditorNodeTypes.TaskList,
+ attrs: {
+ id: node.id,
+ },
+ content: mapNodesToContents(node.id, nodes),
+ };
+};
+
+const mapTaskItemToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.TaskItem,
+ parentId: parentId,
+ index: index,
+ attributes: [
+ {
+ nodeId: id,
+ type: AttributeTypes.Checked,
+ key: '1',
+ numberValue: content.attrs?.checked ? 1 : 0,
+ textValue: null,
+ foreignNodeId: null,
+ },
+ ],
+ content: null,
+ });
+
+ mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
+};
+
+const mapTaskItemToContent = (
+ node: LocalNodeWithAttributes,
+ nodes: LocalNodeWithAttributes[],
+): JSONContent => {
+ const checkedAttribute = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Checked,
+ );
+
+ const checked = checkedAttribute?.numberValue === 1;
+ return {
+ type: EditorNodeTypes.TaskItem,
+ attrs: {
+ id: node.id,
+ checked: checked,
+ },
+ content: mapNodesToContents(node.id, nodes),
+ };
+};
+
+const mapPageToNode = (
+ content: JSONContent,
+ parentId: string,
+ editorNodes: EditorNode[],
+ nodesMap: Map<string, LocalNodeWithAttributes>,
+): void => {
+ const id = getIdFromContent(content);
+ const index = nodesMap.get(id)?.index;
+
+ editorNodes.push({
+ id: id,
+ type: NodeTypes.Page,
+ parentId: parentId,
+ index: index,
+ attributes: [],
+ content: null,
+ });
+};
+
+const mapPageToContent = (node: LocalNodeWithAttributes): JSONContent => {
+ const name = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ return {
+ type: EditorNodeTypes.Page,
+ attrs: {
+ id: node.id,
+ name: name,
+ avatar: avatar,
+ },
+ content: null,
+ };
+};
+
+const getIdFromContent = (content: JSONContent): string => {
+ return (
+ content.attrs?.id ??
+ NeuronId.generate(NeuronId.getIdTypeFromNode(content.type))
+ );
+};
+
+const mapContentsToNodeBlocks = (
+ contents?: JSONContent[],
+): NodeBlock[] | null => {
+ if (contents == null) {
+ return null;
+ }
+
+ const nodeBlocks: NodeBlock[] = [];
+ for (const content of contents) {
+ nodeBlocks.push({
+ type: content.type,
+ text: content.text,
+ marks:
+ content.marks?.map((mark) => {
+ return {
+ type: mark.type,
+ attrs: mark.attrs,
+ };
+ }) ?? null,
+ });
+ }
+
+ return nodeBlocks;
+};
+
+const mapNodeBlocksToContents = (
+ nodeBlocks: NodeBlock[] | null,
+): JSONContent[] | null => {
+ if (nodeBlocks == null) {
+ return null;
+ }
+
+ const contents: JSONContent[] = [];
+ for (const nodeBlock of nodeBlocks) {
+ contents.push({
+ type: nodeBlock.type,
+ text: nodeBlock.text,
+ marks:
+ nodeBlock.marks?.map((mark) => {
+ return {
+ type: mark.type,
+ attrs: mark.attrs,
+ };
+ }) ?? null,
+ });
+ }
+
+ return contents;
+};
diff --git a/desktop/src/editor/observer.ts b/desktop/src/editor/observer.ts
index 66b6723e..9737d381 100644
--- a/desktop/src/editor/observer.ts
+++ b/desktop/src/editor/observer.ts
@@ -1,19 +1,22 @@
import { WorkspaceDatabaseSchema } from '@/data/schemas/workspace';
-import { LeafNodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { LocalNode, NodeBlock } from '@/types/nodes';
+import {
+ LocalNode,
+ LocalNodeAttribute,
+ LocalNodeWithAttributes,
+} from '@/types/nodes';
import { Workspace } from '@/types/workspaces';
import { Editor, JSONContent } from '@tiptap/core';
import { CompiledQuery, Kysely } from 'kysely';
import { debounce, isEqual } from 'lodash';
+import { mapContentsToEditorNodes, mapNodesToContents } from '@/editor/mappers';
+import { EditorNode, EditorNodeAttribute } from '@/types/editor';
export class EditorObserver {
private readonly workspace: Workspace;
private readonly database: Kysely<WorkspaceDatabaseSchema>;
private readonly rootNode: LocalNode;
- private readonly nodesMap: Map<string, LocalNode>;
+ private readonly nodesMap: Map<string, LocalNodeWithAttributes>;
private editorContent: JSONContent;
private readonly onEditorUpdateDebounced: () => void;
@@ -26,7 +29,7 @@ export class EditorObserver {
workspace: Workspace,
database: Kysely<WorkspaceDatabaseSchema>,
rootNode: LocalNode,
- nodesMap: Map<string, LocalNode>,
+ nodesMap: Map<string, LocalNodeWithAttributes>,
) {
this.workspace = workspace;
this.database = database;
@@ -55,15 +58,7 @@ export class EditorObserver {
private buildEditorContent(): JSONContent {
const nodesArray = Array.from(this.nodesMap.values());
- const contents: JSONContent[] = [];
- const childrenNodes = nodesArray
- .filter((node) => node.parentId === this.rootNode.id)
- .sort((a, b) => compareString(a.index, b.index));
-
- for (const child of childrenNodes) {
- const content = this.buildEditorContentFromNode(child, nodesArray);
- contents.push(content);
- }
+ const contents = mapNodesToContents(this.rootNode.id, nodesArray);
if (!contents.length) {
contents.push({
@@ -77,115 +72,235 @@ export class EditorObserver {
};
}
- private buildEditorContentFromNode(
- node: LocalNode,
- nodesArray: LocalNode[],
- ): JSONContent {
- const editorContent: JSONContent = {
- type: node.type,
- attrs: {
- ...node.attrs,
- id: node.id,
- },
- };
-
- const childrenNodes = nodesArray
- .filter((n) => n.parentId === node.id)
- .sort((a, b) => compareString(a.index, b.index));
-
- if (childrenNodes.length > 0) {
- editorContent.content = editorContent.content || [];
- childrenNodes.forEach((child) => {
- editorContent.content.push(
- this.buildEditorContentFromNode(child, nodesArray),
- );
- });
- } else if (node.content && node.content.length > 0) {
- editorContent.content = editorContent.content || [];
- node.content.forEach((child) => {
- const childContent: JSONContent = {
- type: child.type,
- text: child.text,
- };
-
- if (child.marks && child.marks.length > 0) {
- childContent.marks = child.marks.map((mark) => {
- return {
- type: mark.type,
- attrs: mark.attrs,
- };
- });
- }
+ private async checkEditorContentChanges() {
+ const editorNodes = mapContentsToEditorNodes(
+ this.editorContent.content,
+ this.rootNode.id,
+ this.nodesMap,
+ );
- editorContent.content.push(childContent);
- });
+ const editorNodesMap = new Map<string, EditorNode>();
+ for (const node of editorNodes) {
+ editorNodesMap.set(node.id, node);
}
- return editorContent;
- }
-
- private async checkEditorContentChanges() {
- const newNodesMap = this.buildNodesMapFromEditorContent(this.editorContent);
const allNodeIds = new Set([
...this.nodesMap.keys(),
- ...newNodesMap.keys(),
+ ...editorNodesMap.keys(),
]);
const insertQueries: CompiledQuery[] = [];
const updateQueries: CompiledQuery[] = [];
const deleteQueries: CompiledQuery[] = [];
+
for (const nodeId of allNodeIds) {
- const oldNode = this.nodesMap.get(nodeId);
- const newNode = newNodesMap.get(nodeId);
+ const existingNode = this.nodesMap.get(nodeId);
+ const editorNode = editorNodesMap.get(nodeId);
+
+ if (!existingNode) {
+ const newNode: LocalNodeWithAttributes = {
+ id: editorNode.id,
+ type: editorNode.type,
+ parentId: editorNode.parentId,
+ index: editorNode.index,
+ content: editorNode.content,
+ createdAt: new Date().toISOString(),
+ createdBy: this.workspace.userId,
+ versionId: NeuronId.generate(NeuronId.Type.Version),
+ updatedAt: null,
+ updatedBy: null,
+ serverCreatedAt: null,
+ serverUpdatedAt: null,
+ serverVersionId: null,
+ attributes: [],
+ };
- if (!oldNode) {
- const query = this.database
+ const insertNodeQuery = this.database
.insertInto('nodes')
.values({
- id: newNode.id,
- type: newNode.type,
- parent_id: newNode.parentId,
- index: newNode.index,
- attrs: newNode.attrs ? JSON.stringify(newNode.attrs) : null,
- content: newNode.content ? JSON.stringify(newNode.content) : null,
- created_at: newNode.createdAt,
- created_by: newNode.createdBy,
- version_id: newNode.versionId,
+ id: editorNode.id,
+ type: editorNode.type,
+ parent_id: editorNode.parentId,
+ index: editorNode.index,
+ content: editorNode.content
+ ? JSON.stringify(editorNode.content)
+ : null,
+ created_at: new Date().toISOString(),
+ created_by: this.workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
})
.compile();
- insertQueries.push(query);
+ insertQueries.push(insertNodeQuery);
this.nodesMap.set(newNode.id, newNode);
- } else if (!newNode) {
+
+ if (editorNode.attributes && editorNode.attributes.length > 0) {
+ for (const attribute of editorNode.attributes) {
+ const nodeAttribute: LocalNodeAttribute = {
+ nodeId: newNode.id,
+ type: attribute.type,
+ key: attribute.key,
+ textValue: attribute.textValue,
+ numberValue: attribute.numberValue,
+ foreignNodeId: attribute.foreignNodeId,
+ createdAt: new Date().toISOString(),
+ createdBy: this.workspace.userId,
+ versionId: NeuronId.generate(NeuronId.Type.Version),
+ updatedAt: null,
+ updatedBy: null,
+ serverCreatedAt: null,
+ serverUpdatedAt: null,
+ serverVersionId: null,
+ };
+
+ newNode.attributes.push(nodeAttribute);
+
+ const insertNodeAttributeQuery = this.database
+ .insertInto('node_attributes')
+ .values({
+ node_id: newNode.id,
+ type: nodeAttribute.type,
+ key: nodeAttribute.key,
+ text_value: nodeAttribute.textValue,
+ number_value: nodeAttribute.numberValue,
+ foreign_node_id: nodeAttribute.foreignNodeId,
+ created_at: new Date().toISOString(),
+ created_by: this.workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ insertQueries.push(insertNodeAttributeQuery);
+ }
+ }
+ } else if (!editorNode) {
const query = this.database
.deleteFrom('nodes')
- .where('id', '=', oldNode.id)
+ .where('id', '=', existingNode.id)
.compile();
deleteQueries.push(query);
- this.nodesMap.delete(oldNode.id);
- } else if (!this.nodeEquals(oldNode, newNode)) {
- newNode.updatedAt = new Date().toISOString();
- newNode.updatedBy = this.workspace.userId;
- newNode.versionId = NeuronId.generate(NeuronId.Type.Version);
+ this.nodesMap.delete(existingNode.id);
+ } else {
+ if (!this.nodeContentEquals(existingNode, editorNode)) {
+ existingNode.type = editorNode.type;
+ existingNode.parentId = editorNode.parentId;
+ existingNode.index = editorNode.index;
+ existingNode.content = editorNode.content;
+ existingNode.updatedAt = new Date().toISOString();
+ existingNode.updatedBy = this.workspace.userId;
+ existingNode.versionId = NeuronId.generate(NeuronId.Type.Version);
+
+ const query = this.database
+ .updateTable('nodes')
+ .set({
+ type: existingNode.type,
+ parent_id: existingNode.parentId,
+ index: existingNode.index,
+ content: existingNode.content
+ ? JSON.stringify(existingNode.content)
+ : null,
+ updated_at: existingNode.updatedAt,
+ updated_by: existingNode.updatedBy,
+ version_id: existingNode.versionId,
+ })
+ .where('id', '=', existingNode.id)
+ .compile();
+
+ updateQueries.push(query);
+ }
- const query = this.database
- .updateTable('nodes')
- .set({
- type: newNode.type,
- parent_id: newNode.parentId,
- index: newNode.index,
- attrs: newNode.attrs ? JSON.stringify(newNode.attrs) : null,
- content: newNode.content ? JSON.stringify(newNode.content) : null,
- updated_at: newNode.updatedAt,
- updated_by: newNode.updatedBy,
- version_id: newNode.versionId,
- })
- .where('id', '=', newNode.id)
- .compile();
+ for (const attribute of editorNode.attributes) {
+ const existingAttribute = existingNode.attributes.find(
+ (attr) =>
+ attr.nodeId === existingNode.id &&
+ attr.type === attribute.type &&
+ attr.key === attribute.key,
+ );
+
+ if (!existingAttribute) {
+ const newAttribute: LocalNodeAttribute = {
+ nodeId: existingNode.id,
+ type: attribute.type,
+ key: attribute.key,
+ textValue: attribute.textValue,
+ numberValue: attribute.numberValue,
+ foreignNodeId: attribute.foreignNodeId,
+ createdAt: new Date().toISOString(),
+ createdBy: this.workspace.userId,
+ versionId: NeuronId.generate(NeuronId.Type.Version),
+ updatedAt: null,
+ updatedBy: null,
+ serverCreatedAt: null,
+ serverUpdatedAt: null,
+ serverVersionId: null,
+ };
- updateQueries.push(query);
- this.nodesMap.set(newNode.id, newNode);
+ existingNode.attributes.push(newAttribute);
+
+ const insertNodeAttributeQuery = this.database
+ .insertInto('node_attributes')
+ .values({
+ node_id: existingNode.id,
+ type: newAttribute.type,
+ key: newAttribute.key,
+ text_value: newAttribute.textValue,
+ number_value: newAttribute.numberValue,
+ foreign_node_id: newAttribute.foreignNodeId,
+ created_at: newAttribute.createdAt,
+ created_by: newAttribute.createdBy,
+ version_id: newAttribute.versionId,
+ })
+ .compile();
+
+ insertQueries.push(insertNodeAttributeQuery);
+ } else if (!this.nodeAttributesEqual(existingAttribute, attribute)) {
+ const updateNodeAttributeQuery = this.database
+ .updateTable('node_attributes')
+ .set({
+ text_value: attribute.textValue,
+ number_value: attribute.numberValue,
+ foreign_node_id: attribute.foreignNodeId,
+ updated_at: new Date().toISOString(),
+ updated_by: this.workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', existingAttribute.nodeId),
+ eb('type', '=', existingAttribute.type),
+ eb('key', '=', existingAttribute.key),
+ ]),
+ )
+ .compile();
+
+ updateQueries.push(updateNodeAttributeQuery);
+ }
+ }
+
+ for (const attribute of existingNode.attributes) {
+ const editorAttribute = editorNode.attributes.find(
+ (attr) =>
+ attr.nodeId === existingNode.id &&
+ attr.type === attribute.type &&
+ attr.key === attribute.key,
+ );
+
+ if (!editorAttribute) {
+ const deleteNodeAttributeQuery = this.database
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', existingNode.id),
+ eb('type', '=', attribute.type),
+ eb('key', '=', attribute.key),
+ ]),
+ )
+ .compile();
+
+ deleteQueries.push(deleteNodeAttributeQuery);
+ }
+ }
}
}
@@ -203,152 +318,8 @@ export class EditorObserver {
}
}
- private buildNodesMapFromEditorContent(
- editorContent: JSONContent,
- ): Map<string, LocalNode> {
- const newNodesMap = new Map<string, LocalNode>();
- if (editorContent.content && editorContent.content.length > 0) {
- for (const child of editorContent.content) {
- this.buildNodeFromEditorContent(this.rootNode.id, child, newNodesMap);
- }
- }
- this.validateNodesIndexes(newNodesMap);
- return newNodesMap;
- }
-
- private buildNodeFromEditorContent(
- parentId: string,
- content: JSONContent,
- newNodesMap: Map<string, LocalNode>,
- ) {
- let id = content.attrs?.id;
- if (!id) {
- id = NeuronId.generate(NeuronId.getIdTypeFromNode(content.type));
- }
-
- const existingNode = this.nodesMap.get(id);
- const newNode: LocalNode = existingNode
- ? { ...existingNode }
- : {
- id,
- type: content.type,
- parentId,
- index: null,
- attrs: null,
- content: null,
- createdAt: new Date().toISOString(),
- createdBy: this.workspace.userId,
- updatedAt: null,
- updatedBy: null,
- versionId: NeuronId.generate(NeuronId.Type.Version),
- serverCreatedAt: null,
- serverUpdatedAt: null,
- serverVersionId: null,
- };
-
- if (parentId !== newNode.parentId) {
- newNode.parentId = parentId;
- }
-
- if (content.attrs) {
- let attrs = { ...content.attrs };
- delete attrs.id;
-
- if (Object.keys(attrs).length > 0) {
- newNode.attrs = attrs;
- }
- }
-
- const contentChildren = content.content;
- const hasContentChildren = contentChildren && contentChildren.length > 0;
- const isLeafNode = LeafNodeTypes.includes(content.type);
-
- if (hasContentChildren && isLeafNode) {
- const nodeContent: NodeBlock[] = [];
-
- for (const child of content.content) {
- const nodeBlock: NodeBlock = {
- type: child.type,
- text: child.text,
- };
-
- if (child.marks && child.marks.length > 0) {
- nodeBlock.marks = child.marks.map((mark) => {
- return {
- type: mark.type,
- attrs: mark.attrs,
- };
- });
- }
-
- nodeContent.push(nodeBlock);
- }
-
- if (nodeContent.length > 0) {
- newNode.content = nodeContent;
- }
- }
-
- newNodesMap.set(newNode.id, newNode);
-
- if (hasContentChildren && !isLeafNode) {
- for (const child of content.content) {
- this.buildNodeFromEditorContent(newNode.id, child, newNodesMap);
- }
- }
- }
-
- private validateNodesIndexes(nodesMap: Map<string, LocalNode>) {
- //group by parentId
- const groupedNodes: { [key: string]: LocalNode[] } = {};
- for (const node of nodesMap.values()) {
- if (!groupedNodes[node.parentId]) {
- groupedNodes[node.parentId] = [];
- }
-
- groupedNodes[node.parentId].push(node);
- }
-
- for (const parentId in groupedNodes) {
- const nodes = groupedNodes[parentId];
- for (let i = 0; i < nodes.length; i++) {
- const currentIndex = nodes[i].index;
- const beforeIndex = i === 0 ? null : nodes[i - 1].index;
-
- // find the lowest index after the current node
- // we do this because sometimes nodes can be ordered in such a way that
- // the current node's index is higher than one of its siblings
- // after the next sibling
- // for example: 1, {current}, 4, 3
- let afterIndex = i === nodes.length - 1 ? null : nodes[i + 1].index;
- for (let j = i + 1; j < nodes.length; j++) {
- if (nodes[j].index < afterIndex) {
- afterIndex = nodes[j].index;
- break;
- }
- }
-
- // extra check to make sure that the beforeIndex is less than the afterIndex
- // because otherwise the fractional index library will throw an error
- if (afterIndex < beforeIndex) {
- afterIndex = generateNodeIndex(null, beforeIndex);
- } else if (beforeIndex === afterIndex) {
- afterIndex = generateNodeIndex(beforeIndex, null);
- }
-
- if (
- !currentIndex ||
- currentIndex <= beforeIndex ||
- currentIndex > afterIndex
- ) {
- nodes[i].index = generateNodeIndex(beforeIndex, afterIndex);
- }
- }
- }
- }
-
private checkNodesChanges(
- newNodesMap: Map<string, LocalNode>,
+ newNodesMap: Map<string, LocalNodeWithAttributes>,
editor: Editor,
) {
const allNodeIds = new Set([
@@ -368,7 +339,7 @@ export class EditorObserver {
this.nodesMap.delete(oldNode.id);
hasChanges = true;
} else if (
- !this.nodeEquals(oldNode, newNode) &&
+ !this.nodeContentEquals(oldNode, newNode) &&
oldNode.updatedAt !== null &&
newNode.updatedAt !== null
) {
@@ -396,24 +367,50 @@ export class EditorObserver {
}
}
- private nodeEquals(oldNode: LocalNode, newNode: LocalNode): boolean {
- if (oldNode.index !== newNode.index) {
+ private nodeContentEquals(
+ existingNode: EditorNode,
+ editorNode: EditorNode,
+ ): boolean {
+ if (existingNode.index !== editorNode.index) {
+ return false;
+ }
+
+ if (existingNode.parentId !== editorNode.parentId) {
+ return false;
+ }
+
+ if (existingNode.type !== editorNode.type) {
+ return false;
+ }
+
+ if (!isEqual(existingNode.content, editorNode.content)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private nodeAttributesEqual(
+ existingAttribute: EditorNodeAttribute,
+ editorAttribute: EditorNodeAttribute,
+ ): boolean {
+ if (existingAttribute.key !== editorAttribute.key) {
return false;
}
- if (oldNode.parentId !== newNode.parentId) {
+ if (existingAttribute.type !== editorAttribute.type) {
return false;
}
- if (oldNode.type !== newNode.type) {
+ if (existingAttribute.textValue !== editorAttribute.textValue) {
return false;
}
- if (!isEqual(oldNode.attrs, newNode.attrs)) {
+ if (existingAttribute.numberValue !== editorAttribute.numberValue) {
return false;
}
- if (!isEqual(oldNode.content, newNode.content)) {
+ if (existingAttribute.foreignNodeId !== editorAttribute.foreignNodeId) {
return false;
}
diff --git a/desktop/src/editor/renderers/blockquote.tsx b/desktop/src/editor/renderers/blockquote.tsx
index 55792e1c..409f532e 100644
--- a/desktop/src/editor/renderers/blockquote.tsx
+++ b/desktop/src/editor/renderers/blockquote.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface BlockquoteRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/bullet-list.tsx b/desktop/src/editor/renderers/bullet-list.tsx
index fdb9d9a6..32cc453a 100644
--- a/desktop/src/editor/renderers/bullet-list.tsx
+++ b/desktop/src/editor/renderers/bullet-list.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface BulletListRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/code-block.tsx b/desktop/src/editor/renderers/code-block.tsx
index 28765dc8..00e98214 100644
--- a/desktop/src/editor/renderers/code-block.tsx
+++ b/desktop/src/editor/renderers/code-block.tsx
@@ -2,19 +2,23 @@ import React from 'react';
import { Icon } from '@/components/ui/icon';
import { defaultClasses } from '@/editor/classes';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
import { highlightCode, languages } from '@/lib/lowlight';
+import { AttributeTypes } from '@/lib/constants';
interface CodeBlockRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
-export const CodeBLockRenderer = ({
+export const CodeBlockRenderer = ({
node,
keyPrefix,
}: CodeBlockRendererProps) => {
- const language = node.attrs?.language;
+ const language = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Language,
+ )?.textValue;
+
const [copied, setCopied] = React.useState(false);
const code = node.content?.[0].text ?? '';
diff --git a/desktop/src/editor/renderers/document.tsx b/desktop/src/editor/renderers/document.tsx
index fa90a32c..6b6e3185 100644
--- a/desktop/src/editor/renderers/document.tsx
+++ b/desktop/src/editor/renderers/document.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface DocumentRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/heading.tsx b/desktop/src/editor/renderers/heading.tsx
deleted file mode 100644
index 0c7e653d..00000000
--- a/desktop/src/editor/renderers/heading.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import React from 'react';
-import { defaultClasses } from '@/editor/classes';
-import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
-
-interface HeadingRendererProps {
- node: LocalNodeWithChildren;
- keyPrefix: string | null;
-}
-
-export const HeadingRenderer = ({ node, keyPrefix }: HeadingRendererProps) => {
- const level = node.attrs?.level;
-
- if (level === 1) {
- return (
- <h1 className={defaultClasses.heading[1]}>
- <NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
- </h1>
- );
- }
-
- if (level === 2) {
- return (
- <h2 className={defaultClasses.heading[2]}>
- <NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
- </h2>
- );
- }
-
- if (level === 3) {
- return (
- <h3 className={defaultClasses.heading[3]}>
- <NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
- </h3>
- );
- }
-
- return null;
-};
diff --git a/desktop/src/editor/renderers/heading1.tsx b/desktop/src/editor/renderers/heading1.tsx
new file mode 100644
index 00000000..f7be9259
--- /dev/null
+++ b/desktop/src/editor/renderers/heading1.tsx
@@ -0,0 +1,20 @@
+import React from 'react';
+import { defaultClasses } from '@/editor/classes';
+import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+
+interface Heading1RendererProps {
+ node: LocalNodeWithAttributesAndChildren;
+ keyPrefix: string | null;
+}
+
+export const Heading1Renderer = ({
+ node,
+ keyPrefix,
+}: Heading1RendererProps) => {
+ return (
+ <h1 className={defaultClasses.heading1}>
+ <NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
+ </h1>
+ );
+};
diff --git a/desktop/src/editor/renderers/heading2.tsx b/desktop/src/editor/renderers/heading2.tsx
new file mode 100644
index 00000000..5d466635
--- /dev/null
+++ b/desktop/src/editor/renderers/heading2.tsx
@@ -0,0 +1,20 @@
+import React from 'react';
+import { defaultClasses } from '@/editor/classes';
+import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+
+interface Heading2RendererProps {
+ node: LocalNodeWithAttributesAndChildren;
+ keyPrefix: string | null;
+}
+
+export const Heading2Renderer = ({
+ node,
+ keyPrefix,
+}: Heading2RendererProps) => {
+ return (
+ <h2 className={defaultClasses.heading2}>
+ <NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
+ </h2>
+ );
+};
diff --git a/desktop/src/editor/renderers/heading3.tsx b/desktop/src/editor/renderers/heading3.tsx
new file mode 100644
index 00000000..d67600d0
--- /dev/null
+++ b/desktop/src/editor/renderers/heading3.tsx
@@ -0,0 +1,20 @@
+import React from 'react';
+import { defaultClasses } from '@/editor/classes';
+import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+
+interface Heading3RendererProps {
+ node: LocalNodeWithAttributesAndChildren;
+ keyPrefix: string | null;
+}
+
+export const Heading3Renderer = ({
+ node,
+ keyPrefix,
+}: Heading3RendererProps) => {
+ return (
+ <h3 className={defaultClasses.heading3}>
+ <NodeChildrenRenderer node={node} keyPrefix={keyPrefix} />
+ </h3>
+ );
+};
diff --git a/desktop/src/editor/renderers/list-item.tsx b/desktop/src/editor/renderers/list-item.tsx
index 5389edc9..72f72a5d 100644
--- a/desktop/src/editor/renderers/list-item.tsx
+++ b/desktop/src/editor/renderers/list-item.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface ListItemRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/message.tsx b/desktop/src/editor/renderers/message.tsx
index 2bafae83..743e73fd 100644
--- a/desktop/src/editor/renderers/message.tsx
+++ b/desktop/src/editor/renderers/message.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface MessageRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/node-children.tsx b/desktop/src/editor/renderers/node-children.tsx
index b104cd94..c493708e 100644
--- a/desktop/src/editor/renderers/node-children.tsx
+++ b/desktop/src/editor/renderers/node-children.tsx
@@ -1,11 +1,11 @@
import React from 'react';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
import { NodeBlockRenderer } from '@/editor/renderers/node-block';
import { NodeRenderer } from '@/editor/renderers/node';
interface NodeChildrenRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/node.tsx b/desktop/src/editor/renderers/node.tsx
index 4c83ac97..72707b27 100644
--- a/desktop/src/editor/renderers/node.tsx
+++ b/desktop/src/editor/renderers/node.tsx
@@ -1,9 +1,11 @@
import React, { ReactElement } from 'react';
import { BlockquoteRenderer } from '@/editor/renderers/blockquote';
import { BulletListRenderer } from '@/editor/renderers/bullet-list';
-import { CodeBLockRenderer } from '@/editor/renderers/code-block';
+import { CodeBlockRenderer } from '@/editor/renderers/code-block';
import { DocumentRenderer } from '@/editor/renderers/document';
-import { HeadingRenderer } from '@/editor/renderers/heading';
+import { Heading1Renderer } from '@/editor/renderers/heading1';
+import { Heading2Renderer } from '@/editor/renderers/heading2';
+import { Heading3Renderer } from '@/editor/renderers/heading3';
import { ListItemRenderer } from '@/editor/renderers/list-item';
import { MessageRenderer } from '@/editor/renderers/message';
import { OrderedListRenderer } from '@/editor/renderers/ordered-list';
@@ -11,11 +13,11 @@ import { ParagraphRenderer } from '@/editor/renderers/paragraph';
import { TaskItemRenderer } from '@/editor/renderers/task-item';
import { TaskListRenderer } from '@/editor/renderers/task-list';
import { TextRenderer } from '@/editor/renderers/text';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
import { match } from 'ts-pattern';
interface NodeRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
@@ -32,8 +34,14 @@ export const NodeRenderer = ({
.with('paragraph', () => (
<ParagraphRenderer node={node} keyPrefix={keyPrefix} />
))
- .with('heading', () => (
- <HeadingRenderer node={node} keyPrefix={keyPrefix} />
+ .with('heading1', () => (
+ <Heading1Renderer node={node} keyPrefix={keyPrefix} />
+ ))
+ .with('heading2', () => (
+ <Heading2Renderer node={node} keyPrefix={keyPrefix} />
+ ))
+ .with('heading3', () => (
+ <Heading3Renderer node={node} keyPrefix={keyPrefix} />
))
.with('blockquote', () => (
<BlockquoteRenderer node={node} keyPrefix={keyPrefix} />
@@ -54,7 +62,7 @@ export const NodeRenderer = ({
<TaskItemRenderer node={node} keyPrefix={keyPrefix} />
))
.with('codeBlock', () => (
- <CodeBLockRenderer node={node} keyPrefix={keyPrefix} />
+ <CodeBlockRenderer node={node} keyPrefix={keyPrefix} />
))
.otherwise(null);
};
diff --git a/desktop/src/editor/renderers/ordered-list.tsx b/desktop/src/editor/renderers/ordered-list.tsx
index 6df470dd..7ebaf9dd 100644
--- a/desktop/src/editor/renderers/ordered-list.tsx
+++ b/desktop/src/editor/renderers/ordered-list.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface OrderedListRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/paragraph.tsx b/desktop/src/editor/renderers/paragraph.tsx
index 08a94a8c..31e139cf 100644
--- a/desktop/src/editor/renderers/paragraph.tsx
+++ b/desktop/src/editor/renderers/paragraph.tsx
@@ -1,11 +1,11 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
import { cn } from '@/lib/utils';
interface ParagraphRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/task-item.tsx b/desktop/src/editor/renderers/task-item.tsx
index 09f3b1c8..29e7de47 100644
--- a/desktop/src/editor/renderers/task-item.tsx
+++ b/desktop/src/editor/renderers/task-item.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface TaskItemRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/task-list.tsx b/desktop/src/editor/renderers/task-list.tsx
index 1e14023b..75591fb9 100644
--- a/desktop/src/editor/renderers/task-list.tsx
+++ b/desktop/src/editor/renderers/task-list.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
interface TaskListRendererProps {
- node: LocalNodeWithChildren;
+ node: LocalNodeWithAttributesAndChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/lib/constants.ts b/desktop/src/lib/constants.ts
index cfdbe45a..9bcd0469 100644
--- a/desktop/src/lib/constants.ts
+++ b/desktop/src/lib/constants.ts
@@ -3,17 +3,20 @@ export const NodeTypes = {
Space: 'space',
Page: 'page',
Channel: 'channel',
+ Chat: 'chat',
Message: 'message',
Paragraph: 'paragraph',
- Heading: 'heading',
+ Heading1: 'heading1',
+ Heading2: 'heading2',
+ Heading3: 'heading3',
Blockquote: 'blockquote',
- BulletList: 'bulletList',
- CodeBlock: 'codeBlock',
- ListItem: 'listItem',
- OrderedList: 'orderedList',
- TaskList: 'taskList',
- TaskItem: 'taskItem',
- HorizontalRule: 'horizontalRule',
+ BulletList: 'bullet_list',
+ CodeBlock: 'code_block',
+ ListItem: 'list_item',
+ OrderedList: 'ordered_list',
+ TaskList: 'task_list',
+ TaskItem: 'task_item',
+ HorizontalRule: 'horizontal_rule',
Database: 'database',
DatabaseReplica: 'database_replica',
Record: 'record',
@@ -25,9 +28,27 @@ export const NodeTypes = {
SelectOption: 'select_option',
};
+export const EditorNodeTypes = {
+ Paragraph: 'paragraph',
+ Heading1: 'heading1',
+ Heading2: 'heading2',
+ Heading3: 'heading3',
+ Blockquote: 'blockquote',
+ BulletList: 'bulletList',
+ CodeBlock: 'codeBlock',
+ ListItem: 'listItem',
+ OrderedList: 'orderedList',
+ TaskList: 'taskList',
+ TaskItem: 'taskItem',
+ HorizontalRule: 'horizontalRule',
+ Page: 'page',
+};
+
export const LeafNodeTypes: string[] = [
NodeTypes.Paragraph,
- NodeTypes.Heading,
+ NodeTypes.Heading1,
+ NodeTypes.Heading2,
+ NodeTypes.Heading3,
NodeTypes.HorizontalRule,
NodeTypes.CodeBlock,
];
@@ -44,3 +65,17 @@ export const ViewNodeTypes: string[] = [
NodeTypes.BoardView,
NodeTypes.CalendarView,
];
+
+export const AttributeTypes = {
+ Name: 'name',
+ Description: 'description',
+ Avatar: 'avatar',
+ Color: 'color',
+ DataType: 'data_type',
+ Language: 'language',
+ Checked: 'checked',
+ HiddenField: 'hidden_field',
+ FieldWidth: 'field_width',
+ FieldIndex: 'field_index',
+ NameWidth: 'name_width',
+};
diff --git a/desktop/src/lib/databases.ts b/desktop/src/lib/databases.ts
index 179d3397..d951b9f4 100644
--- a/desktop/src/lib/databases.ts
+++ b/desktop/src/lib/databases.ts
@@ -1,10 +1,6 @@
-import { SelectNode } from '@/data/schemas/workspace';
-import { Field, FieldType, RecordNode, SelectOption } from '@/types/databases';
-import { NodeTypes } from '@/lib/constants';
-import { LocalNode } from '@/types/nodes';
-import { compareString } from '@/lib/utils';
+import { FieldDataType } from '@/types/databases';
-export const getFieldIcon = (type?: FieldType): string => {
+export const getFieldIcon = (type?: FieldDataType): string => {
if (!type) return '';
switch (type) {
@@ -39,7 +35,7 @@ export const getFieldIcon = (type?: FieldType): string => {
}
};
-export const getDefaultFieldWidth = (type: FieldType): number => {
+export const getDefaultFieldWidth = (type: FieldDataType): number => {
if (!type) return 0;
switch (type.toLowerCase()) {
@@ -152,164 +148,3 @@ export const getRandomSelectOptionColor = (): string => {
Math.floor(Math.random() * selectOptionColors.length)
].value;
};
-
-export const mapField = (
- node: SelectNode,
- selectOptionNodes: SelectNode[],
-): Field => {
- const attrsJson = node.attrs;
- const attrs = attrsJson ? JSON.parse(attrsJson) : {};
- const type: FieldType = attrs.type ?? 'text';
-
- switch (type) {
- case 'boolean': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'boolean',
- index: node.index,
- };
- }
- case 'collaborator': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'collaborator',
- index: node.index,
- };
- }
- case 'created_at': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'created_at',
- index: node.index,
- };
- }
- case 'created_by': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'created_by',
- index: node.index,
- };
- }
- case 'date': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'date',
- index: node.index,
- };
- }
- case 'email': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'email',
- index: node.index,
- };
- }
- case 'file': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'file',
- index: node.index,
- };
- }
- case 'multi_select': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'multi_select',
- index: node.index,
- options: selectOptionNodes.map((option) => buildSelectOption(option)),
- };
- }
- case 'number': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'number',
- index: node.index,
- };
- }
- case 'phone': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'phone',
- index: node.index,
- };
- }
- case 'select': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'select',
- index: node.index,
- options: selectOptionNodes.map((option) => buildSelectOption(option)),
- };
- }
- case 'text': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'text',
- index: node.index,
- };
- }
- case 'url': {
- return {
- id: node.id,
- name: attrs.name,
- type: 'url',
- index: node.index,
- };
- }
- }
-};
-
-export const buildSelectOption = (node: SelectNode): SelectOption => {
- const attrsJson = node.attrs;
- const attrs = attrsJson ? JSON.parse(attrsJson) : {};
- return {
- id: node.id,
- name: attrs.name ?? 'Unnamed',
- color: attrs.color ?? 'gray',
- };
-};
-
-export const buildRecords = (allNodes: LocalNode[]): RecordNode[] => {
- const recordNodes = allNodes.filter((node) => node.type === NodeTypes.Record);
-
- const authorNodes = allNodes.filter((node) => node.type === NodeTypes.User);
- const records: RecordNode[] = [];
- const authorMap = new Map<string, LocalNode>();
-
- for (const author of authorNodes) {
- authorMap.set(author.id, author);
- }
-
- for (const node of recordNodes) {
- const author = authorMap.get(node.createdBy);
- const record: RecordNode = {
- id: node.id,
- parentId: node.parentId,
- index: node.index,
- attrs: node.attrs,
- createdAt: new Date(node.createdAt),
- createdBy: {
- id: author?.id ?? node.createdBy,
- name: author?.attrs?.name ?? 'Unknown',
- avatar: author?.attrs?.avatar ?? '',
- },
- versionId: node.versionId,
- };
-
- records.push(record);
- }
-
- return records.sort((a, b) => compareString(a.index, b.index));
-};
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index e22c6275..858ab5ac 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -16,7 +16,9 @@ enum IdType {
Message = 'ms',
Subscriber = 'sb',
Paragraph = 'pa',
- Heading = 'he',
+ Heading1 = 'h1',
+ Heading2 = 'h2',
+ Heading3 = 'h3',
Blockquote = 'bq',
CodeBlock = 'cb',
ListItem = 'li',
@@ -63,8 +65,12 @@ export class NeuronId {
return IdType.Message;
case NodeTypes.Paragraph:
return IdType.Paragraph;
- case NodeTypes.Heading:
- return IdType.Heading;
+ case NodeTypes.Heading1:
+ return IdType.Heading1;
+ case NodeTypes.Heading2:
+ return IdType.Heading2;
+ case NodeTypes.Heading3:
+ return IdType.Heading3;
case NodeTypes.Blockquote:
return IdType.Blockquote;
case NodeTypes.BulletList:
diff --git a/desktop/src/lib/messages.ts b/desktop/src/lib/messages.ts
deleted file mode 100644
index 36a40577..00000000
--- a/desktop/src/lib/messages.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { CreateNode } from '@/data/schemas/workspace';
-import { JSONContent } from '@tiptap/core';
-import { NeuronId } from '@/lib/id';
-import { LocalNode, NodeBlock } from '@/types/nodes';
-import { LeafNodeTypes, NodeTypes } from '@/lib/constants';
-import { buildNodeWithChildren, generateNodeIndex } from '@/lib/nodes';
-import { MessageNode } from '@/types/messages';
-import { compareString } from './utils';
-
-export const buildMessageCreateNodes = (
- nodes: CreateNode[],
- userId: string,
- workspaceId: string,
- parentId: string,
- content: JSONContent,
- index?: string | null,
-) => {
- const id =
- content.attrs?.id ??
- NeuronId.generate(NeuronId.getIdTypeFromNode(content.type));
-
- let attrs = content.attrs ? { ...content.attrs } : null;
- if (attrs) {
- delete attrs.id;
-
- if (Object.keys(attrs).length === 0) {
- attrs = null;
- }
- }
-
- let nodeContent: NodeBlock[] | null = null;
- if (LeafNodeTypes.includes(content.type)) {
- nodeContent = [];
- for (const child of content.content) {
- nodeContent.push({
- type: child.type,
- text: child.text,
- marks: child.marks?.map((mark) => {
- return {
- type: mark.type,
- attrs: mark.attrs,
- };
- }),
- });
- }
- }
-
- if (nodeContent && nodeContent.length === 0) {
- nodeContent = null;
- }
-
- nodes.push({
- id: id,
- parent_id: parentId,
- type: content.type,
- attrs: attrs ? JSON.stringify(attrs) : null,
- index: index,
- content: nodeContent ? JSON.stringify(nodeContent) : null,
- created_at: new Date().toISOString(),
- created_by: userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- });
-
- if (nodeContent == null && content.content && content.content.length > 0) {
- let lastIndex: string | null = null;
- for (const child of content.content) {
- lastIndex = generateNodeIndex(lastIndex, null);
- buildMessageCreateNodes(nodes, userId, workspaceId, id, child, lastIndex);
- }
- }
-};
-
-export const buildMessages = (allNodes: LocalNode[]): MessageNode[] => {
- const messageNodes = allNodes.filter(
- (node) => node.type === NodeTypes.Message,
- );
-
- const authorNodes = allNodes.filter((node) => node.type === NodeTypes.User);
- const messages: MessageNode[] = [];
- const authorMap = new Map<string, LocalNode>();
-
- for (const author of authorNodes) {
- authorMap.set(author.id, author);
- }
-
- for (const node of messageNodes) {
- const messageNode = buildNodeWithChildren(node, allNodes);
- const author = authorMap.get(node.createdBy);
- const message: MessageNode = {
- ...messageNode,
- author,
- };
-
- messages.push(message);
- }
-
- return messages.sort((a, b) => compareString(a.id, b.id));
-};
diff --git a/desktop/src/lib/nodes.ts b/desktop/src/lib/nodes.ts
index 57080a5e..8ea645db 100644
--- a/desktop/src/lib/nodes.ts
+++ b/desktop/src/lib/nodes.ts
@@ -1,5 +1,15 @@
-import { SelectNode } from '@/data/schemas/workspace';
-import { LocalNode, LocalNodeWithChildren } from '@/types/nodes';
+import {
+ SelectNode,
+ SelectNodeAttribute,
+ SelectNodeWithAttributes,
+} from '@/data/schemas/workspace';
+import {
+ LocalNode,
+ LocalNodeAttribute,
+ LocalNodeWithAttributes,
+ LocalNodeWithAttributesAndChildren,
+ LocalNodeWithChildren,
+} from '@/types/nodes';
import { generateKeyBetween } from 'fractional-indexing-jittered';
import { NodeTypes } from '@/lib/constants';
@@ -17,6 +27,20 @@ export const buildNodeWithChildren = (
};
};
+export const buildNodeWithAttributesAndChildren = (
+ node: LocalNodeWithAttributes,
+ allNodes: LocalNodeWithAttributes[],
+): LocalNodeWithAttributesAndChildren => {
+ const children: LocalNodeWithAttributesAndChildren[] = allNodes
+ .filter((n) => n.parentId === node.id)
+ .map((n) => buildNodeWithAttributesAndChildren(n, allNodes));
+
+ return {
+ ...node,
+ children: children,
+ };
+};
+
export const generateNodeIndex = (
previous?: string | null,
next?: string | null,
@@ -33,7 +57,6 @@ export const mapNode = (row: SelectNode): LocalNode => {
type: row.type,
index: row.index,
parentId: row.parent_id,
- attrs: row.attrs ? JSON.parse(row.attrs) : null,
content: row.content ? JSON.parse(row.content) : null,
createdAt: row.created_at,
createdBy: row.created_by,
@@ -46,6 +69,40 @@ export const mapNode = (row: SelectNode): LocalNode => {
};
};
+export const mapNodeAttribute = (
+ row: SelectNodeAttribute,
+): LocalNodeAttribute => {
+ return {
+ nodeId: row.node_id,
+ type: row.type,
+ key: row.key,
+ textValue: row.text_value,
+ numberValue: row.number_value,
+ foreignNodeId: row.foreign_node_id,
+ createdAt: row.created_at,
+ createdBy: row.created_by,
+ updatedAt: row.updated_at,
+ updatedBy: row.updated_by,
+ versionId: row.version_id,
+ serverCreatedAt: row.server_created_at,
+ serverUpdatedAt: row.server_updated_at,
+ serverVersionId: row.server_version_id,
+ };
+};
+
+export const mapNodeWithAttributes = (
+ row: SelectNodeWithAttributes,
+): LocalNodeWithAttributes => {
+ const attributes: SelectNodeAttribute[] = row.attributes
+ ? JSON.parse(row.attributes)
+ : [];
+
+ return {
+ ...mapNode(row),
+ attributes: attributes.map(mapNodeAttribute),
+ };
+};
+
export const getDefaultNodeIcon = (type: string) => {
switch (type) {
case NodeTypes.Channel:
diff --git a/desktop/src/mutations/use-channel-create-mutation.tsx b/desktop/src/mutations/use-channel-create-mutation.tsx
new file mode 100644
index 00000000..07d8837a
--- /dev/null
+++ b/desktop/src/mutations/use-channel-create-mutation.tsx
@@ -0,0 +1,64 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { useMutation } from '@tanstack/react-query';
+
+interface ChannelCreateMutationInput {
+ spaceId: string;
+ name: string;
+}
+
+export const useChannelCreateMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation({
+ mutationFn: async (input: ChannelCreateMutationInput) => {
+ const siblingsQuery = workspace.schema
+ .selectFrom('nodes')
+ .where('parent_id', '=', input.spaceId)
+ .selectAll()
+ .compile();
+
+ const result = await workspace.query(siblingsQuery);
+ const siblings = result.rows;
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const channelId = NeuronId.generate(NeuronId.Type.Channel);
+ const insertChannelQuery = workspace.schema
+ .insertInto('nodes')
+ .values({
+ id: channelId,
+ type: NodeTypes.Channel,
+ parent_id: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ const insertChannelNameQuery = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: channelId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: input.name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ await workspace.mutate([insertChannelQuery, insertChannelNameQuery]);
+ return channelId;
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-database-create-mutation.tsx b/desktop/src/mutations/use-database-create-mutation.tsx
new file mode 100644
index 00000000..c214b196
--- /dev/null
+++ b/desktop/src/mutations/use-database-create-mutation.tsx
@@ -0,0 +1,117 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { useMutation } from '@tanstack/react-query';
+
+interface DatabaseCreateMutationInput {
+ spaceId: string;
+ name: string;
+}
+
+export const useDatabaseCreateMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation({
+ mutationFn: async (input: DatabaseCreateMutationInput) => {
+ const siblingsQuery = workspace.schema
+ .selectFrom('nodes')
+ .where('parent_id', '=', input.spaceId)
+ .selectAll()
+ .compile();
+
+ const result = await workspace.query(siblingsQuery);
+ const siblings = result.rows;
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const databaseId = NeuronId.generate(NeuronId.Type.Database);
+ const tableViewId = NeuronId.generate(NeuronId.Type.TableView);
+ const fieldId = NeuronId.generate(NeuronId.Type.Field);
+ const insertNodesQuery = workspace.schema
+ .insertInto('nodes')
+ .values([
+ {
+ id: databaseId,
+ type: NodeTypes.Database,
+ parent_id: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ id: tableViewId,
+ type: NodeTypes.TableView,
+ parent_id: databaseId,
+ index: generateNodeIndex(null, null),
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ id: fieldId,
+ type: NodeTypes.Field,
+ parent_id: databaseId,
+ index: generateNodeIndex(null, null),
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ const insertAttributesQuery = workspace.schema
+ .insertInto('node_attributes')
+ .values([
+ {
+ node_id: databaseId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: input.name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: tableViewId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: 'Default',
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: fieldId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: 'Comment',
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: fieldId,
+ type: AttributeTypes.DataType,
+ key: '1',
+ text_value: 'text',
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ await workspace.mutate([insertNodesQuery, insertAttributesQuery]);
+ return databaseId;
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-field-create-mutation.tsx b/desktop/src/mutations/use-field-create-mutation.tsx
new file mode 100644
index 00000000..aee9d3a6
--- /dev/null
+++ b/desktop/src/mutations/use-field-create-mutation.tsx
@@ -0,0 +1,78 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { useMutation } from '@tanstack/react-query';
+
+interface FieldCreateMutationInput {
+ databaseId: string;
+ name: string;
+ dataType: string;
+}
+
+export const useFieldCreateMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (values: FieldCreateMutationInput) => {
+ const lastFieldQuery = workspace.schema
+ .selectFrom('nodes')
+ .where((eb) =>
+ eb.and({
+ parent_id: values.databaseId,
+ type: NodeTypes.Field,
+ }),
+ )
+ .selectAll()
+ .orderBy('index', 'desc')
+ .limit(1)
+ .compile();
+
+ const result = await workspace.query(lastFieldQuery);
+ const lastChild =
+ result.rows && result.rows.length > 0 ? result.rows[0] : null;
+ const maxIndex = lastChild?.index ? lastChild.index : null;
+
+ const fieldId = NeuronId.generate(NeuronId.Type.Field);
+ const insertFieldQuery = workspace.schema
+ .insertInto('nodes')
+ .values({
+ id: fieldId,
+ type: NodeTypes.Field,
+ parent_id: values.databaseId,
+ index: generateNodeIndex(maxIndex, null),
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ const insertFieldAttributesQuery = workspace.schema
+ .insertInto('node_attributes')
+ .values([
+ {
+ node_id: fieldId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: values.name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: fieldId,
+ type: AttributeTypes.DataType,
+ key: '1',
+ text_value: values.dataType,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ await workspace.mutate([insertFieldQuery, insertFieldAttributesQuery]);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-message-create-mutation.tsx b/desktop/src/mutations/use-message-create-mutation.tsx
new file mode 100644
index 00000000..9884de00
--- /dev/null
+++ b/desktop/src/mutations/use-message-create-mutation.tsx
@@ -0,0 +1,86 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { CreateNode, CreateNodeAttribute } from '@/data/schemas/workspace';
+import { mapContentsToEditorNodes } from '@/editor/mappers';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { LocalNodeWithAttributes } from '@/types/nodes';
+import { useMutation } from '@tanstack/react-query';
+import { JSONContent } from '@tiptap/core';
+import { CompiledQuery } from 'kysely';
+
+interface MessageCreateMutationInput {
+ conversationId: string;
+ content: JSONContent;
+}
+
+export const useMessageCreateMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation({
+ mutationFn: async (input: MessageCreateMutationInput) => {
+ const messageId = NeuronId.generate(NeuronId.Type.Message);
+ const editorNodes = mapContentsToEditorNodes(
+ input.content.content,
+ messageId,
+ new Map<string, LocalNodeWithAttributes>(),
+ );
+
+ if (editorNodes.length === 0) {
+ return;
+ }
+
+ const nodesToCreate: CreateNode[] = [
+ {
+ id: messageId,
+ type: NodeTypes.Message,
+ parent_id: input.conversationId,
+ index: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ];
+ const nodeAttributesToCreate: CreateNodeAttribute[] = [];
+
+ for (const node of editorNodes) {
+ nodesToCreate.push({
+ id: node.id,
+ type: node.type,
+ parent_id: node.parentId,
+ index: node.index,
+ content: node.content != null ? JSON.stringify(node.content) : null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ });
+
+ for (const attribute of node.attributes) {
+ nodeAttributesToCreate.push({
+ node_id: node.id,
+ type: attribute.type,
+ key: attribute.key,
+ text_value: attribute.textValue,
+ number_value: attribute.numberValue,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ });
+ }
+ }
+
+ const queries: CompiledQuery[] = [
+ workspace.schema.insertInto('nodes').values(nodesToCreate).compile(),
+ ];
+
+ if (nodeAttributesToCreate.length > 0) {
+ queries.push(
+ workspace.schema
+ .insertInto('node_attributes')
+ .values(nodeAttributesToCreate)
+ .compile(),
+ );
+ }
+
+ await workspace.mutate(queries);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-node-delete-mutation.tsx b/desktop/src/mutations/use-node-delete-mutation.tsx
new file mode 100644
index 00000000..cd856fe8
--- /dev/null
+++ b/desktop/src/mutations/use-node-delete-mutation.tsx
@@ -0,0 +1,17 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { useMutation } from '@tanstack/react-query';
+
+export const useNodeDeleteMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (nodeId: string) => {
+ const mutation = workspace.schema
+ .deleteFrom('nodes')
+ .where('id', '=', nodeId)
+ .compile();
+
+ await workspace.mutate(mutation);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-node-update-name-mutation.tsx b/desktop/src/mutations/use-node-update-name-mutation.tsx
new file mode 100644
index 00000000..e954381e
--- /dev/null
+++ b/desktop/src/mutations/use-node-update-name-mutation.tsx
@@ -0,0 +1,42 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface NodeUpdateNameInput {
+ id: string;
+ name: string;
+}
+
+export const useNodeUpdateNameMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: NodeUpdateNameInput) => {
+ const { id, name } = input;
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: id,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((b) =>
+ b.doUpdateSet({
+ text_value: name,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-page-create-mutation.tsx b/desktop/src/mutations/use-page-create-mutation.tsx
new file mode 100644
index 00000000..ced2f779
--- /dev/null
+++ b/desktop/src/mutations/use-page-create-mutation.tsx
@@ -0,0 +1,68 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { useMutation } from '@tanstack/react-query';
+
+interface PageCreateMutationInput {
+ spaceId: string;
+ name: string;
+}
+
+export const usePageCreateMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: PageCreateMutationInput) => {
+ const siblingsQuery = workspace.schema
+ .selectFrom('nodes')
+ .where('parent_id', '=', input.spaceId)
+ .selectAll()
+ .compile();
+
+ const result = await workspace.query(siblingsQuery);
+ const siblings = result.rows;
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.Page);
+ const index = generateNodeIndex(maxIndex, null);
+ const insertPageQuery = workspace.schema
+ .insertInto('nodes')
+ .values({
+ id,
+ type: NodeTypes.Page,
+ parent_id: input.spaceId,
+ index,
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ const insertPageAttributesQuery = workspace.schema
+ .insertInto('node_attributes')
+ .values([
+ {
+ node_id: id,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: input.name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ await workspace.mutate([insertPageQuery, insertPageAttributesQuery]);
+ return id;
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-record-create-mutation.tsx b/desktop/src/mutations/use-record-create-mutation.tsx
new file mode 100644
index 00000000..cf64d586
--- /dev/null
+++ b/desktop/src/mutations/use-record-create-mutation.tsx
@@ -0,0 +1,47 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { useMutation } from '@tanstack/react-query';
+
+interface RecordCreateInput {
+ databaseId: string;
+}
+
+export const useRecordCreateMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: RecordCreateInput) => {
+ const lastChildQuery = workspace.schema
+ .selectFrom('nodes')
+ .where('parent_id', '=', input.databaseId)
+ .selectAll()
+ .orderBy('index', 'desc')
+ .limit(1)
+ .compile();
+
+ const result = await workspace.query(lastChildQuery);
+ const lastChild =
+ result.rows && result.rows.length > 0 ? result.rows[0] : null;
+ const maxIndex = lastChild?.index ? lastChild.index : null;
+
+ const index = generateNodeIndex(maxIndex, null);
+ const query = workspace.schema
+ .insertInto('nodes')
+ .values({
+ id: NeuronId.generate(NeuronId.Type.Record),
+ type: NodeTypes.Record,
+ parent_id: input.databaseId,
+ index,
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-select-option-create-mutation.tsx b/desktop/src/mutations/use-select-option-create-mutation.tsx
new file mode 100644
index 00000000..70549e65
--- /dev/null
+++ b/desktop/src/mutations/use-select-option-create-mutation.tsx
@@ -0,0 +1,81 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { useMutation } from '@tanstack/react-query';
+
+interface CreateSelectOptionInput {
+ fieldId: string;
+ name: string;
+ color: string;
+}
+
+export const useSelectOptionCreateMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation({
+ mutationFn: async (input: CreateSelectOptionInput) => {
+ const lastChildQuery = workspace.schema
+ .selectFrom('nodes')
+ .where((eb) =>
+ eb.and({
+ parent_id: input.fieldId,
+ type: NodeTypes.SelectOption,
+ }),
+ )
+ .selectAll()
+ .orderBy('index', 'desc')
+ .limit(1)
+ .compile();
+
+ const result = await workspace.query(lastChildQuery);
+ const lastChild =
+ result.rows && result.rows.length > 0 ? result.rows[0] : null;
+ const maxIndex = lastChild?.index ? lastChild.index : null;
+
+ const selectOptionId = NeuronId.generate(NeuronId.Type.SelectOption);
+ const insertSelectOptionQuery = workspace.schema
+ .insertInto('nodes')
+ .values({
+ id: selectOptionId,
+ type: NodeTypes.SelectOption,
+ parent_id: input.fieldId,
+ index: generateNodeIndex(maxIndex, null),
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .compile();
+
+ const insertSelectOptionAttributesQuery = workspace.schema
+ .insertInto('node_attributes')
+ .values([
+ {
+ node_id: selectOptionId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: input.name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: selectOptionId,
+ type: AttributeTypes.Color,
+ key: '1',
+ text_value: input.color,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ await workspace.mutate([
+ insertSelectOptionQuery,
+ insertSelectOptionAttributesQuery,
+ ]);
+ return selectOptionId;
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-space-create-mutation.tsx b/desktop/src/mutations/use-space-create-mutation.tsx
new file mode 100644
index 00000000..5ed3b331
--- /dev/null
+++ b/desktop/src/mutations/use-space-create-mutation.tsx
@@ -0,0 +1,105 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { generateNodeIndex } from '@/lib/nodes';
+import { useMutation } from '@tanstack/react-query';
+
+interface SpaceCreateMutationInput {
+ name: string;
+ description: string;
+}
+
+export const useSpaceCreateMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation({
+ mutationFn: async (values: SpaceCreateMutationInput) => {
+ const spaceId = NeuronId.generate(NeuronId.Type.Space);
+ const pageId = NeuronId.generate(NeuronId.Type.Page);
+ const channelId = NeuronId.generate(NeuronId.Type.Channel);
+
+ const pageIndex = generateNodeIndex(null, null);
+ const channelIndex = generateNodeIndex(pageIndex, null);
+
+ const insertNodesQuery = workspace.schema
+ .insertInto('nodes')
+ .values([
+ {
+ id: spaceId,
+ type: NodeTypes.Space,
+ parent_id: null,
+ index: null,
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ id: pageId,
+ type: NodeTypes.Page,
+ parent_id: spaceId,
+ index: pageIndex,
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ id: channelId,
+ type: NodeTypes.Channel,
+ parent_id: spaceId,
+ index: channelIndex,
+ content: null,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ const insertNodeAttributesQuery = workspace.schema
+ .insertInto('node_attributes')
+ .values([
+ {
+ node_id: spaceId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: values.name,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: spaceId,
+ type: AttributeTypes.Description,
+ key: '1',
+ text_value: values.description,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: pageId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: 'Home',
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: channelId,
+ type: AttributeTypes.Name,
+ key: '1',
+ text_value: 'Discussions',
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+
+ await workspace.mutate([insertNodesQuery, insertNodeAttributesQuery]);
+ return spaceId;
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-boolean-field-value-mutation.tsx b/desktop/src/mutations/use-update-boolean-field-value-mutation.tsx
new file mode 100644
index 00000000..66143ba4
--- /dev/null
+++ b/desktop/src/mutations/use-update-boolean-field-value-mutation.tsx
@@ -0,0 +1,48 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateBooleanFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ value: boolean;
+}
+
+export const useUpdateBooleanFieldValueMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation<void, Error, UpdateBooleanFieldValueMutationProps>({
+ mutationFn: async ({ recordId, fieldId, value }) => {
+ if (!value) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: recordId,
+ type: fieldId,
+ key: fieldId,
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ number_value: 1,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) => ob.doNothing())
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-email-field-value-mutation.tsx b/desktop/src/mutations/use-update-email-field-value-mutation.tsx
new file mode 100644
index 00000000..66db5c48
--- /dev/null
+++ b/desktop/src/mutations/use-update-email-field-value-mutation.tsx
@@ -0,0 +1,55 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateEmailFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ value: string;
+}
+
+export const useUpdateEmailFieldValueMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation<void, Error, UpdateEmailFieldValueMutationProps>({
+ mutationFn: async ({ recordId, fieldId, value }) => {
+ if (value.length === 0) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ text_value: value,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ text_value: value,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-hidden-field-mutation.tsx b/desktop/src/mutations/use-update-hidden-field-mutation.tsx
new file mode 100644
index 00000000..60d34a28
--- /dev/null
+++ b/desktop/src/mutations/use-update-hidden-field-mutation.tsx
@@ -0,0 +1,53 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateHiddenFieldInput {
+ viewId: string;
+ fieldId: string;
+ hide: boolean;
+}
+
+export const useUpdateViewHiddenFieldMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: UpdateHiddenFieldInput) => {
+ const { viewId, fieldId, hide } = input;
+
+ if (hide) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: viewId,
+ type: AttributeTypes.HiddenField,
+ key: fieldId,
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: viewId,
+ type: AttributeTypes.HiddenField,
+ key: fieldId,
+ text_value: fieldId,
+ foreign_node_id: fieldId,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) => ob.doNothing())
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-multi-select-field-value-mutation.tsx b/desktop/src/mutations/use-update-multi-select-field-value-mutation.tsx
new file mode 100644
index 00000000..03b5c626
--- /dev/null
+++ b/desktop/src/mutations/use-update-multi-select-field-value-mutation.tsx
@@ -0,0 +1,54 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateMultiSelectFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ selectOptionId: string;
+ add: boolean;
+}
+
+export const useUpdateMultiSelectFieldValueMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async ({
+ recordId,
+ fieldId,
+ selectOptionId,
+ add,
+ }: UpdateMultiSelectFieldValueMutationProps) => {
+ if (add) {
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: selectOptionId,
+ foreign_node_id: selectOptionId,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) => ob.doNothing())
+ .compile();
+
+ await workspace.mutate(query);
+ } else {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', recordId),
+ eb('type', '=', fieldId),
+ eb('key', '=', selectOptionId),
+ ]),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ }
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-number-field-value-mutation.tsx b/desktop/src/mutations/use-update-number-field-value-mutation.tsx
new file mode 100644
index 00000000..a9f429e3
--- /dev/null
+++ b/desktop/src/mutations/use-update-number-field-value-mutation.tsx
@@ -0,0 +1,55 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateNumberFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ value: number | null;
+}
+
+export const useUpdateNumberFieldValueMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation<void, Error, UpdateNumberFieldValueMutationProps>({
+ mutationFn: async ({ recordId, fieldId, value }) => {
+ if (value === null) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ number_value: value,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ number_value: value,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-phone-field-value-mutation.tsx b/desktop/src/mutations/use-update-phone-field-value-mutation.tsx
new file mode 100644
index 00000000..adbfa3ae
--- /dev/null
+++ b/desktop/src/mutations/use-update-phone-field-value-mutation.tsx
@@ -0,0 +1,55 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdatePhoneFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ value: string;
+}
+
+export const useUpdatePhoneFieldValueMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation<void, Error, UpdatePhoneFieldValueMutationProps>({
+ mutationFn: async ({ recordId, fieldId, value }) => {
+ if (value.length === 0) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ text_value: value,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ text_value: value,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-select-field-value-mutation.tsx b/desktop/src/mutations/use-update-select-field-value-mutation.tsx
new file mode 100644
index 00000000..e5bb939a
--- /dev/null
+++ b/desktop/src/mutations/use-update-select-field-value-mutation.tsx
@@ -0,0 +1,61 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateSelectFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ selectOptionId: string;
+ add: boolean;
+}
+
+export const useUpdateSelectFieldValueMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async ({
+ recordId,
+ fieldId,
+ selectOptionId,
+ add,
+ }: UpdateSelectFieldValueMutationProps) => {
+ if (add) {
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ foreign_node_id: selectOptionId,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ foreign_node_id: selectOptionId,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ } else {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', recordId),
+ eb('type', '=', fieldId),
+ eb('key', '=', '1'),
+ ]),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ }
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-select-option-color-mutation.tsx b/desktop/src/mutations/use-update-select-option-color-mutation.tsx
new file mode 100644
index 00000000..9ee4c48d
--- /dev/null
+++ b/desktop/src/mutations/use-update-select-option-color-mutation.tsx
@@ -0,0 +1,42 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateSelectOptionColorInput {
+ id: string;
+ color: string;
+}
+
+export const useUpdateSelectOptionColorMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: UpdateSelectOptionColorInput) => {
+ const { id, color } = input;
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: id,
+ type: AttributeTypes.Color,
+ key: '1',
+ text_value: color,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((b) =>
+ b.doUpdateSet({
+ text_value: color,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-text-field-value-mutation.tsx b/desktop/src/mutations/use-update-text-field-value-mutation.tsx
new file mode 100644
index 00000000..773b28cf
--- /dev/null
+++ b/desktop/src/mutations/use-update-text-field-value-mutation.tsx
@@ -0,0 +1,55 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateTextFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ value: string;
+}
+
+export const useUpdateTextFieldValueMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation<void, Error, UpdateTextFieldValueMutationProps>({
+ mutationFn: async ({ recordId, fieldId, value }) => {
+ if (value.length === 0) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: recordId,
+ type: fieldId,
+ key: fieldId,
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ text_value: value,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ text_value: value,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-url-field-value-mutation.tsx b/desktop/src/mutations/use-update-url-field-value-mutation.tsx
new file mode 100644
index 00000000..dfd331ce
--- /dev/null
+++ b/desktop/src/mutations/use-update-url-field-value-mutation.tsx
@@ -0,0 +1,55 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateUrlFieldValueMutationProps {
+ recordId: string;
+ fieldId: string;
+ value: string;
+}
+
+export const useUpdateUrlFieldValueMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation<void, Error, UpdateUrlFieldValueMutationProps>({
+ mutationFn: async ({ recordId, fieldId, value }) => {
+ if (value.length === 0) {
+ const query = workspace.schema
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and({
+ node_id: recordId,
+ type: fieldId,
+ key: fieldId,
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ return;
+ }
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: recordId,
+ type: fieldId,
+ key: '1',
+ text_value: value,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ text_value: value,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-view-field-index-mutation.tsx b/desktop/src/mutations/use-update-view-field-index-mutation.tsx
new file mode 100644
index 00000000..782b6bc3
--- /dev/null
+++ b/desktop/src/mutations/use-update-view-field-index-mutation.tsx
@@ -0,0 +1,45 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateViewFieldIndexInput {
+ viewId: string;
+ fieldId: string;
+ index: string;
+}
+
+export const useUpdateViewFieldIndexMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: UpdateViewFieldIndexInput) => {
+ const { viewId, fieldId, index } = input;
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: viewId,
+ type: AttributeTypes.FieldIndex,
+ key: fieldId,
+ text_value: index,
+ foreign_node_id: fieldId,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ text_value: index,
+ foreign_node_id: fieldId,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-view-field-width-mutation.tsx b/desktop/src/mutations/use-update-view-field-width-mutation.tsx
new file mode 100644
index 00000000..a5e99cd7
--- /dev/null
+++ b/desktop/src/mutations/use-update-view-field-width-mutation.tsx
@@ -0,0 +1,41 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateViewFieldWidthInput {
+ viewId: string;
+ fieldId: string;
+ width: number;
+}
+
+export const useUpdateViewFieldWidthMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: UpdateViewFieldWidthInput) => {
+ const { viewId, fieldId, width } = input;
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: viewId,
+ type: AttributeTypes.FieldWidth,
+ key: '1',
+ number_value: width,
+ foreign_node_id: fieldId,
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ number_value: width,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-update-view-name-width-mutation.tsx b/desktop/src/mutations/use-update-view-name-width-mutation.tsx
new file mode 100644
index 00000000..ea3dfd65
--- /dev/null
+++ b/desktop/src/mutations/use-update-view-name-width-mutation.tsx
@@ -0,0 +1,41 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { useMutation } from '@tanstack/react-query';
+
+interface UpdateViewNameWidthInput {
+ viewId: string;
+ width: number;
+}
+
+export const useUpdateViewNameWidthMutation = () => {
+ const workspace = useWorkspace();
+ return useMutation({
+ mutationFn: async (input: UpdateViewNameWidthInput) => {
+ const { viewId, width } = input;
+
+ const query = workspace.schema
+ .insertInto('node_attributes')
+ .values({
+ node_id: viewId,
+ type: AttributeTypes.NameWidth,
+ key: '1',
+ number_value: width,
+ created_at: new Date().toISOString(),
+ created_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .onConflict((ob) =>
+ ob.doUpdateSet({
+ number_value: width,
+ updated_at: new Date().toISOString(),
+ updated_by: workspace.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ }),
+ )
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/queries/use-breadcrumb-query.tsx b/desktop/src/queries/use-breadcrumb-query.tsx
new file mode 100644
index 00000000..e2ba7ebd
--- /dev/null
+++ b/desktop/src/queries/use-breadcrumb-query.tsx
@@ -0,0 +1,105 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { AttributeTypes } from '@/lib/constants';
+import { mapNodeWithAttributes } from '@/lib/nodes';
+import { BreadcrumbNode } from '@/types/workspaces';
+import { useQuery } from '@tanstack/react-query';
+import { QueryResult, sql } from 'kysely';
+
+export const useBreadcrumbQuery = (nodeId: string) => {
+ const workspace = useWorkspace();
+ return useQuery<
+ QueryResult<SelectNodeWithAttributes>,
+ Error,
+ BreadcrumbNode[],
+ string[]
+ >({
+ queryKey: ['breadcrumb', nodeId],
+ queryFn: async ({ queryKey }) => {
+ const query = sql<SelectNodeWithAttributes>`
+ WITH RECURSIVE breadcrumb_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE id = ${nodeId}
+ UNION ALL
+ SELECT n.*
+ FROM nodes n
+ INNER JOIN breadcrumb_nodes b ON n.id = b.parent_id
+ )
+ SELECT
+ n.*,
+ CASE
+ WHEN COUNT(na.node_id) = 0 THEN json('[]')
+ ELSE json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.'updated_by',
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ )
+ END as attributes
+ FROM breadcrumb_nodes n
+ LEFT JOIN node_attributes na ON n.id = na.node_id
+ GROUP BY n.id;
+ `.compile(workspace.schema);
+
+ return await workspace.queryAndSubscribe({
+ key: queryKey,
+ query,
+ });
+ },
+ select: (data: QueryResult<SelectNodeWithAttributes>): BreadcrumbNode[] => {
+ const rows = data?.rows ?? [];
+ return buildBreadcrumbNodes(nodeId, rows);
+ },
+ });
+};
+
+const buildBreadcrumbNodes = (
+ nodeId: string,
+ rows: SelectNodeWithAttributes[],
+): BreadcrumbNode[] => {
+ const breadcrumbNodes: BreadcrumbNode[] = [];
+
+ let currentId = nodeId;
+ while (currentId !== null && currentId !== undefined) {
+ const row = rows.find((row) => row.id === currentId);
+ if (row) {
+ breadcrumbNodes.push(buildBreadcrumbNode(row));
+ currentId = row.parent_id;
+ } else {
+ currentId = null;
+ }
+ }
+ return breadcrumbNodes.reverse();
+};
+
+const buildBreadcrumbNode = (row: SelectNodeWithAttributes): BreadcrumbNode => {
+ const nodeWithAttributes = mapNodeWithAttributes(row);
+
+ const name = nodeWithAttributes.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = nodeWithAttributes.attributes.find(
+ (attr) => attr.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ return {
+ id: nodeWithAttributes.id,
+ type: nodeWithAttributes.type,
+ name,
+ avatar,
+ };
+};
diff --git a/desktop/src/queries/use-database-query.tsx b/desktop/src/queries/use-database-query.tsx
new file mode 100644
index 00000000..5686a3ee
--- /dev/null
+++ b/desktop/src/queries/use-database-query.tsx
@@ -0,0 +1,352 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { AttributeTypes, NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { mapNodeWithAttributes } from '@/lib/nodes';
+import {
+ DatabaseNode,
+ FieldDataType,
+ FieldNode,
+ SelectOptionNode,
+ TableViewNode,
+ ViewNode,
+} from '@/types/databases';
+import { LocalNodeWithAttributes } from '@/types/nodes';
+import { useQuery } from '@tanstack/react-query';
+import { QueryResult, sql } from 'kysely';
+
+export const useDatabaseQuery = (databaseId: string) => {
+ const workspace = useWorkspace();
+ return useQuery<
+ QueryResult<SelectNodeWithAttributes>,
+ Error,
+ DatabaseNode | null,
+ string[]
+ >({
+ queryKey: ['database', databaseId],
+ queryFn: async ({ queryKey }) => {
+ const query = sql<SelectNodeWithAttributes>`
+ WITH database_node AS (
+ SELECT *
+ FROM nodes
+ WHERE id = ${databaseId}
+ ),
+ field_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${databaseId} AND type = ${NodeTypes.Field}
+ ),
+ view_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${databaseId} AND type IN (${sql.join(ViewNodeTypes)})
+ ),
+ select_option_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IN
+ (
+ SELECT id
+ FROM field_nodes
+ )
+ AND type = ${NodeTypes.SelectOption}
+ ),
+ all_nodes AS (
+ SELECT * FROM database_node
+ UNION ALL
+ SELECT * FROM field_nodes
+ UNION ALL
+ SELECT * FROM view_nodes
+ UNION ALL
+ SELECT * FROM select_option_nodes
+ )
+ SELECT
+ n.*,
+ CASE
+ WHEN COUNT(na.node_id) = 0 THEN json('[]')
+ ELSE json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.'updated_by',
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ )
+ END as attributes
+ FROM all_nodes n
+ LEFT JOIN node_attributes na ON n.id = na.node_id
+ GROUP BY n.id;
+ `.compile(workspace.schema);
+
+ return await workspace.queryAndSubscribe({
+ key: queryKey,
+ query,
+ });
+ },
+ select: (
+ data: QueryResult<SelectNodeWithAttributes>,
+ ): DatabaseNode | null => {
+ const rows = data?.rows ?? [];
+ return buildDatabaseNode(rows);
+ },
+ });
+};
+
+const buildDatabaseNode = (
+ rows: SelectNodeWithAttributes[],
+): DatabaseNode | null => {
+ const nodes = rows.map((row) => mapNodeWithAttributes(row));
+
+ const databaseLocalNode = nodes.find(
+ (node) => node.type === NodeTypes.Database,
+ );
+ if (!databaseLocalNode) {
+ return null;
+ }
+
+ const name = databaseLocalNode.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Name,
+ )?.textValue;
+
+ 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, LocalNodeWithAttributes[]>,
+ );
+
+ const fields: FieldNode[] = [];
+ for (const fieldNode of fieldsNodes) {
+ const selectOptions = groupedSelectOptions[fieldNode.id] ?? [];
+ const field = buildFieldNode(fieldNode, selectOptions);
+ if (field) {
+ fields.push(field);
+ }
+ }
+
+ const viewNodes = nodes.filter((node) => ViewNodeTypes.includes(node.type));
+ const views: ViewNode[] = [];
+ for (const viewNode of viewNodes) {
+ const view = buildViewNode(viewNode);
+ if (view) {
+ views.push(view);
+ }
+ }
+
+ return {
+ id: databaseLocalNode.id,
+ name: name,
+ fields,
+ views,
+ };
+};
+
+export const buildFieldNode = (
+ node: LocalNodeWithAttributes,
+ selectOptions: LocalNodeWithAttributes[],
+): FieldNode | null => {
+ const name = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const dataType = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.DataType,
+ )?.textValue 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(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(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;
+ }
+};
+
+export const buildSelectOption = (
+ node: LocalNodeWithAttributes,
+): SelectOptionNode => {
+ const name = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const color = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Color,
+ )?.textValue;
+
+ return {
+ id: node.id,
+ name: name ?? 'Unnamed',
+ color: color ?? 'gray',
+ };
+};
+
+export const buildViewNode = (
+ node: LocalNodeWithAttributes,
+): ViewNode | null => {
+ if (node.type === NodeTypes.TableView) {
+ return buildTableViewNode(node);
+ }
+
+ return null;
+};
+
+export const buildTableViewNode = (
+ node: LocalNodeWithAttributes,
+): TableViewNode => {
+ const name = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const hiddenFields = node.attributes
+ .filter((attribute) => attribute.type === AttributeTypes.HiddenField)
+ .map((attribute) => attribute.foreignNodeId);
+
+ const fieldIndexes = node.attributes
+ .filter((attribute) => attribute.type === AttributeTypes.FieldIndex)
+ .reduce(
+ (acc, attribute) => {
+ if (attribute.foreignNodeId && attribute.textValue !== null) {
+ acc[attribute.foreignNodeId] = attribute.textValue;
+ }
+ return acc;
+ },
+ {} as Record<string, string>,
+ );
+
+ const fieldWidths = node.attributes
+ .filter((attribute) => attribute.type === AttributeTypes.FieldWidth)
+ .reduce(
+ (acc, attribute) => {
+ if (attribute.foreignNodeId && attribute.numberValue !== null) {
+ acc[attribute.foreignNodeId] = attribute.numberValue;
+ }
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+
+ const nameWidth = node.attributes.find(
+ (attribute) => attribute.type === AttributeTypes.NameWidth,
+ )?.numberValue;
+
+ return {
+ id: node.id,
+ name: name ?? 'Unnamed',
+ type: 'table_view',
+ hiddenFields,
+ fieldIndexes,
+ fieldWidths,
+ nameWidth: nameWidth,
+ versionId: node.versionId,
+ };
+};
diff --git a/desktop/src/queries/use-document-query.tsx b/desktop/src/queries/use-document-query.tsx
new file mode 100644
index 00000000..dc00a716
--- /dev/null
+++ b/desktop/src/queries/use-document-query.tsx
@@ -0,0 +1,75 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { useQuery } from '@tanstack/react-query';
+import { QueryResult, sql } from 'kysely';
+import { LocalNodeWithAttributes } from '@/types/nodes';
+import { mapNodeWithAttributes } from '@/lib/nodes';
+
+export const useDocumentQuery = (id: string) => {
+ const workspace = useWorkspace();
+
+ return useQuery<
+ QueryResult<SelectNodeWithAttributes>,
+ Error,
+ Map<string, LocalNodeWithAttributes>,
+ string[]
+ >({
+ queryKey: ['document', id],
+ queryFn: async ({ queryKey }) => {
+ const query = sql<SelectNodeWithAttributes>`
+ WITH RECURSIVE document_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${id}
+
+ UNION ALL
+
+ SELECT child.*
+ FROM nodes child
+ INNER JOIN document_nodes parent ON child.parent_id = parent.id
+ WHERE parent.type NOT IN (${NodeTypes.Page})
+ )
+ SELECT
+ n.*,
+ json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.updated_by,
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ ) as attributes
+ FROM document_nodes n
+ LEFT JOIN node_attributes na ON n.id = na.node_id
+ GROUP BY n.id;
+ `.compile(workspace.schema);
+
+ return await workspace.queryAndSubscribe({
+ query,
+ key: queryKey,
+ });
+ },
+ select: (data) => buildMap(data?.rows ?? []),
+ });
+};
+
+const buildMap = (
+ rows: SelectNodeWithAttributes[],
+): Map<string, LocalNodeWithAttributes> => {
+ const map = new Map<string, LocalNodeWithAttributes>();
+ rows.forEach((row) => {
+ map.set(row.id, mapNodeWithAttributes(row));
+ });
+ return map;
+};
diff --git a/desktop/src/queries/use-messages-query.tsx b/desktop/src/queries/use-messages-query.tsx
new file mode 100644
index 00000000..f267735e
--- /dev/null
+++ b/desktop/src/queries/use-messages-query.tsx
@@ -0,0 +1,164 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { SelectNode, SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import {
+ buildNodeWithAttributesAndChildren,
+ mapNodeWithAttributes,
+} from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MessageNode } from '@/types/messages';
+import { User } from '@/types/users';
+import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
+import { QueryResult, sql } from 'kysely';
+
+const MESSAGES_PER_PAGE = 50;
+
+export const useMessagesQuery = (conversationId: string) => {
+ const workspace = useWorkspace();
+
+ return useInfiniteQuery<
+ QueryResult<SelectNodeWithAttributes>,
+ Error,
+ MessageNode[],
+ string[],
+ number
+ >({
+ queryKey: ['conversation', conversationId],
+ initialPageParam: 0,
+ getNextPageParam: (
+ lastPage: QueryResult<SelectNode>,
+ pages,
+ ): number | undefined => {
+ if (lastPage && lastPage.rows) {
+ const messageCount = lastPage.rows.filter(
+ (row) => row.type === NodeTypes.Message,
+ ).length;
+
+ if (messageCount >= MESSAGES_PER_PAGE) {
+ return pages.length;
+ }
+ }
+ return undefined;
+ },
+ queryFn: async ({ queryKey, pageParam }) => {
+ const offset = pageParam * MESSAGES_PER_PAGE;
+ const query = sql<SelectNodeWithAttributes>`
+ WITH message_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${conversationId} AND type = ${NodeTypes.Message}
+ ORDER BY id DESC
+ LIMIT ${sql.lit(MESSAGES_PER_PAGE)}
+ OFFSET ${sql.lit(offset)}
+ ),
+ descendant_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IN (SELECT id FROM message_nodes)
+ UNION ALL
+ SELECT child.*
+ FROM nodes child
+ INNER JOIN descendant_nodes parent ON child.parent_id = parent.id
+ ),
+ author_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE id IN (SELECT DISTINCT created_by FROM message_nodes)
+ ),
+ all_nodes AS (
+ SELECT * FROM message_nodes
+ UNION ALL
+ SELECT * FROM descendant_nodes
+ UNION ALL
+ SELECT * FROM author_nodes
+ )
+ SELECT
+ n.*,
+ CASE
+ WHEN COUNT(na.node_id) = 0 THEN json('[]')
+ ELSE json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.'updated_by',
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ )
+ END as attributes
+ FROM all_nodes n
+ LEFT JOIN node_attributes na ON n.id = na.node_id
+ GROUP BY n.id;
+ `.compile(workspace.schema);
+
+ return await workspace.queryAndSubscribe({
+ key: queryKey,
+ page: pageParam,
+ query,
+ });
+ },
+ select: (
+ data: InfiniteData<QueryResult<SelectNodeWithAttributes>>,
+ ): MessageNode[] => {
+ const pages = data?.pages ?? [];
+ const rows = pages.map((page) => page.rows).flat();
+ return buildMessages(rows);
+ },
+ });
+};
+
+const buildMessages = (rows: SelectNodeWithAttributes[]): MessageNode[] => {
+ const nodes = rows.map(mapNodeWithAttributes);
+ const messageNodes = nodes.filter((node) => node.type === NodeTypes.Message);
+
+ const authorNodes = nodes.filter((node) => node.type === NodeTypes.User);
+ const messages: MessageNode[] = [];
+ const authorMap = new Map<string, User>();
+
+ for (const author of authorNodes) {
+ const name = author.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = author.attributes.find(
+ (attr) => attr.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ authorMap.set(author.id, {
+ id: author.id,
+ name: name ?? 'Unknown User',
+ avatar,
+ });
+ }
+
+ for (const node of messageNodes) {
+ const author = authorMap.get(node.createdBy);
+ const children = nodes
+ .filter((n) => n.parentId === node.id)
+ .map((n) => buildNodeWithAttributesAndChildren(n, nodes));
+
+ const message: MessageNode = {
+ id: node.id,
+ createdAt: node.createdAt,
+ author: author ?? {
+ id: node.createdBy,
+ name: 'Unknown User',
+ avatar: null,
+ },
+ content: children,
+ };
+
+ messages.push(message);
+ }
+
+ return messages.sort((a, b) => compareString(a.id, b.id));
+};
diff --git a/desktop/src/queries/use-records-query.tsx b/desktop/src/queries/use-records-query.tsx
new file mode 100644
index 00000000..388031cd
--- /dev/null
+++ b/desktop/src/queries/use-records-query.tsx
@@ -0,0 +1,160 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { SelectNode, SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { mapNodeWithAttributes } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { RecordNode } from '@/types/databases';
+import { User } from '@/types/users';
+import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
+import { QueryResult, sql } from 'kysely';
+
+const RECORDS_PER_PAGE = 50;
+
+export const useRecordsQuery = (databaseId: string) => {
+ const workspace = useWorkspace();
+
+ return useInfiniteQuery<
+ QueryResult<SelectNodeWithAttributes>,
+ Error,
+ RecordNode[],
+ string[],
+ number
+ >({
+ queryKey: ['records', databaseId],
+ initialPageParam: 0,
+ getNextPageParam: (lastPage: QueryResult<SelectNode>, pages) => {
+ if (lastPage && lastPage.rows) {
+ const recordsCount = lastPage.rows.filter(
+ (row) => row.type === NodeTypes.Record,
+ ).length;
+
+ if (recordsCount >= RECORDS_PER_PAGE) {
+ return pages.length;
+ }
+ }
+ return undefined;
+ },
+ queryFn: async ({ queryKey, pageParam }) => {
+ const offset = pageParam * RECORDS_PER_PAGE;
+ const query = sql<SelectNodeWithAttributes>`
+ WITH record_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${databaseId} AND type = ${NodeTypes.Record}
+ ORDER BY ${sql.ref('index')} ASC
+ LIMIT ${sql.lit(RECORDS_PER_PAGE)}
+ OFFSET ${sql.lit(offset)}
+ ),
+ author_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE id IN (SELECT DISTINCT created_by FROM record_nodes)
+ ),
+ referenced_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE id IN
+ (
+ SELECT DISTINCT foreign_node_id
+ FROM node_attributes
+ WHERE node_id IN (SELECT id FROM record_nodes)
+ )
+ ),
+ all_nodes as (
+ SELECT * FROM record_nodes
+ UNION ALL
+ SELECT * FROM author_nodes
+ UNION ALL
+ SELECT * FROM referenced_nodes
+ )
+ SELECT
+ n.*,
+ json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.updated_by,
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ ) as attributes
+ FROM all_nodes n
+ LEFT JOIN node_attributes na ON n.id = na.node_id
+ GROUP BY n.id;
+ `.compile(workspace.schema);
+
+ return await workspace.queryAndSubscribe({
+ key: queryKey,
+ page: pageParam,
+ query,
+ });
+ },
+ select: (
+ data: InfiniteData<QueryResult<SelectNodeWithAttributes>>,
+ ): RecordNode[] => {
+ const pages = data?.pages ?? [];
+ const rows = pages.map((page) => page.rows).flat();
+ return buildRecords(rows);
+ },
+ });
+};
+
+const buildRecords = (rows: SelectNodeWithAttributes[]): RecordNode[] => {
+ const nodes = rows.map(mapNodeWithAttributes);
+ 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, User>();
+
+ for (const author of authorNodes) {
+ const name = author.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = author.attributes.find(
+ (attr) => attr.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ authorMap.set(author.id, {
+ id: author.id,
+ name: name ?? 'Unknown User',
+ avatar,
+ });
+ }
+
+ for (const node of recordNodes) {
+ const name = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ 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',
+ avatar: null,
+ },
+ versionId: node.versionId,
+ };
+
+ records.push(record);
+ }
+
+ return records.sort((a, b) => compareString(a.index, b.index));
+};
diff --git a/desktop/src/queries/use-sidebar-query.tsx b/desktop/src/queries/use-sidebar-query.tsx
new file mode 100644
index 00000000..dde4b87d
--- /dev/null
+++ b/desktop/src/queries/use-sidebar-query.tsx
@@ -0,0 +1,171 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { mapNodeWithAttributes } from '@/lib/nodes';
+import { LocalNodeWithAttributes } from '@/types/nodes';
+import {
+ SidebarChatNode,
+ SidebarNode,
+ SidebarSpaceNode,
+} from '@/types/workspaces';
+import { useQuery } from '@tanstack/react-query';
+import { QueryResult, sql } from 'kysely';
+
+export type SidebarQueryResult = {
+ spaces: SidebarSpaceNode[];
+ chats: SidebarChatNode[];
+};
+
+export const useSidebarQuery = () => {
+ const workspace = useWorkspace();
+
+ return useQuery<
+ QueryResult<SelectNodeWithAttributes>,
+ Error,
+ SidebarQueryResult,
+ string[]
+ >({
+ queryKey: ['sidebar', workspace.id],
+ queryFn: async ({ queryKey }) => {
+ const query = sql<SelectNodeWithAttributes>`
+ WITH space_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IS NULL AND type = ${NodeTypes.Space}
+ ),
+ space_children_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IN (SELECT id FROM space_nodes)
+ ),
+ chat_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IS NULL AND type = ${NodeTypes.Chat}
+ ),
+ all_nodes AS (
+ SELECT * FROM space_nodes
+ UNION ALL
+ SELECT * FROM space_children_nodes
+ UNION ALL
+ SELECT * FROM chat_nodes
+ )
+ SELECT
+ n.*,
+ CASE
+ WHEN COUNT(na.node_id) = 0 THEN json('[]')
+ ELSE json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.'updated_by',
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ )
+ END as attributes
+ FROM all_nodes n
+ LEFT JOIN node_attributes na ON n.id = na.node_id
+ GROUP BY n.id;
+ `.compile(workspace.schema);
+
+ return await workspace.queryAndSubscribe({
+ key: queryKey,
+ query,
+ });
+ },
+ select: (
+ data: QueryResult<SelectNodeWithAttributes>,
+ ): SidebarQueryResult => {
+ const rows = data?.rows ?? [];
+ return buildSidebarNodes(rows);
+ },
+ });
+};
+
+const buildSidebarNodes = (
+ rows: SelectNodeWithAttributes[],
+): SidebarQueryResult => {
+ const nodes: LocalNodeWithAttributes[] = rows.map(mapNodeWithAttributes);
+
+ const spaces: SidebarSpaceNode[] = [];
+ const chats: SidebarChatNode[] = [];
+
+ for (const node of nodes) {
+ if (node.type === NodeTypes.Space) {
+ const children = nodes.filter((n) => n.parentId === node.id);
+ spaces.push(buildSpaceNode(node, children));
+ } else if (node.type === NodeTypes.Chat) {
+ chats.push(buildChatNode(node));
+ }
+ }
+
+ return {
+ spaces,
+ chats,
+ };
+};
+
+const buildSpaceNode = (
+ node: LocalNodeWithAttributes,
+ children: LocalNodeWithAttributes[],
+): SidebarSpaceNode => {
+ const name = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ return {
+ id: node.id,
+ type: node.type,
+ name: name ?? null,
+ avatar: avatar ?? null,
+ children: children.map(buildSidearNode),
+ };
+};
+
+const buildSidearNode = (node: LocalNodeWithAttributes): SidebarNode => {
+ const name = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ return {
+ id: node.id,
+ type: node.type,
+ name: name ?? null,
+ avatar: avatar ?? null,
+ };
+};
+
+const buildChatNode = (node: LocalNodeWithAttributes): SidebarChatNode => {
+ const name = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Name,
+ )?.textValue;
+
+ const avatar = node.attributes.find(
+ (attr) => attr.type === AttributeTypes.Avatar,
+ )?.textValue;
+
+ return {
+ id: node.id,
+ type: node.type,
+ name: name ?? null,
+ avatar: avatar ?? null,
+ };
+};
diff --git a/desktop/src/types/databases.ts b/desktop/src/types/databases.ts
index e9478f93..626f8de5 100644
--- a/desktop/src/types/databases.ts
+++ b/desktop/src/types/databases.ts
@@ -1,6 +1,39 @@
import { User } from '@/types/users';
+import { LocalNodeAttribute } from './nodes';
-export type FieldType =
+export type DatabaseNode = {
+ id: string;
+ name: string;
+ fields: FieldNode[];
+ views: ViewNode[];
+};
+
+export type ViewNode = TableViewNode | BoardViewNode | CalendarViewNode;
+
+export type TableViewNode = {
+ id: string;
+ name: string;
+ type: 'table_view';
+ hiddenFields: string[];
+ fieldIndexes: Record<string, string>;
+ fieldWidths: Record<string, number>;
+ nameWidth: number;
+ versionId: string;
+};
+
+export type BoardViewNode = {
+ id: string;
+ name: string;
+ type: 'board_view';
+};
+
+export type CalendarViewNode = {
+ id: string;
+ name: string;
+ type: 'calendar_view';
+};
+
+export type FieldDataType =
| 'boolean'
| 'collaborator'
| 'created_at'
@@ -15,114 +48,114 @@ export type FieldType =
| 'text'
| 'url';
-export type Field =
- | BooleanField
- | CollaboratorField
- | CreatedAtField
- | CreatedByField
- | DateField
- | EmailField
- | FileField
- | MultiSelectField
- | NumberField
- | PhoneField
- | SelectField
- | TextField
- | UrlField;
-
-export type BooleanField = {
- id: string;
- type: 'boolean';
+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 CollaboratorField = {
+export type CollaboratorFieldNode = {
id: string;
- type: 'collaborator';
+ dataType: 'collaborator';
name: string;
index: string;
};
-export type CreatedAtField = {
+export type CreatedAtFieldNode = {
id: string;
- type: 'created_at';
+ dataType: 'created_at';
name: string;
index: string;
};
-export type CreatedByField = {
+export type CreatedByFieldNode = {
id: string;
- type: 'created_by';
+ dataType: 'created_by';
name: string;
index: string;
};
-export type DateField = {
+export type DateFieldNode = {
id: string;
- type: 'date';
+ dataType: 'date';
name: string;
index: string;
};
-export type EmailField = {
+export type EmailFieldNode = {
id: string;
- type: 'email';
+ dataType: 'email';
name: string;
index: string;
};
-export type FileField = {
+export type FileFieldNode = {
id: string;
- type: 'file';
+ dataType: 'file';
name: string;
index: string;
};
-export type MultiSelectField = {
+export type MultiSelectFieldNode = {
id: string;
- type: 'multi_select';
+ dataType: 'multi_select';
name: string;
index: string;
- options: SelectOption[];
+ options: SelectOptionNode[];
};
-export type NumberField = {
+export type NumberFieldNode = {
id: string;
- type: 'number';
+ dataType: 'number';
name: string;
index: string;
};
-export type PhoneField = {
+export type PhoneFieldNode = {
id: string;
- type: 'phone';
+ dataType: 'phone';
name: string;
index: string;
};
-export type SelectField = {
+export type SelectFieldNode = {
id: string;
- type: 'select';
+ dataType: 'select';
name: string;
index: string;
- options: SelectOption[];
+ options: SelectOptionNode[];
};
-export type TextField = {
+export type TextFieldNode = {
id: string;
- type: 'text';
+ dataType: 'text';
name: string;
index: string;
};
-export type UrlField = {
+export type UrlFieldNode = {
id: string;
- type: 'url';
+ dataType: 'url';
name: string;
index: string;
};
-export type SelectOption = {
+export type SelectOptionNode = {
id: string;
name: string;
color: string;
@@ -130,10 +163,12 @@ export type SelectOption = {
export type RecordNode = {
id: string;
+ name: string | null;
parentId: string;
index: string;
- attrs: Record<string, any>;
createdAt: Date;
createdBy: User;
versionId: string;
+
+ attributes: LocalNodeAttribute[];
};
diff --git a/desktop/src/types/editor.ts b/desktop/src/types/editor.ts
index 36e0e8ee..f40dd04e 100644
--- a/desktop/src/types/editor.ts
+++ b/desktop/src/types/editor.ts
@@ -18,3 +18,21 @@ export type EditorCommand = {
handler: (props: EditorCommandProps) => void;
disabled?: boolean;
};
+
+export type EditorNode = {
+ id: string;
+ type: string;
+ parentId: string;
+ index: string;
+ attributes: EditorNodeAttribute[];
+ content: NodeBlock[] | null;
+};
+
+export type EditorNodeAttribute = {
+ nodeId: string;
+ type: string;
+ key: string;
+ textValue: string | null;
+ numberValue: number | null;
+ foreignNodeId: string | null;
+};
diff --git a/desktop/src/types/messages.ts b/desktop/src/types/messages.ts
index 56e05711..007a3ed4 100644
--- a/desktop/src/types/messages.ts
+++ b/desktop/src/types/messages.ts
@@ -1,5 +1,9 @@
-import { LocalNode, LocalNodeWithChildren } from '@/types/nodes';
+import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { User } from '@/types/users';
-export type MessageNode = LocalNodeWithChildren & {
- author?: LocalNode | null;
+export type MessageNode = {
+ id: string;
+ content: LocalNodeWithAttributesAndChildren[];
+ createdAt: string;
+ author: User;
};
diff --git a/desktop/src/types/nodes.ts b/desktop/src/types/nodes.ts
index 5266676e..71b75dc8 100644
--- a/desktop/src/types/nodes.ts
+++ b/desktop/src/types/nodes.ts
@@ -3,7 +3,6 @@ export type LocalNode = {
parentId: string | null;
type: string;
index: string | null;
- attrs: Record<string, any> | null;
content: NodeBlock[] | null;
createdAt: string;
createdBy: string;
@@ -15,6 +14,27 @@ export type LocalNode = {
serverVersionId: string | null;
};
+export type LocalNodeAttribute = {
+ nodeId: string;
+ type: string;
+ key: string;
+ textValue: string | null;
+ numberValue: number | null;
+ foreignNodeId: string | null;
+ createdAt: string;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ versionId: string;
+ serverCreatedAt: string | null;
+ serverUpdatedAt: string | null;
+ serverVersionId: string | null;
+};
+
+export type LocalNodeWithAttributes = LocalNode & {
+ attributes: LocalNodeAttribute[];
+};
+
export type NodeBlock = {
type: string;
text?: string | null;
@@ -30,12 +50,15 @@ export type LocalNodeWithChildren = LocalNode & {
children: LocalNodeWithChildren[];
};
+export type LocalNodeWithAttributesAndChildren = LocalNodeWithAttributes & {
+ children: LocalNodeWithAttributesAndChildren[];
+};
+
export type ServerNode = {
id: string;
parentId: string | null;
type: string;
index: string | null;
- attrs: Record<string, any> | null;
content: NodeBlock[] | null;
createdAt: string;
createdBy: string;
@@ -45,3 +68,20 @@ export type ServerNode = {
serverCreatedAt: string | null;
serverUpdatedAt: string | null;
};
+
+export type ServerNodeAttribute = {
+ id: string;
+ nodeId: string;
+ type: string;
+ key: string;
+ textValue: string | null;
+ numberValue: number | null;
+ foreignNodeId: string | null;
+ createdAt: string;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ versionId: string;
+ serverCreatedAt: string | null;
+ serverUpdatedAt: string | null;
+};
diff --git a/desktop/src/types/workspaces.ts b/desktop/src/types/workspaces.ts
index 05da5c4a..15c2a03c 100644
--- a/desktop/src/types/workspaces.ts
+++ b/desktop/src/types/workspaces.ts
@@ -1,4 +1,4 @@
-import { LocalNode } from '@/types/nodes';
+import { ServerNode, ServerNodeAttribute } from '@/types/nodes';
export enum WorkspaceRole {
Owner = 1,
@@ -20,5 +20,31 @@ export type Workspace = {
};
export type WorkspaceSyncData = {
- nodes: LocalNode[];
+ nodes: ServerNode[];
+ nodeAttributes: ServerNodeAttribute[];
+};
+
+export type SidebarNode = {
+ id: string;
+ type: string;
+ name: string | null;
+ avatar: string | null;
+};
+
+export type SidebarSpaceNode = SidebarNode & {
+ children: SidebarNode[];
+};
+
+export type SidebarChatNode = {
+ id: string;
+ type: string;
+ name: string | null;
+ avatar: string | null;
+};
+
+export type BreadcrumbNode = {
+ id: string;
+ type: string;
+ name: string | null;
+ avatar: string | null;
};
diff --git a/desktop/tsconfig.json b/desktop/tsconfig.json
index 19f787d2..11a3d90b 100644
--- a/desktop/tsconfig.json
+++ b/desktop/tsconfig.json
@@ -12,9 +12,10 @@
"moduleResolution": "node",
"resolveJsonModule": true,
"jsx": "react",
+ "noEmit": true,
"paths": {
"@/*": ["./src/*"]
}
},
- "exclude": ["node_modules", "build", "dist"],
+ "exclude": ["node_modules", "build", "dist"]
}
diff --git a/server/src/consumers/node-attribute-changes.ts b/server/src/consumers/node-attribute-changes.ts
new file mode 100644
index 00000000..ab8a345e
--- /dev/null
+++ b/server/src/consumers/node-attribute-changes.ts
@@ -0,0 +1,173 @@
+import { kafka, TOPIC_NAMES, CONSUMER_IDS } from '@/data/kafka';
+import { ChangeMessage, NodeAttributeChangeData } from '@/types/changes';
+import { PostgresOperation } from '@/lib/constants';
+import { database } from '@/data/database';
+import { NeuronId } from '@/lib/id';
+import { ServerNode, ServerNodeAttribute } from '@/types/nodes';
+
+export const initNodeAttributeChangesConsumer = async () => {
+ const consumer = kafka.consumer({
+ groupId: CONSUMER_IDS.NODE_ATTRIBUTE_CHANGES,
+ });
+
+ await consumer.connect();
+ await consumer.subscribe({ topic: TOPIC_NAMES.NODE_ATTRIBUTE_CHANGES });
+
+ await consumer.run({
+ eachMessage: async ({ message }) => {
+ if (!message || !message.value) {
+ return;
+ }
+
+ const change = JSON.parse(
+ message.value.toString(),
+ ) as ChangeMessage<NodeAttributeChangeData>;
+
+ await handleNodeAttributeChange(change);
+ },
+ });
+};
+
+const handleNodeAttributeChange = async (
+ change: ChangeMessage<NodeAttributeChangeData>,
+) => {
+ switch (change.op) {
+ case PostgresOperation.CREATE: {
+ await handleNodeAttributeCreate(change);
+ break;
+ }
+ case PostgresOperation.UPDATE: {
+ await handleNodeAttributeUpdate(change);
+ break;
+ }
+ case PostgresOperation.DELETE: {
+ await handleNodeAttributeDelete(change);
+ break;
+ }
+ }
+};
+
+const handleNodeAttributeCreate = async (
+ change: ChangeMessage<NodeAttributeChangeData>,
+) => {
+ const node = change.after;
+ if (!node) {
+ return;
+ }
+
+ const deviceIds = await getDeviceIds(node.workspace_id);
+ if (deviceIds.length == 0) {
+ return;
+ }
+
+ const serverNodeAttribute: ServerNodeAttribute = mapNodeAttribute(node);
+ await database
+ .insertInto('mutations')
+ .values({
+ id: NeuronId.generate(NeuronId.Type.Mutation),
+ table: 'node_attributes',
+ action: 'insert',
+ workspace_id: node.workspace_id,
+ created_at: new Date(),
+ after: JSON.stringify(serverNodeAttribute),
+ device_ids: deviceIds,
+ })
+ .execute();
+};
+
+const handleNodeAttributeUpdate = async (
+ change: ChangeMessage<NodeAttributeChangeData>,
+) => {
+ const node = change.after;
+ if (!node) {
+ return;
+ }
+
+ const deviceIds = await getDeviceIds(node.workspace_id);
+ if (deviceIds.length == 0) {
+ return;
+ }
+
+ const serverNodeAttribute: ServerNodeAttribute = mapNodeAttribute(node);
+ await database
+ .insertInto('mutations')
+ .values({
+ id: NeuronId.generate(NeuronId.Type.Mutation),
+ table: 'node_attributes',
+ action: 'update',
+ workspace_id: node.workspace_id,
+ created_at: new Date(),
+ before: change.before ? JSON.stringify(change.before) : null,
+ after: JSON.stringify(serverNodeAttribute),
+ device_ids: deviceIds,
+ })
+ .execute();
+};
+
+const handleNodeAttributeDelete = async (
+ change: ChangeMessage<NodeAttributeChangeData>,
+) => {
+ const node = change.before;
+ if (!node) {
+ return;
+ }
+
+ const deviceIds = await getDeviceIds(node.workspace_id);
+ if (deviceIds.length == 0) {
+ return;
+ }
+
+ const serverNodeAttribute: ServerNodeAttribute = mapNodeAttribute(node);
+ await database
+ .insertInto('mutations')
+ .values({
+ id: NeuronId.generate(NeuronId.Type.Mutation),
+ table: 'node_attributes',
+ action: 'delete',
+ workspace_id: node.workspace_id,
+ created_at: new Date(),
+ before: JSON.stringify(serverNodeAttribute),
+ after: null,
+ device_ids: deviceIds,
+ })
+ .execute();
+};
+
+const getDeviceIds = async (workspaceId: string) => {
+ const accountDevices = await database
+ .selectFrom('account_devices')
+ .where(
+ 'account_id',
+ 'in',
+ database
+ .selectFrom('workspace_accounts')
+ .where('workspace_id', '=', workspaceId)
+ .select('account_id'),
+ )
+ .select('id')
+ .execute();
+
+ const deviceIds = accountDevices.map((account) => account.id);
+ return deviceIds;
+};
+
+const mapNodeAttribute = (
+ node: NodeAttributeChangeData,
+): ServerNodeAttribute => {
+ return {
+ nodeId: node.node_id,
+ type: node.type,
+ key: node.key,
+ workspaceId: node.workspace_id,
+ textValue: node.text_value,
+ numberValue: node.number_value,
+ foreignNodeId: node.foreign_node_id,
+ createdAt: node.created_at,
+ createdBy: node.created_by,
+ updatedAt: node.updated_at,
+ updatedBy: node.updated_by,
+ versionId: node.version_id,
+ serverCreatedAt: node.server_created_at,
+ serverUpdatedAt: node.server_updated_at,
+ };
+};
diff --git a/server/src/consumers/node-changes.ts b/server/src/consumers/node-changes.ts
index afe55184..f45227e6 100644
--- a/server/src/consumers/node-changes.ts
+++ b/server/src/consumers/node-changes.ts
@@ -148,7 +148,6 @@ const mapNode = (node: NodeChangeData): ServerNode => {
parentId: node.parent_id,
type: node.type,
index: node.index,
- attrs: node.attrs ? JSON.parse(node.attrs) : null,
content: node.content ? JSON.parse(node.content) : null,
createdAt: node.created_at,
createdBy: node.created_by,
diff --git a/server/src/data/kafka.ts b/server/src/data/kafka.ts
index 64962df4..5c945802 100644
--- a/server/src/data/kafka.ts
+++ b/server/src/data/kafka.ts
@@ -23,6 +23,9 @@ export const producer = kafka.producer();
export const TOPIC_NAMES = {
NODE_CHANGES:
process.env.KAFKA_NODE_CHANGES_TOPIC_NAME ?? 'neuron_node_changes',
+ NODE_ATTRIBUTE_CHANGES:
+ process.env.KAFKA_NODE_ATTRIBUTE_CHANGES_TOPIC_NAME ??
+ 'neuron_node_attribute_changes',
MUTATION_CHANGES:
process.env.KAFKA_MUTATION_CHANGES_TOPIC_NAME ?? 'neuron_mutation_changes',
};
@@ -31,6 +34,9 @@ export const CONSUMER_IDS = {
NODE_CHANGES:
process.env.KAFKA_NODE_CHANGES_CONSUMER_ID ??
'neuron_node_changes_consumer',
+ NODE_ATTRIBUTE_CHANGES:
+ process.env.KAFKA_NODE_ATTRIBUTE_CHANGES_CONSUMER_ID ??
+ 'neuron_node_attribute_changes_consumer',
MUTATION_CHANGES:
process.env.KAFKA_MUTATION_CHANGES_CONSUMER_ID ??
'neuron_mutation_changes_consumer',
diff --git a/server/src/data/migrations.ts b/server/src/data/migrations.ts
index ca165e0f..9a0f4084 100644
--- a/server/src/data/migrations.ts
+++ b/server/src/data/migrations.ts
@@ -74,10 +74,11 @@ const createNodesTable: Migration = {
.createTable('nodes')
.addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
.addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('parent_id', 'varchar(30)')
+ .addColumn('parent_id', 'varchar(30)', (col) =>
+ col.references('nodes.id').onDelete('cascade'),
+ )
.addColumn('type', 'varchar(30)', (col) => col.notNull())
.addColumn('index', 'varchar(30)')
- .addColumn('attrs', 'jsonb')
.addColumn('content', 'jsonb')
.addColumn('created_at', 'timestamptz', (col) => col.notNull())
.addColumn('created_by', 'varchar(30)', (col) => col.notNull())
@@ -86,13 +87,33 @@ const createNodesTable: Migration = {
.addColumn('version_id', 'varchar(30)', (col) => col.notNull())
.addColumn('server_created_at', 'timestamptz', (col) => col.notNull())
.addColumn('server_updated_at', 'timestamptz')
- .addForeignKeyConstraint(
- 'nodes_parent_id_fkey',
- ['parent_id'],
- 'nodes',
- ['id'],
- (cb) => cb.onDelete('cascade'),
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('nodes').execute();
+ },
+};
+
+const createNodeAttributesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('node_attributes')
+ .addColumn('node_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('type', 'varchar(30)', (col) => col.notNull())
+ .addColumn('key', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('text_value', 'varchar(30)')
+ .addColumn('number_value', 'numeric')
+ .addColumn('foreign_node_id', 'varchar(30)', (col) =>
+ col.references('nodes.id').onDelete('cascade'),
)
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('updated_by', 'varchar(30)')
+ .addColumn('version_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('server_created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('server_updated_at', 'timestamptz')
.execute();
},
down: async (db) => {
@@ -141,10 +162,11 @@ const createMutationsTable: Migration = {
};
export const databaseMigrations: Record<string, Migration> = {
- '202408011709_create_accounts_table': createAccountsTable,
- '202408011712_create_workspaces_table': createWorkspacesTable,
- '202408011715_create_workspace_accounts_table': createWorkspaceAccountsTable,
- '202408011718_create_nodes_table': createNodesTable,
- '202408011721_create_account_devices_table': createAccountDevicesTable,
- '202408011724_create_mutations_table': createMutationsTable,
+ '00001_create_accounts_table': createAccountsTable,
+ '00002_create_workspaces_table': createWorkspacesTable,
+ '00003_create_workspace_accounts_table': createWorkspaceAccountsTable,
+ '00004_create_nodes_table': createNodesTable,
+ '00005_create_node_attributes_table': createNodeAttributesTable,
+ '00006_create_account_devices_table': createAccountDevicesTable,
+ '00007_create_mutations_table': createMutationsTable,
};
diff --git a/server/src/data/schema.ts b/server/src/data/schema.ts
index 9a8811c1..03f06145 100644
--- a/server/src/data/schema.ts
+++ b/server/src/data/schema.ts
@@ -82,11 +82,6 @@ interface NodeTable {
parent_id: ColumnType<string | null, string | null, string | null>;
type: ColumnType<string, string, string>;
index: ColumnType<string | null, string | null, string | null>;
- attrs: JSONColumnType<
- Record<string, any> | null,
- string | null,
- string | null
- >;
content: JSONColumnType<NodeBlock[] | null, string | null, string | null>;
created_at: ColumnType<Date, Date, never>;
updated_at: ColumnType<Date | null, Date | null, Date>;
@@ -101,6 +96,27 @@ export type SelectNode = Selectable<NodeTable>;
export type CreateNode = Insertable<NodeTable>;
export type UpdateNode = Updateable<NodeTable>;
+interface NodeAttributeTable {
+ node_id: ColumnType<string, string, never>;
+ type: ColumnType<string, string, never>;
+ key: ColumnType<string, string, string>;
+ workspace_id: ColumnType<string, string, never>;
+ text_value: ColumnType<string | null, string | null, string | null>;
+ number_value: ColumnType<number | null, number | null, number | null>;
+ foreign_node_id: ColumnType<string | null, string | null, string | null>;
+ created_at: ColumnType<Date, Date, never>;
+ updated_at: ColumnType<Date | null, Date | null, Date>;
+ created_by: ColumnType<string, string, never>;
+ updated_by: ColumnType<string | null, string | null, string>;
+ version_id: ColumnType<string, string, string>;
+ server_created_at: ColumnType<Date, Date, never>;
+ server_updated_at: ColumnType<Date | null, Date | null, Date>;
+}
+
+export type SelectNodeAttribute = Selectable<NodeAttributeTable>;
+export type CreateNodeAttribute = Insertable<NodeAttributeTable>;
+export type UpdateNodeAttribute = Updateable<NodeAttributeTable>;
+
interface MutationTable {
id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
@@ -122,5 +138,6 @@ export interface DatabaseSchema {
workspace_accounts: WorkspaceAccountTable;
account_devices: AccountDeviceTable;
nodes: NodeTable;
+ node_attributes: NodeAttributeTable;
mutations: MutationTable;
}
diff --git a/server/src/routes/mutations.ts b/server/src/routes/mutations.ts
index dbc0e8a3..2646e6f7 100644
--- a/server/src/routes/mutations.ts
+++ b/server/src/routes/mutations.ts
@@ -3,6 +3,7 @@ import { Router } from 'express';
import {
ExecuteLocalMutationsInput,
LocalMutation,
+ LocalNodeAttributeMutationData,
LocalNodeMutationData,
} from '@/types/mutations';
import { database } from '@/data/database';
@@ -29,6 +30,31 @@ mutationsRouter.post('/', async (req: NeuronRequest, res: NeuronResponse) => {
}
}
}
+ case 'node_attributes': {
+ switch (mutation.action) {
+ case 'insert': {
+ await handleCreateNodeAttributeMutation(
+ input.workspaceId,
+ mutation,
+ );
+ break;
+ }
+ case 'update': {
+ await handleUpdateNodeAttributeMutation(
+ input.workspaceId,
+ mutation,
+ );
+ break;
+ }
+ case 'delete': {
+ await handleDeleteNodeAttributeMutation(
+ input.workspaceId,
+ mutation,
+ );
+ break;
+ }
+ }
+ }
}
}
@@ -61,7 +87,6 @@ const handleCreateNodeMutation = async (
workspace_id: workspaceId,
type: nodeData.type,
index: nodeData.index,
- attrs: nodeData.attrs,
content: nodeData.content,
created_at: new Date(nodeData.created_at),
created_by: nodeData.created_by,
@@ -100,7 +125,6 @@ const handleUpdateNodeMutation = async (
parent_id: nodeData.parent_id,
type: nodeData.type,
index: nodeData.index,
- attrs: nodeData.attrs,
content: nodeData.content,
updated_at: updatedAt,
updated_by: updatedBy,
@@ -132,3 +156,143 @@ const handleDeleteNodeMutation = async (
await database.deleteFrom('nodes').where('id', '=', nodeData.id).execute();
};
+
+const handleCreateNodeAttributeMutation = async (
+ workspaceId: string,
+ mutation: LocalMutation,
+): Promise<void> => {
+ if (!mutation.after) {
+ return;
+ }
+
+ const nodeAttributeData = JSON.parse(
+ mutation.after,
+ ) as LocalNodeAttributeMutationData;
+ const existingNodeAttribute = await database
+ .selectFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttributeData.node_id),
+ eb('type', '=', nodeAttributeData.type),
+ eb('key', '=', nodeAttributeData.key),
+ ]),
+ )
+ .executeTakeFirst();
+
+ if (existingNodeAttribute) {
+ return;
+ }
+
+ await database
+ .insertInto('node_attributes')
+ .values({
+ node_id: nodeAttributeData.node_id,
+ type: nodeAttributeData.type,
+ key: nodeAttributeData.key,
+ workspace_id: workspaceId,
+ text_value: nodeAttributeData.text_value,
+ number_value: nodeAttributeData.number_value,
+ foreign_node_id: nodeAttributeData.foreign_node_id,
+ created_at: new Date(nodeAttributeData.created_at),
+ created_by: nodeAttributeData.created_by,
+ version_id: nodeAttributeData.version_id,
+ server_created_at: new Date(),
+ })
+ .execute();
+};
+
+const handleUpdateNodeAttributeMutation = async (
+ workspaceId: string,
+ mutation: LocalMutation,
+): Promise<void> => {
+ if (!mutation.after) {
+ return;
+ }
+
+ const nodeAttributeData = JSON.parse(
+ mutation.after,
+ ) as LocalNodeAttributeMutationData;
+ const existingNodeAttribute = await database
+ .selectFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttributeData.node_id),
+ eb('type', '=', nodeAttributeData.type),
+ eb('key', '=', nodeAttributeData.key),
+ ]),
+ )
+ .executeTakeFirst();
+
+ if (!existingNodeAttribute) {
+ return;
+ }
+
+ const updatedAt = nodeAttributeData.updated_at
+ ? new Date(nodeAttributeData.updated_at)
+ : new Date();
+
+ const updatedBy =
+ nodeAttributeData.updated_by ?? nodeAttributeData.created_by;
+
+ await database
+ .updateTable('node_attributes')
+ .set({
+ text_value: nodeAttributeData.text_value,
+ number_value: nodeAttributeData.number_value,
+ foreign_node_id: nodeAttributeData.foreign_node_id,
+ updated_at: updatedAt,
+ updated_by: updatedBy,
+ version_id: nodeAttributeData.version_id,
+ server_updated_at: new Date(),
+ })
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttributeData.node_id),
+ eb('type', '=', nodeAttributeData.type),
+ eb('key', '=', nodeAttributeData.key),
+ ]),
+ )
+ .execute();
+};
+
+const handleDeleteNodeAttributeMutation = async (
+ workspaceId: string,
+ mutation: LocalMutation,
+): Promise<void> => {
+ if (!mutation.before) {
+ return;
+ }
+
+ const nodeAttributeData = JSON.parse(
+ mutation.before,
+ ) as LocalNodeAttributeMutationData;
+ const existingNodeAttribute = await database
+ .selectFrom('node_attributes')
+ .selectAll()
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttributeData.node_id),
+ eb('type', '=', nodeAttributeData.type),
+ eb('key', '=', nodeAttributeData.key),
+ ]),
+ )
+ .executeTakeFirst();
+
+ if (
+ !existingNodeAttribute ||
+ existingNodeAttribute.workspace_id !== workspaceId
+ ) {
+ return;
+ }
+
+ await database
+ .deleteFrom('node_attributes')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', nodeAttributeData.node_id),
+ eb('type', '=', nodeAttributeData.type),
+ eb('key', '=', nodeAttributeData.key),
+ ]),
+ )
+ .execute();
+};
diff --git a/server/src/routes/sync.ts b/server/src/routes/sync.ts
index f1667f45..6743946d 100644
--- a/server/src/routes/sync.ts
+++ b/server/src/routes/sync.ts
@@ -1,7 +1,7 @@
import { NeuronRequest, NeuronResponse } from '@/types/api';
import { database } from '@/data/database';
import { Router } from 'express';
-import { ServerNode } from '@/types/nodes';
+import { ServerNode, ServerNodeAttribute } from '@/types/nodes';
export const syncRouter = Router();
@@ -9,20 +9,25 @@ syncRouter.get(
'/:workspaceId/sync',
async (req: NeuronRequest, res: NeuronResponse) => {
const workspaceId = req.params.workspaceId as string;
- const nodes = await database
+ const nodeRows = await database
.selectFrom('nodes')
.selectAll()
.where('workspace_id', '=', workspaceId)
.execute();
- const outputs: ServerNode[] = nodes.map((node) => {
+ const nodeAttributeRows = await database
+ .selectFrom('node_attributes')
+ .selectAll()
+ .where('workspace_id', '=', workspaceId)
+ .execute();
+
+ const nodes: ServerNode[] = nodeRows.map((node) => {
return {
id: node.id,
parentId: node.parent_id,
workspaceId: node.workspace_id,
type: node.type,
index: node.index,
- attrs: node.attrs,
createdAt: node.created_at.toISOString(),
createdBy: node.created_by,
versionId: node.version_id,
@@ -34,8 +39,28 @@ syncRouter.get(
};
});
+ const nodeAttributes: ServerNodeAttribute[] = nodeAttributeRows.map(
+ (nodeAttribute) => {
+ return {
+ nodeId: nodeAttribute.node_id,
+ type: nodeAttribute.type,
+ key: nodeAttribute.key,
+ textValue: nodeAttribute.text_value,
+ numberValue: nodeAttribute.number_value,
+ foreignNodeId: nodeAttribute.foreign_node_id,
+ workspaceId: nodeAttribute.workspace_id,
+ createdAt: nodeAttribute.created_at.toISOString(),
+ createdBy: nodeAttribute.created_by,
+ versionId: nodeAttribute.version_id,
+ serverCreatedAt: nodeAttribute.server_created_at.toISOString(),
+ serverUpdatedAt: nodeAttribute.server_updated_at?.toISOString(),
+ };
+ },
+ );
+
res.status(200).json({
- nodes: outputs,
+ nodes,
+ nodeAttributes,
});
},
);
diff --git a/server/src/routes/workspaces.ts b/server/src/routes/workspaces.ts
index 08e6cee0..bebef315 100644
--- a/server/src/routes/workspaces.ts
+++ b/server/src/routes/workspaces.ts
@@ -89,11 +89,6 @@ workspacesRouter.post('/', async (req: NeuronRequest, res: NeuronResponse) => {
id: userId,
workspace_id: workspace.id,
type: 'user',
- attrs: JSON.stringify({
- accountId: account.id,
- name: account.name,
- avatar: account.avatar,
- }),
created_at: workspaceAccount.createdAt,
created_by: workspaceAccount.createdBy,
version_id: userVersionId,
@@ -101,6 +96,34 @@ workspacesRouter.post('/', async (req: NeuronRequest, res: NeuronResponse) => {
})
.execute();
+ await trx
+ .insertInto('node_attributes')
+ .values([
+ {
+ node_id: userId,
+ type: 'name',
+ key: '1',
+ workspace_id: workspace.id,
+ text_value: account.name,
+ created_at: workspaceAccount.createdAt,
+ created_by: workspaceAccount.createdBy,
+ version_id: userVersionId,
+ server_created_at: new Date(),
+ },
+ {
+ node_id: userId,
+ type: 'avatar',
+ key: '1',
+ workspace_id: workspace.id,
+ text_value: account.avatar,
+ created_at: workspaceAccount.createdAt,
+ created_by: workspaceAccount.createdBy,
+ version_id: userVersionId,
+ server_created_at: new Date(),
+ },
+ ])
+ .execute();
+
await trx
.insertInto('workspace_accounts')
.values({
diff --git a/server/src/types/changes.ts b/server/src/types/changes.ts
index e2ad1fa6..ab54de3d 100644
--- a/server/src/types/changes.ts
+++ b/server/src/types/changes.ts
@@ -52,3 +52,20 @@ export type NodeChangeData = {
server_created_at: string;
server_updated_at: string | null;
};
+
+export type NodeAttributeChangeData = {
+ node_id: string;
+ type: string;
+ key: string;
+ workspace_id: string;
+ text_value: string | null;
+ number_value: number | null;
+ foreign_node_id: string | null;
+ created_at: string;
+ created_by: string;
+ updated_at: string | null;
+ updated_by: string | null;
+ version_id: string;
+ server_created_at: string;
+ server_updated_at: string | null;
+};
diff --git a/server/src/types/mutations.ts b/server/src/types/mutations.ts
index 60aac21f..a2458187 100644
--- a/server/src/types/mutations.ts
+++ b/server/src/types/mutations.ts
@@ -29,6 +29,23 @@ export type LocalNodeMutationData = {
server_version_id: string;
};
+export type LocalNodeAttributeMutationData = {
+ node_id: string;
+ type: string;
+ key: string;
+ text_value: string | null;
+ number_value: number | null;
+ foreign_node_id: string | null;
+ created_at: string;
+ updated_at?: string | null;
+ created_by: string;
+ updated_by?: string | null;
+ version_id: string;
+ server_created_at: string;
+ server_updated_at: string;
+ server_version_id: string;
+};
+
export type ServerMutation = {
id: string;
table: string;
diff --git a/server/src/types/nodes.ts b/server/src/types/nodes.ts
index 203d9b92..0349fd55 100644
--- a/server/src/types/nodes.ts
+++ b/server/src/types/nodes.ts
@@ -4,7 +4,6 @@ export type ServerNode = {
parentId?: string | null;
type: string;
index: string | null;
- attrs?: Record<string, any> | null;
content?: NodeBlock[] | null;
createdAt: string;
createdBy: string;
@@ -15,6 +14,23 @@ export type ServerNode = {
serverUpdatedAt?: string | null;
};
+export type ServerNodeAttribute = {
+ nodeId: string;
+ type: string;
+ key: string;
+ workspaceId: string;
+ textValue: string | null;
+ numberValue: number | null;
+ foreignNodeId: string | null;
+ createdAt: string;
+ createdBy: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ versionId: string;
+ serverCreatedAt: string;
+ serverUpdatedAt?: string | null;
+};
+
export type NodeBlock = {
type: string;
text?: string | null;
diff --git a/server/tsconfig.json b/server/tsconfig.json
index b680ffff..ed3fa107 100644
--- a/server/tsconfig.json
+++ b/server/tsconfig.json
@@ -6,9 +6,10 @@
"rootDir": ".",
"strict": true,
"esModuleInterop": true,
+ "noEmit": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
- },
+ }
}
}