Skip to content

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

Refactor mutations and queries

Hakan Shehu43889aa9016a
diff --git a/desktop/src/components/accounts/email-login.tsx b/desktop/src/components/accounts/email-login.tsx
index 7a3c6966..929989d8 100644
--- a/desktop/src/components/accounts/email-login.tsx
+++ b/desktop/src/components/accounts/email-login.tsx
@@ -13,10 +13,9 @@ import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from '@/components/ui/use-toast';
-import { parseApiError } from '@/lib/axios';
import { Icon } from '@/components/ui/icon';
import { Server } from '@/types/servers';
-import { useEmailLoginMutation } from '@/mutations/use-email-login-mutation';
+import { useMutation } from '@/hooks/use-mutation';
const formSchema = z.object({
email: z.string().min(2).email(),
@@ -28,7 +27,7 @@ interface EmailLoginProps {
}
export const EmailLogin = ({ server }: EmailLoginProps) => {
- const { mutate, isPending } = useEmailLoginMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -38,26 +37,25 @@ export const EmailLogin = ({ server }: EmailLoginProps) => {
});
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(
- {
+ mutate({
+ input: {
+ type: 'email_login',
email: values.email,
password: values.password,
- server: server,
+ server: server.domain,
},
- {
- onSuccess: () => {
- window.location.href = '/';
- },
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to login',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onSuccess() {
+ window.location.href = '/';
},
- );
+ onError() {
+ toast({
+ title: 'Failed to login',
+ description:
+ 'Something went wrong trying to login. Please try again.',
+ variant: 'destructive',
+ });
+ },
+ });
};
return (
diff --git a/desktop/src/components/accounts/email-register.tsx b/desktop/src/components/accounts/email-register.tsx
index 16208597..9c399b81 100644
--- a/desktop/src/components/accounts/email-register.tsx
+++ b/desktop/src/components/accounts/email-register.tsx
@@ -13,9 +13,8 @@ import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from '@/components/ui/use-toast';
-import { parseApiError } from '@/lib/axios';
import { Icon } from '@/components/ui/icon';
-import { useEmailRegisterMutation } from '@/mutations/use-email-register-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { Server } from '@/types/servers';
const formSchema = z.object({
@@ -29,7 +28,7 @@ interface EmailRegisterProps {
}
export const EmailRegister = ({ server }: EmailRegisterProps) => {
- const { mutate, isPending } = useEmailRegisterMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -40,27 +39,26 @@ export const EmailRegister = ({ server }: EmailRegisterProps) => {
});
const onSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(
- {
+ mutate({
+ input: {
+ type: 'email_register',
name: values.name,
email: values.email,
password: values.password,
- server: server,
+ server: server.domain,
},
- {
- onSuccess: () => {
- window.location.href = '/';
- },
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to login',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onSuccess() {
+ window.location.href = '/';
},
- );
+ onError() {
+ toast({
+ title: 'Failed to register',
+ description:
+ 'Something went wrong trying to register. Please try again.',
+ variant: 'destructive',
+ });
+ },
+ });
};
return (
diff --git a/desktop/src/components/accounts/login.tsx b/desktop/src/components/accounts/login.tsx
index 6f47112e..73b6ff12 100644
--- a/desktop/src/components/accounts/login.tsx
+++ b/desktop/src/components/accounts/login.tsx
@@ -1,9 +1,11 @@
import React from 'react';
-import { LoginForm } from './login-form';
-import { useServersQuery } from '@/queries/use-servers-query';
+import { LoginForm } from '@/components/accounts/login-form';
+import { useQuery } from '@/hooks/use-query';
export const Login = () => {
- const { data, isPending } = useServersQuery();
+ const { data, isPending } = useQuery({
+ type: 'server_list',
+ });
return (
<div className="grid h-screen min-h-screen w-full grid-cols-5">
diff --git a/desktop/src/components/app.tsx b/desktop/src/components/app.tsx
index f7011fc3..12905997 100644
--- a/desktop/src/components/app.tsx
+++ b/desktop/src/components/app.tsx
@@ -7,18 +7,21 @@ import { AxiosContext } from '@/contexts/axios';
import { Outlet } from 'react-router-dom';
import { AccountLogout } from '@/components/accounts/account-logout';
import { DelayedComponent } from '@/components/ui/delayed-component';
-import { useAccountsQuery } from '@/queries/use-accounts-query';
-import { useWorkspacesQuery } from '@/queries/use-workspaces-query';
-import { useServersQuery } from '@/queries/use-servers-query';
+import { useQuery } from '@/hooks/use-query';
import { buildApiBaseUrl } from '@/lib/servers';
export const App = () => {
const [showLogout, setShowLogout] = React.useState(false);
- const { data: servers, isPending: isPendingServers } = useServersQuery();
- const { data: accounts, isPending: isPendingAccounts } = useAccountsQuery();
- const { data: workspaces, isPending: isPendingWorkspaces } =
- useWorkspacesQuery();
+ const { data: servers, isPending: isPendingServers } = useQuery({
+ type: 'server_list',
+ });
+ const { data: accounts, isPending: isPendingAccounts } = useQuery({
+ type: 'account_list',
+ });
+ const { data: workspaces, isPending: isPendingWorkspaces } = useQuery({
+ type: 'workspace_list',
+ });
const isPending =
isPendingServers || isPendingAccounts || isPendingWorkspaces;
diff --git a/desktop/src/components/channels/channel-create-dialog.tsx b/desktop/src/components/channels/channel-create-dialog.tsx
index 0b55ac77..59113134 100644
--- a/desktop/src/components/channels/channel-create-dialog.tsx
+++ b/desktop/src/components/channels/channel-create-dialog.tsx
@@ -22,7 +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 { useChannelCreateMutation } from '@/mutations/use-channel-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -40,7 +40,7 @@ export const ChannelCreateDialog = ({
onOpenChange,
}: ChannelCreateDialogProps) => {
const workspace = useWorkspace();
- const { mutate, isPending } = useChannelCreateMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -59,19 +59,19 @@ export const ChannelCreateDialog = ({
return;
}
- mutate(
- {
- spaceId,
+ mutate({
+ input: {
+ type: 'channel_create',
+ spaceId: spaceId,
name: values.name,
+ userId: workspace.userId,
},
- {
- onSuccess: (id) => {
- onOpenChange(false);
- form.reset();
- workspace.navigateToNode(id);
- },
+ onSuccess(output) {
+ onOpenChange(false);
+ form.reset();
+ workspace.navigateToNode(output.id);
},
- );
+ });
};
return (
diff --git a/desktop/src/components/chats/chat-create-command.tsx b/desktop/src/components/chats/chat-create-command.tsx
new file mode 100644
index 00000000..f7e0fe3a
--- /dev/null
+++ b/desktop/src/components/chats/chat-create-command.tsx
@@ -0,0 +1,73 @@
+import React from 'react';
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '@/components/ui/command';
+import { useWorkspace } from '@/contexts/workspace';
+import { useQuery } from '@/hooks/use-query';
+import { useMutation } from '@/hooks/use-mutation';
+import { Avatar } from '@/components/ui/avatar';
+
+export const ChatCreateCommand = () => {
+ const workspace = useWorkspace();
+
+ const [query, setQuery] = React.useState('');
+ const { data } = useQuery({
+ type: 'user_search',
+ searchQuery: query,
+ userId: workspace.userId,
+ });
+
+ const { mutate } = useMutation();
+
+ return (
+ <Command className="min-h-min" shouldFilter={false}>
+ <CommandInput
+ value={query}
+ onValueChange={setQuery}
+ placeholder="Search users..."
+ className="h-9"
+ />
+ <CommandEmpty>No user found.</CommandEmpty>
+ <CommandList>
+ <CommandGroup className="h-min max-h-96">
+ {data?.map((user) => (
+ <CommandItem
+ key={user.id}
+ onSelect={() => {
+ mutate({
+ input: {
+ type: 'chat_create',
+ userId: workspace.userId,
+ otherUserId: user.id,
+ },
+ onSuccess(output) {
+ workspace.navigateToNode(output.id);
+ setQuery('');
+ },
+ });
+ }}
+ >
+ <div className="flex w-full flex-row items-center gap-2">
+ <Avatar
+ id={user.id}
+ name={user.name}
+ avatar={user.avatar}
+ className="h-7 w-7"
+ />
+ <div className="flex flex-grow flex-col">
+ <p className="text-sm">{user.name}</p>
+ <p className="text-xs text-muted-foreground">{user.email}</p>
+ </div>
+ </div>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ );
+};
diff --git a/desktop/src/components/chats/chat-create-popover.tsx b/desktop/src/components/chats/chat-create-popover.tsx
index c592dd26..56c7b7aa 100644
--- a/desktop/src/components/chats/chat-create-popover.tsx
+++ b/desktop/src/components/chats/chat-create-popover.tsx
@@ -5,26 +5,10 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from '@/components/ui/command';
-import { Avatar } from '@/components/ui/avatar';
-import { useUserSearchQuery } from '@/queries/use-user-search-query';
-import { useChatCreateMutation } from '@/mutations/use-chat-create-mutation';
-import { useWorkspace } from '@/contexts/workspace';
+import { ChatCreateCommand } from '@/components/chats/chat-create-command';
export const ChatCreatePopover = () => {
- const workspace = useWorkspace();
-
- const [query, setQuery] = React.useState('');
const [open, setOpen] = React.useState(false);
- const { data } = useUserSearchQuery(query);
- const { mutate } = useChatCreateMutation();
return (
<Popover open={open} onOpenChange={setOpen} modal={true}>
@@ -32,52 +16,7 @@ export const ChatCreatePopover = () => {
<Icon name="add-line" className="mr-2 h-3 w-3 cursor-pointer" />
</PopoverTrigger>
<PopoverContent className="w-96 p-1">
- <Command className="min-h-min" shouldFilter={false}>
- <CommandInput
- value={query}
- onValueChange={setQuery}
- placeholder="Search users..."
- className="h-9"
- />
- <CommandEmpty>No user found.</CommandEmpty>
- <CommandList>
- <CommandGroup className="h-min max-h-96">
- {data?.map((user) => (
- <CommandItem
- key={user.id}
- onSelect={() => {
- mutate(
- {
- userId: user.id,
- },
- {
- onSuccess: (id) => {
- workspace.navigateToNode(id);
- },
- },
- );
- setQuery('');
- }}
- >
- <div className="flex w-full flex-row items-center gap-2">
- <Avatar
- id={user.id}
- name={user.name}
- avatar={user.avatar}
- className="h-7 w-7"
- />
- <div className="flex flex-grow flex-col">
- <p className="text-sm">{user.name}</p>
- <p className="text-xs text-muted-foreground">
- {user.email}
- </p>
- </div>
- </div>
- </CommandItem>
- ))}
- </CommandGroup>
- </CommandList>
- </Command>
+ <ChatCreateCommand />
</PopoverContent>
</Popover>
);
diff --git a/desktop/src/components/collaborators/node-collaborator-create.tsx b/desktop/src/components/collaborators/node-collaborator-create.tsx
index 36fc196a..1d48b09f 100644
--- a/desktop/src/components/collaborators/node-collaborator-create.tsx
+++ b/desktop/src/components/collaborators/node-collaborator-create.tsx
@@ -4,8 +4,9 @@ import { NodeCollaboratorNode } from '@/types/nodes';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { NodeCollaboratorRoleDropdown } from '@/components/collaborators/node-collaborator-role-dropdown';
-import { useNodeCollaboratorCreateMutation } from '@/mutations/use-node-collaborator-create-mutation';
-import { toast } from '../ui/use-toast';
+import { useMutation } from '@/hooks/use-mutation';
+import { toast } from '@/components/ui/use-toast';
+import { useWorkspace } from '@/contexts/workspace';
interface NodeCollaboratorCreate {
id: string;
@@ -16,7 +17,8 @@ export const NodeCollaboratorCreate = ({
id,
existingCollaborators,
}: NodeCollaboratorCreate) => {
- const { mutate, isPending } = useNodeCollaboratorCreateMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [collaborators, setCollaborators] = React.useState<
NodeCollaboratorNode[]
@@ -42,28 +44,28 @@ export const NodeCollaboratorCreate = ({
return;
}
- mutate(
- {
+ mutate({
+ input: {
+ type: 'node_collaborator_create',
nodeId: id,
collaboratorIds: collaborators.map(
(collaborator) => collaborator.id,
),
role: role,
+ userId: workspace.userId,
},
- {
- onSuccess() {
- setCollaborators([]);
- },
- onError() {
- toast({
- title: 'Failed to add collaborators',
- description:
- 'Something went wrong trying to add collaborators. Please try again.',
- variant: 'destructive',
- });
- },
+ onSuccess() {
+ setCollaborators([]);
},
- );
+ onError() {
+ toast({
+ title: 'Failed to add collaborators',
+ description:
+ 'Something went wrong trying to add collaborators. Please try again.',
+ variant: 'destructive',
+ });
+ },
+ });
}}
>
{isPending && <Spinner className="mr-1" />}
diff --git a/desktop/src/components/collaborators/node-collaborator-search.tsx b/desktop/src/components/collaborators/node-collaborator-search.tsx
index 73bf04a6..36097433 100644
--- a/desktop/src/components/collaborators/node-collaborator-search.tsx
+++ b/desktop/src/components/collaborators/node-collaborator-search.tsx
@@ -17,7 +17,8 @@ import {
import { Icon } from '@/components/ui/icon';
import { Badge } from '@/components/ui/badge';
import { Avatar } from '@/components/ui/avatar';
-import { useNodeCollaboratorSearchQuery } from '@/queries/use-node-collaborator-search-query';
+import { useQuery } from '@/hooks/use-query';
+import { useWorkspace } from '@/contexts/workspace';
interface NodeCollaboratorSearchProps {
excluded: string[];
@@ -30,9 +31,17 @@ export const NodeCollaboratorSearch = ({
value,
onChange,
}: NodeCollaboratorSearchProps) => {
+ const workspace = useWorkspace();
+
const [query, setQuery] = React.useState('');
const [open, setOpen] = React.useState(false);
- const { data } = useNodeCollaboratorSearchQuery(query, excluded);
+
+ const { data } = useQuery({
+ type: 'node_collaborator_search',
+ searchQuery: query,
+ excluded: excluded,
+ userId: workspace.userId,
+ });
return (
<Popover open={open} onOpenChange={setOpen} modal={true}>
diff --git a/desktop/src/components/collaborators/node-collaborator.tsx b/desktop/src/components/collaborators/node-collaborator.tsx
index 29e35432..8cb10612 100644
--- a/desktop/src/components/collaborators/node-collaborator.tsx
+++ b/desktop/src/components/collaborators/node-collaborator.tsx
@@ -3,8 +3,8 @@ import { NodeCollaboratorNode } from '@/types/nodes';
import { Avatar } from '@/components/ui/avatar';
import { Icon } from '@/components/ui/icon';
import { NodeCollaboratorRoleDropdown } from '@/components/collaborators/node-collaborator-role-dropdown';
-import { useNodeCollaboratorDeleteMutation } from '@/mutations/use-node-collaborator-delete-mutation';
-import { useNodeCollaboratorUpdateMutation } from '@/mutations/use-node-collaborator-update-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface NodeCollaboratorProps {
nodeId: string;
@@ -17,8 +17,9 @@ export const NodeCollaborator = ({
collaborator,
removable,
}: NodeCollaboratorProps) => {
- const { mutate: updateCollaborator } = useNodeCollaboratorUpdateMutation();
- const { mutate: deleteCollaborator } = useNodeCollaboratorDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate } = useMutation();
+
return (
<div className="flex items-center justify-between space-x-3">
<div className="flex items-center space-x-3">
@@ -38,10 +39,14 @@ export const NodeCollaborator = ({
<NodeCollaboratorRoleDropdown
value={collaborator.role}
onChange={(newRole) => {
- updateCollaborator({
- nodeId: nodeId,
- collaboratorId: collaborator.id,
- role: newRole,
+ mutate({
+ input: {
+ type: 'node_collaborator_update',
+ nodeId: nodeId,
+ collaboratorId: collaborator.id,
+ role: newRole,
+ userId: workspace.userId,
+ },
});
}}
/>
@@ -50,9 +55,13 @@ export const NodeCollaborator = ({
name="delete-bin-line"
className="h-4 w-4 cursor-pointer text-muted-foreground hover:text-foreground"
onClick={() => {
- deleteCollaborator({
- nodeId: nodeId,
- collaboratorId: collaborator.id,
+ mutate({
+ input: {
+ type: 'node_collaborator_delete',
+ nodeId: nodeId,
+ collaboratorId: collaborator.id,
+ userId: workspace.userId,
+ },
});
}}
/>
diff --git a/desktop/src/components/collaborators/node-collaborators.tsx b/desktop/src/components/collaborators/node-collaborators.tsx
index c7189d48..a5febbdb 100644
--- a/desktop/src/components/collaborators/node-collaborators.tsx
+++ b/desktop/src/components/collaborators/node-collaborators.tsx
@@ -2,14 +2,20 @@ import React from 'react';
import { Separator } from '@/components/ui/separator';
import { NodeCollaborator } from '@/components/collaborators/node-collaborator';
import { NodeCollaboratorCreate } from '@/components/collaborators/node-collaborator-create';
-import { useNodeCollaboratorsQuery } from '@/queries/use-node-collaborators-query';
+import { useQuery } from '@/hooks/use-query';
+import { useWorkspace } from '@/contexts/workspace';
interface NodeCollaboratorsProps {
id: string;
}
export const NodeCollaborators = ({ id }: NodeCollaboratorsProps) => {
- const { data, isPending } = useNodeCollaboratorsQuery(id);
+ const workspace = useWorkspace();
+ const { data, isPending } = useQuery({
+ type: 'node_collaborator_list',
+ nodeId: id,
+ userId: workspace.userId,
+ });
if (isPending) {
return null;
diff --git a/desktop/src/components/databases/boards/board-view-card.tsx b/desktop/src/components/databases/boards/board-view-card.tsx
index ab6c7f80..254a12f3 100644
--- a/desktop/src/components/databases/boards/board-view-card.tsx
+++ b/desktop/src/components/databases/boards/board-view-card.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import { useWorkspace } from '@/contexts/workspace';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import {
RecordNode,
SelectFieldNode,
@@ -20,7 +20,7 @@ interface DragResult {
export const BoardViewCard = ({ record }: BoardViewCardProps) => {
const workspace = useWorkspace();
- const { mutate, isPending } = useNodeAttributeSetMutation();
+ const { mutate, isPending } = useMutation();
const [, drag] = useDrag({
type: 'board-record',
@@ -41,9 +41,13 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
}
mutate({
- nodeId: record.id,
- key: fieldId,
- value: optionId,
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: fieldId,
+ value: optionId,
+ userId: workspace.userId,
+ },
});
}
},
diff --git a/desktop/src/components/databases/boards/board-view-column-records.tsx b/desktop/src/components/databases/boards/board-view-column-records.tsx
index 26dec3ac..9b593dd8 100644
--- a/desktop/src/components/databases/boards/board-view-column-records.tsx
+++ b/desktop/src/components/databases/boards/board-view-column-records.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import { useDatabase } from '@/contexts/database';
-import { useRecordsQuery } from '@/queries/use-records-query';
+import { useInfiniteQuery } from '@/hooks/use-infinite-query';
import {
BoardViewNode,
SelectFieldNode,
@@ -8,6 +8,9 @@ import {
ViewFilter,
} from '@/types/databases';
import { BoardViewCard } from '@/components/databases/boards/board-view-card';
+import { useWorkspace } from '@/contexts/workspace';
+
+const RECORDS_PER_PAGE = 50;
interface BoardViewColumnRecordsProps {
view: BoardViewNode;
@@ -20,6 +23,7 @@ export const BoardViewColumnRecords = ({
field,
option,
}: BoardViewColumnRecordsProps) => {
+ const workspace = useWorkspace();
const database = useDatabase();
const filters: ViewFilter[] = [
@@ -33,9 +37,39 @@ export const BoardViewColumnRecords = ({
},
];
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useRecordsQuery(database.id, filters, view.sorts);
+ useInfiniteQuery({
+ initialPageInput: {
+ type: 'record_list',
+ databaseId: database.id,
+ filters: filters,
+ sorts: view.sorts,
+ page: 0,
+ count: RECORDS_PER_PAGE,
+ userId: workspace.userId,
+ },
+ getNextPageInput(page, pages) {
+ if (page > pages.length) {
+ return undefined;
+ }
+
+ const lastPage = pages[page - 1];
+ if (lastPage.length < RECORDS_PER_PAGE) {
+ return undefined;
+ }
+
+ return {
+ type: 'record_list',
+ databaseId: database.id,
+ filters: filters,
+ sorts: view.sorts,
+ page: page,
+ count: RECORDS_PER_PAGE,
+ userId: workspace.userId,
+ };
+ },
+ });
- const records = data ?? [];
+ const records = data?.flatMap((page) => page) ?? [];
return (
<div className="mt-3 flex flex-col gap-2">
{records.map((record) => {
diff --git a/desktop/src/components/databases/calendars/calendar-view-grid.tsx b/desktop/src/components/databases/calendars/calendar-view-grid.tsx
index ef7f5d4b..1a1e5419 100644
--- a/desktop/src/components/databases/calendars/calendar-view-grid.tsx
+++ b/desktop/src/components/databases/calendars/calendar-view-grid.tsx
@@ -5,11 +5,13 @@ import { cn, getDisplayedDates, toUTCDate } from '@/lib/utils';
import { DayPicker, DayProps } from 'react-day-picker';
import { CalendarViewDay } from '@/components/databases/calendars/calendar-view-day';
import { CalendarViewNode, FieldNode, ViewFilter } from '@/types/databases';
-import { useRecordsQuery } from '@/queries/use-records-query';
+import { useInfiniteQuery } from '@/hooks/use-infinite-query';
import { useDatabase } from '@/contexts/database';
import { filterRecords } from '@/lib/databases';
import { useWorkspace } from '@/contexts/workspace';
+const RECORDS_PER_PAGE = 50;
+
interface CalendarViewGridProps {
view: CalendarViewNode;
field: FieldNode;
@@ -41,13 +43,43 @@ export const CalendarViewGrid = ({ view, field }: CalendarViewGridProps) => {
];
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useRecordsQuery(database.id, filters, view.sorts);
+ useInfiniteQuery({
+ initialPageInput: {
+ type: 'record_list',
+ databaseId: database.id,
+ filters: filters,
+ sorts: view.sorts,
+ page: 0,
+ count: RECORDS_PER_PAGE,
+ userId: workspace.userId,
+ },
+ getNextPageInput(page, pages) {
+ if (page > pages.length) {
+ return undefined;
+ }
+
+ const lastPage = pages[page - 1];
+ if (lastPage.length < RECORDS_PER_PAGE) {
+ return undefined;
+ }
+
+ return {
+ type: 'record_list',
+ databaseId: database.id,
+ filters: filters,
+ sorts: view.sorts,
+ page: page,
+ count: RECORDS_PER_PAGE,
+ userId: workspace.userId,
+ };
+ },
+ });
if (isPending) {
return null;
}
- const records = data ?? [];
+ const records = data?.flatMap((page) => page) ?? [];
return (
<DayPicker
showOutsideDays
diff --git a/desktop/src/components/databases/database-container-node.tsx b/desktop/src/components/databases/database-container-node.tsx
index fed9db81..1982c853 100644
--- a/desktop/src/components/databases/database-container-node.tsx
+++ b/desktop/src/components/databases/database-container-node.tsx
@@ -1,21 +1,28 @@
import React from 'react';
import { LocalNode } from '@/types/nodes';
-import { useDatabaseQuery } from '@/queries/use-database-query';
+import { useQuery } from '@/hooks/use-query';
import { Database } from '@/components/databases/database';
import { DatabaseViews } from '@/components/databases/database-views';
-import { useDatabaseViewsQuery } from '@/queries/use-database-views-query';
+import { useWorkspace } from '@/contexts/workspace';
interface DatabaseContainerNodeProps {
node: LocalNode;
}
export const DatabaseContainerNode = ({ node }: DatabaseContainerNodeProps) => {
- const { data: database, isPending: isDatabasePending } = useDatabaseQuery(
- node.id,
- );
- const { data: views, isPending: isViewsPending } = useDatabaseViewsQuery(
- node.id,
- );
+ const workspace = useWorkspace();
+
+ const { data: database, isPending: isDatabasePending } = useQuery({
+ type: 'database_get',
+ databaseId: node.id,
+ userId: workspace.userId,
+ });
+
+ const { data: views, isPending: isViewsPending } = useQuery({
+ type: 'database_view_list',
+ databaseId: node.id,
+ userId: workspace.userId,
+ });
if (isDatabasePending || isViewsPending) {
return null;
diff --git a/desktop/src/components/databases/database-create-dialog.tsx b/desktop/src/components/databases/database-create-dialog.tsx
index cb79bc2c..6ae7a0bd 100644
--- a/desktop/src/components/databases/database-create-dialog.tsx
+++ b/desktop/src/components/databases/database-create-dialog.tsx
@@ -22,7 +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 { useDatabaseCreateMutation } from '@/mutations/use-database-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -40,7 +40,7 @@ export const DatabaseCreateDialog = ({
onOpenChange,
}: DatabaseCreateDialogProps) => {
const workspace = useWorkspace();
- const { mutate, isPending } = useDatabaseCreateMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -55,16 +55,19 @@ export const DatabaseCreateDialog = ({
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(
- { spaceId, name: values.name },
- {
- onSuccess: (id) => {
- onOpenChange(false);
- form.reset();
- workspace.navigateToNode(id);
- },
+ mutate({
+ input: {
+ type: 'database_create',
+ spaceId: spaceId,
+ name: values.name,
+ userId: workspace.userId,
},
- );
+ onSuccess(output) {
+ onOpenChange(false);
+ form.reset();
+ workspace.navigateToNode(output.id);
+ },
+ });
};
return (
diff --git a/desktop/src/components/databases/fields/field-create-popover.tsx b/desktop/src/components/databases/fields/field-create-popover.tsx
index 2d2fbbce..6d58fcdb 100644
--- a/desktop/src/components/databases/fields/field-create-popover.tsx
+++ b/desktop/src/components/databases/fields/field-create-popover.tsx
@@ -23,7 +23,8 @@ import { FieldDataTypeSelect } from '@/components/databases/fields/field-type-se
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';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
const formSchema = z.object({
name: z.string(),
@@ -50,8 +51,11 @@ const formSchema = z.object({
export const FieldCreatePopover = () => {
const [open, setOpen] = React.useState(false);
+ const workspace = useWorkspace();
const database = useDatabase();
+ const { mutate, isPending } = useMutation();
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -60,27 +64,25 @@ export const FieldCreatePopover = () => {
},
});
- const { mutate, isPending } = useFieldCreateMutation();
-
const handleCancelClick = () => {
setOpen(false);
form.reset();
};
const handleSubmit = (values: z.infer<typeof formSchema>) => {
- mutate(
- {
+ mutate({
+ input: {
+ type: 'field_create',
databaseId: database.id,
name: values.name,
dataType: values.dataType,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setOpen(false);
- form.reset();
- },
+ onSuccess: () => {
+ setOpen(false);
+ form.reset();
},
- );
+ });
};
return (
diff --git a/desktop/src/components/databases/fields/field-delete-dialog.tsx b/desktop/src/components/databases/fields/field-delete-dialog.tsx
index 8a2644cd..f4a2266e 100644
--- a/desktop/src/components/databases/fields/field-delete-dialog.tsx
+++ b/desktop/src/components/databases/fields/field-delete-dialog.tsx
@@ -9,7 +9,8 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface FieldDeleteDialogProps {
id: string;
@@ -22,7 +23,8 @@ export const FieldDeleteDialog = ({
open,
onOpenChange,
}: FieldDeleteDialogProps) => {
- const { mutate, isPending } = useNodeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
@@ -42,8 +44,13 @@ export const FieldDeleteDialog = ({
variant="destructive"
disabled={isPending}
onClick={async () => {
- mutate(id, {
- onSuccess: () => {
+ mutate({
+ input: {
+ type: 'node_delete',
+ nodeId: id,
+ userId: workspace.userId,
+ },
+ onSuccess() {
onOpenChange(false);
},
});
diff --git a/desktop/src/components/databases/fields/field-rename-input.tsx b/desktop/src/components/databases/fields/field-rename-input.tsx
index 5d4b21d0..efc7fd39 100644
--- a/desktop/src/components/databases/fields/field-rename-input.tsx
+++ b/desktop/src/components/databases/fields/field-rename-input.tsx
@@ -1,14 +1,16 @@
import React from 'react';
import { FieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useWorkspace } from '@/contexts/workspace';
interface FieldRenameInputProps {
field: FieldNode;
}
export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
- const { mutate, isPending } = useNodeAttributeSetMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<div className="w-full p-1">
@@ -19,9 +21,13 @@ export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
if (newName === field.name) return;
mutate({
- nodeId: field.id,
- key: 'name',
- value: newName,
+ input: {
+ type: 'node_attribute_set',
+ nodeId: field.id,
+ attribute: 'name',
+ value: newName,
+ userId: workspace.userId,
+ },
});
}}
/>
diff --git a/desktop/src/components/databases/fields/select-field-options.tsx b/desktop/src/components/databases/fields/select-field-options.tsx
index 9f66c07a..898717b7 100644
--- a/desktop/src/components/databases/fields/select-field-options.tsx
+++ b/desktop/src/components/databases/fields/select-field-options.tsx
@@ -12,7 +12,8 @@ import { Icon } from '@/components/ui/icon';
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';
+import { useWorkspace } from '@/contexts/workspace';
+import { useMutation } from '@/hooks/use-mutation';
interface SelectFieldOptionsProps {
field: SelectFieldNode | MultiSelectFieldNode;
@@ -27,7 +28,8 @@ export const SelectFieldOptions = ({
onSelect,
allowAdd,
}: SelectFieldOptionsProps) => {
- const { mutate, isPending } = useSelectOptionCreateMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [inputValue, setInputValue] = React.useState('');
const [color, setColor] = React.useState(getRandomSelectOptionColor());
@@ -106,20 +108,20 @@ export const SelectFieldOptions = ({
return;
}
- mutate(
- {
+ mutate({
+ input: {
+ type: 'select_option_create',
fieldId: field.id,
name: inputValue.trim(),
color,
+ userId: workspace.userId,
},
- {
- onSuccess: (id) => {
- setInputValue('');
- setColor(getRandomSelectOptionColor());
- onSelect(id);
- },
+ onSuccess(output) {
+ setInputValue('');
+ setColor(getRandomSelectOptionColor());
+ onSelect(output.id);
},
- );
+ });
}}
className="flex flex-row items-center gap-2"
>
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 683cbac9..a119a944 100644
--- a/desktop/src/components/databases/fields/select-option-delete-dialog.tsx
+++ b/desktop/src/components/databases/fields/select-option-delete-dialog.tsx
@@ -9,7 +9,8 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface SelectOptionDeleteDialogProps {
id: string;
@@ -22,7 +23,8 @@ export const SelectOptionDeleteDialog = ({
open,
onOpenChange,
}: SelectOptionDeleteDialogProps) => {
- const { mutate, isPending } = useNodeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
@@ -41,10 +43,12 @@ export const SelectOptionDeleteDialog = ({
<Button
variant="destructive"
disabled={isPending}
- onClick={async () => {
- mutate(id, {
- onSuccess: () => {
- onOpenChange(false);
+ onClick={() => {
+ mutate({
+ input: {
+ type: 'node_delete',
+ nodeId: id,
+ userId: workspace.userId,
},
});
}}
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 c1c00948..609698e6 100644
--- a/desktop/src/components/databases/fields/select-option-settings-popover.tsx
+++ b/desktop/src/components/databases/fields/select-option-settings-popover.tsx
@@ -11,8 +11,9 @@ import { selectOptionColors } from '@/lib/databases';
import { cn } from '@/lib/utils';
import { SelectOptionNode } from '@/types/databases';
import { SelectOptionDeleteDialog } from '@/components/databases/fields/select-option-delete-dialog';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useWorkspace } from '@/contexts/workspace';
interface SelectOptionSettingsPopoverProps {
option: SelectOptionNode;
@@ -21,7 +22,8 @@ interface SelectOptionSettingsPopoverProps {
export const SelectOptionSettingsPopover = ({
option,
}: SelectOptionSettingsPopoverProps) => {
- const { mutate, isPending } = useNodeAttributeSetMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [openSetttingsPopover, setOpenSetttingsPopover] = React.useState(false);
const [openDeleteDialog, setOpenDeleteDialog] = React.useState(false);
@@ -45,9 +47,13 @@ export const SelectOptionSettingsPopover = ({
if (newName === option.name) return;
mutate({
- nodeId: option.id,
- key: 'name',
- value: newName,
+ input: {
+ type: 'node_attribute_set',
+ nodeId: option.id,
+ attribute: 'name',
+ value: newName,
+ userId: workspace.userId,
+ },
});
}}
/>
@@ -61,10 +67,15 @@ export const SelectOptionSettingsPopover = ({
className="flex cursor-pointer flex-row items-center gap-2 rounded-md p-1 hover:bg-gray-100"
onClick={() => {
if (isPending) return;
+
mutate({
- nodeId: option.id,
- key: 'color',
- value: color.value,
+ input: {
+ type: 'node_attribute_set',
+ nodeId: option.id,
+ attribute: 'color',
+ value: color.value,
+ userId: workspace.userId,
+ },
});
}}
>
diff --git a/desktop/src/components/databases/search/view-search-provider.tsx b/desktop/src/components/databases/search/view-search-provider.tsx
index 6b9f05aa..e14b93b1 100644
--- a/desktop/src/components/databases/search/view-search-provider.tsx
+++ b/desktop/src/components/databases/search/view-search-provider.tsx
@@ -4,7 +4,8 @@ import { ViewFieldFilter, ViewFilter, ViewSort } from '@/types/databases';
import { useDatabase } from '@/contexts/database';
import { NeuronId } from '@/lib/id';
import { getFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface ViewSearchProviderProps {
id: string;
@@ -19,9 +20,9 @@ export const ViewSearchProvider = ({
sorts,
children,
}: ViewSearchProviderProps) => {
+ const workspace = useWorkspace();
const database = useDatabase();
- const { mutate: setNodeAttribute, isPending: isSetingNodeAttribute } =
- useNodeAttributeSetMutation();
+ const { mutate, isPending } = useMutation();
const [isSearchBarOpened, setIsSearchBarOpened] = React.useState(false);
const [isSortsOpened, setIsSortsOpened] = React.useState(false);
@@ -35,7 +36,7 @@ export const ViewSearchProvider = ({
id,
filters: filters,
sorts: sorts,
- isSaving: isSetingNodeAttribute,
+ isSaving: isPending,
isSearchBarOpened: isSearchBarOpened,
isSortsOpened: isSortsOpened,
isFieldFilterOpened: (fieldId: string) =>
@@ -67,19 +68,19 @@ export const ViewSearchProvider = ({
};
const newFilters = [...filters, filter];
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: id,
- key: 'filters',
+ attribute: 'filters',
value: newFilters,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setOpenedFieldFilters((prev) => [...prev, filter.id]);
- setIsSearchBarOpened(true);
- },
+ onSuccess() {
+ setOpenedFieldFilters((prev) => [...prev, filter.id]);
+ setIsSearchBarOpened(true);
},
- );
+ });
},
updateFilter: (filterId: string, newFilter: ViewFieldFilter) => {
const newFilters = filters.map((filter) =>
@@ -88,37 +89,33 @@ export const ViewSearchProvider = ({
: filter,
);
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: id,
- key: 'filters',
+ attribute: 'filters',
value: newFilters,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setIsSearchBarOpened(true);
- },
+ onSuccess() {
+ setIsSearchBarOpened(true);
},
- );
+ });
},
removeFilter: (filterId: string) => {
const newFilters = filters.filter((filter) => filter.id !== filterId);
-
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: id,
- key: 'filters',
+ attribute: 'filters',
value: newFilters,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setOpenedFieldFilters((prev) =>
- prev.filter((id) => id !== filterId),
- );
- setIsSearchBarOpened(true);
- },
+ onSuccess() {
+ setIsSearchBarOpened(true);
},
- );
+ });
},
initFieldSort: (fieldId: string) => {
const field = database.fields.find((field) => field.id === fieldId);
@@ -145,54 +142,54 @@ export const ViewSearchProvider = ({
};
const newSorts = [...sorts, sort];
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: id,
- key: 'sorts',
+ attribute: 'sorts',
value: newSorts,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setIsSearchBarOpened(true);
- setIsSortsOpened(true);
- },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ setIsSortsOpened(true);
},
- );
+ });
},
updateSort: (sortId: string, newSort: ViewSort) => {
const newSorts = sorts.map((sort) =>
sort.id === sortId ? newSort : sort,
);
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: id,
- key: 'sorts',
+ attribute: 'sorts',
value: newSorts,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setIsSortsOpened(true);
- setIsSearchBarOpened(true);
- },
+ onSuccess() {
+ setIsSearchBarOpened(true);
+ setIsSortsOpened(true);
},
- );
+ });
},
removeSort: (sortId: string) => {
const newSorts = sorts.filter((sort) => sort.id !== sortId);
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: id,
- key: 'sorts',
+ attribute: 'sorts',
value: newSorts,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setIsSearchBarOpened(true);
- },
+ onSuccess() {
+ setIsSearchBarOpened(true);
},
- );
+ });
},
openSearchBar: () => setIsSearchBarOpened(true),
closeSearchBar: () => setIsSearchBarOpened(false),
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 4872af0d..0dc0b019 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,8 +1,8 @@
import React from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { BooleanFieldNode, RecordNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewBooleanCellProps {
record: RecordNode;
@@ -13,12 +13,8 @@ export const TableViewBooleanCell = ({
record,
field,
}: TableViewBooleanCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
-
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
const [input, setInput] = React.useState<boolean>(
@@ -42,15 +38,23 @@ export const TableViewBooleanCell = ({
setInput(e.valueOf());
const checked = e.valueOf();
if (checked) {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: checked,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: checked,
+ userId: workspace.userId,
+ },
});
} else {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
}
}
diff --git a/desktop/src/components/databases/tables/cells/table-view-date-cell.tsx b/desktop/src/components/databases/tables/cells/table-view-date-cell.tsx
index b603ae57..59860d24 100644
--- a/desktop/src/components/databases/tables/cells/table-view-date-cell.tsx
+++ b/desktop/src/components/databases/tables/cells/table-view-date-cell.tsx
@@ -1,8 +1,8 @@
import React from 'react';
-import { RecordNode, EmailFieldNode, DateFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { RecordNode, DateFieldNode } from '@/types/databases';
+import { useMutation } from '@/hooks/use-mutation';
import { DatePicker } from '@/components/ui/date-picker';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewDateCellProps {
record: RecordNode;
@@ -13,13 +13,9 @@ export const TableViewDateCell = ({
record,
field,
}: TableViewDateCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
-
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<DatePicker
@@ -29,15 +25,23 @@ export const TableViewDateCell = ({
if (!canEdit) return;
if (newValue === null || newValue === undefined) {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue.toISOString(),
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue.toISOString(),
+ userId: workspace.userId,
+ },
});
}
}}
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 4889e4e3..292751b2 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,8 +1,8 @@
import React from 'react';
import { RecordNode, EmailFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewEmailCellProps {
record: RecordNode;
@@ -13,13 +13,10 @@ export const TableViewEmailCell = ({
record,
field,
}: TableViewEmailCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
@@ -30,15 +27,23 @@ export const TableViewEmailCell = ({
if (!canEdit) return;
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
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 0976fe41..bb6aa6e4 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
@@ -7,8 +7,8 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewMultiSelectCellProps {
record: RecordNode;
@@ -19,12 +19,8 @@ export const TableViewMultiSelectCell = ({
record,
field,
}: TableViewMultiSelectCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
-
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState(
@@ -62,17 +58,25 @@ export const TableViewMultiSelectCell = ({
if (selectedValues.includes(id)) {
setSelectedValues(selectedValues.filter((v) => v !== id));
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
const values = [...selectedValues, id];
setSelectedValues(values);
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: values,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: values,
+ userId: workspace.userId,
+ },
});
}
}}
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 a1d352d7..afbe2b5d 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,9 +1,9 @@
import React from 'react';
import { RecordNode } from '@/types/databases';
import { NumberFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartNumberInput } from '@/components/ui/smart-number-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewNumberCellProps {
record: RecordNode;
@@ -14,13 +14,10 @@ export const TableViewNumberCell = ({
record,
field,
}: TableViewNumberCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartNumberInput
@@ -35,15 +32,23 @@ export const TableViewNumberCell = ({
}
if (newValue === null) {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
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 fc36b3eb..eaf1bb9b 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,8 +1,8 @@
import React from 'react';
import { RecordNode, PhoneFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewPhoneCellProps {
record: RecordNode;
@@ -13,13 +13,10 @@ export const TableViewPhoneCell = ({
record,
field,
}: TableViewPhoneCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
@@ -34,15 +31,23 @@ export const TableViewPhoneCell = ({
}
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
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 43d34003..a29c5ea6 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
@@ -7,8 +7,8 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewSelectCellProps {
record: RecordNode;
@@ -19,12 +19,8 @@ export const TableViewSelectCell = ({
record,
field,
}: TableViewSelectCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
-
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(
@@ -65,23 +61,27 @@ export const TableViewSelectCell = ({
if (selectedValue === id) {
setSelectedValue('');
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: record.id,
- key: field.id,
+ attribute: field.id,
value: id,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setOpen(false);
- },
+ onSuccess() {
+ setOpen(false);
},
- );
+ });
}
setSelectedValue(id);
}}
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 6204e6e7..d09e1b9f 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,8 +1,8 @@
import React from 'react';
import { RecordNode, TextFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewTextCellProps {
record: RecordNode;
@@ -13,13 +13,10 @@ export const TableViewTextCell = ({
record,
field,
}: TableViewTextCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
@@ -34,15 +31,23 @@ export const TableViewTextCell = ({
}
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
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 1b82dec4..33f951b5 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
@@ -7,9 +7,9 @@ import {
HoverCardTrigger,
} from '@/components/ui/hover-card';
import { Icon } from '@/components/ui/icon';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewUrlCellProps {
record: RecordNode;
@@ -17,13 +17,10 @@ interface TableViewUrlCellProps {
}
export const TableViewUrlCell = ({ record, field }: TableViewUrlCellProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const text = record.attributes[field.id];
const isUrl = text.length > 0 && isValidUrl(text);
@@ -42,15 +39,23 @@ export const TableViewUrlCell = ({ record, field }: TableViewUrlCellProps) => {
}
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/databases/tables/table-view-body.tsx b/desktop/src/components/databases/tables/table-view-body.tsx
index 0512f52f..e385892d 100644
--- a/desktop/src/components/databases/tables/table-view-body.tsx
+++ b/desktop/src/components/databases/tables/table-view-body.tsx
@@ -2,18 +2,52 @@ import React from 'react';
import { useDatabase } from '@/contexts/database';
import { TableViewRow } from '@/components/databases/tables/table-view-row';
import { TableViewEmptyPlaceholder } from '@/components/databases/tables/table-view-empty-placeholder';
-import { TableViewLoadMoreRow } from './table-view-load-more-row';
-import { useRecordsQuery } from '@/queries/use-records-query';
+import { TableViewLoadMoreRow } from '@/components/databases/tables/table-view-load-more-row';
+import { useInfiniteQuery } from '@/hooks/use-infinite-query';
import { useViewSearch } from '@/contexts/view-search';
+import { useWorkspace } from '@/contexts/workspace';
+
+const RECORDS_PER_PAGE = 50;
export const TableViewBody = () => {
+ const workspace = useWorkspace();
const database = useDatabase();
const viewSearch = useViewSearch();
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useRecordsQuery(database.id, viewSearch.filters, viewSearch.sorts);
+ useInfiniteQuery({
+ initialPageInput: {
+ type: 'record_list',
+ databaseId: database.id,
+ filters: viewSearch.filters,
+ sorts: viewSearch.sorts,
+ page: 0,
+ count: RECORDS_PER_PAGE,
+ userId: workspace.userId,
+ },
+ getNextPageInput(page, pages) {
+ if (page > pages.length) {
+ return undefined;
+ }
+
+ const lastPage = pages[page - 1];
+ if (lastPage.length < RECORDS_PER_PAGE) {
+ return undefined;
+ }
+
+ return {
+ type: 'record_list',
+ databaseId: database.id,
+ filters: viewSearch.filters,
+ sorts: viewSearch.sorts,
+ page: page,
+ count: RECORDS_PER_PAGE,
+ userId: workspace.userId,
+ };
+ },
+ });
- const records = data ?? [];
+ const records = data?.flatMap((page) => page) ?? [];
return (
<div className="border-t">
{records.length === 0 && <TableViewEmptyPlaceholder />}
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 19da3e75..8b32c2bf 100644
--- a/desktop/src/components/databases/tables/table-view-name-cell.tsx
+++ b/desktop/src/components/databases/tables/table-view-name-cell.tsx
@@ -4,7 +4,7 @@ import { Icon } from '@/components/ui/icon';
import { useWorkspace } from '@/contexts/workspace';
import { Spinner } from '@/components/ui/spinner';
import { RecordNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
interface NameEditorProps {
initialValue: string;
@@ -54,23 +54,23 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
const workspace = useWorkspace();
const [isEditing, setIsEditing] = React.useState(false);
- const { mutate, isPending } = useNodeAttributeSetMutation();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
const hasName = record.name && record.name.length > 0;
const handleSave = (newName: string) => {
- mutate(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: record.id,
- key: 'name',
+ attribute: 'name',
value: newName,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setIsEditing(false);
- },
+ onSuccess() {
+ setIsEditing(false);
},
- );
+ });
};
return (
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 2d43251c..424859f5 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,13 +1,13 @@
import React from 'react';
import { Icon } from '@/components/ui/icon';
import { useDatabase } from '@/contexts/database';
-import { useRecordCreateMutation } from '@/mutations/use-record-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { useWorkspace } from '@/contexts/workspace';
export const TableViewRecordCreateRow = () => {
const workspace = useWorkspace();
const database = useDatabase();
- const { mutate, isPending } = useRecordCreateMutation();
+ const { mutate, isPending } = useMutation();
return (
<button
@@ -15,16 +15,16 @@ 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({
+ input: {
+ type: 'record_create',
databaseId: database.id,
+ userId: workspace.userId,
},
- {
- onSuccess: (recordId) => {
- workspace.openModal(recordId);
- },
+ onSuccess: (output) => {
+ workspace.openModal(output.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 7f6b07f7..aef197ce 100644
--- a/desktop/src/components/databases/tables/table-view-row.tsx
+++ b/desktop/src/components/databases/tables/table-view-row.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import { TableViewNameCell } from '@/components/databases/tables/table-view-name-cell';
-import { TableViewFieldCell } from './table-view-field-cell';
+import { TableViewFieldCell } from '@/components/databases/tables/table-view-field-cell';
import { RecordNode } from '@/types/databases';
import { useTableView } from '@/contexts/table-view';
diff --git a/desktop/src/components/databases/tables/table-view-settings-popover.tsx b/desktop/src/components/databases/tables/table-view-settings-popover.tsx
index cb09b1ee..6ad18790 100644
--- a/desktop/src/components/databases/tables/table-view-settings-popover.tsx
+++ b/desktop/src/components/databases/tables/table-view-settings-popover.tsx
@@ -16,14 +16,16 @@ import {
TooltipTrigger,
} from '@/components/ui/tooltip';
import { FieldDeleteDialog } from '@/components/databases/fields/field-delete-dialog';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { ViewDeleteDialog } from '@/components/databases/view-delete-dialog';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useWorkspace } from '@/contexts/workspace';
export const TableViewSettingsPopover = () => {
+ const workspace = useWorkspace();
const tableView = useTableView();
const database = useDatabase();
- const { mutate, isPending } = useNodeAttributeSetMutation();
+ const { mutate, isPending } = useMutation();
const [open, setOpen] = React.useState(false);
const [openDelete, setOpenDelete] = React.useState(false);
@@ -49,9 +51,13 @@ export const TableViewSettingsPopover = () => {
if (newName === tableView.name) return;
mutate({
- nodeId: tableView.id,
- key: 'name',
- value: newName,
+ input: {
+ type: 'node_attribute_set',
+ nodeId: tableView.id,
+ attribute: 'name',
+ value: newName,
+ userId: workspace.userId,
+ },
});
}}
/>
diff --git a/desktop/src/components/databases/tables/table-view.tsx b/desktop/src/components/databases/tables/table-view.tsx
index 0c3b3b50..7e048f4f 100644
--- a/desktop/src/components/databases/tables/table-view.tsx
+++ b/desktop/src/components/databases/tables/table-view.tsx
@@ -10,22 +10,21 @@ import { ViewTabs } from '@/components/databases/view-tabs';
import { TableViewSettingsPopover } from '@/components/databases/tables/table-view-settings-popover';
import { getDefaultFieldWidth, getDefaultNameWidth } from '@/lib/databases';
import { generateNodeIndex } from '@/lib/nodes';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { ViewSearchBar } from '@/components/databases/search/view-search-bar';
import { ViewFilterButton } from '@/components/databases/search/view-filter-button';
import { ViewSortButton } from '@/components/databases/search/view-sort-button';
import { ViewSearchProvider } from '@/components/databases/search/view-search-provider';
+import { useWorkspace } from '@/contexts/workspace';
interface TableViewProps {
node: TableViewNode;
}
export const TableView = ({ node }: TableViewProps) => {
+ const workspace = useWorkspace();
const database = useDatabase();
-
- const { mutate: setNodeAttribute } = useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute } = useNodeAttributeDeleteMutation();
+ const { mutate } = useMutation();
const [hiddenFields, setHiddenFields] = React.useState<string[]>(
node.hiddenFields ?? [],
@@ -71,10 +70,14 @@ export const TableView = ({ node }: TableViewProps) => {
const newHiddenFields = [...hiddenFields, id];
setHiddenFields(newHiddenFields);
- setNodeAttribute({
- nodeId: node.id,
- key: 'hiddenFields',
- value: newHiddenFields,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: node.id,
+ attribute: 'hiddenFields',
+ value: newHiddenFields,
+ userId: workspace.userId,
+ },
});
},
showField: (id: string) => {
@@ -84,19 +87,28 @@ export const TableView = ({ node }: TableViewProps) => {
const newHiddenFields = hiddenFields.filter((f) => f !== id);
setHiddenFields(newHiddenFields);
- deleteNodeAttribute({
- nodeId: node.id,
- key: 'hiddenFields',
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: node.id,
+ attribute: 'hiddenFields',
+ value: newHiddenFields,
+ userId: workspace.userId,
+ },
});
},
isHiddenField: (id: string) => hiddenFields.includes(id),
getNameWidth: () => nameWidth,
resizeName: (width: number) => {
setNameWidth(width);
- setNodeAttribute({
- nodeId: node.id,
- key: 'nameWidth',
- value: width,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: node.id,
+ attribute: 'nameWidth',
+ value: width,
+ userId: workspace.userId,
+ },
});
},
getFieldWidth: (id: string, type: FieldDataType) => {
@@ -104,10 +116,14 @@ export const TableView = ({ node }: TableViewProps) => {
},
resizeField: (id, width) => {
setFieldWidths({ ...fieldWidths, [id]: width });
- setNodeAttribute({
- nodeId: node.id,
- key: 'fieldWidths',
- value: { ...fieldWidths, [id]: width },
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: node.id,
+ attribute: 'fieldWidths',
+ value: { ...fieldWidths, [id]: width },
+ userId: workspace.userId,
+ },
});
},
moveField: (id, after) => {
@@ -178,10 +194,14 @@ export const TableView = ({ node }: TableViewProps) => {
...fieldIndexes,
[id]: newIndex,
});
- setNodeAttribute({
- nodeId: node.id,
- key: 'fieldIndexes',
- value: { ...fieldIndexes, [id]: newIndex },
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: node.id,
+ attribute: 'fieldIndexes',
+ value: { ...fieldIndexes, [id]: newIndex },
+ userId: workspace.userId,
+ },
});
},
}}
diff --git a/desktop/src/components/databases/view-create-dialog.tsx b/desktop/src/components/databases/view-create-dialog.tsx
index 3702a2fe..59905c0c 100644
--- a/desktop/src/components/databases/view-create-dialog.tsx
+++ b/desktop/src/components/databases/view-create-dialog.tsx
@@ -23,12 +23,11 @@ import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { cn } from '@/lib/utils';
import { Icon } from '@/components/ui/icon';
-import { useTableViewCreateMutation } from '@/mutations/use-table-view-create-mutation';
-import { useBoardViewCreateMutation } from '@/mutations/use-board-view-create-mutation';
-import { useCalendarViewCreateMutation } from '@/mutations/use-calendar-view-create-mutation';
import { useDatabase } from '@/contexts/database';
import { FieldSelect } from '@/components/databases/fields/field-select';
import { toast } from '@/components/ui/use-toast';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -69,15 +68,9 @@ export const ViewCreateDialog = ({
open,
onOpenChange,
}: ViewCreateDialogProps) => {
+ const workspace = useWorkspace();
const database = useDatabase();
- const tableViewCreateMutation = useTableViewCreateMutation();
- const boardViewCreateMutation = useBoardViewCreateMutation();
- const calendarViewCreateMutation = useCalendarViewCreateMutation();
-
- const isPending =
- tableViewCreateMutation.isPending ||
- boardViewCreateMutation.isPending ||
- calendarViewCreateMutation.isPending;
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -99,18 +92,18 @@ export const ViewCreateDialog = ({
}
if (values.type === 'TABLE') {
- tableViewCreateMutation.mutate(
- {
+ mutate({
+ input: {
+ type: 'table_view_create',
databaseId: database.id,
name: values.name,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- form.reset();
- onOpenChange(false);
- },
+ onSuccess() {
+ form.reset();
+ onOpenChange(false);
},
- );
+ });
} else if (values.type === 'BOARD') {
if (!values.groupBy) {
toast({
@@ -122,19 +115,19 @@ export const ViewCreateDialog = ({
return;
}
- boardViewCreateMutation.mutate(
- {
+ mutate({
+ input: {
+ type: 'board_view_create',
databaseId: database.id,
name: values.name,
groupBy: values.groupBy,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- form.reset();
- onOpenChange(false);
- },
+ onSuccess() {
+ form.reset();
+ onOpenChange(false);
},
- );
+ });
} else if (values.type === 'CALENDAR') {
if (!values.groupBy) {
toast({
@@ -146,19 +139,19 @@ export const ViewCreateDialog = ({
return;
}
- calendarViewCreateMutation.mutate(
- {
+ mutate({
+ input: {
+ type: 'calendar_view_create',
databaseId: database.id,
name: values.name,
groupBy: values.groupBy,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- form.reset();
- onOpenChange(false);
- },
+ onSuccess() {
+ form.reset();
+ onOpenChange(false);
},
- );
+ });
}
};
diff --git a/desktop/src/components/databases/view-delete-dialog.tsx b/desktop/src/components/databases/view-delete-dialog.tsx
index 67b38dd9..02662173 100644
--- a/desktop/src/components/databases/view-delete-dialog.tsx
+++ b/desktop/src/components/databases/view-delete-dialog.tsx
@@ -9,7 +9,8 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface ViewDeleteDialogProps {
id: string;
@@ -22,7 +23,8 @@ export const ViewDeleteDialog = ({
open,
onOpenChange,
}: ViewDeleteDialogProps) => {
- const { mutate, isPending } = useNodeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
@@ -41,9 +43,14 @@ export const ViewDeleteDialog = ({
<Button
variant="destructive"
disabled={isPending}
- onClick={async () => {
- mutate(id, {
- onSuccess: () => {
+ onClick={() => {
+ mutate({
+ input: {
+ type: 'node_delete',
+ nodeId: id,
+ userId: workspace.userId,
+ },
+ onSuccess() {
onOpenChange(false);
},
});
diff --git a/desktop/src/components/documents/document-editor.tsx b/desktop/src/components/documents/document-editor.tsx
index 9da26a7d..b28845fe 100644
--- a/desktop/src/components/documents/document-editor.tsx
+++ b/desktop/src/components/documents/document-editor.tsx
@@ -61,7 +61,7 @@ interface DocumentEditorProps {
export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {
const workspace = useWorkspace();
const observer = React.useMemo<EditorObserver>(
- () => new EditorObserver(workspace, workspace.schema, node, nodes),
+ () => new EditorObserver(workspace, workspace as any, node, nodes),
[node.id],
);
diff --git a/desktop/src/components/documents/document.tsx b/desktop/src/components/documents/document.tsx
index a9e96714..3a262b0b 100644
--- a/desktop/src/components/documents/document.tsx
+++ b/desktop/src/components/documents/document.tsx
@@ -1,18 +1,24 @@
import React from 'react';
import { LocalNode } from '@/types/nodes';
-import { DocumentEditor } from './document-editor';
-import { useDocumentQuery } from '@/queries/use-document-query';
+import { DocumentEditor } from '@/components/documents/document-editor';
+import { useQuery } from '@/hooks/use-query';
+import { useWorkspace } from '@/contexts/workspace';
interface DocumentProps {
node: LocalNode;
}
export const Document = ({ node }: DocumentProps) => {
- const { data, isPending } = useDocumentQuery(node.id);
+ const workspace = useWorkspace();
+ const { data, isPending } = useQuery({
+ type: 'document_get',
+ nodeId: node.id,
+ userId: workspace.userId,
+ });
if (isPending) {
return null;
}
- return <DocumentEditor key={node.id} node={node} nodes={data} />;
+ return <DocumentEditor key={node.id} node={node} nodes={data?.nodes} />;
};
diff --git a/desktop/src/components/messages/message-create.tsx b/desktop/src/components/messages/message-create.tsx
index a509a143..46b019c7 100644
--- a/desktop/src/components/messages/message-create.tsx
+++ b/desktop/src/components/messages/message-create.tsx
@@ -1,20 +1,31 @@
import React from 'react';
import { MessageEditor } from '@/components/messages/message-editor';
-import { useMessageCreateMutation } from '@/mutations/use-message-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface MessageCreateProps {
conversationId: string;
}
export const MessageCreate = ({ conversationId }: MessageCreateProps) => {
- const { mutate, isPending } = useMessageCreateMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<div className="container mt-1 px-10">
<div className="flex flex-col">
<MessageEditor
conversationId={conversationId}
- onSubmit={(content) => mutate({ conversationId, content })}
+ onSubmit={(content) => {
+ mutate({
+ input: {
+ type: 'message_create',
+ conversationId: conversationId,
+ content: content,
+ userId: workspace.userId,
+ },
+ });
+ }}
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 756bc27e..cffba7f3 100644
--- a/desktop/src/components/messages/message-delete-button.tsx
+++ b/desktop/src/components/messages/message-delete-button.tsx
@@ -10,15 +10,17 @@ import {
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface MessageDeleteButtonProps {
id: string;
}
export const MessageDeleteButton = ({ id }: MessageDeleteButtonProps) => {
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [showDeleteModal, setShowDeleteModal] = React.useState(false);
- const { mutate, isPending } = useNodeDeleteMutation();
return (
<React.Fragment>
@@ -39,9 +41,14 @@ export const MessageDeleteButton = ({ id }: MessageDeleteButtonProps) => {
<Button
variant="destructive"
disabled={isPending}
- onClick={async () => {
- mutate(id, {
- onSuccess: () => {
+ onClick={() => {
+ mutate({
+ input: {
+ type: 'node_delete',
+ nodeId: id,
+ userId: workspace.userId,
+ },
+ onSuccess() {
setShowDeleteModal(false);
},
});
diff --git a/desktop/src/components/messages/message-list.tsx b/desktop/src/components/messages/message-list.tsx
index 2f4f3f44..0a14f054 100644
--- a/desktop/src/components/messages/message-list.tsx
+++ b/desktop/src/components/messages/message-list.tsx
@@ -1,25 +1,60 @@
import React from 'react';
import { InView } from 'react-intersection-observer';
import { Message } from '@/components/messages/message';
-import { useMessagesQuery } from '@/queries/use-messages-query';
+import { useInfiniteQuery } from '@/hooks/use-infinite-query';
+import { useWorkspace } from '@/contexts/workspace';
+import { compareString } from '@/lib/utils';
interface MessageListProps {
conversationId: string;
onLastMessageIdChange: (id: string) => void;
}
+const MESSAGES_PER_PAGE = 50;
+
export const MessageList = ({
conversationId,
onLastMessageIdChange,
}: MessageListProps) => {
+ const workspace = useWorkspace();
const lastMessageId = React.useRef<string | null>(null);
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useMessagesQuery(conversationId);
+ useInfiniteQuery({
+ initialPageInput: {
+ type: 'message_list',
+ conversationId: conversationId,
+ userId: workspace.userId,
+ page: 0,
+ count: MESSAGES_PER_PAGE,
+ },
+ getNextPageInput(page, pages) {
+ if (page > pages.length) {
+ return undefined;
+ }
+
+ const lastPage = pages[page - 1];
+ if (lastPage.length < MESSAGES_PER_PAGE) {
+ return undefined;
+ }
+
+ return {
+ type: 'message_list',
+ conversationId: conversationId,
+ userId: workspace.userId,
+ page: page,
+ count: MESSAGES_PER_PAGE,
+ };
+ },
+ });
+
+ const messages = (data?.flatMap((page) => page) ?? []).sort((a, b) =>
+ compareString(a.id, b.id),
+ );
React.useEffect(() => {
- if (data?.length > 0) {
- const lastMessage = data[data.length - 1];
+ if (messages.length > 0) {
+ const lastMessage = messages[messages.length - 1];
if (lastMessage.id !== lastMessageId.current) {
lastMessageId.current = lastMessage.id;
onLastMessageIdChange(lastMessageId.current);
@@ -41,8 +76,8 @@ export const MessageList = ({
}
}}
></InView>
- {data.map((message, index) => {
- const previousMessage = index > 0 ? data[index - 1] : null;
+ {messages.map((message, index) => {
+ const previousMessage = index > 0 ? messages[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 59ecf4c1..8b371b74 100644
--- a/desktop/src/components/messages/message.tsx
+++ b/desktop/src/components/messages/message.tsx
@@ -13,8 +13,8 @@ import { MessageDeleteButton } from '@/components/messages/message-delete-button
import { NodeRenderer } from '@/editor/renderers/node';
import { MessageNode } from '@/types/messages';
import { MessageReactions } from '@/components/messages/message-reactions';
-import { useReactionCreateMutation } from '@/mutations/use-reaction-create-mutation';
-import { useReactionDeleteMutation } from '@/mutations/use-reaction-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface MessageProps {
message: MessageNode;
@@ -40,10 +40,8 @@ const shouldDisplayUserInfo = (
};
export const Message = ({ message, previousMessage }: MessageProps) => {
- const { mutate: createReaction, isPending: isCreatingReaction } =
- useReactionCreateMutation();
- const { mutate: deleteReaction, isPending: isDeletingReaction } =
- useReactionDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
if (!message.content || message.content.length === 0) {
return null;
@@ -106,11 +104,18 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
<li className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200">
<MessageReactionCreatePopover
onReactionClick={(reaction) => {
- if (isCreatingReaction || isDeletingReaction) {
+ if (isPending) {
return;
}
- createReaction({ nodeId: message.id, reaction });
+ mutate({
+ input: {
+ type: 'node_reaction_create',
+ nodeId: message.id,
+ userId: workspace.userId,
+ reaction,
+ },
+ });
}}
/>
</li>
@@ -132,14 +137,28 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
<MessageReactions
message={message}
onReactionClick={(reaction) => {
- if (isCreatingReaction || isDeletingReaction) {
+ if (isPending) {
return;
}
if (message.userReactions.includes(reaction)) {
- deleteReaction({ nodeId: message.id, reaction });
+ mutate({
+ input: {
+ type: 'node_reaction_delete',
+ nodeId: message.id,
+ userId: workspace.userId,
+ reaction,
+ },
+ });
} else {
- createReaction({ nodeId: message.id, reaction });
+ mutate({
+ input: {
+ type: 'node_reaction_create',
+ nodeId: message.id,
+ userId: workspace.userId,
+ reaction,
+ },
+ });
}
}}
/>
diff --git a/desktop/src/components/pages/page-create-dialog.tsx b/desktop/src/components/pages/page-create-dialog.tsx
index 3a4cba5c..fb64a0ef 100644
--- a/desktop/src/components/pages/page-create-dialog.tsx
+++ b/desktop/src/components/pages/page-create-dialog.tsx
@@ -22,7 +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 { usePageCreateMutation } from '@/mutations/use-page-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -40,7 +40,7 @@ export const PageCreateDialog = ({
onOpenChange,
}: PageCreateDialogProps) => {
const workspace = useWorkspace();
- const { mutate, isPending } = usePageCreateMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -55,16 +55,19 @@ export const PageCreateDialog = ({
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(
- { spaceId, name: values.name },
- {
- onSuccess: (id) => {
- onOpenChange(false);
- form.reset();
- workspace.navigateToNode(id);
- },
+ mutate({
+ input: {
+ type: 'page_create',
+ spaceId: spaceId,
+ name: values.name,
+ userId: workspace.userId,
},
- );
+ onSuccess(output) {
+ onOpenChange(false);
+ form.reset();
+ workspace.navigateToNode(output.id);
+ },
+ });
};
return (
diff --git a/desktop/src/components/records/record-container-node.tsx b/desktop/src/components/records/record-container-node.tsx
index 5021e482..70d32527 100644
--- a/desktop/src/components/records/record-container-node.tsx
+++ b/desktop/src/components/records/record-container-node.tsx
@@ -1,22 +1,31 @@
import React from 'react';
-import { useDatabaseQuery } from '@/queries/use-database-query';
-import { useRecordQuery } from '@/queries/use-record-query';
+import { useQuery } from '@/hooks/use-query';
import { LocalNode } from '@/types/nodes';
import { Database } from '@/components/databases/database';
import { RecordAttributes } from '@/components/records/record-attributes';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Document } from '@/components/documents/document';
import { Separator } from '@/components/ui/separator';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordContainerNodeProps {
node: LocalNode;
}
export const RecordContainerNode = ({ node }: RecordContainerNodeProps) => {
- const { data: record, isPending: isRecordPending } = useRecordQuery(node.id);
- const { data: database, isPending: isDatabasePending } = useDatabaseQuery(
- node.parentId,
- );
+ const workspace = useWorkspace();
+
+ const { data: record, isPending: isRecordPending } = useQuery({
+ type: 'record_get',
+ recordId: node.id,
+ userId: workspace.userId,
+ });
+
+ const { data: database, isPending: isDatabasePending } = useQuery({
+ type: 'database_get',
+ databaseId: node.parentId,
+ userId: workspace.userId,
+ });
if (isRecordPending || isDatabasePending) {
return null;
diff --git a/desktop/src/components/records/record-name.tsx b/desktop/src/components/records/record-name.tsx
index 35d59a92..f6386019 100644
--- a/desktop/src/components/records/record-name.tsx
+++ b/desktop/src/components/records/record-name.tsx
@@ -1,14 +1,16 @@
import React from 'react';
import { RecordNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordNameProps {
record: RecordNode;
}
export const RecordName = ({ record }: RecordNameProps) => {
- const { mutate, isPending } = useNodeAttributeSetMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<SmartTextInput
@@ -23,9 +25,13 @@ export const RecordName = ({ record }: RecordNameProps) => {
}
mutate({
- nodeId: record.id,
- key: 'name',
- value: value,
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: 'name',
+ value: value,
+ userId: workspace.userId,
+ },
});
}}
className="font-heading border-b border-none pl-1 text-4xl font-bold shadow-none focus-visible:ring-0"
diff --git a/desktop/src/components/records/values/record-boolean-value.tsx b/desktop/src/components/records/values/record-boolean-value.tsx
index 1bc538c6..b9137f21 100644
--- a/desktop/src/components/records/values/record-boolean-value.tsx
+++ b/desktop/src/components/records/values/record-boolean-value.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { BooleanFieldNode, RecordNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordBooleanValueProps {
record: RecordNode;
@@ -13,12 +13,9 @@ export const RecordBooleanValue = ({
record,
field,
}: RecordBooleanValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const canEdit = true;
const [input, setInput] = React.useState<boolean>(
@@ -42,15 +39,23 @@ export const RecordBooleanValue = ({
setInput(e.valueOf());
const checked = e.valueOf();
if (checked) {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: checked,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: checked,
+ userId: workspace.userId,
+ },
});
} else {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
}
}
diff --git a/desktop/src/components/records/values/record-email-value.tsx b/desktop/src/components/records/values/record-email-value.tsx
index 530779d5..510d3523 100644
--- a/desktop/src/components/records/values/record-email-value.tsx
+++ b/desktop/src/components/records/values/record-email-value.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import { RecordNode, EmailFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordEmailValueProps {
record: RecordNode;
@@ -10,13 +10,10 @@ interface RecordEmailValueProps {
}
export const RecordEmailValue = ({ record, field }: RecordEmailValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
@@ -27,15 +24,23 @@ export const RecordEmailValue = ({ record, field }: RecordEmailValueProps) => {
if (!canEdit) return;
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/records/values/record-multi-select-value.tsx b/desktop/src/components/records/values/record-multi-select-value.tsx
index 8b14d839..c96bede9 100644
--- a/desktop/src/components/records/values/record-multi-select-value.tsx
+++ b/desktop/src/components/records/values/record-multi-select-value.tsx
@@ -7,8 +7,8 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordMultiSelectValueProps {
record: RecordNode;
@@ -19,12 +19,8 @@ export const RecordMultiSelectValue = ({
record,
field,
}: RecordMultiSelectValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
-
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState(
@@ -63,17 +59,25 @@ export const RecordMultiSelectValue = ({
if (selectedValues.includes(id)) {
const values = selectedValues.filter((v) => v !== id);
setSelectedValues(values);
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
const values = [...selectedValues, id];
setSelectedValues(values);
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: values,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: values,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/records/values/record-number-value.tsx b/desktop/src/components/records/values/record-number-value.tsx
index 406acb54..df9f11db 100644
--- a/desktop/src/components/records/values/record-number-value.tsx
+++ b/desktop/src/components/records/values/record-number-value.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { RecordNode } from '@/types/databases';
import { NumberFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartNumberInput } from '@/components/ui/smart-number-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordNumberValueProps {
record: RecordNode;
@@ -14,13 +14,10 @@ export const RecordNumberValue = ({
record,
field,
}: RecordNumberValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartNumberInput
@@ -35,15 +32,23 @@ export const RecordNumberValue = ({
}
if (newValue === null) {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/records/values/record-phone-value.tsx b/desktop/src/components/records/values/record-phone-value.tsx
index 0c42a11b..f659128e 100644
--- a/desktop/src/components/records/values/record-phone-value.tsx
+++ b/desktop/src/components/records/values/record-phone-value.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import { RecordNode, PhoneFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordPhoneValueProps {
record: RecordNode;
@@ -10,13 +10,10 @@ interface RecordPhoneValueProps {
}
export const RecordPhoneValue = ({ record, field }: RecordPhoneValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
@@ -31,15 +28,23 @@ export const RecordPhoneValue = ({ record, field }: RecordPhoneValueProps) => {
}
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/records/values/record-select-value.tsx b/desktop/src/components/records/values/record-select-value.tsx
index b06e9f0a..6a98ceb5 100644
--- a/desktop/src/components/records/values/record-select-value.tsx
+++ b/desktop/src/components/records/values/record-select-value.tsx
@@ -7,8 +7,8 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordSelectValueProps {
record: RecordNode;
@@ -19,12 +19,8 @@ export const RecordSelectValue = ({
record,
field,
}: RecordSelectValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
-
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(
@@ -64,23 +60,27 @@ export const RecordSelectValue = ({
if (selectedValue === id) {
setSelectedValue('');
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute(
- {
+ mutate({
+ input: {
+ type: 'node_attribute_set',
nodeId: record.id,
- key: field.id,
+ attribute: field.id,
value: id,
+ userId: workspace.userId,
},
- {
- onSuccess: () => {
- setOpen(false);
- },
+ onSuccess() {
+ setOpen(false);
},
- );
+ });
}
setSelectedValue(id);
}}
diff --git a/desktop/src/components/records/values/record-text-value.tsx b/desktop/src/components/records/values/record-text-value.tsx
index 1ddc4875..f0c9b725 100644
--- a/desktop/src/components/records/values/record-text-value.tsx
+++ b/desktop/src/components/records/values/record-text-value.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import { RecordNode, TextFieldNode } from '@/types/databases';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordTextValueProps {
record: RecordNode;
@@ -10,13 +10,10 @@ interface RecordTextValueProps {
}
export const RecordTextValue = ({ record, field }: RecordTextValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
@@ -31,15 +28,23 @@ export const RecordTextValue = ({ record, field }: RecordTextValueProps) => {
}
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/records/values/record-url-value.tsx b/desktop/src/components/records/values/record-url-value.tsx
index 4b49b704..7da18ced 100644
--- a/desktop/src/components/records/values/record-url-value.tsx
+++ b/desktop/src/components/records/values/record-url-value.tsx
@@ -7,9 +7,9 @@ import {
HoverCardTrigger,
} from '@/components/ui/hover-card';
import { Icon } from '@/components/ui/icon';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface RecordUrlValueProps {
record: RecordNode;
@@ -17,13 +17,10 @@ interface RecordUrlValueProps {
}
export const RecordUrlValue = ({ record, field }: RecordUrlValueProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
- const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
- useNodeAttributeDeleteMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const canEdit = true;
- const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const text = record.attributes[field.id];
const isUrl = text.length > 0 && isValidUrl(text);
@@ -42,15 +39,23 @@ export const RecordUrlValue = ({ record, field }: RecordUrlValueProps) => {
}
if (newValue === null || newValue === '') {
- deleteNodeAttribute({
- nodeId: record.id,
- key: field.id,
+ mutate({
+ input: {
+ type: 'node_attribute_delete',
+ nodeId: record.id,
+ attribute: field.id,
+ userId: workspace.userId,
+ },
});
} else {
- setNodeAttribute({
- nodeId: record.id,
- key: field.id,
- value: newValue,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: record.id,
+ attribute: field.id,
+ value: newValue,
+ userId: workspace.userId,
+ },
});
}
}}
diff --git a/desktop/src/components/root.tsx b/desktop/src/components/root.tsx
index 8f0a3fc0..fde54478 100644
--- a/desktop/src/components/root.tsx
+++ b/desktop/src/components/root.tsx
@@ -12,15 +12,6 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { useEventBus } from '@/hooks/use-event-bus';
-import {
- DummyDriver,
- Kysely,
- SqliteAdapter,
- SqliteIntrospector,
- SqliteQueryCompiler,
-} from 'kysely';
-import { AppDatabaseSchema } from '@/electron/schemas/app';
-import { AppDatabaseContext } from '@/contexts/app-database';
const router = createBrowserRouter([
{
@@ -49,15 +40,6 @@ const router = createBrowserRouter([
},
]);
-const appDatabase = new Kysely<AppDatabaseSchema>({
- dialect: {
- createAdapter: () => new SqliteAdapter(),
- createDriver: () => new DummyDriver(),
- createIntrospector: (db) => new SqliteIntrospector(db),
- createQueryCompiler: () => new SqliteQueryCompiler(),
- },
-});
-
export const Root = () => {
const eventBus = useEventBus();
const queryClient = React.useMemo(() => {
@@ -133,22 +115,12 @@ export const Root = () => {
return (
<QueryClientProvider client={queryClient}>
- <AppDatabaseContext.Provider
- value={{
- database: appDatabase,
- query: (query) => window.neuron.executeAppQuery(query),
- queryAndSubscribe: (context) =>
- window.neuron.executeAppQueryAndSubscribe(context),
- mutate: (mutation) => window.neuron.executeAppMutation(mutation),
- }}
- >
- <DndProvider backend={HTML5Backend}>
- <TooltipProvider>
- <RouterProvider router={router} />
- </TooltipProvider>
- <Toaster />
- </DndProvider>
- </AppDatabaseContext.Provider>
+ <DndProvider backend={HTML5Backend}>
+ <TooltipProvider>
+ <RouterProvider router={router} />
+ </TooltipProvider>
+ <Toaster />
+ </DndProvider>
</QueryClientProvider>
);
};
diff --git a/desktop/src/components/servers/server-create-dialog.tsx b/desktop/src/components/servers/server-create-dialog.tsx
index 7436aa48..bc966f36 100644
--- a/desktop/src/components/servers/server-create-dialog.tsx
+++ b/desktop/src/components/servers/server-create-dialog.tsx
@@ -12,8 +12,7 @@ import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { toast } from '@/components/ui/use-toast';
-import { parseApiError } from '@/lib/axios';
-import { useServerCreateMutation } from '@/mutations/use-server-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
interface ServerCreateDialogProps {
open: boolean;
@@ -24,7 +23,7 @@ export const ServerCreateDialog = ({
open,
onOpenChange,
}: ServerCreateDialogProps) => {
- const { mutate, isPending } = useServerCreateMutation();
+ const { mutate, isPending } = useMutation();
const [domain, setDomain] = React.useState('');
return (
@@ -50,24 +49,23 @@ export const ServerCreateDialog = ({
type="button"
disabled={isPending}
onClick={() => {
- mutate(
- {
- domain: domain,
+ mutate({
+ input: {
+ type: 'server_create',
+ domain,
},
- {
- onSuccess() {
- onOpenChange(false);
- },
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to login',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onSuccess() {
+ onOpenChange(false);
},
- );
+ onError() {
+ toast({
+ title: 'Failed to login',
+ description:
+ 'Something went wrong adding the server. Please make sure the domain is correct.',
+ variant: 'destructive',
+ });
+ },
+ });
}}
>
{isPending && <Spinner className="mr-1" />}
diff --git a/desktop/src/components/servers/server-dropdown.tsx b/desktop/src/components/servers/server-dropdown.tsx
index 06ec80cf..f83c7fbb 100644
--- a/desktop/src/components/servers/server-dropdown.tsx
+++ b/desktop/src/components/servers/server-dropdown.tsx
@@ -8,7 +8,7 @@ import {
import { Icon } from '@/components/ui/icon';
import { Avatar } from '@/components/ui/avatar';
import { Server } from '@/types/servers';
-import { ServerCreateDialog } from './server-create-dialog';
+import { ServerCreateDialog } from '@/components/servers/server-create-dialog';
import { DropdownMenuSeparator } from '@radix-ui/react-dropdown-menu';
interface ServerDropdownProps {
diff --git a/desktop/src/components/spaces/space-create-dialog.tsx b/desktop/src/components/spaces/space-create-dialog.tsx
index 2adf4194..37278ad3 100644
--- a/desktop/src/components/spaces/space-create-dialog.tsx
+++ b/desktop/src/components/spaces/space-create-dialog.tsx
@@ -22,7 +22,8 @@ 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 { useSpaceCreateMutation } from '@/mutations/use-space-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
@@ -38,7 +39,8 @@ export const SpaceCreateDialog = ({
open,
onOpenChange,
}: SpaceCreateDialogProps) => {
- const { mutate, isPending } = useSpaceCreateMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -54,15 +56,18 @@ export const SpaceCreateDialog = ({
};
const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- mutate(
- { name: values.name, description: values.description },
- {
- onSuccess: () => {
- onOpenChange(false);
- form.reset();
- },
+ mutate({
+ input: {
+ type: 'space_create',
+ name: values.name,
+ description: values.description,
+ userId: workspace.userId,
},
- );
+ onSuccess() {
+ onOpenChange(false);
+ form.reset();
+ },
+ });
};
return (
diff --git a/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx b/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
index 712759fd..e477db46 100644
--- a/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
+++ b/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
@@ -1,28 +1,33 @@
import React from 'react';
import { BreadcrumbNode } from '@/types/workspaces';
-import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
+import { useMutation } from '@/hooks/use-mutation';
+import { useWorkspace } from '@/contexts/workspace';
interface BreadcrumbItemEditorProps {
node: BreadcrumbNode;
}
export const BreadcrumbItemEditor = ({ node }: BreadcrumbItemEditorProps) => {
- const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
- useNodeAttributeSetMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
return (
<div>
<SmartTextInput
value={node.name}
onChange={(newName) => {
- if (isSettingNodeAttribute) return;
+ if (isPending) return;
if (newName === node.name) return;
- setNodeAttribute({
- nodeId: node.id,
- key: 'name',
- value: newName,
+ mutate({
+ input: {
+ type: 'node_attribute_set',
+ nodeId: node.id,
+ attribute: 'name',
+ value: newName,
+ userId: workspace.userId,
+ },
});
}}
/>
diff --git a/desktop/src/components/workspaces/containers/breadcrumb.tsx b/desktop/src/components/workspaces/containers/breadcrumb.tsx
index dbe616b3..a8d33361 100644
--- a/desktop/src/components/workspaces/containers/breadcrumb.tsx
+++ b/desktop/src/components/workspaces/containers/breadcrumb.tsx
@@ -22,7 +22,7 @@ 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';
+import { useQuery } from '@/hooks/use-query';
interface BreadcrumbProps {
node: LocalNode;
@@ -30,7 +30,11 @@ interface BreadcrumbProps {
export const Breadcrumb = ({ node }: BreadcrumbProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useBreadcrumbQuery(node.id);
+ const { data, isPending } = useQuery({
+ type: 'breadcrumb_list',
+ nodeId: node.id,
+ userId: workspace.userId,
+ });
if (isPending) {
return null;
diff --git a/desktop/src/components/workspaces/containers/container.tsx b/desktop/src/components/workspaces/containers/container.tsx
index 14bfddfa..19f8af78 100644
--- a/desktop/src/components/workspaces/containers/container.tsx
+++ b/desktop/src/components/workspaces/containers/container.tsx
@@ -6,32 +6,36 @@ import { PageContainerNode } from '@/components/pages/page-container-node';
import { ChannelContainerNode } from '@/components/channels/channel-container-node';
import { ContainerHeader } from '@/components/workspaces/containers/container-header';
import { Spinner } from '@/components/ui/spinner';
-import { mapNode } from '@/lib/nodes';
import { DatabaseContainerNode } from '@/components/databases/database-container-node';
-import { useNodeQuery } from '@/queries/use-node-query';
+import { useQuery } from '@/hooks/use-query';
import { RecordContainerNode } from '@/components/records/record-container-node';
+import { useWorkspace } from '@/contexts/workspace';
export const Container = () => {
+ const workspace = useWorkspace();
const { nodeId } = useParams<{ nodeId: string }>();
- const { data, isPending } = useNodeQuery(nodeId);
+ const { data, isPending } = useQuery({
+ type: 'node_get',
+ nodeId: nodeId,
+ userId: workspace.userId,
+ });
if (isPending) {
return <Spinner />;
}
- if (!data || data.rows.length === 0) {
+ if (!data) {
return null;
}
- const node = mapNode(data.rows[0]);
return (
<div className="flex h-full w-full flex-col">
- <ContainerHeader node={node} />
- {match(node.type)
- .with(NodeTypes.Channel, () => <ChannelContainerNode node={node} />)
- .with(NodeTypes.Page, () => <PageContainerNode node={node} />)
- .with(NodeTypes.Database, () => <DatabaseContainerNode node={node} />)
- .with(NodeTypes.Record, () => <RecordContainerNode node={node} />)
+ <ContainerHeader node={data} />
+ {match(data.type)
+ .with(NodeTypes.Channel, () => <ChannelContainerNode node={data} />)
+ .with(NodeTypes.Page, () => <PageContainerNode node={data} />)
+ .with(NodeTypes.Database, () => <DatabaseContainerNode node={data} />)
+ .with(NodeTypes.Record, () => <RecordContainerNode node={data} />)
.otherwise(() => null)}
</div>
);
diff --git a/desktop/src/components/workspaces/modals/modal-content.tsx b/desktop/src/components/workspaces/modals/modal-content.tsx
index 1323d984..e5108c67 100644
--- a/desktop/src/components/workspaces/modals/modal-content.tsx
+++ b/desktop/src/components/workspaces/modals/modal-content.tsx
@@ -1,38 +1,41 @@
import React from 'react';
import { Spinner } from '@/components/ui/spinner';
-import { useNodeQuery } from '@/queries/use-node-query';
-import { mapNode } from '@/lib/nodes';
+import { useQuery } from '@/hooks/use-query';
import { match } from 'ts-pattern';
import { NodeTypes } from '@/lib/constants';
import { ChannelContainerNode } from '@/components/channels/channel-container-node';
import { PageContainerNode } from '@/components/pages/page-container-node';
import { DatabaseContainerNode } from '@/components/databases/database-container-node';
import { RecordContainerNode } from '@/components/records/record-container-node';
+import { useWorkspace } from '@/contexts/workspace';
interface ModalContentProps {
nodeId: string;
}
export const ModalContent = ({ nodeId }: ModalContentProps) => {
- const { data, isPending } = useNodeQuery(nodeId);
+ const workspace = useWorkspace();
+ const { data, isPending } = useQuery({
+ type: 'node_get',
+ nodeId: nodeId,
+ userId: workspace.userId,
+ });
if (isPending) {
return <Spinner />;
}
- if (!data || data.rows.length === 0) {
+ if (!data) {
return null;
}
- const node = mapNode(data.rows[0]);
-
return (
<div className="flex h-full w-full flex-col">
- {match(node.type)
- .with(NodeTypes.Channel, () => <ChannelContainerNode node={node} />)
- .with(NodeTypes.Page, () => <PageContainerNode node={node} />)
- .with(NodeTypes.Database, () => <DatabaseContainerNode node={node} />)
- .with(NodeTypes.Record, () => <RecordContainerNode node={node} />)
+ {match(data.type)
+ .with(NodeTypes.Channel, () => <ChannelContainerNode node={data} />)
+ .with(NodeTypes.Page, () => <PageContainerNode node={data} />)
+ .with(NodeTypes.Database, () => <DatabaseContainerNode node={data} />)
+ .with(NodeTypes.Record, () => <RecordContainerNode node={data} />)
.otherwise(() => null)}
</div>
);
diff --git a/desktop/src/components/workspaces/sidebars/sidebar-chats.tsx b/desktop/src/components/workspaces/sidebars/sidebar-chats.tsx
index be88a5bb..abd91b41 100644
--- a/desktop/src/components/workspaces/sidebars/sidebar-chats.tsx
+++ b/desktop/src/components/workspaces/sidebars/sidebar-chats.tsx
@@ -1,10 +1,15 @@
import React from 'react';
import { ChatCreatePopover } from '@/components/chats/chat-create-popover';
-import { useSidebarChatsQuery } from '@/queries/use-sidebar-chats-query';
-import { SidebarChatItem } from './sidebar-chat-item';
+import { useQuery } from '@/hooks/use-query';
+import { SidebarChatItem } from '@/components/workspaces/sidebars/sidebar-chat-item';
+import { useWorkspace } from '@/contexts/workspace';
export const SidebarChats = () => {
- const { data } = useSidebarChatsQuery();
+ const workspace = useWorkspace();
+ const { data } = useQuery({
+ type: 'sidebar_chat_list',
+ userId: workspace.userId,
+ });
return (
<div className="pt-2 first:pt-0">
diff --git a/desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx b/desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx
index 0541fc37..907f8b04 100644
--- a/desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx
+++ b/desktop/src/components/workspaces/sidebars/sidebar-spaces.tsx
@@ -1,10 +1,16 @@
import React from 'react';
import { SpaceCreateButton } from '@/components/spaces/space-create-button';
import { SidebarSpaceItem } from '@/components/workspaces/sidebars/sidebar-space-item';
-import { useSidebarSpacesQuery } from '@/queries/use-sidebar-spaces-query';
+import { useQuery } from '@/hooks/use-query';
+import { useWorkspace } from '@/contexts/workspace';
export const SidebarSpaces = () => {
- const { data } = useSidebarSpacesQuery();
+ const workspace = useWorkspace();
+ const { data } = useQuery({
+ type: 'sidebar_space_list',
+ userId: workspace.userId,
+ });
+
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/workspace-create.tsx b/desktop/src/components/workspaces/workspace-create.tsx
index fa90f304..62772d22 100644
--- a/desktop/src/components/workspaces/workspace-create.tsx
+++ b/desktop/src/components/workspaces/workspace-create.tsx
@@ -15,8 +15,7 @@ import { Spinner } from '@/components/ui/spinner';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from '@/components/ui/use-toast';
-import { parseApiError } from '@/lib/axios';
-import { useWorkspaceCreateMutation } from '@/mutations/use-workspace-create-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { useAccount } from '@/contexts/account';
import { useNavigate } from 'react-router-dom';
@@ -31,7 +30,7 @@ export const WorkspaceCreate = () => {
const account = useAccount();
const navigate = useNavigate();
- const { mutate, isPending } = useWorkspaceCreateMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<formSchemaType>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -41,25 +40,25 @@ export const WorkspaceCreate = () => {
});
const handleSubmit = async (values: formSchemaType) => {
- mutate(
- {
+ mutate({
+ input: {
+ type: 'workspace_create',
name: values.name,
description: values.description,
+ accountId: account.id,
},
- {
- onSuccess: () => {
- window.location.href = '/';
- },
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to create workspace',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onSuccess() {
+ window.location.href = '/';
},
- );
+ onError() {
+ toast({
+ title: 'Failed to create workspace',
+ description:
+ 'Somewthing went wrong creating the workspace. Please try again!',
+ variant: 'destructive',
+ });
+ },
+ });
};
return (
diff --git a/desktop/src/components/workspaces/workspace-update.tsx b/desktop/src/components/workspaces/workspace-update.tsx
index eaef145a..56b62b8e 100644
--- a/desktop/src/components/workspaces/workspace-update.tsx
+++ b/desktop/src/components/workspaces/workspace-update.tsx
@@ -15,8 +15,7 @@ import { Spinner } from '@/components/ui/spinner';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from '@/components/ui/use-toast';
-import { parseApiError } from '@/lib/axios';
-import { useWorkspaceUpdateMutation } from '@/mutations/use-workspace-update-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { useWorkspace } from '@/contexts/workspace';
const formSchema = z.object({
@@ -28,7 +27,7 @@ type formSchemaType = z.infer<typeof formSchema>;
export const WorkspaceUpdate = () => {
const workspace = useWorkspace();
- const { mutate, isPending } = useWorkspaceUpdateMutation();
+ const { mutate, isPending } = useMutation();
const form = useForm<formSchemaType>({
resolver: zodResolver(formSchema),
@@ -39,30 +38,30 @@ export const WorkspaceUpdate = () => {
});
const handleSubmit = async (values: formSchemaType) => {
- mutate(
- {
+ mutate({
+ input: {
+ type: 'workspace_update',
id: workspace.id,
+ accountId: workspace.accountId,
name: values.name,
description: values.description,
},
- {
- onSuccess: () => {
- toast({
- title: 'Workspace updated',
- description: 'Workspace was updated successfully',
- variant: 'default',
- });
- },
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to update workspace',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onSuccess() {
+ toast({
+ title: 'Workspace updated',
+ description: 'Workspace was updated successfully',
+ variant: 'default',
+ });
},
- );
+ onError() {
+ toast({
+ title: 'Failed to update workspace',
+ description:
+ 'Something went wrong updating workspace. Please try again!',
+ variant: 'destructive',
+ });
+ },
+ });
};
return (
diff --git a/desktop/src/components/workspaces/workspace-user-invite.tsx b/desktop/src/components/workspaces/workspace-user-invite.tsx
index 7b5c8475..ac324017 100644
--- a/desktop/src/components/workspaces/workspace-user-invite.tsx
+++ b/desktop/src/components/workspaces/workspace-user-invite.tsx
@@ -2,15 +2,17 @@ import React from 'react';
import { Icon } from '@/components/ui/icon';
import { isValidEmail } from '@/lib/utils';
import { Button } from '@/components/ui/button';
-import { useWorkspaceAccountsInviteMutation } from '@/mutations/use-workspace-accounts-invite-mutation';
+import { useMutation } from '@/hooks/use-mutation';
import { Spinner } from '@/components/ui/spinner';
-import { parseApiError } from '@/lib/axios';
import { toast } from '@/components/ui/use-toast';
+import { useWorkspace } from '@/contexts/workspace';
export const WorkspaceUserInvite = () => {
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
+
const [input, setInput] = React.useState('');
const [emails, setEmails] = React.useState<string[]>([]);
- const { mutate, isPending } = useWorkspaceAccountsInviteMutation();
return (
<div className="flex flex-col space-y-2">
@@ -73,21 +75,21 @@ export const WorkspaceUserInvite = () => {
return;
}
- mutate(
- {
+ mutate({
+ input: {
+ type: 'workspace_accounts_invite',
emails: emails,
+ userId: workspace.userId,
},
- {
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to login',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onError() {
+ toast({
+ title: 'Failed to invite users',
+ description:
+ 'Something went wrong inviting userts to workspace. Please try again!',
+ variant: 'destructive',
+ });
},
- );
+ });
}}
>
{isPending && <Spinner className="mr-1" />}
diff --git a/desktop/src/components/workspaces/workspace-user-role-dropdown.tsx b/desktop/src/components/workspaces/workspace-user-role-dropdown.tsx
index dbb19e91..93a7c250 100644
--- a/desktop/src/components/workspaces/workspace-user-role-dropdown.tsx
+++ b/desktop/src/components/workspaces/workspace-user-role-dropdown.tsx
@@ -8,9 +8,9 @@ import {
import { WorkspaceRole } from '@/types/workspaces';
import { Spinner } from '@/components/ui/spinner';
import { Icon } from '@/components/ui/icon';
-import { useWorkspaceAccountRoleUpdateMutation } from '@/mutations/use-workspace-account-role-update-mutation';
-import { parseApiError } from '@/lib/axios';
+import { useMutation } from '@/hooks/use-mutation';
import { toast } from '@/components/ui/use-toast';
+import { useWorkspace } from '@/contexts/workspace';
interface WorkspaceRoleItem {
name: string;
@@ -49,7 +49,8 @@ export const WorkspaceUserRoleDropdown = ({
accountId,
value,
}: WorkspaceUserRoleDropdownProps) => {
- const { mutate, isPending } = useWorkspaceAccountRoleUpdateMutation();
+ const workspace = useWorkspace();
+ const { mutate, isPending } = useMutation();
const currentRole = roles.find((role) => role.value === value);
return (
@@ -76,22 +77,22 @@ export const WorkspaceUserRoleDropdown = ({
return;
}
- mutate(
- {
- accountId,
+ mutate({
+ input: {
+ type: 'workspace_account_role_update',
+ accountId: accountId,
role: role.value,
+ userId: workspace.userId,
},
- {
- onError: (error) => {
- const apiError = parseApiError(error);
- toast({
- title: 'Failed to update role',
- description: apiError.message,
- variant: 'destructive',
- });
- },
+ onError() {
+ toast({
+ title: 'Failed to update role',
+ description:
+ 'Something went wrong updating user role. Please try again!',
+ variant: 'destructive',
+ });
},
- );
+ });
}}
>
<div className="flex w-full flex-row items-center justify-between">
diff --git a/desktop/src/components/workspaces/workspace-users.tsx b/desktop/src/components/workspaces/workspace-users.tsx
index 4d07c9d6..81b322c9 100644
--- a/desktop/src/components/workspaces/workspace-users.tsx
+++ b/desktop/src/components/workspaces/workspace-users.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { useWorkspaceUsersQuery } from '@/queries/use-workspace-users-query';
+import { useInfiniteQuery } from '@/hooks/use-infinite-query';
import { Separator } from '@/components/ui/separator';
import { WorkspaceUserInvite } from '@/components/workspaces/workspace-user-invite';
import { Avatar } from '@/components/ui/avatar';
@@ -7,15 +7,45 @@ import { Spinner } from '@/components/ui/spinner';
import { InView } from 'react-intersection-observer';
import { WorkspaceUserRoleDropdown } from '@/components/workspaces/workspace-user-role-dropdown';
import { WorkspaceRole } from '@/types/workspaces';
+import { useWorkspace } from '@/contexts/workspace';
+
+const USERS_PER_PAGE = 50;
export const WorkspaceUsers = () => {
+ const workspace = useWorkspace();
+
const { data, isPending, hasNextPage, fetchNextPage, isFetchingNextPage } =
- useWorkspaceUsersQuery();
+ useInfiniteQuery({
+ initialPageInput: {
+ type: 'workspace_user_list',
+ page: 0,
+ count: USERS_PER_PAGE,
+ userId: workspace.userId,
+ },
+ getNextPageInput(page, pages) {
+ if (page > pages.length) {
+ return undefined;
+ }
+
+ const lastPage = pages[page - 1];
+ if (lastPage.length < USERS_PER_PAGE) {
+ return undefined;
+ }
+
+ return {
+ type: 'workspace_user_list',
+ page: page,
+ count: USERS_PER_PAGE,
+ userId: workspace.userId,
+ };
+ },
+ });
if (isPending) {
return null;
}
+ const users = data?.flatMap((page) => page) ?? [];
return (
<div className="flex flex-col space-y-4">
<WorkspaceUserInvite />
@@ -27,7 +57,7 @@ export const WorkspaceUsers = () => {
</p>
</div>
<div className="flex flex-col gap-2">
- {data.map((user) => {
+ {users.map((user) => {
const name: string = user.attributes.name ?? 'Unknown';
const email: string = user.attributes.email ?? ' ';
const avatar: string | null | undefined = user.attributes.avatar;
diff --git a/desktop/src/components/workspaces/workspace.tsx b/desktop/src/components/workspaces/workspace.tsx
index 2daeb3c8..366770cd 100644
--- a/desktop/src/components/workspaces/workspace.tsx
+++ b/desktop/src/components/workspaces/workspace.tsx
@@ -7,29 +7,10 @@ import {
useParams,
useSearchParams,
} from 'react-router-dom';
-import {
- DummyDriver,
- Kysely,
- SqliteAdapter,
- SqliteIntrospector,
- SqliteQueryCompiler,
-} from 'kysely';
-import { WorkspaceDatabaseSchema } from '@/electron/schemas/workspace';
import { useAccount } from '@/contexts/account';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { useEventBus } from '@/hooks/use-event-bus';
import { Modal } from '@/components/workspaces/modals/modal';
import { WorkspaceSettingsDialog } from '@/components/workspaces/workspace-settings-dialog';
-const workspaceDatabase = new Kysely<WorkspaceDatabaseSchema>({
- dialect: {
- createAdapter: () => new SqliteAdapter(),
- createDriver: () => new DummyDriver(),
- createIntrospector: (db) => new SqliteIntrospector(db),
- createQueryCompiler: () => new SqliteQueryCompiler(),
- },
-});
-
export const Workspace = () => {
const { workspaceId } = useParams<{ workspaceId: string }>();
@@ -37,165 +18,59 @@ export const Workspace = () => {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const [openSettings, setOpenSettings] = React.useState(false);
-
- const eventBus = useEventBus();
const workspace = account.workspaces.find((w) => w.id === workspaceId);
- const queryClient = React.useMemo(() => {
- return new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- });
- }, [workspaceId]);
-
- React.useEffect(() => {
- if (!workspace) {
- return;
- }
-
- const id = eventBus.subscribe((event) => {
- if (event.event === 'workspace_query_updated') {
- const result = event.payload.result;
- const queryKey = event.payload.key;
- const page = event.payload.page;
-
- if (!result) {
- return;
- }
-
- if (!queryKey) {
- return;
- }
-
- const existingData = queryClient.getQueryData<any>(queryKey);
-
- if (!existingData) {
- window.neuron.unsubscribeWorkspaceQuery(
- workspace.accountId,
- workspace.id,
- queryKey,
- );
- return;
- }
-
- if (page !== undefined && page != null) {
- const index = existingData.pageParams.indexOf(page);
- if (index === -1) {
- return;
- }
-
- const newData = {
- pageParams: existingData.pageParams,
- pages: existingData.pages.map((p: any, i: number) => {
- if (i === index) {
- return result;
- }
-
- return p;
- }),
- };
- queryClient.setQueryData(queryKey, newData);
- } else {
- queryClient.setQueryData(queryKey, result);
- }
- }
- });
-
- queryClient.getQueryCache().subscribe(async (event) => {
- if (
- event.type === 'removed' &&
- event.query &&
- event.query.queryKey &&
- event.query.queryKey.length > 0
- ) {
- await window.neuron.unsubscribeWorkspaceQuery(
- workspace.accountId,
- workspace.id,
- event.query.queryKey,
- );
- }
- });
-
- return () => {
- eventBus.unsubscribe(id);
- };
- }, [workspace]);
-
if (!workspace) {
return <p>Workspace not found</p>;
}
const modal = searchParams.get('modal');
return (
- <QueryClientProvider client={queryClient}>
- <WorkspaceContext.Provider
- value={{
- ...workspace,
- schema: workspaceDatabase,
- mutate: (input) =>
- window.neuron.executeWorkspaceMutation(
- workspace.accountId,
- workspace.id,
- input,
- ),
- query: (query) =>
- window.neuron.executeWorkspaceQuery(
- workspace.accountId,
- workspace.id,
- query,
- ),
- queryAndSubscribe: (context) =>
- window.neuron.executeWorkspaceQueryAndSubscribe(
- workspace.accountId,
- workspace.id,
- context,
- ),
- navigateToNode(nodeId) {
- navigate(`/${workspaceId}/${nodeId}`);
- },
- openModal(modal) {
- setSearchParams((prev) => {
- return {
- ...prev,
- modal: modal,
- };
- });
- },
- openSettings() {
- setOpenSettings(true);
- },
- }}
- >
- <div className="flex h-screen max-h-screen flex-row">
- <div className="w-96">
- <Sidebar />
- </div>
- <main className="h-full w-full min-w-128 flex-grow overflow-hidden bg-white">
- <Outlet />
- </main>
- {modal && (
- <Modal
- nodeId={modal}
- key={modal}
- onClose={() => {
- setSearchParams((prev) => {
- prev.delete('modal');
- return prev;
- });
- }}
- />
- )}
+ <WorkspaceContext.Provider
+ value={{
+ ...workspace,
+ navigateToNode(nodeId) {
+ navigate(`/${workspaceId}/${nodeId}`);
+ },
+ openModal(modal) {
+ setSearchParams((prev) => {
+ return {
+ ...prev,
+ modal: modal,
+ };
+ });
+ },
+ openSettings() {
+ setOpenSettings(true);
+ },
+ }}
+ >
+ <div className="flex h-screen max-h-screen flex-row">
+ <div className="w-96">
+ <Sidebar />
</div>
- {openSettings && (
- <WorkspaceSettingsDialog
- open={openSettings}
- onOpenChange={setOpenSettings}
+ <main className="h-full w-full min-w-128 flex-grow overflow-hidden bg-white">
+ <Outlet />
+ </main>
+ {modal && (
+ <Modal
+ nodeId={modal}
+ key={modal}
+ onClose={() => {
+ setSearchParams((prev) => {
+ prev.delete('modal');
+ return prev;
+ });
+ }}
/>
)}
- </WorkspaceContext.Provider>
- </QueryClientProvider>
+ </div>
+ {openSettings && (
+ <WorkspaceSettingsDialog
+ open={openSettings}
+ onOpenChange={setOpenSettings}
+ />
+ )}
+ </WorkspaceContext.Provider>
);
};
diff --git a/desktop/src/contexts/app-database.ts b/desktop/src/contexts/app-database.ts
deleted file mode 100644
index ba861265..00000000
--- a/desktop/src/contexts/app-database.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import React from 'react';
-import { CompiledQuery, Kysely, QueryResult } from 'kysely';
-import { AppDatabaseSchema } from '@/electron/schemas/app';
-import { SubscribedQueryContext } from '@/types/queries';
-
-interface AppDatabaseContext {
- database: Kysely<AppDatabaseSchema>;
- mutate: (mutation: CompiledQuery | CompiledQuery[]) => Promise<void>;
- query: <R>(query: CompiledQuery<R>) => Promise<QueryResult<R>>;
- queryAndSubscribe: <R>(
- context: SubscribedQueryContext<R>,
- ) => Promise<QueryResult<R>>;
-}
-
-export const AppDatabaseContext = React.createContext<AppDatabaseContext>(
- {} as AppDatabaseContext,
-);
-
-export const useAppDatabase = () => React.useContext(AppDatabaseContext)!;
diff --git a/desktop/src/contexts/workspace.ts b/desktop/src/contexts/workspace.ts
index 3f84bc9b..96c66b0d 100644
--- a/desktop/src/contexts/workspace.ts
+++ b/desktop/src/contexts/workspace.ts
@@ -1,16 +1,7 @@
import { createContext, useContext } from 'react';
import { Workspace } from '@/types/workspaces';
-import { CompiledQuery, Kysely, QueryResult } from 'kysely';
-import { WorkspaceDatabaseSchema } from '@/electron/schemas/workspace';
-import { SubscribedQueryContext } from '@/types/queries';
interface WorkspaceContext extends Workspace {
- schema: Kysely<WorkspaceDatabaseSchema>;
- mutate: (mutation: CompiledQuery | CompiledQuery[]) => Promise<void>;
- query: <R>(query: CompiledQuery<R>) => Promise<QueryResult<R>>;
- queryAndSubscribe: <R>(
- context: SubscribedQueryContext<R>,
- ) => Promise<QueryResult<R>>;
navigateToNode: (nodeId: string) => void;
openModal: (nodeId: string) => void;
openSettings: () => void;
diff --git a/desktop/src/electron/account-manager.ts b/desktop/src/electron/account-manager.ts
index 6cd80f08..98afe46e 100644
--- a/desktop/src/electron/account-manager.ts
+++ b/desktop/src/electron/account-manager.ts
@@ -1,137 +1,137 @@
-import * as fs from 'node:fs';
-import Axios, { AxiosInstance } from 'axios';
-import { Account } from '@/types/accounts';
-import { Workspace } from '@/types/workspaces';
-import { WorkspaceManager } from '@/electron/workspace-manager';
-import { SocketManager } from '@/electron/socket-manager';
-import { ServerMutation } from '@/types/mutations';
-import { Kysely } from 'kysely';
-import { AppDatabaseSchema } from '@/electron/schemas/app';
-import { Server } from '@/types/servers';
-import { buildApiBaseUrl } from '@/lib/servers';
-
-export class AccountManager {
- public readonly account: Account;
- private readonly accountPath: string;
- private readonly socket: SocketManager;
- private readonly axios: AxiosInstance;
- private readonly workspaces: Map<string, WorkspaceManager>;
- private readonly database: Kysely<AppDatabaseSchema>;
-
- constructor(
- server: Server,
- account: Account,
- appPath: string,
- workspaces: Workspace[],
- database: Kysely<AppDatabaseSchema>,
- ) {
- this.account = account;
- this.database = database;
- this.socket = new SocketManager(server, account);
- this.axios = Axios.create({
- baseURL: buildApiBaseUrl(server),
- headers: {
- Authorization: `Bearer ${account.token}`,
- DeviceId: account.deviceId,
- },
- });
-
- this.workspaces = new Map<string, WorkspaceManager>();
- this.accountPath = `${appPath}/${account.id}`;
- if (!fs.existsSync(this.accountPath)) {
- fs.mkdirSync(this.accountPath);
- }
-
- for (const workspace of workspaces) {
- this.workspaces.set(
- workspace.id,
- new WorkspaceManager(workspace, this.axios, this.accountPath),
- );
- }
-
- this.socket.on('mutation', async (mutation) => {
- try {
- const serverMutation = mutation as ServerMutation;
- const workspace = this.workspaces.get(serverMutation.workspaceId);
- if (!workspace) {
- return;
- }
-
- const executed = await workspace.executeServerMutation(serverMutation);
- if (executed) {
- this.socket.send({
- type: 'mutation_ack',
- payload: {
- id: serverMutation.id,
- workspaceId: serverMutation.workspaceId,
- },
- });
- }
- } catch (error) {
- console.log(error);
- }
- });
- }
-
- public async init(): Promise<void> {
- for (const workspace of this.workspaces.values()) {
- await workspace.init();
- }
- }
-
- public getWorkspace(workspaceId: string): WorkspaceManager | undefined {
- return this.workspaces.get(workspaceId);
- }
-
- public async addWorkspace(workspace: Workspace): Promise<void> {
- const workspaceManager = new WorkspaceManager(
- workspace,
- this.axios,
- this.accountPath,
- );
-
- await workspaceManager.init();
- this.workspaces.set(workspace.id, workspaceManager);
- }
-
- public async logout(): Promise<boolean> {
- const { status } = await this.axios.delete(
- `v1/accounts/logout/${this.account.deviceId}`,
- );
-
- if (status !== 200) {
- return false;
- }
-
- if (fs.existsSync(this.accountPath)) {
- fs.rm(this.accountPath, { recursive: true, force: true }, (err) => {
- if (err) {
- console.error('Error deleting account directory: ', err);
- }
- });
- }
-
- if (this.socket) {
- this.socket.close();
- }
-
- return true;
- }
-
- public async executeEventLoop(): Promise<void> {
- this.socket.checkConnection();
- for (const workspace of this.workspaces.values()) {
- if (!workspace.isSynced()) {
- const synced = await workspace.sync();
- if (synced) {
- await this.database
- .updateTable('workspaces')
- .set({ synced: 1 })
- .where('id', '=', workspace.getWorkspace().id)
- .execute();
- }
- }
- await workspace.sendMutations();
- }
- }
-}
+// import * as fs from 'node:fs';
+// import Axios, { AxiosInstance } from 'axios';
+// import { Account } from '@/types/accounts';
+// import { Workspace } from '@/types/workspaces';
+// import { WorkspaceManager } from '@/electron/workspace-manager';
+// import { SocketManager } from '@/electron/socket-manager';
+// import { ServerMutation } from '@/types/mutations';
+// import { Kysely } from 'kysely';
+// import { AppDatabaseSchema } from '@/electron/schemas/app';
+// import { Server } from '@/types/servers';
+// import { buildApiBaseUrl } from '@/lib/servers';
+
+// export class AccountManager {
+// public readonly account: Account;
+// private readonly accountPath: string;
+// private readonly socket: SocketManager;
+// private readonly axios: AxiosInstance;
+// private readonly workspaces: Map<string, WorkspaceManager>;
+// private readonly database: Kysely<AppDatabaseSchema>;
+
+// constructor(
+// server: Server,
+// account: Account,
+// appPath: string,
+// workspaces: Workspace[],
+// database: Kysely<AppDatabaseSchema>,
+// ) {
+// this.account = account;
+// this.database = database;
+// this.socket = new SocketManager(server, account);
+// this.axios = Axios.create({
+// baseURL: buildApiBaseUrl(server),
+// headers: {
+// Authorization: `Bearer ${account.token}`,
+// DeviceId: account.deviceId,
+// },
+// });
+
+// this.workspaces = new Map<string, WorkspaceManager>();
+// this.accountPath = `${appPath}/${account.id}`;
+// if (!fs.existsSync(this.accountPath)) {
+// fs.mkdirSync(this.accountPath);
+// }
+
+// for (const workspace of workspaces) {
+// this.workspaces.set(
+// workspace.id,
+// new WorkspaceManager(workspace, this.axios, this.accountPath),
+// );
+// }
+
+// this.socket.on('mutation', async (mutation) => {
+// try {
+// const serverMutation = mutation as ServerMutation;
+// const workspace = this.workspaces.get(serverMutation.workspaceId);
+// if (!workspace) {
+// return;
+// }
+
+// const executed = await workspace.executeServerMutation(serverMutation);
+// if (executed) {
+// this.socket.send({
+// type: 'mutation_ack',
+// payload: {
+// id: serverMutation.id,
+// workspaceId: serverMutation.workspaceId,
+// },
+// });
+// }
+// } catch (error) {
+// console.log(error);
+// }
+// });
+// }
+
+// public async init(): Promise<void> {
+// for (const workspace of this.workspaces.values()) {
+// await workspace.init();
+// }
+// }
+
+// public getWorkspace(workspaceId: string): WorkspaceManager | undefined {
+// return this.workspaces.get(workspaceId);
+// }
+
+// public async addWorkspace(workspace: Workspace): Promise<void> {
+// const workspaceManager = new WorkspaceManager(
+// workspace,
+// this.axios,
+// this.accountPath,
+// );
+
+// await workspaceManager.init();
+// this.workspaces.set(workspace.id, workspaceManager);
+// }
+
+// public async logout(): Promise<boolean> {
+// const { status } = await this.axios.delete(
+// `v1/accounts/logout/${this.account.deviceId}`,
+// );
+
+// if (status !== 200) {
+// return false;
+// }
+
+// if (fs.existsSync(this.accountPath)) {
+// fs.rm(this.accountPath, { recursive: true, force: true }, (err) => {
+// if (err) {
+// console.error('Error deleting account directory: ', err);
+// }
+// });
+// }
+
+// if (this.socket) {
+// this.socket.close();
+// }
+
+// return true;
+// }
+
+// public async executeEventLoop(): Promise<void> {
+// this.socket.checkConnection();
+// for (const workspace of this.workspaces.values()) {
+// if (!workspace.isSynced()) {
+// const synced = await workspace.sync();
+// if (synced) {
+// await this.database
+// .updateTable('workspaces')
+// .set({ synced: 1 })
+// .where('id', '=', workspace.getWorkspace().id)
+// .execute();
+// }
+// }
+// await workspace.sendMutations();
+// }
+// }
+// }
diff --git a/desktop/src/electron/app-manager.ts b/desktop/src/electron/app-manager.ts
index 83add467..c680d63f 100644
--- a/desktop/src/electron/app-manager.ts
+++ b/desktop/src/electron/app-manager.ts
@@ -1,383 +1,383 @@
-import { app } from 'electron';
-import {
- CompiledQuery,
- Kysely,
- Migration,
- Migrator,
- QueryResult,
- SqliteDialect,
-} from 'kysely';
-import { AccountManager } from '@/electron/account-manager';
-import { AppDatabaseSchema } from '@/electron/schemas/app';
-import { appDatabaseMigrations } from '@/electron/migrations/app';
-import { Account } from '@/types/accounts';
-import {
- buildSqlite,
- extractTablesFromSql,
- resultHasChanged,
-} from '@/electron/utils';
-import { Workspace, WorkspaceRole } from '@/types/workspaces';
-import { SubscribedQueryContext, SubscribedQueryResult } from '@/types/queries';
-import { eventBus } from '@/lib/event-bus';
-import { isEqual } from 'lodash';
-import { Server } from '@/types/servers';
-
-const EVENT_LOOP_INTERVAL = 1000;
-
-class AppManager {
- private readonly servers: Map<string, Server>;
- private readonly accounts: Map<string, AccountManager>;
- private readonly appPath: string;
- private readonly database: Kysely<AppDatabaseSchema>;
- private readonly subscribers: Map<string, SubscribedQueryResult<unknown>>;
- private initPromise: Promise<void> | null = null;
-
- constructor() {
- this.servers = new Map<string, Server>();
- this.accounts = new Map<string, AccountManager>();
- this.appPath = app.getPath('userData');
- this.subscribers = new Map();
-
- const dialect = new SqliteDialect({
- database: buildSqlite(`${this.appPath}/app.db`),
- });
-
- this.database = new Kysely<AppDatabaseSchema>({
- dialect,
- });
-
- this.executeEventLoop = this.executeEventLoop.bind(this);
- }
-
- public async getAccount(
- accountId: string,
- ): Promise<AccountManager | undefined> {
- await this.waitForInit();
- return this.accounts.get(accountId);
- }
-
- public async init(): Promise<void> {
- if (!this.initPromise) {
- this.initPromise = this.executeInit();
- }
-
- await this.initPromise;
- }
-
- public async executeQuery<T>(
- query: CompiledQuery<T>,
- ): Promise<QueryResult<T>> {
- await this.waitForInit();
- const result = await this.database.executeQuery(query);
-
- //only mutations should have side effects
- if (result.numAffectedRows > 0) {
- throw new Error('Query should not have any side effects');
- }
-
- return result;
- }
-
- public async executeQueryAndSubscribe<T>(
- context: SubscribedQueryContext<T>,
- ): Promise<QueryResult<T>> {
- await this.waitForInit();
- const result = await this.database.executeQuery(context.query);
-
- // only mutations should have side effects
- if (result.numAffectedRows > 0) {
- throw new Error('Query should not have any side effects');
- }
-
- const queryId = context.key.join('|') + context.page;
- const selectedTables = extractTablesFromSql(context.query.sql);
- const subscriberData: SubscribedQueryResult<T> = {
- context,
- tables: selectedTables,
- result: result,
- };
- this.subscribers.set(queryId, subscriberData);
-
- return result;
- }
-
- public async executeMutation(
- mutation: CompiledQuery | CompiledQuery[],
- ): Promise<void> {
- const affectedTables = new Set<string>();
- let numAffectedRows = 0n;
-
- if (Array.isArray(mutation)) {
- // Execute multiple queries as a transaction
- await this.database.transaction().execute(async (trx) => {
- for (const query of mutation) {
- const result = await trx.executeQuery(query);
- if (result.numAffectedRows > 0n) {
- numAffectedRows += result.numAffectedRows;
- extractTablesFromSql(query.sql).forEach((table) =>
- affectedTables.add(table),
- );
- }
- }
- });
- } else {
- // Execute single query
- const result = await this.database.executeQuery(mutation);
- numAffectedRows = result.numAffectedRows;
- if (numAffectedRows > 0n) {
- extractTablesFromSql(mutation.sql).forEach((table) =>
- affectedTables.add(table),
- );
- }
- }
-
- if (numAffectedRows === 0n) {
- return;
- }
-
- if (affectedTables.size === 0) {
- return;
- }
-
- if (affectedTables.has('servers')) {
- const servers = await this.getServers();
- for (const server of servers) {
- this.servers.set(server.domain, server);
- }
- }
-
- if (affectedTables.has('accounts')) {
- const accounts = await this.getAccounts();
- for (const account of accounts) {
- if (this.accounts.has(account.id)) {
- continue;
- }
-
- const server = this.servers.get(account.server);
- if (!server) {
- continue;
- }
-
- const accountManager = new AccountManager(
- server,
- account,
- this.appPath,
- [],
- this.database,
- );
-
- await accountManager.init();
- this.accounts.set(account.id, accountManager);
- }
- }
-
- if (affectedTables.has('workspaces')) {
- const workspaces = await this.getWorkspaces();
- for (const workspace of workspaces) {
- const accountManager = this.accounts.get(workspace.accountId);
- if (!accountManager) {
- continue;
- }
-
- const workspaceManager = accountManager.getWorkspace(workspace.id);
- if (!workspaceManager) {
- await accountManager.addWorkspace(workspace);
- }
- }
- }
-
- for (const subscriber of this.subscribers.values()) {
- const hasAffectedTables = subscriber.tables.some((table) =>
- affectedTables.has(table),
- );
-
- if (!hasAffectedTables) {
- continue;
- }
-
- const newResult = await this.database.executeQuery(
- subscriber.context.query,
- );
-
- if (resultHasChanged(subscriber.result, newResult)) {
- subscriber.result = newResult;
- eventBus.publish({
- event: 'app_query_updated',
- payload: {
- key: subscriber.context.key,
- page: subscriber.context.page,
- result: newResult,
- },
- });
- }
- }
- }
-
- public unsubscribeQuery(queryKey: string[]): void {
- var queryIds = [...this.subscribers.keys()];
- for (const queryId of queryIds) {
- const subscriberData = this.subscribers.get(queryId);
- if (isEqual(subscriberData.context.key, queryKey)) {
- this.subscribers.delete(queryId);
- }
- }
- }
-
- public async logout(accountId: string): Promise<void> {
- await this.waitForInit();
- const accountManager = this.accounts.get(accountId);
- if (!accountManager) {
- throw new Error(`Account not found: ${accountId}`);
- }
-
- accountManager.account.status = 'logout';
- const markAccountLoggedOutQuery = this.database
- .updateTable('accounts')
- .set({
- status: 'logout',
- })
- .where('id', '=', accountId)
- .compile();
-
- await this.executeMutation(markAccountLoggedOutQuery);
- }
-
- private async waitForInit(): Promise<void> {
- if (!this.initPromise) {
- this.initPromise = this.executeInit();
- }
-
- await this.initPromise;
- }
-
- private async executeInit(): Promise<void> {
- await this.migrate();
-
- const servers = await this.getServers();
- for (const server of servers) {
- this.servers.set(server.domain, server);
- }
-
- const accounts = await this.getAccounts();
- const workspaces = await this.getWorkspaces();
- for (const account of accounts) {
- const accountWorkspaces = workspaces.filter(
- (workspace) => workspace.accountId === account.id,
- );
-
- const server = this.servers.get(account.server);
- if (!server) {
- continue;
- }
-
- const accountManager = new AccountManager(
- server,
- account,
- this.appPath,
- accountWorkspaces,
- this.database,
- );
- await accountManager.init();
-
- this.accounts.set(account.id, accountManager);
- }
-
- setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
- }
-
- private async executeEventLoop(): Promise<void> {
- try {
- for (const accountManager of this.accounts.values()) {
- if (accountManager.account.status === 'logout') {
- const loggedOut = await accountManager.logout();
- if (loggedOut) {
- await this.database
- .deleteFrom('accounts')
- .where('id', '=', accountManager.account.id)
- .execute();
-
- this.accounts.delete(accountManager.account.id);
- }
- } else {
- await accountManager.executeEventLoop();
- }
- }
- } catch (error) {
- // console.error('Error in event loop:', error);
- }
- setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
- }
-
- private async migrate(): Promise<void> {
- const migrator = new Migrator({
- db: this.database,
- provider: {
- getMigrations(): Promise<Record<string, Migration>> {
- return Promise.resolve(appDatabaseMigrations);
- },
- },
- });
-
- await migrator.migrateToLatest();
- }
-
- private async getServers(): Promise<Server[]> {
- const servers = await this.database
- .selectFrom('servers')
- .selectAll()
- .execute();
-
- return servers.map((server) => ({
- domain: server.domain,
- name: server.name,
- avatar: server.avatar,
- attributes: JSON.parse(server.attributes),
- version: server.version,
- createdAt: new Date(server.created_at),
- lastSyncedAt: server.last_synced_at
- ? new Date(server.last_synced_at)
- : null,
- }));
- }
-
- private async getAccounts(): Promise<Account[]> {
- const accounts = await this.database
- .selectFrom('accounts')
- .selectAll()
- .execute();
-
- return accounts.map((account) => ({
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- token: account.token,
- deviceId: account.device_id,
- server: account.server,
- status: account.status,
- }));
- }
-
- private async getWorkspaces(): Promise<Workspace[]> {
- const workspaces = await this.database
- .selectFrom('workspaces')
- .selectAll()
- .execute();
-
- return workspaces.map(
- (workspace): Workspace => ({
- id: workspace.id,
- accountId: workspace.account_id,
- name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
- versionId: workspace.version_id,
- role: workspace.role as WorkspaceRole,
- userId: workspace.user_id,
- synced: workspace.synced === 1,
- }),
- );
- }
-}
-
-export const appManager = new AppManager();
+// import { app } from 'electron';
+// import {
+// CompiledQuery,
+// Kysely,
+// Migration,
+// Migrator,
+// QueryResult,
+// SqliteDialect,
+// } from 'kysely';
+// import { AccountManager } from '@/electron/account-manager';
+// import { AppDatabaseSchema } from '@/electron/schemas/app';
+// import { appDatabaseMigrations } from '@/electron/migrations/app';
+// import { Account } from '@/types/accounts';
+// import {
+// buildSqlite,
+// extractTablesFromSql,
+// resultHasChanged,
+// } from '@/electron/utils';
+// import { Workspace, WorkspaceRole } from '@/types/workspaces';
+// import { SubscribedQueryContext, SubscribedQueryResult } from '@/types/queries';
+// import { eventBus } from '@/lib/event-bus';
+// import { isEqual } from 'lodash';
+// import { Server } from '@/types/servers';
+
+// const EVENT_LOOP_INTERVAL = 1000;
+
+// class AppManager {
+// private readonly servers: Map<string, Server>;
+// private readonly accounts: Map<string, AccountManager>;
+// private readonly appPath: string;
+// private readonly database: Kysely<AppDatabaseSchema>;
+// private readonly subscribers: Map<string, SubscribedQueryResult<unknown>>;
+// private initPromise: Promise<void> | null = null;
+
+// constructor() {
+// this.servers = new Map<string, Server>();
+// this.accounts = new Map<string, AccountManager>();
+// this.appPath = app.getPath('userData');
+// this.subscribers = new Map();
+
+// const dialect = new SqliteDialect({
+// database: buildSqlite(`${this.appPath}/app.db`),
+// });
+
+// this.database = new Kysely<AppDatabaseSchema>({
+// dialect,
+// });
+
+// this.executeEventLoop = this.executeEventLoop.bind(this);
+// }
+
+// public async getAccount(
+// accountId: string,
+// ): Promise<AccountManager | undefined> {
+// await this.waitForInit();
+// return this.accounts.get(accountId);
+// }
+
+// public async init(): Promise<void> {
+// if (!this.initPromise) {
+// this.initPromise = this.executeInit();
+// }
+
+// await this.initPromise;
+// }
+
+// public async executeQuery<T>(
+// query: CompiledQuery<T>,
+// ): Promise<QueryResult<T>> {
+// await this.waitForInit();
+// const result = await this.database.executeQuery(query);
+
+// //only mutations should have side effects
+// if (result.numAffectedRows > 0) {
+// throw new Error('Query should not have any side effects');
+// }
+
+// return result;
+// }
+
+// public async executeQueryAndSubscribe<T>(
+// context: SubscribedQueryContext<T>,
+// ): Promise<QueryResult<T>> {
+// await this.waitForInit();
+// const result = await this.database.executeQuery(context.query);
+
+// // only mutations should have side effects
+// if (result.numAffectedRows > 0) {
+// throw new Error('Query should not have any side effects');
+// }
+
+// const queryId = context.key.join('|') + context.page;
+// const selectedTables = extractTablesFromSql(context.query.sql);
+// const subscriberData: SubscribedQueryResult<T> = {
+// context,
+// tables: selectedTables,
+// result: result,
+// };
+// this.subscribers.set(queryId, subscriberData);
+
+// return result;
+// }
+
+// public async executeMutation(
+// mutation: CompiledQuery | CompiledQuery[],
+// ): Promise<void> {
+// const affectedTables = new Set<string>();
+// let numAffectedRows = 0n;
+
+// if (Array.isArray(mutation)) {
+// // Execute multiple queries as a transaction
+// await this.database.transaction().execute(async (trx) => {
+// for (const query of mutation) {
+// const result = await trx.executeQuery(query);
+// if (result.numAffectedRows > 0n) {
+// numAffectedRows += result.numAffectedRows;
+// extractTablesFromSql(query.sql).forEach((table) =>
+// affectedTables.add(table),
+// );
+// }
+// }
+// });
+// } else {
+// // Execute single query
+// const result = await this.database.executeQuery(mutation);
+// numAffectedRows = result.numAffectedRows;
+// if (numAffectedRows > 0n) {
+// extractTablesFromSql(mutation.sql).forEach((table) =>
+// affectedTables.add(table),
+// );
+// }
+// }
+
+// if (numAffectedRows === 0n) {
+// return;
+// }
+
+// if (affectedTables.size === 0) {
+// return;
+// }
+
+// if (affectedTables.has('servers')) {
+// const servers = await this.getServers();
+// for (const server of servers) {
+// this.servers.set(server.domain, server);
+// }
+// }
+
+// if (affectedTables.has('accounts')) {
+// const accounts = await this.getAccounts();
+// for (const account of accounts) {
+// if (this.accounts.has(account.id)) {
+// continue;
+// }
+
+// const server = this.servers.get(account.server);
+// if (!server) {
+// continue;
+// }
+
+// const accountManager = new AccountManager(
+// server,
+// account,
+// this.appPath,
+// [],
+// this.database,
+// );
+
+// await accountManager.init();
+// this.accounts.set(account.id, accountManager);
+// }
+// }
+
+// if (affectedTables.has('workspaces')) {
+// const workspaces = await this.getWorkspaces();
+// for (const workspace of workspaces) {
+// const accountManager = this.accounts.get(workspace.accountId);
+// if (!accountManager) {
+// continue;
+// }
+
+// const workspaceManager = accountManager.getWorkspace(workspace.id);
+// if (!workspaceManager) {
+// await accountManager.addWorkspace(workspace);
+// }
+// }
+// }
+
+// for (const subscriber of this.subscribers.values()) {
+// const hasAffectedTables = subscriber.tables.some((table) =>
+// affectedTables.has(table),
+// );
+
+// if (!hasAffectedTables) {
+// continue;
+// }
+
+// const newResult = await this.database.executeQuery(
+// subscriber.context.query,
+// );
+
+// if (resultHasChanged(subscriber.result, newResult)) {
+// subscriber.result = newResult;
+// eventBus.publish({
+// event: 'app_query_updated',
+// payload: {
+// key: subscriber.context.key,
+// page: subscriber.context.page,
+// result: newResult,
+// },
+// });
+// }
+// }
+// }
+
+// public unsubscribeQuery(queryKey: string[]): void {
+// var queryIds = [...this.subscribers.keys()];
+// for (const queryId of queryIds) {
+// const subscriberData = this.subscribers.get(queryId);
+// if (isEqual(subscriberData.context.key, queryKey)) {
+// this.subscribers.delete(queryId);
+// }
+// }
+// }
+
+// public async logout(accountId: string): Promise<void> {
+// await this.waitForInit();
+// const accountManager = this.accounts.get(accountId);
+// if (!accountManager) {
+// throw new Error(`Account not found: ${accountId}`);
+// }
+
+// accountManager.account.status = 'logout';
+// const markAccountLoggedOutQuery = this.database
+// .updateTable('accounts')
+// .set({
+// status: 'logout',
+// })
+// .where('id', '=', accountId)
+// .compile();
+
+// await this.executeMutation(markAccountLoggedOutQuery);
+// }
+
+// private async waitForInit(): Promise<void> {
+// if (!this.initPromise) {
+// this.initPromise = this.executeInit();
+// }
+
+// await this.initPromise;
+// }
+
+// private async executeInit(): Promise<void> {
+// await this.migrate();
+
+// const servers = await this.getServers();
+// for (const server of servers) {
+// this.servers.set(server.domain, server);
+// }
+
+// const accounts = await this.getAccounts();
+// const workspaces = await this.getWorkspaces();
+// for (const account of accounts) {
+// const accountWorkspaces = workspaces.filter(
+// (workspace) => workspace.accountId === account.id,
+// );
+
+// const server = this.servers.get(account.server);
+// if (!server) {
+// continue;
+// }
+
+// const accountManager = new AccountManager(
+// server,
+// account,
+// this.appPath,
+// accountWorkspaces,
+// this.database,
+// );
+// await accountManager.init();
+
+// this.accounts.set(account.id, accountManager);
+// }
+
+// setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
+// }
+
+// private async executeEventLoop(): Promise<void> {
+// try {
+// for (const accountManager of this.accounts.values()) {
+// if (accountManager.account.status === 'logout') {
+// const loggedOut = await accountManager.logout();
+// if (loggedOut) {
+// await this.database
+// .deleteFrom('accounts')
+// .where('id', '=', accountManager.account.id)
+// .execute();
+
+// this.accounts.delete(accountManager.account.id);
+// }
+// } else {
+// await accountManager.executeEventLoop();
+// }
+// }
+// } catch (error) {
+// // console.error('Error in event loop:', error);
+// }
+// setTimeout(this.executeEventLoop, EVENT_LOOP_INTERVAL);
+// }
+
+// private async migrate(): Promise<void> {
+// const migrator = new Migrator({
+// db: this.database,
+// provider: {
+// getMigrations(): Promise<Record<string, Migration>> {
+// return Promise.resolve(appDatabaseMigrations);
+// },
+// },
+// });
+
+// await migrator.migrateToLatest();
+// }
+
+// private async getServers(): Promise<Server[]> {
+// const servers = await this.database
+// .selectFrom('servers')
+// .selectAll()
+// .execute();
+
+// return servers.map((server) => ({
+// domain: server.domain,
+// name: server.name,
+// avatar: server.avatar,
+// attributes: JSON.parse(server.attributes),
+// version: server.version,
+// createdAt: new Date(server.created_at),
+// lastSyncedAt: server.last_synced_at
+// ? new Date(server.last_synced_at)
+// : null,
+// }));
+// }
+
+// private async getAccounts(): Promise<Account[]> {
+// const accounts = await this.database
+// .selectFrom('accounts')
+// .selectAll()
+// .execute();
+
+// return accounts.map((account) => ({
+// id: account.id,
+// name: account.name,
+// email: account.email,
+// avatar: account.avatar,
+// token: account.token,
+// deviceId: account.device_id,
+// server: account.server,
+// status: account.status,
+// }));
+// }
+
+// private async getWorkspaces(): Promise<Workspace[]> {
+// const workspaces = await this.database
+// .selectFrom('workspaces')
+// .selectAll()
+// .execute();
+
+// return workspaces.map(
+// (workspace): Workspace => ({
+// id: workspace.id,
+// accountId: workspace.account_id,
+// name: workspace.name,
+// description: workspace.description,
+// avatar: workspace.avatar,
+// versionId: workspace.version_id,
+// role: workspace.role as WorkspaceRole,
+// userId: workspace.user_id,
+// synced: workspace.synced === 1,
+// }),
+// );
+// }
+// }
+
+// export const appManager = new AppManager();
diff --git a/desktop/src/electron/database-context.ts b/desktop/src/electron/database-context.ts
new file mode 100644
index 00000000..a1e091c7
--- /dev/null
+++ b/desktop/src/electron/database-context.ts
@@ -0,0 +1,136 @@
+import { app } from 'electron';
+import * as fs from 'node:fs';
+import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
+import { AppDatabaseSchema, SelectWorkspace } from '@/electron/schemas/app';
+import { WorkspaceDatabaseSchema } from '@/electron/schemas/workspace';
+import { buildSqlite } from '@/electron/utils';
+import { appDatabaseMigrations } from '@/electron/migrations/app';
+import { workspaceDatabaseMigrations } from '@/electron/migrations/workspace';
+
+class DatabaseContext {
+ private readonly appPath: string;
+ private initPromise: Promise<void> | null = null;
+ private readonly workspaceDatabases: Map<
+ string,
+ Kysely<WorkspaceDatabaseSchema>
+ > = new Map();
+
+ public readonly appDatabase: Kysely<AppDatabaseSchema>;
+
+ constructor() {
+ this.appPath = app.getPath('userData');
+
+ const dialect = new SqliteDialect({
+ database: buildSqlite(`${this.appPath}/app.db`),
+ });
+
+ this.appDatabase = new Kysely<AppDatabaseSchema>({ dialect });
+ }
+
+ public async init(): Promise<void> {
+ if (!this.initPromise) {
+ this.initPromise = this.executeInit();
+ }
+
+ await this.initPromise;
+ }
+
+ public async getWorkspaceDatabase(
+ userId: string,
+ ): Promise<Kysely<WorkspaceDatabaseSchema> | null> {
+ this.waitForInit();
+
+ if (this.workspaceDatabases.has(userId)) {
+ return this.workspaceDatabases.get(userId);
+ }
+
+ //try and check if it's in database but hasn't been loaded yet
+ const workspace = await this.appDatabase
+ .selectFrom('workspaces')
+ .selectAll()
+ .where('user_id', '=', userId)
+ .executeTakeFirst();
+
+ if (!workspace) {
+ return null;
+ }
+
+ await this.initWorkspaceDatabase(workspace);
+ if (this.workspaceDatabases.has(userId)) {
+ return this.workspaceDatabases.get(userId);
+ }
+
+ return null;
+ }
+
+ private async waitForInit(): Promise<void> {
+ if (!this.initPromise) {
+ this.initPromise = this.executeInit();
+ }
+
+ await this.initPromise;
+ }
+
+ private async executeInit(): Promise<void> {
+ await this.migrateAppDatabase();
+
+ const workspaces = await this.appDatabase
+ .selectFrom('workspaces')
+ .selectAll()
+ .execute();
+
+ for (const workspace of workspaces) {
+ await this.initWorkspaceDatabase(workspace);
+ }
+ }
+
+ private async initWorkspaceDatabase(
+ workspace: SelectWorkspace,
+ ): Promise<void> {
+ const workspaceDir = `${this.appPath}/${workspace.user_id}`;
+ if (!fs.existsSync(workspaceDir)) {
+ fs.mkdirSync(workspaceDir);
+ }
+
+ const dialect = new SqliteDialect({
+ database: buildSqlite(`${workspaceDir}/workspace.db`),
+ });
+
+ const workspaceDatabase = new Kysely<WorkspaceDatabaseSchema>({
+ dialect,
+ });
+
+ await this.migrateWorkspaceDatabase(workspaceDatabase);
+ this.workspaceDatabases.set(workspace.user_id, workspaceDatabase);
+ }
+
+ private async migrateAppDatabase(): Promise<void> {
+ const migrator = new Migrator({
+ db: this.appDatabase,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(appDatabaseMigrations);
+ },
+ },
+ });
+
+ await migrator.migrateToLatest();
+ }
+
+ private async migrateWorkspaceDatabase(
+ database: Kysely<WorkspaceDatabaseSchema>,
+ ): Promise<void> {
+ const migrator = new Migrator({
+ db: database,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(workspaceDatabaseMigrations);
+ },
+ },
+ });
+
+ await migrator.migrateToLatest();
+ }
+}
+
+export const databaseContext = new DatabaseContext();
diff --git a/desktop/src/electron/mediator.ts b/desktop/src/electron/mediator.ts
new file mode 100644
index 00000000..c9f48832
--- /dev/null
+++ b/desktop/src/electron/mediator.ts
@@ -0,0 +1,85 @@
+import {
+ MutationChange,
+ MutationHandler,
+ MutationInput,
+ MutationMap,
+} from '@/types/mutations';
+import { mutationHandlerMap } from '@/electron/mutations';
+import {
+ QueryHandler,
+ QueryInput,
+ QueryMap,
+ SubscribedQuery,
+} from '@/types/queries';
+import { queryHandlerMap } from '@/electron/queries';
+import { eventBus } from '@/lib/event-bus';
+
+class Mediator {
+ private readonly subscribedQueries: Map<string, SubscribedQuery<QueryInput>> =
+ new Map();
+
+ public async handleMutation<T extends MutationInput>(
+ input: T,
+ ): Promise<MutationMap[T['type']]['output']> {
+ const handler = mutationHandlerMap[input.type] as MutationHandler<T>;
+ const result = await handler.handleMutation(input);
+
+ if (result.changedTables) {
+ await this.checkForQueryChanges(result.changedTables);
+ }
+
+ return result.output;
+ }
+
+ public async handleQuery<T extends QueryInput>(
+ id: string,
+ input: T,
+ ): Promise<QueryMap[T['type']]['output']> {
+ const handler = queryHandlerMap[input.type] as QueryHandler<T>;
+ const result = await handler.handleQuery(input);
+ this.subscribedQueries.set(id, {
+ input,
+ result,
+ });
+ return result.output;
+ }
+
+ public unsubscribeQuery(id: string) {
+ this.subscribedQueries.delete(id);
+ }
+
+ private async checkForQueryChanges(changes: MutationChange[]): Promise<void> {
+ if (changes.length === 0) {
+ return;
+ }
+
+ for (const [id, query] of this.subscribedQueries) {
+ const handler = queryHandlerMap[query.input.type] as QueryHandler<
+ typeof query.input
+ >;
+
+ const changeCheckResult = await handler.checkForChanges(
+ changes,
+ query.input,
+ query.result.state,
+ );
+ if (changeCheckResult.hasChanges && changeCheckResult.result) {
+ const newResult = changeCheckResult.result;
+ this.subscribedQueries.set(id, {
+ input: query.input,
+ result: newResult,
+ });
+
+ eventBus.publish({
+ event: 'query_result_updated',
+ payload: {
+ id: id,
+ result: newResult.output,
+ },
+ });
+ }
+ }
+ }
+}
+
+export const mediator = new Mediator();
diff --git a/desktop/src/electron/migrations/app.ts b/desktop/src/electron/migrations/app.ts
index b5a55ac1..836d311e 100644
--- a/desktop/src/electron/migrations/app.ts
+++ b/desktop/src/electron/migrations/app.ts
@@ -81,7 +81,8 @@ const createWorkspacesTable: Migration = {
up: async (db) => {
await db.schema
.createTable('workspaces')
- .addColumn('id', 'text', (col) => col.notNull())
+ .addColumn('user_id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('workspace_id', 'text', (col) => col.notNull())
.addColumn('account_id', 'text', (col) =>
col.notNull().references('accounts.id').onDelete('cascade'),
)
@@ -90,7 +91,6 @@ const createWorkspacesTable: Migration = {
.addColumn('avatar', 'text')
.addColumn('version_id', 'text', (col) => col.notNull())
.addColumn('role', 'text', (col) => col.notNull())
- .addColumn('user_id', 'text', (col) => col.notNull())
.addColumn('synced', 'integer')
.execute();
},
diff --git a/desktop/src/electron/migrations/workspace.ts b/desktop/src/electron/migrations/workspace.ts
index 45353190..633cb59e 100644
--- a/desktop/src/electron/migrations/workspace.ts
+++ b/desktop/src/electron/migrations/workspace.ts
@@ -101,7 +101,7 @@ const createNodeReactionsTable: Migration = {
.addColumn('node_id', 'text', (col) =>
col.notNull().references('nodes.id').onDelete('cascade'),
)
- .addColumn('reactor_id', 'text', (col) =>
+ .addColumn('actor_id', 'text', (col) =>
col.notNull().references('nodes.id').onDelete('cascade'),
)
.addColumn('reaction', 'text', (col) => col.notNull())
@@ -109,7 +109,7 @@ const createNodeReactionsTable: Migration = {
.addColumn('server_created_at', 'text')
.addPrimaryKeyConstraint('node_reactions_pkey', [
'node_id',
- 'reactor_id',
+ 'actor_id',
'reaction',
])
.execute();
@@ -460,7 +460,7 @@ const createNodeReactionInsertMutationTrigger: Migration = {
'node_reactions',
json_object(
'node_id', NEW.'node_id',
- 'reactor_id', NEW.'reactor_id',
+ 'actor_id', NEW.'actor_id',
'reaction', NEW.'reaction',
'created_at', NEW.'created_at',
'server_created_at', NEW.'server_created_at'
@@ -488,7 +488,7 @@ const createNodeReactionDeleteMutationTrigger: Migration = {
'node_reactions',
json_object(
'node_id', OLD.'node_id',
- 'reactor_id', OLD.'reactor_id',
+ 'actor_id', OLD.'actor_id',
'reaction', OLD.'reaction',
'created_at', OLD.'created_at',
'server_created_at', OLD.'server_created_at'
diff --git a/desktop/src/electron/mutations/board-view-create.ts b/desktop/src/electron/mutations/board-view-create.ts
new file mode 100644
index 00000000..584b9bfe
--- /dev/null
+++ b/desktop/src/electron/mutations/board-view-create.ts
@@ -0,0 +1,72 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { BoardViewCreateMutationInput } from '@/types/mutations/board-view-create';
+
+export class BoardViewCreateMutationHandler
+ implements MutationHandler<BoardViewCreateMutationInput>
+{
+ async handleMutation(
+ input: BoardViewCreateMutationInput,
+ ): Promise<MutationResult<BoardViewCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.databaseId),
+ eb('type', 'in', ViewNodeTypes),
+ ]),
+ )
+ .selectAll()
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.BoardView);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.BoardView,
+ parentId: input.databaseId,
+ index: generateNodeIndex(maxIndex, null),
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/calendar-view-create.ts b/desktop/src/electron/mutations/calendar-view-create.ts
new file mode 100644
index 00000000..89c9da65
--- /dev/null
+++ b/desktop/src/electron/mutations/calendar-view-create.ts
@@ -0,0 +1,72 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { CalendarViewCreateMutationInput } from '@/types/mutations/calendar-view-create';
+
+export class CalendarViewCreateMutationHandler
+ implements MutationHandler<CalendarViewCreateMutationInput>
+{
+ async handleMutation(
+ input: CalendarViewCreateMutationInput,
+ ): Promise<MutationResult<CalendarViewCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.databaseId),
+ eb('type', 'in', ViewNodeTypes),
+ ]),
+ )
+ .selectAll()
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.CalendarView);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.CalendarView,
+ parentId: input.databaseId,
+ index: generateNodeIndex(maxIndex, null),
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/channel-create.ts b/desktop/src/electron/mutations/channel-create.ts
new file mode 100644
index 00000000..84dfcff0
--- /dev/null
+++ b/desktop/src/electron/mutations/channel-create.ts
@@ -0,0 +1,67 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { ChannelCreateMutationInput } from '@/types/mutations/channel-create';
+
+export class ChannelCreateMutationHandler
+ implements MutationHandler<ChannelCreateMutationInput>
+{
+ async handleMutation(
+ input: ChannelCreateMutationInput,
+ ): Promise<MutationResult<ChannelCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', '=', input.spaceId)
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.Channel);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Channel,
+ parentId: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/chat-create.ts b/desktop/src/electron/mutations/chat-create.ts
new file mode 100644
index 00000000..6fdcae7c
--- /dev/null
+++ b/desktop/src/electron/mutations/chat-create.ts
@@ -0,0 +1,105 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode } from '@/lib/nodes';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { ChatCreateMutationInput } from '@/types/mutations/chat-create';
+
+export class ChatCreateMutationHandler
+ implements MutationHandler<ChatCreateMutationInput>
+{
+ async handleMutation(
+ input: ChatCreateMutationInput,
+ ): Promise<MutationResult<ChatCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const existingChats = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('type', '=', NodeTypes.Chat)
+ .where(
+ 'id',
+ 'in',
+ workspaceDatabase
+ .selectFrom('node_collaborators')
+ .select('node_id')
+ .where('collaborator_id', 'in', [input.userId, input.otherUserId])
+ .groupBy('node_id')
+ .having(workspaceDatabase.fn.count('collaborator_id'), '=', 2),
+ )
+ .execute();
+
+ if (existingChats.length > 0) {
+ const chat = existingChats[0];
+ return {
+ output: {
+ id: chat.id,
+ },
+ };
+ }
+
+ const id = NeuronId.generate(NeuronId.Type.Chat);
+ await workspaceDatabase.transaction().execute(async (trx) => {
+ await trx
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Chat,
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ await trx
+ .insertInto('node_collaborators')
+ .values([
+ {
+ node_id: id,
+ collaborator_id: input.userId,
+ role: 'owner',
+ created_at: new Date().toISOString(),
+ created_by: input.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ {
+ node_id: id,
+ collaborator_id: input.otherUserId,
+ role: 'owner',
+ created_at: new Date().toISOString(),
+ created_by: input.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ },
+ ])
+ .compile();
+ });
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ {
+ type: 'workspace',
+ table: 'node_collaborators',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/database-create.ts b/desktop/src/electron/mutations/database-create.ts
new file mode 100644
index 00000000..3b2021b2
--- /dev/null
+++ b/desktop/src/electron/mutations/database-create.ts
@@ -0,0 +1,96 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { DatabaseCreateMutationInput } from '@/types/mutations/database-create';
+
+export class DatabaseCreateMutationHandler
+ implements MutationHandler<DatabaseCreateMutationInput>
+{
+ async handleMutation(
+ input: DatabaseCreateMutationInput,
+ ): Promise<MutationResult<DatabaseCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', '=', input.spaceId)
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const databaseId = NeuronId.generate(NeuronId.Type.Database);
+ const tableViewId = NeuronId.generate(NeuronId.Type.TableView);
+ const fieldId = NeuronId.generate(NeuronId.Type.Field);
+
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values([
+ buildCreateNode(
+ {
+ id: databaseId,
+ attributes: {
+ type: NodeTypes.Database,
+ parentId: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ name: input.name,
+ },
+ },
+ input.userId,
+ ),
+ buildCreateNode(
+ {
+ id: tableViewId,
+ attributes: {
+ type: NodeTypes.TableView,
+ parentId: databaseId,
+ index: generateNodeIndex(null, null),
+ name: 'Default',
+ },
+ },
+ input.userId,
+ ),
+ buildCreateNode(
+ {
+ id: fieldId,
+ attributes: {
+ type: NodeTypes.Field,
+ parentId: databaseId,
+ index: generateNodeIndex(null, null),
+ name: 'Comment',
+ dataType: 'text',
+ },
+ },
+ input.userId,
+ ),
+ ])
+ .execute();
+
+ return {
+ output: {
+ id: databaseId,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/email-login.ts b/desktop/src/electron/mutations/email-login.ts
new file mode 100644
index 00000000..7a8bb908
--- /dev/null
+++ b/desktop/src/electron/mutations/email-login.ts
@@ -0,0 +1,94 @@
+import axios from 'axios';
+import { LoginOutput } from '@/types/accounts';
+import { databaseContext } from '@/electron/database-context';
+import { buildApiBaseUrl, mapServer } from '@/lib/servers';
+import { EmailLoginMutationInput } from '@/types/mutations/email-login';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/types/mutations';
+
+export class EmailLoginMutationHandler
+ implements MutationHandler<EmailLoginMutationInput>
+{
+ async handleMutation(
+ input: EmailLoginMutationInput,
+ ): Promise<MutationResult<EmailLoginMutationInput>> {
+ const serverRow = await databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .where('domain', '=', input.server)
+ .executeTakeFirst();
+
+ if (!serverRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const server = mapServer(serverRow);
+ const { data } = await axios.post<LoginOutput>(
+ `${buildApiBaseUrl(server)}/v1/accounts/login/email`,
+ {
+ email: input.email,
+ password: input.password,
+ },
+ );
+ const changedTables: MutationChange[] = [];
+ await databaseContext.appDatabase.transaction().execute(async (trx) => {
+ await trx
+ .insertInto('accounts')
+ .values({
+ id: data.account.id,
+ name: data.account.name,
+ avatar: data.account.avatar,
+ device_id: data.account.deviceId,
+ email: data.account.email,
+ token: data.account.token,
+ server: server.domain,
+ })
+ .execute();
+
+ changedTables.push({
+ type: 'app',
+ table: 'accounts',
+ });
+
+ if (data.workspaces.length === 0) {
+ return;
+ }
+
+ await trx
+ .insertInto('workspaces')
+ .values(
+ data.workspaces.map((workspace) => ({
+ id: workspace.id,
+ name: workspace.name,
+ account_id: data.account.id,
+ avatar: workspace.avatar,
+ role: workspace.role,
+ description: workspace.description,
+ synced: 0,
+ user_id: workspace.userId,
+ version_id: workspace.versionId,
+ })),
+ )
+ .execute();
+
+ changedTables.push({
+ type: 'app',
+ table: 'workspaces',
+ });
+ });
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: changedTables,
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/email-register.ts b/desktop/src/electron/mutations/email-register.ts
new file mode 100644
index 00000000..9cf7ac62
--- /dev/null
+++ b/desktop/src/electron/mutations/email-register.ts
@@ -0,0 +1,96 @@
+import axios from 'axios';
+import { LoginOutput } from '@/types/accounts';
+import { databaseContext } from '@/electron/database-context';
+import { buildApiBaseUrl, mapServer } from '@/lib/servers';
+import { EmailRegisterMutationInput } from '@/types/mutations/email-register';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/types/mutations';
+
+export class EmailRegisterMutationHandler
+ implements MutationHandler<EmailRegisterMutationInput>
+{
+ handleMutation = async (
+ input: EmailRegisterMutationInput,
+ ): Promise<MutationResult<EmailRegisterMutationInput>> => {
+ const serverRow = await databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .where('domain', '=', input.server)
+ .executeTakeFirst();
+
+ if (!serverRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const server = mapServer(serverRow);
+ const { data } = await axios.post<LoginOutput>(
+ `${buildApiBaseUrl(server)}/v1/accounts/register/email`,
+ {
+ name: input.name,
+ email: input.email,
+ password: input.password,
+ },
+ );
+
+ const changedTables: MutationChange[] = [];
+ await databaseContext.appDatabase.transaction().execute(async (trx) => {
+ await trx
+ .insertInto('accounts')
+ .values({
+ id: data.account.id,
+ name: data.account.name,
+ avatar: data.account.avatar,
+ device_id: data.account.deviceId,
+ email: data.account.email,
+ token: data.account.token,
+ server: serverRow.domain,
+ })
+ .execute();
+
+ changedTables.push({
+ type: 'app',
+ table: 'accounts',
+ });
+
+ if (data.workspaces.length === 0) {
+ return;
+ }
+
+ await trx
+ .insertInto('workspaces')
+ .values(
+ data.workspaces.map((workspace) => ({
+ id: workspace.id,
+ name: workspace.name,
+ account_id: data.account.id,
+ avatar: workspace.avatar,
+ role: workspace.role,
+ description: workspace.description,
+ synced: 0,
+ user_id: workspace.userId,
+ version_id: workspace.versionId,
+ })),
+ )
+ .execute();
+
+ changedTables.push({
+ type: 'app',
+ table: 'workspaces',
+ });
+ });
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: changedTables,
+ };
+ };
+}
diff --git a/desktop/src/electron/mutations/field-create.ts b/desktop/src/electron/mutations/field-create.ts
new file mode 100644
index 00000000..8fff095a
--- /dev/null
+++ b/desktop/src/electron/mutations/field-create.ts
@@ -0,0 +1,74 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { FieldCreateMutationInput } from '@/types/mutations/field-create';
+
+export class FieldCreateMutationHandler
+ implements MutationHandler<FieldCreateMutationInput>
+{
+ async handleMutation(
+ input: FieldCreateMutationInput,
+ ): Promise<MutationResult<FieldCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .where((eb) =>
+ eb.and({
+ parent_id: input.databaseId,
+ type: NodeTypes.Field,
+ }),
+ )
+ .selectAll()
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.Field);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Field,
+ parentId: input.databaseId,
+ index: generateNodeIndex(maxIndex, null),
+ name: input.name,
+ dataType: input.dataType,
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/index.ts b/desktop/src/electron/mutations/index.ts
new file mode 100644
index 00000000..0e96f214
--- /dev/null
+++ b/desktop/src/electron/mutations/index.ts
@@ -0,0 +1,63 @@
+import { MutationHandler, MutationMap } from '@/types/mutations';
+import { EmailLoginMutationHandler } from '@/electron/mutations/email-login';
+import { EmailRegisterMutationHandler } from '@/electron/mutations/email-register';
+import { BoardViewCreateMutationHandler } from '@/electron/mutations/board-view-create';
+import { CalendarViewCreateMutationHandler } from '@/electron/mutations/calendar-view-create';
+import { ChannelCreateMutationHandler } from '@/electron/mutations/channel-create';
+import { ChatCreateMutationHandler } from '@/electron/mutations/chat-create';
+import { TableViewCreateMutationHandler } from '@/electron/mutations/table-view-create';
+import { DatabaseCreateMutationHandler } from '@/electron/mutations/database-create';
+import { FieldCreateMutationHandler } from '@/electron/mutations/field-create';
+import { MessageCreateMutationHandler } from '@/electron/mutations/message-create';
+import { NodeAttributeDeleteMutationHandler } from '@/electron/mutations/node-attribute-delete';
+import { NodeAttributeSetMutationHandler } from '@/electron/mutations/node-attribute-set';
+import { NodeCollaboratorCreateMutationHandler } from '@/electron/mutations/node-collaborator-create';
+import { NodeCollaboratorDeleteMutationHandler } from '@/electron/mutations/node-collaborator-delete';
+import { NodeCollaboratorUpdateMutationHandler } from '@/electron/mutations/node-collaborator-update';
+import { NodeDeleteMutationHandler } from '@/electron/mutations/node-delete';
+import { PageCreateMutationHandler } from '@/electron/mutations/page-create';
+import { NodeReactionCreateMutationHandler } from '@/electron/mutations/node-reaction-create';
+import { NodeReactionDeleteMutationHandler } from '@/electron/mutations/node-reaction-delete';
+import { RecordCreateMutationHandler } from '@/electron/mutations/record-create';
+import { SelectOptionCreateMutationHandler } from '@/electron/mutations/select-option-create';
+import { ServerCreateMutationHandler } from '@/electron/mutations/server-create';
+import { SpaceCreateMutationHandler } from '@/electron/mutations/space-create';
+import { WorkspaceAccountRoleUpdateMutationHandler } from '@/electron/mutations/workspace-account-role-update';
+import { WorkspaceAccountsInviteMutationHandler } from '@/electron/mutations/workspace-accounts-invite';
+import { WorkspaceCreateMutationHandler } from '@/electron/mutations/workspace-create';
+import { WorkspaceUpdateMutationHandler } from '@/electron/mutations/workspace-update';
+
+type MutationHandlerMap = {
+ [K in keyof MutationMap]: MutationHandler<MutationMap[K]['input']>;
+};
+
+export const mutationHandlerMap: MutationHandlerMap = {
+ email_login: new EmailLoginMutationHandler(),
+ email_register: new EmailRegisterMutationHandler(),
+ board_view_create: new BoardViewCreateMutationHandler(),
+ calendar_view_create: new CalendarViewCreateMutationHandler(),
+ channel_create: new ChannelCreateMutationHandler(),
+ chat_create: new ChatCreateMutationHandler(),
+ table_view_create: new TableViewCreateMutationHandler(),
+ database_create: new DatabaseCreateMutationHandler(),
+ field_create: new FieldCreateMutationHandler(),
+ message_create: new MessageCreateMutationHandler(),
+ node_attribute_delete: new NodeAttributeDeleteMutationHandler(),
+ node_attribute_set: new NodeAttributeSetMutationHandler(),
+ node_collaborator_create: new NodeCollaboratorCreateMutationHandler(),
+ node_collaborator_delete: new NodeCollaboratorDeleteMutationHandler(),
+ node_collaborator_update: new NodeCollaboratorUpdateMutationHandler(),
+ node_delete: new NodeDeleteMutationHandler(),
+ page_create: new PageCreateMutationHandler(),
+ node_reaction_create: new NodeReactionCreateMutationHandler(),
+ node_reaction_delete: new NodeReactionDeleteMutationHandler(),
+ record_create: new RecordCreateMutationHandler(),
+ select_option_create: new SelectOptionCreateMutationHandler(),
+ server_create: new ServerCreateMutationHandler(),
+ space_create: new SpaceCreateMutationHandler(),
+ workspace_account_role_update:
+ new WorkspaceAccountRoleUpdateMutationHandler(),
+ workspace_accounts_invite: new WorkspaceAccountsInviteMutationHandler(),
+ workspace_create: new WorkspaceCreateMutationHandler(),
+ workspace_update: new WorkspaceUpdateMutationHandler(),
+};
diff --git a/desktop/src/electron/mutations/message-create.ts b/desktop/src/electron/mutations/message-create.ts
new file mode 100644
index 00000000..346b436a
--- /dev/null
+++ b/desktop/src/electron/mutations/message-create.ts
@@ -0,0 +1,72 @@
+import { mapContentsToEditorNodes } from '@/editor/mappers';
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode } from '@/lib/nodes';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { MessageCreateMutationInput } from '@/types/mutations/message-create';
+import { LocalNode } from '@/types/nodes';
+import { CreateNode } from '@/electron/schemas/workspace';
+
+export class MessageCreateMutationHandler
+ implements MutationHandler<MessageCreateMutationInput>
+{
+ async handleMutation(
+ input: MessageCreateMutationInput,
+ ): Promise<MutationResult<MessageCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const id = NeuronId.generate(NeuronId.Type.Message);
+ const editorNodes = mapContentsToEditorNodes(
+ input.content.content,
+ id,
+ new Map<string, LocalNode>(),
+ );
+
+ const nodesToCreate: CreateNode[] = [
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Message,
+ parentId: input.conversationId,
+ },
+ },
+ input.userId,
+ ),
+ ];
+
+ for (const editorNode of editorNodes) {
+ nodesToCreate.push(
+ buildCreateNode(
+ {
+ id: editorNode.id,
+ attributes: editorNode.attributes,
+ },
+ input.userId,
+ ),
+ );
+ }
+
+ await workspaceDatabase.insertInto('nodes').values(nodesToCreate).execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-attribute-delete.ts b/desktop/src/electron/mutations/node-attribute-delete.ts
new file mode 100644
index 00000000..820da022
--- /dev/null
+++ b/desktop/src/electron/mutations/node-attribute-delete.ts
@@ -0,0 +1,76 @@
+import { databaseContext } from '@/electron/database-context';
+import { NeuronId } from '@/lib/id';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeAttributeDeleteMutationInput } from '@/types/mutations/node-attribute-delete';
+import { fromUint8Array, toUint8Array } from 'js-base64';
+import * as Y from 'yjs';
+
+export class NodeAttributeDeleteMutationHandler
+ implements MutationHandler<NodeAttributeDeleteMutationInput>
+{
+ async handleMutation(
+ input: NodeAttributeDeleteMutationInput,
+ ): Promise<MutationResult<NodeAttributeDeleteMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const node = await workspaceDatabase
+ .selectFrom('nodes')
+ .where('id', '=', input.nodeId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!node) {
+ throw new Error('Node not found');
+ }
+
+ const doc = new Y.Doc({
+ guid: node.id,
+ });
+
+ Y.applyUpdate(doc, toUint8Array(node.state));
+
+ const attributesMap = doc.getMap('attributes');
+ if (!attributesMap.has(input.attribute)) {
+ return {
+ output: {
+ success: true,
+ },
+ };
+ }
+
+ attributesMap.delete(input.attribute);
+ const attributes = JSON.stringify(attributesMap.toJSON());
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ await workspaceDatabase
+ .updateTable('nodes')
+ .set({
+ state: encodedState,
+ attributes: attributes,
+ updated_at: new Date().toISOString(),
+ updated_by: input.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .where('id', '=', input.nodeId)
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-attribute-set.ts b/desktop/src/electron/mutations/node-attribute-set.ts
new file mode 100644
index 00000000..2c0c8994
--- /dev/null
+++ b/desktop/src/electron/mutations/node-attribute-set.ts
@@ -0,0 +1,69 @@
+import { databaseContext } from '@/electron/database-context';
+import { NeuronId } from '@/lib/id';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeAttributeSetMutationInput } from '@/types/mutations/node-attribute-set';
+import { fromUint8Array, toUint8Array } from 'js-base64';
+import * as Y from 'yjs';
+
+export class NodeAttributeSetMutationHandler
+ implements MutationHandler<NodeAttributeSetMutationInput>
+{
+ async handleMutation(
+ input: NodeAttributeSetMutationInput,
+ ): Promise<MutationResult<NodeAttributeSetMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const node = await workspaceDatabase
+ .selectFrom('nodes')
+ .where('id', '=', input.nodeId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!node) {
+ throw new Error('Node not found');
+ }
+
+ const doc = new Y.Doc({
+ guid: node.id,
+ });
+
+ Y.applyUpdate(doc, toUint8Array(node.state));
+
+ const attributesMap = doc.getMap('attributes');
+ attributesMap.set(input.attribute, input.value);
+
+ const attributes = JSON.stringify(attributesMap.toJSON());
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ await workspaceDatabase
+ .updateTable('nodes')
+ .set({
+ state: encodedState,
+ attributes: attributes,
+ updated_at: new Date().toISOString(),
+ updated_by: input.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .where('id', '=', input.nodeId)
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-collaborator-create.ts b/desktop/src/electron/mutations/node-collaborator-create.ts
new file mode 100644
index 00000000..b1bec68b
--- /dev/null
+++ b/desktop/src/electron/mutations/node-collaborator-create.ts
@@ -0,0 +1,50 @@
+import { databaseContext } from '@/electron/database-context';
+import { NeuronId } from '@/lib/id';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeCollaboratorCreateMutationInput } from '@/types/mutations/node-collaborator-create';
+
+export class NodeCollaboratorCreateMutationHandler
+ implements MutationHandler<NodeCollaboratorCreateMutationInput>
+{
+ async handleMutation(
+ input: NodeCollaboratorCreateMutationInput,
+ ): Promise<MutationResult<NodeCollaboratorCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .insertInto('node_collaborators')
+ .values([
+ input.collaboratorIds.map((collaboratorId) => {
+ return {
+ node_id: input.nodeId,
+ collaborator_id: collaboratorId,
+ role: input.role,
+ created_at: new Date().toISOString(),
+ created_by: input.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ };
+ }),
+ ])
+ .onConflict((cb) => cb.doNothing())
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'node_collaborators',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-collaborator-delete.ts b/desktop/src/electron/mutations/node-collaborator-delete.ts
new file mode 100644
index 00000000..0a92e966
--- /dev/null
+++ b/desktop/src/electron/mutations/node-collaborator-delete.ts
@@ -0,0 +1,42 @@
+import { databaseContext } from '@/electron/database-context';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeCollaboratorDeleteMutationInput } from '@/types/mutations/node-collaborator-delete';
+
+export class NodeCollaboratorDeleteMutationHandler
+ implements MutationHandler<NodeCollaboratorDeleteMutationInput>
+{
+ async handleMutation(
+ input: NodeCollaboratorDeleteMutationInput,
+ ): Promise<MutationResult<NodeCollaboratorDeleteMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .deleteFrom('node_collaborators')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', input.nodeId),
+ eb('collaborator_id', '=', input.collaboratorId),
+ ]),
+ )
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'node_collaborators',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-collaborator-update.ts b/desktop/src/electron/mutations/node-collaborator-update.ts
new file mode 100644
index 00000000..08d100ac
--- /dev/null
+++ b/desktop/src/electron/mutations/node-collaborator-update.ts
@@ -0,0 +1,49 @@
+import { databaseContext } from '@/electron/database-context';
+import { NeuronId } from '@/lib/id';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeCollaboratorUpdateMutationInput } from '@/types/mutations/node-collaborator-update';
+
+export class NodeCollaboratorUpdateMutationHandler
+ implements MutationHandler<NodeCollaboratorUpdateMutationInput>
+{
+ async handleMutation(
+ input: NodeCollaboratorUpdateMutationInput,
+ ): Promise<MutationResult<NodeCollaboratorUpdateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .updateTable('node_collaborators')
+ .set({
+ role: input.role,
+ updated_at: new Date().toISOString(),
+ updated_by: input.userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
+ })
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', input.nodeId),
+ eb('collaborator_id', '=', input.collaboratorId),
+ ]),
+ )
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'node_collaborators',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-delete.ts b/desktop/src/electron/mutations/node-delete.ts
new file mode 100644
index 00000000..077ceec8
--- /dev/null
+++ b/desktop/src/electron/mutations/node-delete.ts
@@ -0,0 +1,37 @@
+import { databaseContext } from '@/electron/database-context';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeDeleteMutationInput } from '@/types/mutations/node-delete';
+
+export class NodeDeleteMutationHandler
+ implements MutationHandler<NodeDeleteMutationInput>
+{
+ async handleMutation(
+ input: NodeDeleteMutationInput,
+ ): Promise<MutationResult<NodeDeleteMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .deleteFrom('nodes')
+ .where('id', '=', input.nodeId)
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-reaction-create.ts b/desktop/src/electron/mutations/node-reaction-create.ts
new file mode 100644
index 00000000..b7d477b6
--- /dev/null
+++ b/desktop/src/electron/mutations/node-reaction-create.ts
@@ -0,0 +1,44 @@
+import { databaseContext } from '@/electron/database-context';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeReactionCreateMutationInput } from '@/types/mutations/node-reaction-create';
+
+export class NodeReactionCreateMutationHandler
+ implements MutationHandler<NodeReactionCreateMutationInput>
+{
+ async handleMutation(
+ input: NodeReactionCreateMutationInput,
+ ): Promise<MutationResult<NodeReactionCreateMutationInput>> {
+ console.log('create node reaction', input);
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .insertInto('node_reactions')
+ .values({
+ node_id: input.nodeId,
+ actor_id: input.userId,
+ reaction: input.reaction,
+ created_at: new Date().toISOString(),
+ })
+ .onConflict((b) => b.doNothing())
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'node_reactions',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/node-reaction-delete.ts b/desktop/src/electron/mutations/node-reaction-delete.ts
new file mode 100644
index 00000000..a8839ffe
--- /dev/null
+++ b/desktop/src/electron/mutations/node-reaction-delete.ts
@@ -0,0 +1,43 @@
+import { databaseContext } from '@/electron/database-context';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { NodeReactionDeleteMutationInput } from '@/types/mutations/node-reaction-delete';
+
+export class NodeReactionDeleteMutationHandler
+ implements MutationHandler<NodeReactionDeleteMutationInput>
+{
+ async handleMutation(
+ input: NodeReactionDeleteMutationInput,
+ ): Promise<MutationResult<NodeReactionDeleteMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .deleteFrom('node_reactions')
+ .where((eb) =>
+ eb.and([
+ eb('node_id', '=', input.nodeId),
+ eb('actor_id', '=', input.userId),
+ eb('reaction', '=', input.reaction),
+ ]),
+ )
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'node_reactions',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/page-create.ts b/desktop/src/electron/mutations/page-create.ts
new file mode 100644
index 00000000..df9b9c68
--- /dev/null
+++ b/desktop/src/electron/mutations/page-create.ts
@@ -0,0 +1,67 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { PageCreateMutationInput } from '@/types/mutations/page-create';
+
+export class PageCreateMutationHandler
+ implements MutationHandler<PageCreateMutationInput>
+{
+ async handleMutation(
+ input: PageCreateMutationInput,
+ ): Promise<MutationResult<PageCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', '=', input.spaceId)
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.Page);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Page,
+ parentId: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/record-create.ts b/desktop/src/electron/mutations/record-create.ts
new file mode 100644
index 00000000..7c23de29
--- /dev/null
+++ b/desktop/src/electron/mutations/record-create.ts
@@ -0,0 +1,68 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { RecordCreateMutationInput } from '@/types/mutations/record-create';
+
+export class RecordCreateMutationHandler
+ implements MutationHandler<RecordCreateMutationInput>
+{
+ async handleMutation(
+ input: RecordCreateMutationInput,
+ ): Promise<MutationResult<RecordCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const lastChild = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.databaseId),
+ eb('type', '=', NodeTypes.Record),
+ ]),
+ )
+ .orderBy('index', 'desc')
+ .limit(1)
+ .executeTakeFirst();
+
+ const maxIndex = lastChild?.index ? lastChild.index : null;
+
+ const id = NeuronId.generate(NeuronId.Type.Record);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Record,
+ parentId: input.databaseId,
+ index: generateNodeIndex(maxIndex, null),
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/select-option-create.ts b/desktop/src/electron/mutations/select-option-create.ts
new file mode 100644
index 00000000..6637f213
--- /dev/null
+++ b/desktop/src/electron/mutations/select-option-create.ts
@@ -0,0 +1,69 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { SelectOptionCreateMutationInput } from '@/types/mutations/select-option-create';
+
+export class SelectOptionCreateMutationHandler
+ implements MutationHandler<SelectOptionCreateMutationInput>
+{
+ async handleMutation(
+ input: SelectOptionCreateMutationInput,
+ ): Promise<MutationResult<SelectOptionCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const lastChild = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.fieldId),
+ eb('type', '=', NodeTypes.SelectOption),
+ ]),
+ )
+ .orderBy('index', 'desc')
+ .limit(1)
+ .executeTakeFirst();
+
+ const maxIndex = lastChild?.index ? lastChild.index : null;
+ const id = NeuronId.generate(NeuronId.Type.SelectOption);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.SelectOption,
+ parentId: input.fieldId,
+ index: generateNodeIndex(maxIndex, null),
+ name: input.name,
+ color: input.color,
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/server-create.ts b/desktop/src/electron/mutations/server-create.ts
new file mode 100644
index 00000000..3e648c10
--- /dev/null
+++ b/desktop/src/electron/mutations/server-create.ts
@@ -0,0 +1,41 @@
+import axios from 'axios';
+import { databaseContext } from '@/electron/database-context';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { ServerCreateMutationInput } from '@/types/mutations/server-create';
+import { ServerConfig } from '@/types/servers';
+
+export class ServerCreateMutationHandler
+ implements MutationHandler<ServerCreateMutationInput>
+{
+ async handleMutation(
+ input: ServerCreateMutationInput,
+ ): Promise<MutationResult<ServerCreateMutationInput>> {
+ const { data } = await axios.get<ServerConfig>(
+ `http://${input.domain}/v1/config`,
+ );
+
+ await databaseContext.appDatabase
+ .insertInto('servers')
+ .values({
+ domain: input.domain,
+ name: data.name,
+ avatar: data.avatar,
+ attributes: JSON.stringify(data.attributes),
+ version: data.version,
+ created_at: new Date().toISOString(),
+ })
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: [
+ {
+ type: 'app',
+ table: 'servers',
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/space-create.ts b/desktop/src/electron/mutations/space-create.ts
new file mode 100644
index 00000000..f7abe6e2
--- /dev/null
+++ b/desktop/src/electron/mutations/space-create.ts
@@ -0,0 +1,83 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { SpaceCreateMutationInput } from '@/types/mutations/space-create';
+
+export class SpaceCreateMutationHandler
+ implements MutationHandler<SpaceCreateMutationInput>
+{
+ async handleMutation(
+ input: SpaceCreateMutationInput,
+ ): Promise<MutationResult<SpaceCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ 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);
+
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values([
+ buildCreateNode(
+ {
+ id: spaceId,
+ attributes: {
+ type: NodeTypes.Space,
+ name: input.name,
+ description: input.description,
+ },
+ },
+ input.userId,
+ ),
+ buildCreateNode(
+ {
+ id: pageId,
+ attributes: {
+ type: NodeTypes.Page,
+ parentId: spaceId,
+ index: pageIndex,
+ name: 'Home',
+ },
+ },
+ input.userId,
+ ),
+ buildCreateNode(
+ {
+ id: channelId,
+ attributes: {
+ type: NodeTypes.Channel,
+ parentId: spaceId,
+ index: channelIndex,
+ name: 'Discussions',
+ },
+ },
+ input.userId,
+ ),
+ ])
+ .execute();
+
+ return {
+ output: {
+ id: spaceId,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/table-view-create.ts b/desktop/src/electron/mutations/table-view-create.ts
new file mode 100644
index 00000000..a3ec4902
--- /dev/null
+++ b/desktop/src/electron/mutations/table-view-create.ts
@@ -0,0 +1,72 @@
+import { databaseContext } from '@/electron/database-context';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NeuronId } from '@/lib/id';
+import { buildCreateNode, generateNodeIndex } from '@/lib/nodes';
+import { compareString } from '@/lib/utils';
+import { MutationHandler, MutationResult } from '@/types/mutations';
+import { TableViewCreateMutationInput } from '@/types/mutations/table-view-create';
+
+export class TableViewCreateMutationHandler
+ implements MutationHandler<TableViewCreateMutationInput>
+{
+ async handleMutation(
+ input: TableViewCreateMutationInput,
+ ): Promise<MutationResult<TableViewCreateMutationInput>> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const siblings = await workspaceDatabase
+ .selectFrom('nodes')
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.databaseId),
+ eb('type', 'in', ViewNodeTypes),
+ ]),
+ )
+ .selectAll()
+ .execute();
+
+ const maxIndex =
+ siblings.length > 0
+ ? siblings.sort((a, b) => compareString(a.index, b.index))[
+ siblings.length - 1
+ ].index
+ : null;
+
+ const id = NeuronId.generate(NeuronId.Type.TableView);
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(
+ buildCreateNode(
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.TableView,
+ parentId: input.databaseId,
+ index: generateNodeIndex(maxIndex, null),
+ },
+ },
+ input.userId,
+ ),
+ )
+ .execute();
+
+ return {
+ output: {
+ id: id,
+ },
+ changedTables: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/workspace-account-role-update.ts b/desktop/src/electron/mutations/workspace-account-role-update.ts
new file mode 100644
index 00000000..3ab57d74
--- /dev/null
+++ b/desktop/src/electron/mutations/workspace-account-role-update.ts
@@ -0,0 +1,109 @@
+import axios from 'axios';
+import { databaseContext } from '@/electron/database-context';
+import { buildApiBaseUrl, mapServer } from '@/lib/servers';
+import { WorkspaceAccountRoleUpdateMutationInput } from '@/types/mutations/workspace-account-role-update';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/types/mutations';
+import { WorkspaceAccountRoleUpdateOutput } from '@/types/workspaces';
+
+export class WorkspaceAccountRoleUpdateMutationHandler
+ implements MutationHandler<WorkspaceAccountRoleUpdateMutationInput>
+{
+ async handleMutation(
+ input: WorkspaceAccountRoleUpdateMutationInput,
+ ): Promise<MutationResult<WorkspaceAccountRoleUpdateMutationInput>> {
+ const workspaceRow = await databaseContext.appDatabase
+ .selectFrom('workspaces')
+ .selectAll()
+ .where('user_id', '=', input.userId)
+ .executeTakeFirst();
+
+ if (!workspaceRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const accountRow = await databaseContext.appDatabase
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', workspaceRow.account_id)
+ .executeTakeFirst();
+
+ if (!accountRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const serverRow = await databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .where('domain', '=', accountRow.server)
+ .executeTakeFirst();
+
+ if (!serverRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const server = mapServer(serverRow);
+ const { data } = await axios.post<WorkspaceAccountRoleUpdateOutput>(
+ `${buildApiBaseUrl(server)}/v1/workspaces/${workspaceRow.workspace_id}/accounts/${input.accountId}`,
+ {
+ role: input.role,
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${accountRow.token}`,
+ },
+ },
+ );
+
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ await workspaceDatabase
+ .updateTable('nodes')
+ .set({
+ attributes: JSON.stringify(data.user.attributes),
+ updated_at: data.user.updatedAt,
+ updated_by: data.user.updatedBy,
+ version_id: data.user.versionId,
+ server_updated_at: data.user.updatedAt,
+ server_version_id: data.user.versionId,
+ })
+ .where('id', '=', data.user.id)
+ .execute();
+
+ const changedTables: MutationChange[] = [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ];
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: changedTables,
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/workspace-accounts-invite.ts b/desktop/src/electron/mutations/workspace-accounts-invite.ts
new file mode 100644
index 00000000..437ec4b9
--- /dev/null
+++ b/desktop/src/electron/mutations/workspace-accounts-invite.ts
@@ -0,0 +1,119 @@
+import axios from 'axios';
+import { databaseContext } from '@/electron/database-context';
+import { buildApiBaseUrl, mapServer } from '@/lib/servers';
+import { WorkspaceAccountsInviteMutationInput } from '@/types/mutations/workspace-accounts-invite';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/types/mutations';
+import { WorkspaceAccountsInviteOutput } from '@/types/workspaces';
+import { CreateNode } from '@/electron/schemas/workspace';
+
+export class WorkspaceAccountsInviteMutationHandler
+ implements MutationHandler<WorkspaceAccountsInviteMutationInput>
+{
+ async handleMutation(
+ input: WorkspaceAccountsInviteMutationInput,
+ ): Promise<MutationResult<WorkspaceAccountsInviteMutationInput>> {
+ const workspaceRow = await databaseContext.appDatabase
+ .selectFrom('workspaces')
+ .selectAll()
+ .where('user_id', '=', input.userId)
+ .executeTakeFirst();
+
+ if (!workspaceRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const accountRow = await databaseContext.appDatabase
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', workspaceRow.account_id)
+ .executeTakeFirst();
+
+ if (!accountRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const serverRow = await databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .where('domain', '=', accountRow.server)
+ .executeTakeFirst();
+
+ if (!serverRow) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const server = mapServer(serverRow);
+ const { data } = await axios.post<WorkspaceAccountsInviteOutput>(
+ `${buildApiBaseUrl(server)}/v1/workspaces/${workspaceRow.workspace_id}/accounts`,
+ {
+ emails: input.emails,
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${accountRow.token}`,
+ },
+ },
+ );
+
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const usersToCreate: CreateNode[] = data.users.map((user) => {
+ return {
+ id: user.id,
+ attributes: JSON.stringify(user.attributes),
+ state: user.state,
+ created_at: user.createdAt,
+ created_by: user.createdBy,
+ updated_at: user.updatedAt,
+ updated_by: user.updatedBy,
+ server_created_at: user.serverCreatedAt,
+ server_updated_at: user.serverUpdatedAt,
+ server_version_id: user.versionId,
+ version_id: user.versionId,
+ };
+ });
+
+ await workspaceDatabase
+ .insertInto('nodes')
+ .values(usersToCreate)
+ .onConflict((cb) => cb.doNothing())
+ .execute();
+
+ const changedTables: MutationChange[] = [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ ];
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: changedTables,
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/workspace-create.ts b/desktop/src/electron/mutations/workspace-create.ts
new file mode 100644
index 00000000..643e0b4c
--- /dev/null
+++ b/desktop/src/electron/mutations/workspace-create.ts
@@ -0,0 +1,82 @@
+import axios from 'axios';
+import { databaseContext } from '@/electron/database-context';
+import { buildApiBaseUrl, mapServer } from '@/lib/servers';
+import { WorkspaceCreateMutationInput } from '@/types/mutations/workspace-create';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/types/mutations';
+import { Workspace } from '@/types/workspaces';
+
+export class WorkspaceCreateMutationHandler
+ implements MutationHandler<WorkspaceCreateMutationInput>
+{
+ async handleMutation(
+ input: WorkspaceCreateMutationInput,
+ ): Promise<MutationResult<WorkspaceCreateMutationInput>> {
+ const accountRow = await databaseContext.appDatabase
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', input.accountId)
+ .executeTakeFirst();
+
+ if (!accountRow) {
+ throw new Error('Account not found!');
+ }
+
+ const serverRow = await databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .where('domain', '=', accountRow.server)
+ .executeTakeFirst();
+
+ if (!serverRow) {
+ throw new Error('Account not found');
+ }
+
+ const server = mapServer(serverRow);
+ const { data } = await axios.post<Workspace>(
+ `${buildApiBaseUrl(server)}/v1/workspaces`,
+ {
+ name: input.name,
+ description: input.description,
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${accountRow.token}`,
+ },
+ },
+ );
+
+ await databaseContext.appDatabase
+ .insertInto('workspaces')
+ .values({
+ workspace_id: data.id ?? data.id,
+ account_id: data.accountId,
+ name: data.name,
+ description: data.description,
+ avatar: data.avatar,
+ role: data.role,
+ synced: 0,
+ user_id: data.userId,
+ version_id: data.versionId,
+ })
+ .onConflict((cb) => cb.doNothing())
+ .execute();
+
+ const changedTables: MutationChange[] = [
+ {
+ type: 'app',
+ table: 'workspaces',
+ },
+ ];
+
+ return {
+ output: {
+ id: data.id,
+ },
+ changedTables: changedTables,
+ };
+ }
+}
diff --git a/desktop/src/electron/mutations/workspace-update.ts b/desktop/src/electron/mutations/workspace-update.ts
new file mode 100644
index 00000000..84c6de3c
--- /dev/null
+++ b/desktop/src/electron/mutations/workspace-update.ts
@@ -0,0 +1,78 @@
+import axios from 'axios';
+import { databaseContext } from '@/electron/database-context';
+import { buildApiBaseUrl, mapServer } from '@/lib/servers';
+import { WorkspaceUpdateMutationInput } from '@/types/mutations/workspace-update';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/types/mutations';
+import { Workspace } from '@/types/workspaces';
+
+export class WorkspaceUpdateMutationHandler
+ implements MutationHandler<WorkspaceUpdateMutationInput>
+{
+ async handleMutation(
+ input: WorkspaceUpdateMutationInput,
+ ): Promise<MutationResult<WorkspaceUpdateMutationInput>> {
+ const accountRow = await databaseContext.appDatabase
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', input.accountId)
+ .executeTakeFirst();
+
+ if (!accountRow) {
+ throw new Error('Account not found!');
+ }
+
+ const serverRow = await databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .where('domain', '=', accountRow.server)
+ .executeTakeFirst();
+
+ if (!serverRow) {
+ throw new Error('Account not found');
+ }
+
+ const server = mapServer(serverRow);
+ const { data } = await axios.post<Workspace>(
+ `${buildApiBaseUrl(server)}/v1/workspaces/${input.id}`,
+ {
+ name: input.name,
+ description: input.description,
+ },
+ );
+
+ await databaseContext.appDatabase
+ .updateTable('workspaces')
+ .set({
+ name: data.name,
+ description: data.description,
+ avatar: data.avatar,
+ role: data.role,
+ version_id: data.versionId,
+ })
+ .where((eb) =>
+ eb.and([
+ eb('account_id', '=', input.accountId),
+ eb('workspace_id', '=', input.id),
+ ]),
+ )
+ .execute();
+
+ const changedTables: MutationChange[] = [
+ {
+ type: 'app',
+ table: 'workspaces',
+ },
+ ];
+
+ return {
+ output: {
+ success: true,
+ },
+ changedTables: changedTables,
+ };
+ }
+}
diff --git a/desktop/src/electron/queries/accounts-list.ts b/desktop/src/electron/queries/accounts-list.ts
new file mode 100644
index 00000000..fe597a68
--- /dev/null
+++ b/desktop/src/electron/queries/accounts-list.ts
@@ -0,0 +1,79 @@
+import { AccountListQueryInput } from '@/types/queries/account-list';
+import { databaseContext } from '@/electron/database-context';
+import { Account } from '@/types/accounts';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { SelectAccount } from '../schemas/app';
+import { isEqual } from 'lodash';
+import { MutationChange } from '@/types/mutations';
+
+export class AccountListQueryHandler
+ implements QueryHandler<AccountListQueryInput>
+{
+ public async handleQuery(
+ _: AccountListQueryInput,
+ ): Promise<QueryResult<AccountListQueryInput>> {
+ const rows = await this.fetchAccounts();
+ return {
+ output: this.buildAccounts(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ _: AccountListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<AccountListQueryInput>> {
+ if (
+ !changes.some(
+ (change) => change.type === 'app' && change.table === 'accounts',
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchAccounts();
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildAccounts(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private fetchAccounts(): Promise<SelectAccount[]> {
+ return databaseContext.appDatabase
+ .selectFrom('accounts')
+ .selectAll()
+ .where('status', '=', 'active')
+ .execute();
+ }
+
+ private buildAccounts(rows: SelectAccount[]): Account[] {
+ return rows.map((row) => {
+ return {
+ id: row.id,
+ name: row.name,
+ avatar: row.avatar,
+ token: row.token,
+ email: row.email,
+ deviceId: row.device_id,
+ status: row.status,
+ server: row.server,
+ };
+ });
+ }
+}
diff --git a/desktop/src/electron/queries/breadcrumb-list.ts b/desktop/src/electron/queries/breadcrumb-list.ts
new file mode 100644
index 00000000..d4adc917
--- /dev/null
+++ b/desktop/src/electron/queries/breadcrumb-list.ts
@@ -0,0 +1,123 @@
+import { BreadcrumbListQueryInput } from '@/types/queries/breadcrumb-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { BreadcrumbNode } from '@/types/workspaces';
+import { mapNode } from '@/lib/nodes';
+import { isEqual } from 'lodash';
+import { MutationChange } from '@/types/mutations';
+
+export class BreadcrumbListQueryHandler
+ implements QueryHandler<BreadcrumbListQueryInput>
+{
+ public async handleQuery(
+ input: BreadcrumbListQueryInput,
+ ): Promise<QueryResult<BreadcrumbListQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildBreadcrumbNodes(input.nodeId, rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: BreadcrumbListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<BreadcrumbListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildBreadcrumbNodes(input.nodeId, rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: BreadcrumbListQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ WITH RECURSIVE breadcrumb_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE id = ${input.nodeId}
+ UNION ALL
+ SELECT n.*
+ FROM nodes n
+ INNER JOIN breadcrumb_nodes b ON n.id = b.parent_id
+ )
+ SELECT n.*
+ FROM breadcrumb_nodes n;
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildBreadcrumbNodes = (
+ nodeId: string,
+ rows: SelectNode[],
+ ): BreadcrumbNode[] => {
+ const breadcrumbNodes: BreadcrumbNode[] = [];
+
+ let currentId = nodeId;
+ while (currentId !== null && currentId !== undefined) {
+ const row = rows.find((row) => row.id === currentId);
+ if (row) {
+ breadcrumbNodes.push(this.buildBreadcrumbNode(row));
+ currentId = row.parent_id;
+ } else {
+ currentId = null;
+ }
+ }
+ return breadcrumbNodes.reverse();
+ };
+
+ private buildBreadcrumbNode = (row: SelectNode): BreadcrumbNode => {
+ const node = mapNode(row);
+
+ const name = node.attributes.name;
+ const avatar = node.attributes.avatar;
+
+ return {
+ id: node.id,
+ type: node.type,
+ name,
+ avatar,
+ };
+ };
+}
diff --git a/desktop/src/electron/queries/database-get.ts b/desktop/src/electron/queries/database-get.ts
new file mode 100644
index 00000000..ddcb6faf
--- /dev/null
+++ b/desktop/src/electron/queries/database-get.ts
@@ -0,0 +1,273 @@
+import { DatabaseGetQueryInput } from '@/types/queries/database-get';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { mapNode } from '@/lib/nodes';
+import { NodeTypes } from '@/lib/constants';
+import {
+ DatabaseNode,
+ FieldDataType,
+ FieldNode,
+ SelectOptionNode,
+} from '@/types/databases';
+import { LocalNode } from '@/types/nodes';
+import { isEqual } from 'lodash';
+import { MutationChange } from '@/types/mutations';
+
+export class DatabaseGetQueryHandler
+ implements QueryHandler<DatabaseGetQueryInput>
+{
+ public async handleQuery(
+ input: DatabaseGetQueryInput,
+ ): Promise<QueryResult<DatabaseGetQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildDatabaseNode(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: DatabaseGetQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<DatabaseGetQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildDatabaseNode(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: DatabaseGetQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ WITH database_node AS (
+ SELECT *
+ FROM nodes
+ WHERE id = ${input.databaseId}
+ ),
+ field_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${input.databaseId} AND type = ${NodeTypes.Field}
+ ),
+ select_option_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IN
+ (
+ SELECT id
+ FROM field_nodes
+ )
+ AND type = ${NodeTypes.SelectOption}
+ )
+ SELECT * FROM database_node
+ UNION ALL
+ SELECT * FROM field_nodes
+ UNION ALL
+ SELECT * FROM select_option_nodes
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildDatabaseNode = (rows: SelectNode[]): DatabaseNode | null => {
+ const nodes = rows.map((row) => mapNode(row));
+
+ const databaseLocalNode = nodes.find(
+ (node) => node.type === NodeTypes.Database,
+ );
+ if (!databaseLocalNode) {
+ return null;
+ }
+
+ const name = databaseLocalNode.attributes.name;
+ const fieldsNodes = nodes.filter((node) => node.type === NodeTypes.Field);
+ const groupedSelectOptions = nodes
+ .filter((node) => node.type === NodeTypes.SelectOption)
+ .reduce(
+ (acc, node) => {
+ if (!acc[node.parentId]) {
+ acc[node.parentId] = [];
+ }
+ acc[node.parentId].push(node);
+ return acc;
+ },
+ {} as Record<string, LocalNode[]>,
+ );
+
+ const fields: FieldNode[] = [];
+ for (const fieldNode of fieldsNodes) {
+ const selectOptions = groupedSelectOptions[fieldNode.id] ?? [];
+ const field = this.buildFieldNode(fieldNode, selectOptions);
+ if (field) {
+ fields.push(field);
+ }
+ }
+
+ return {
+ id: databaseLocalNode.id,
+ name: name,
+ fields,
+ };
+ };
+
+ private buildFieldNode = (
+ node: LocalNode,
+ selectOptions: LocalNode[],
+ ): FieldNode | null => {
+ const name = node.attributes.name;
+ const dataType = node.attributes.dataType as FieldDataType;
+
+ if (!dataType) {
+ return null;
+ }
+
+ switch (dataType) {
+ case 'boolean':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'collaborator':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'created_at':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'created_by':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'date':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'email':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'file':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'multi_select':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ options: selectOptions.map(this.buildSelectOption),
+ };
+ case 'number':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'phone':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'select':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ options: selectOptions.map(this.buildSelectOption),
+ };
+ case 'text':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ case 'url':
+ return {
+ id: node.id,
+ name,
+ dataType,
+ index: node.index,
+ };
+ default:
+ return null;
+ }
+ };
+
+ private buildSelectOption = (node: LocalNode): SelectOptionNode => {
+ const name = node.attributes.name;
+ const color = node.attributes.color;
+
+ return {
+ id: node.id,
+ name: name ?? 'Unnamed',
+ color: color ?? 'gray',
+ };
+ };
+}
diff --git a/desktop/src/electron/queries/database-view-list.ts b/desktop/src/electron/queries/database-view-list.ts
new file mode 100644
index 00000000..2ab9a76d
--- /dev/null
+++ b/desktop/src/electron/queries/database-view-list.ts
@@ -0,0 +1,173 @@
+import { DatabaseViewListQueryInput } from '@/types/queries/database-view-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { mapNode } from '@/lib/nodes';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { LocalNode } from '@/types/nodes';
+import {
+ BoardViewNode,
+ CalendarViewNode,
+ TableViewNode,
+ ViewNode,
+} from '@/types/databases';
+import { isEqual } from 'lodash';
+import { MutationChange } from '@/types/mutations';
+
+export class DatabaseViewListQueryHandler
+ implements QueryHandler<DatabaseViewListQueryInput>
+{
+ public async handleQuery(
+ input: DatabaseViewListQueryInput,
+ ): Promise<QueryResult<DatabaseViewListQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildViewNodes(rows),
+ state: {
+ rows: rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: DatabaseViewListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<DatabaseViewListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildViewNodes(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: DatabaseViewListQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const rows = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.databaseId),
+ eb('type', 'in', ViewNodeTypes),
+ ]),
+ )
+ .execute();
+ return rows;
+ }
+
+ private buildViewNodes = (rows: SelectNode[]): ViewNode[] => {
+ const nodes = rows.map((row) => mapNode(row));
+ const views: ViewNode[] = [];
+ for (const node of nodes) {
+ const view = this.buildViewNode(node);
+ if (view) {
+ views.push(view);
+ }
+ }
+
+ return views;
+ };
+
+ private buildViewNode = (node: LocalNode): ViewNode | null => {
+ if (node.type === NodeTypes.TableView) {
+ return this.buildTableViewNode(node);
+ } else if (node.type === NodeTypes.BoardView) {
+ return this.buildBoardViewNode(node);
+ } else if (node.type === NodeTypes.CalendarView) {
+ return this.buildCalendarViewNode(node);
+ }
+
+ return null;
+ };
+
+ private buildTableViewNode = (node: LocalNode): TableViewNode => {
+ const name = node.attributes.name;
+ const hiddenFields = node.attributes.hiddenFields;
+ const fieldIndexes = node.attributes.fieldIndexes;
+ const fieldWidths = node.attributes.fieldWidths;
+ const nameWidth = node.attributes.nameWidth;
+
+ const viewFilters = node.attributes.filters;
+ const viewSorts = node.attributes.sorts;
+
+ return {
+ id: node.id,
+ name: name ?? 'Unnamed',
+ type: 'table_view',
+ hiddenFields,
+ fieldIndexes,
+ fieldWidths,
+ nameWidth: nameWidth,
+ versionId: node.versionId,
+ filters: viewFilters ?? [],
+ sorts: viewSorts ?? [],
+ };
+ };
+
+ private buildBoardViewNode = (node: LocalNode): BoardViewNode => {
+ const name = node.attributes.name;
+ const groupBy = node.attributes.groupBy;
+ const viewFilters = node.attributes.filters;
+ const viewSorts = node.attributes.sorts;
+
+ return {
+ id: node.id,
+ name: name ?? 'Unnamed',
+ type: 'board_view',
+ filters: viewFilters ?? [],
+ sorts: viewSorts ?? [],
+ groupBy,
+ };
+ };
+
+ private buildCalendarViewNode = (node: LocalNode): CalendarViewNode => {
+ const name = node.attributes.name;
+ const groupBy = node.attributes.groupBy;
+
+ const viewFilters = node.attributes.filters;
+ const viewSorts = node.attributes.sorts;
+
+ return {
+ id: node.id,
+ name: name ?? 'Unnamed',
+ type: 'calendar_view',
+ filters: viewFilters ?? [],
+ sorts: viewSorts ?? [],
+ groupBy,
+ };
+ };
+}
diff --git a/desktop/src/electron/queries/document-get.ts b/desktop/src/electron/queries/document-get.ts
new file mode 100644
index 00000000..460ef79b
--- /dev/null
+++ b/desktop/src/electron/queries/document-get.ts
@@ -0,0 +1,106 @@
+import { DocumentGetQueryInput } from '@/types/queries/document-get';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { mapNode } from '@/lib/nodes';
+import { NodeTypes } from '@/lib/constants';
+import { LocalNode } from '@/types/nodes';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class DocumentGetQueryHandler
+ implements QueryHandler<DocumentGetQueryInput>
+{
+ public async handleQuery(
+ input: DocumentGetQueryInput,
+ ): Promise<QueryResult<DocumentGetQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: {
+ nodes: this.buildMap(rows),
+ },
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: DocumentGetQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<DocumentGetQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: {
+ nodes: this.buildMap(rows),
+ },
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: DocumentGetQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ WITH RECURSIVE document_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${input.nodeId}
+
+ 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 *
+ FROM document_nodes
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildMap = (rows: SelectNode[]): Map<string, LocalNode> => {
+ const map = new Map<string, LocalNode>();
+ rows.forEach((row) => {
+ map.set(row.id, mapNode(row));
+ });
+ return map;
+ };
+}
diff --git a/desktop/src/electron/queries/index.ts b/desktop/src/electron/queries/index.ts
new file mode 100644
index 00000000..a254ab16
--- /dev/null
+++ b/desktop/src/electron/queries/index.ts
@@ -0,0 +1,42 @@
+import { QueryHandler, QueryMap } from '@/types/queries';
+import { AccountListQueryHandler } from '@/electron/queries/accounts-list';
+import { BreadcrumbListQueryHandler } from '@/electron/queries/breadcrumb-list';
+import { DatabaseGetQueryHandler } from '@/electron/queries/database-get';
+import { DatabaseViewListQueryHandler } from '@/electron/queries/database-view-list';
+import { DocumentGetQueryHandler } from '@/electron/queries/document-get';
+import { MessageListQueryHandler } from '@/electron/queries/message-list';
+import { NodeCollaboratorListQueryHandler } from '@/electron/queries/node-collaborator-list';
+import { NodeCollaboratorSearchQueryHandler } from '@/electron/queries/node-collaborator-search';
+import { NodeGetQueryHandler } from '@/electron/queries/node-get';
+import { RecordGetQueryHandler } from '@/electron/queries/record-get';
+import { ServerListQueryHandler } from '@/electron/queries/server-list';
+import { SidebarChatListQueryHandler } from '@/electron/queries/sidebar-chat-list';
+import { SidebarSpaceListQueryHandler } from '@/electron/queries/sidebar-space-list';
+import { UserSearchQueryHandler } from '@/electron/queries/user-search';
+import { WorkspaceListQueryHandler } from '@/electron/queries/workspace-list';
+import { WorkspaceUserListQueryHandler } from '@/electron/queries/workspace-user-list';
+import { RecordListQueryHandler } from '@/electron/queries/record-list';
+
+type QueryHandlerMap = {
+ [K in keyof QueryMap]: QueryHandler<QueryMap[K]['input']>;
+};
+
+export const queryHandlerMap: QueryHandlerMap = {
+ account_list: new AccountListQueryHandler(),
+ breadcrumb_list: new BreadcrumbListQueryHandler(),
+ database_get: new DatabaseGetQueryHandler(),
+ database_view_list: new DatabaseViewListQueryHandler(),
+ document_get: new DocumentGetQueryHandler(),
+ message_list: new MessageListQueryHandler(),
+ node_collaborator_list: new NodeCollaboratorListQueryHandler(),
+ node_collaborator_search: new NodeCollaboratorSearchQueryHandler(),
+ node_get: new NodeGetQueryHandler(),
+ record_get: new RecordGetQueryHandler(),
+ record_list: new RecordListQueryHandler(),
+ server_list: new ServerListQueryHandler(),
+ sidebar_chat_list: new SidebarChatListQueryHandler(),
+ sidebar_space_list: new SidebarSpaceListQueryHandler(),
+ user_search: new UserSearchQueryHandler(),
+ workspace_list: new WorkspaceListQueryHandler(),
+ workspace_user_list: new WorkspaceUserListQueryHandler(),
+};
diff --git a/desktop/src/electron/queries/message-list.ts b/desktop/src/electron/queries/message-list.ts
new file mode 100644
index 00000000..7b237215
--- /dev/null
+++ b/desktop/src/electron/queries/message-list.ts
@@ -0,0 +1,207 @@
+import { MessageListQueryInput } from '@/types/queries/message-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { MutationChange } from '@/types/mutations';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { sql } from 'kysely';
+import { NodeTypes } from '@/lib/constants';
+import { MessageNode, MessageReactionCount } from '@/types/messages';
+import { buildNodeWithChildren, mapNode } from '@/lib/nodes';
+import { UserNode } from '@/types/users';
+import { compareString } from '@/lib/utils';
+import { isEqual } from 'lodash';
+
+type MessageRow = SelectNode & {
+ reaction_counts: string | null;
+ user_reactions: string | null;
+};
+
+export class MessageListQueryHandler
+ implements QueryHandler<MessageListQueryInput>
+{
+ public async handleQuery(
+ input: MessageListQueryInput,
+ ): Promise<QueryResult<MessageListQueryInput>> {
+ const rows = await this.fetchMesssages(input);
+
+ return {
+ output: this.buildMessages(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: MessageListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<MessageListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ (change.table === 'nodes' || change.table === 'node_reactions') &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchMesssages(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildMessages(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchMesssages(
+ input: MessageListQueryInput,
+ ): Promise<MessageRow[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const offset = input.page * input.count;
+ const query = sql<MessageRow>`
+ WITH message_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${input.conversationId} AND type = ${NodeTypes.Message}
+ ORDER BY id DESC
+ LIMIT ${sql.lit(input.count)}
+ 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
+ ),
+ message_reaction_counts AS (
+ SELECT
+ mrc.node_id,
+ json_group_array(
+ json_object(
+ 'reaction', mrc.'reaction',
+ 'count', mrc.'count'
+ )
+ ) AS reaction_counts
+ FROM (
+ SELECT node_id, reaction, COUNT(*) as count
+ FROM node_reactions
+ WHERE node_id IN (SELECT id FROM message_nodes)
+ GROUP BY node_id, reaction
+ ) mrc
+ GROUP BY mrc.node_id
+ ),
+ user_reactions AS (
+ SELECT
+ ur.node_id,
+ json_group_array(ur.reaction) AS user_reactions
+ FROM node_reactions ur
+ WHERE ur.node_id IN (SELECT id FROM message_nodes) AND ur.actor_id = ${input.userId}
+ GROUP BY ur.node_id
+ )
+ SELECT
+ n.*,
+ COALESCE(mrc.reaction_counts, json('[]')) AS reaction_counts,
+ COALESCE(ur.user_reactions, json('[]')) AS user_reactions
+ FROM all_nodes n
+ LEFT JOIN message_reaction_counts mrc ON n.id = mrc.node_id
+ LEFT JOIN user_reactions ur ON n.id = ur.node_id;
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildMessages = (rows: MessageRow[]): MessageNode[] => {
+ const messageRows = rows.filter((row) => row.type === NodeTypes.Message);
+ const authorRows = rows.filter((row) => row.type === NodeTypes.User);
+ const contentNodes = rows
+ .filter(
+ (row) => row.type !== NodeTypes.User && row.type !== NodeTypes.Message,
+ )
+ .map(mapNode);
+
+ const messages: MessageNode[] = [];
+ const authorMap = new Map<string, UserNode>();
+ for (const authorRow of authorRows) {
+ const authorNode = mapNode(authorRow);
+ const name = authorNode.attributes.name;
+ const email = authorNode.attributes.email;
+ const avatar = authorNode.attributes.avatar;
+
+ authorMap.set(authorRow.id, {
+ id: authorRow.id,
+ name: name ?? 'Unknown User',
+ email,
+ avatar,
+ });
+ }
+
+ for (const messageRow of messageRows) {
+ const messageNode = mapNode(messageRow);
+ const author = authorMap.get(messageNode.createdBy);
+ const children = contentNodes
+ .filter((n) => n.parentId === messageNode.id)
+ .map((n) => buildNodeWithChildren(n, contentNodes));
+
+ const reactionCounts: MessageReactionCount[] = JSON.parse(
+ messageRow.reaction_counts,
+ );
+ const userReactions: string[] = JSON.parse(messageRow.user_reactions);
+
+ const message: MessageNode = {
+ id: messageNode.id,
+ createdAt: messageNode.createdAt,
+ author: author ?? {
+ id: messageNode.createdBy,
+ name: 'Unknown User',
+ email: '[email protected]',
+ avatar: null,
+ },
+ content: children,
+ reactionCounts,
+ userReactions,
+ };
+
+ messages.push(message);
+ }
+
+ return messages.sort((a, b) => compareString(a.id, b.id));
+ };
+}
diff --git a/desktop/src/electron/queries/node-collaborator-list.tsx b/desktop/src/electron/queries/node-collaborator-list.tsx
new file mode 100644
index 00000000..c3c9d523
--- /dev/null
+++ b/desktop/src/electron/queries/node-collaborator-list.tsx
@@ -0,0 +1,177 @@
+import { NodeCollaboratorListQueryInput } from '@/types/queries/node-collaborator-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { NodeTypes } from '@/lib/constants';
+import {
+ InheritNodeCollaboratorsGroup,
+ NodeCollaboratorNode,
+ NodeCollaboratorsWrapper,
+} from '@/types/nodes';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+type NodeCollaboratorRow = {
+ node_id: string;
+ node_level: number;
+ node_attributes: string;
+ node_parent_id: string | null;
+ collaborator_id: string;
+ collaborator_attributes: string;
+ role: string;
+};
+
+export class NodeCollaboratorListQueryHandler
+ implements QueryHandler<NodeCollaboratorListQueryInput>
+{
+ public async handleQuery(
+ input: NodeCollaboratorListQueryInput,
+ ): Promise<QueryResult<NodeCollaboratorListQueryInput>> {
+ const rows = await this.fetchCollaborators(input);
+ return {
+ output: this.buildNodeCollaborators(input.nodeId, rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: NodeCollaboratorListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<NodeCollaboratorListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ (change.table === 'nodes' || change.table === 'node_collaborators') &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchCollaborators(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildNodeCollaborators(input.nodeId, rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchCollaborators(
+ input: NodeCollaboratorListQueryInput,
+ ): Promise<NodeCollaboratorRow[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<NodeCollaboratorRow>`
+ WITH RECURSIVE ancestors(id, parent_id, level) AS (
+ SELECT id, parent_id, 0 AS level
+ FROM nodes
+ WHERE id = ${input.nodeId}
+ UNION ALL
+ SELECT n.id, n.parent_id, a.level + 1
+ FROM nodes n
+ INNER JOIN ancestors a ON n.id = a.parent_id
+ )
+ SELECT
+ nc.node_id,
+ a.level AS node_level,
+ nn.attributes AS node_attributes,
+ nn.parent_id AS node_parent_id,
+ nc.collaborator_id,
+ cn.attributes AS collaborator_attributes,
+ nc.role
+ FROM node_collaborators nc
+ JOIN ancestors a ON nc.node_id = a.id
+ JOIN nodes nn ON nc.node_id = nn.id
+ JOIN nodes cn ON nc.collaborator_id = cn.id
+ WHERE cn.type = ${NodeTypes.User};
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildNodeCollaborators = (
+ nodeId: string,
+ rows: NodeCollaboratorRow[],
+ ): NodeCollaboratorsWrapper => {
+ const direct: NodeCollaboratorNode[] = [];
+ const inheritCollaboratorMap: Map<string, NodeCollaboratorRow> = new Map();
+
+ for (const row of rows) {
+ if (row.node_id === nodeId) {
+ const collaboratorAttributes = JSON.parse(row.collaborator_attributes);
+
+ const collaborator: NodeCollaboratorNode = {
+ id: row.collaborator_id,
+ name: collaboratorAttributes.name,
+ email: collaboratorAttributes.email,
+ avatar: collaboratorAttributes.avatar || null,
+ role: row.role,
+ };
+
+ direct.push(collaborator);
+ } else {
+ if (!inheritCollaboratorMap.has(row.collaborator_id)) {
+ inheritCollaboratorMap.set(row.collaborator_id, row);
+ } else {
+ const existingRow = inheritCollaboratorMap.get(row.collaborator_id);
+ if (!existingRow || existingRow.node_level < row.node_level) {
+ inheritCollaboratorMap.set(row.collaborator_id, row);
+ }
+ }
+ }
+ }
+
+ const inheritLeveledMap: Map<number, InheritNodeCollaboratorsGroup> =
+ new Map();
+
+ for (const row of inheritCollaboratorMap.values()) {
+ if (!inheritLeveledMap.has(row.node_level)) {
+ const nodeAttributes = JSON.parse(row.node_attributes);
+ inheritLeveledMap.set(row.node_level, {
+ id: row.node_id,
+ name: nodeAttributes.name,
+ avatar: nodeAttributes.avatar,
+ collaborators: [],
+ });
+ }
+
+ const group = inheritLeveledMap.get(row.node_level);
+ const collaboratorAttributes = JSON.parse(row.collaborator_attributes);
+ group.collaborators.push({
+ id: row.collaborator_id,
+ name: collaboratorAttributes.name,
+ avatar: collaboratorAttributes.avatar,
+ email: collaboratorAttributes.email,
+ role: row.role,
+ });
+ }
+
+ return {
+ direct,
+ inherit: Array.from(inheritLeveledMap.values()),
+ };
+ };
+}
diff --git a/desktop/src/electron/queries/node-collaborator-search.ts b/desktop/src/electron/queries/node-collaborator-search.ts
new file mode 100644
index 00000000..0713c474
--- /dev/null
+++ b/desktop/src/electron/queries/node-collaborator-search.ts
@@ -0,0 +1,107 @@
+import { NodeCollaboratorSearchQueryInput } from '@/types/queries/node-collaborator-search';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { NodeCollaboratorNode } from '@/types/nodes';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class NodeCollaboratorSearchQueryHandler
+ implements QueryHandler<NodeCollaboratorSearchQueryInput>
+{
+ public async handleQuery(
+ input: NodeCollaboratorSearchQueryInput,
+ ): Promise<QueryResult<NodeCollaboratorSearchQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildCollaboratorNodes(rows),
+ state: {
+ rows: rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: NodeCollaboratorSearchQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<NodeCollaboratorSearchQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildCollaboratorNodes(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: NodeCollaboratorSearchQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ SELECT n.*
+ FROM nodes n
+ JOIN node_names nn ON n.id = nn.id
+ WHERE n.type = ${NodeTypes.User}
+ AND nn.name MATCH ${input.searchQuery + '*'}
+ ${
+ input.excluded.length > 0
+ ? sql`AND n.id NOT IN (${sql.join(
+ input.excluded.map((id) => sql`${id}`),
+ sql`, `,
+ )})`
+ : sql``
+ }
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildCollaboratorNodes = (
+ rows: SelectNode[],
+ ): NodeCollaboratorNode[] => {
+ return rows.map((row) => {
+ const attributes = JSON.parse(row.attributes);
+ return {
+ id: row.id,
+ name: attributes.name,
+ email: attributes.email,
+ avatar: attributes.avatar,
+ role: 'collaborator',
+ };
+ });
+ };
+}
diff --git a/desktop/src/electron/queries/node-get.ts b/desktop/src/electron/queries/node-get.ts
new file mode 100644
index 00000000..48660fd5
--- /dev/null
+++ b/desktop/src/electron/queries/node-get.ts
@@ -0,0 +1,75 @@
+import { NodeGetQueryInput } from '@/types/queries/node-get';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { mapNode } from '@/lib/nodes';
+import { SelectNode } from '../schemas/workspace';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class NodeGetQueryHandler implements QueryHandler<NodeGetQueryInput> {
+ public async handleQuery(
+ input: NodeGetQueryInput,
+ ): Promise<QueryResult<NodeGetQueryInput>> {
+ const row = await this.fetchNode(input);
+ return {
+ output: mapNode(row),
+ state: {
+ row,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: NodeGetQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<NodeGetQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const row = await this.fetchNode(input);
+ if (isEqual(row, state.row)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: mapNode(row),
+ state: {
+ row,
+ },
+ },
+ };
+ }
+
+ private async fetchNode(input: NodeGetQueryInput): Promise<SelectNode> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const row = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', input.nodeId)
+ .executeTakeFirst();
+
+ return row;
+ }
+}
diff --git a/desktop/src/electron/queries/record-get.ts b/desktop/src/electron/queries/record-get.ts
new file mode 100644
index 00000000..f45344f0
--- /dev/null
+++ b/desktop/src/electron/queries/record-get.ts
@@ -0,0 +1,129 @@
+import { RecordGetQueryInput } from '@/types/queries/record-get';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { mapNode } from '@/lib/nodes';
+import { sql } from 'kysely';
+import { SelectNode } from '../schemas/workspace';
+import { RecordNode } from '@/types/databases';
+import { NodeTypes } from '@/lib/constants';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class RecordGetQueryHandler
+ implements QueryHandler<RecordGetQueryInput>
+{
+ async handleQuery(
+ input: RecordGetQueryInput,
+ ): Promise<QueryResult<RecordGetQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildRecord(input.recordId, rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ async checkForChanges(
+ changes: MutationChange[],
+ input: RecordGetQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<RecordGetQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildRecord(input.recordId, rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(input: RecordGetQueryInput): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ WITH record_node AS (
+ SELECT *
+ FROM nodes
+ WHERE id = ${input.recordId}
+ ),
+ author_node AS (
+ SELECT *
+ FROM nodes
+ WHERE id IN (SELECT DISTINCT created_by FROM record_node)
+ )
+ SELECT * FROM record_node
+ UNION ALL
+ SELECT * FROM author_node
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildRecord = (
+ recordId: string,
+ rows: SelectNode[],
+ ): RecordNode | null => {
+ const nodes = rows.map(mapNode);
+ const recordNode = nodes.find((node) => node.id === recordId);
+ if (!recordNode) {
+ return null;
+ }
+
+ const recordName = recordNode.attributes.name;
+ const authorNode = nodes.find((node) => node.type === NodeTypes.User);
+ const author = authorNode
+ ? {
+ id: authorNode.id,
+ name: authorNode.attributes.name,
+ avatar: authorNode.attributes.avatar,
+ email: authorNode.attributes.email,
+ }
+ : {
+ id: recordNode.createdBy,
+ name: 'Unknown User',
+ avatar: null,
+ email: '[email protected]',
+ };
+
+ return {
+ id: recordNode.id,
+ parentId: recordNode.parentId,
+ name: recordName ?? null,
+ index: recordNode.index,
+ attributes: recordNode.attributes,
+ createdAt: new Date(recordNode.createdAt),
+ createdBy: author,
+ versionId: recordNode.versionId,
+ };
+ };
+}
diff --git a/desktop/src/electron/queries/record-list.ts b/desktop/src/electron/queries/record-list.ts
new file mode 100644
index 00000000..4526e6a2
--- /dev/null
+++ b/desktop/src/electron/queries/record-list.ts
@@ -0,0 +1,773 @@
+import { RecordListQueryInput } from '@/types/queries/record-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { MutationChange } from '@/types/mutations';
+import { SelectNode } from '../schemas/workspace';
+import { sql } from 'kysely';
+import {
+ BooleanFieldNode,
+ CreatedAtFieldNode,
+ DatabaseNode,
+ DateFieldNode,
+ EmailFieldNode,
+ FieldNode,
+ MultiSelectFieldNode,
+ NumberFieldNode,
+ PhoneFieldNode,
+ RecordNode,
+ SelectFieldNode,
+ TextFieldNode,
+ UrlFieldNode,
+ ViewFieldFilter,
+ ViewFilter,
+ ViewSort,
+} from '@/types/databases';
+import { isStringArray } from '@/lib/utils';
+import { UserNode } from '@/types/users';
+import { mapNode } from '@/lib/nodes';
+import { NodeTypes } from '@/lib/constants';
+import { DatabaseGetQueryHandler } from './database-get';
+import { isEqual } from 'lodash';
+
+export class RecordListQueryHandler
+ implements QueryHandler<RecordListQueryInput>
+{
+ public async handleQuery(
+ input: RecordListQueryInput,
+ ): Promise<QueryResult<RecordListQueryInput>> {
+ const rows = await this.fetchRecords(input);
+
+ return {
+ output: this.buildRecords(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: RecordListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<RecordListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchRecords(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildRecords(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchRecords(
+ input: RecordListQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const database = await this.fetchDatabase(input.userId, input.databaseId);
+ const filterQuery = this.buildFiltersQuery(input.filters, database.fields);
+ const orderByQuery = `ORDER BY ${input.sorts.length > 0 ? this.buildSortOrdersQuery(input.sorts, database.fields) : 'n."index" ASC'}`;
+ const offset = input.page * input.count;
+ const query = sql<SelectNode>`
+ WITH record_nodes AS (
+ SELECT n.*, ROW_NUMBER() OVER (${sql.raw(orderByQuery)}) AS order_number
+ FROM nodes n
+ WHERE n.parent_id = ${input.databaseId} AND n.type = ${NodeTypes.Record} ${sql.raw(filterQuery)}
+ ${sql.raw(orderByQuery)}
+ LIMIT ${sql.lit(input.count)}
+ OFFSET ${sql.lit(offset)}
+ ),
+ author_nodes AS (
+ SELECT *, NULL AS order_number
+ FROM nodes
+ WHERE id IN (SELECT DISTINCT created_by FROM record_nodes)
+ ),
+ all_nodes as (
+ SELECT * FROM record_nodes
+ UNION ALL
+ SELECT * FROM author_nodes
+ )
+ SELECT n.*
+ FROM all_nodes n
+ ORDER BY n.order_number ASC
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildRecords = (rows: SelectNode[]): RecordNode[] => {
+ const nodes = rows.map(mapNode);
+ const recordNodes = nodes.filter((node) => node.type === NodeTypes.Record);
+
+ const authorNodes = nodes.filter((node) => node.type === NodeTypes.User);
+ const records: RecordNode[] = [];
+ const authorMap = new Map<string, UserNode>();
+
+ for (const author of authorNodes) {
+ const name = author.attributes.name;
+ const avatar = author.attributes.avatar;
+ const email = author.attributes.email;
+
+ authorMap.set(author.id, {
+ id: author.id,
+ name: name ?? 'Unknown User',
+ email,
+ avatar,
+ });
+ }
+
+ for (const node of recordNodes) {
+ const name = node.attributes.name;
+ const author = authorMap.get(node.createdBy);
+ const record: RecordNode = {
+ id: node.id,
+ parentId: node.parentId,
+ name: name ?? null,
+ index: node.index,
+ attributes: node.attributes,
+ createdAt: new Date(node.createdAt),
+ createdBy: author ?? {
+ id: node.createdBy,
+ name: 'Unknown User',
+ email: '[email protected]',
+ avatar: null,
+ },
+ versionId: node.versionId,
+ };
+
+ records.push(record);
+ }
+
+ return records;
+ };
+
+ private async fetchDatabase(
+ userId: string,
+ databaseId: string,
+ ): Promise<DatabaseNode> {
+ const handler = new DatabaseGetQueryHandler();
+ const result = await handler.handleQuery({
+ type: 'database_get',
+ databaseId: databaseId,
+ userId: userId,
+ });
+ return result.output;
+ }
+
+ private buildFiltersQuery = (
+ filters: ViewFilter[],
+ fields: FieldNode[],
+ ): string => {
+ if (filters.length === 0) {
+ return '';
+ }
+
+ const filterQueries = filters
+ .map((filter) => this.buildFilterQuery(filter, fields))
+ .filter((query) => query !== null);
+
+ if (filterQueries.length === 0) {
+ return '';
+ }
+
+ return `AND (${filterQueries.join(' AND ')})`;
+ };
+
+ private buildFilterQuery = (
+ filter: ViewFilter,
+ fields: FieldNode[],
+ ): string | null => {
+ if (filter.type === 'group') {
+ return null;
+ }
+
+ const field = fields.find((field) => field.id === filter.fieldId);
+ if (!field) {
+ return null;
+ }
+
+ switch (field.dataType) {
+ case 'boolean':
+ return this.buildBooleanFilterQuery(filter, field);
+ case 'collaborator':
+ return null;
+ case 'created_at':
+ return this.buildCreatedAtFilterQuery(filter, field);
+ case 'created_by':
+ return null;
+ case 'date':
+ return this.buildDateFilterQuery(filter, field);
+ case 'email':
+ return this.buildEmailFilterQuery(filter, field);
+ case 'file':
+ return null;
+ case 'multi_select':
+ return this.buildMultiSelectFilterQuery(filter, field);
+ case 'number':
+ return this.buildNumberFilterQuery(filter, field);
+ case 'phone':
+ return this.buildPhoneFilterQuery(filter, field);
+ case 'select':
+ return this.buildSelectFilterQuery(filter, field);
+ case 'text':
+ return this.buildTextFilterQuery(filter, field);
+ case 'url':
+ return this.buildUrlFilterQuery(filter, field);
+ default:
+ return null;
+ }
+ };
+
+ buildBooleanFilterQuery = (
+ filter: ViewFieldFilter,
+ field: BooleanFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_true') {
+ return `json_extract(n.attributes, '$.${field.id}') = true`;
+ }
+
+ if (filter.operator === 'is_false') {
+ return `(json_extract(n.attributes, '$.${field.id}') = false OR json_extract(n.attributes, '$.${field.id}') IS NULL)`;
+ }
+
+ return null;
+ };
+
+ private buildNumberFilterQuery = (
+ filter: ViewFieldFilter,
+ field: NumberFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'number') {
+ return null;
+ }
+
+ const value = filter.value as number;
+ let operator: string | null;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'is_greater_than':
+ operator = '>';
+ break;
+ case 'is_less_than':
+ operator = '<';
+ break;
+ case 'is_greater_than_or_equal_to':
+ operator = '>=';
+ break;
+ case 'is_less_than_or_equal_to':
+ operator = '<=';
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${operator} ${value}`;
+ };
+
+ private buildTextFilterQuery = (
+ filter: ViewFieldFilter,
+ field: TextFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'string') {
+ return null;
+ }
+
+ const value = filter.value as string;
+ let operator: string | null;
+ let formattedValue = value;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'contains':
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'does_not_contain':
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'starts_with':
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
+ case 'ends_with':
+ operator = 'LIKE';
+ formattedValue = `%${value}`;
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ };
+
+ private buildEmailFilterQuery = (
+ filter: ViewFilter,
+ field: EmailFieldNode,
+ ): string | null => {
+ if (filter.type === 'group') {
+ return null;
+ }
+
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'string') {
+ return null;
+ }
+
+ const value = filter.value as string;
+ let operator: string | null;
+ let formattedValue = value;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'contains':
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'does_not_contain':
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'starts_with':
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
+ case 'ends_with':
+ operator = 'LIKE';
+ formattedValue = `%${value}`;
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ };
+
+ private buildPhoneFilterQuery = (
+ filter: ViewFieldFilter,
+ field: PhoneFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'string') {
+ return null;
+ }
+
+ const value = filter.value as string;
+ let operator: string | null;
+ let formattedValue = value;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'contains':
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'does_not_contain':
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'starts_with':
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
+ case 'ends_with':
+ operator = 'LIKE';
+ formattedValue = `%${value}`;
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ };
+
+ private buildUrlFilterQuery = (
+ filter: ViewFieldFilter,
+ field: UrlFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'string') {
+ return null;
+ }
+
+ const value = filter.value as string;
+ let operator: string | null;
+ let formattedValue = value;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'contains':
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'does_not_contain':
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
+ case 'starts_with':
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
+ case 'ends_with':
+ operator = 'LIKE';
+ formattedValue = `%${value}`;
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
+ };
+
+ private buildSelectFilterQuery = (
+ filter: ViewFieldFilter,
+ field: SelectFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (!isStringArray(filter.value)) {
+ return null;
+ }
+
+ if (filter.value.length === 0) {
+ return null;
+ }
+
+ const values = this.joinIds(filter.value);
+ switch (filter.operator) {
+ case 'is_in':
+ return `json_extract(n.attributes, '$.${field.id}') IN (${values})`;
+ case 'is_not_in':
+ return `json_extract(n.attributes, '$.${field.id}') NOT IN (${values})`;
+ default:
+ return null;
+ }
+ };
+
+ private buildMultiSelectFilterQuery = (
+ filter: ViewFieldFilter,
+ field: MultiSelectFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return `json_extract(n.attributes, '$.${field.id}') IS NULL OR json_array_length(json_extract(n.attributes, '$.${field.id}')) = 0`;
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return `json_extract(n.attributes, '$.${field.id}') IS NOT NULL AND json_array_length(json_extract(n.attributes, '$.${field.id}')) > 0`;
+ }
+
+ if (!isStringArray(filter.value)) {
+ return null;
+ }
+
+ if (filter.value.length === 0) {
+ return null;
+ }
+
+ const values = this.joinIds(filter.value);
+ switch (filter.operator) {
+ case 'is_in':
+ return `EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.${field.id}')) WHERE json_each.value IN (${values}))`;
+ case 'is_not_in':
+ return `NOT EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.${field.id}')) WHERE json_each.value IN (${values}))`;
+ default:
+ return null;
+ }
+ };
+
+ private buildDateFilterQuery = (
+ filter: ViewFieldFilter,
+ field: DateFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return this.buildIsEmptyFilterQuery(field.id);
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return this.buildIsNotEmptyFilterQuery(field.id);
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'string') {
+ return null;
+ }
+
+ const date = new Date(filter.value);
+ if (isNaN(date.getTime())) {
+ return null;
+ }
+
+ const dateString = date.toISOString().split('T')[0];
+ let operator: string | null;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'is_on_or_after':
+ operator = '>=';
+ break;
+ case 'is_on_or_before':
+ operator = '<=';
+ break;
+ case 'is_after':
+ operator = '>';
+ break;
+ case 'is_before':
+ operator = '<';
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `DATE(json_extract(n.attributes, '$.${field.id}')) ${operator} '${dateString}'`;
+ };
+
+ private buildCreatedAtFilterQuery = (
+ filter: ViewFieldFilter,
+ field: CreatedAtFieldNode,
+ ): string | null => {
+ if (filter.operator === 'is_empty') {
+ return `n.created_at IS NULL`;
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return `n.created_at IS NOT NULL`;
+ }
+
+ if (filter.value === null) {
+ return null;
+ }
+
+ if (typeof filter.value !== 'string') {
+ return null;
+ }
+
+ const date = new Date(filter.value);
+ if (isNaN(date.getTime())) {
+ return null;
+ }
+
+ const dateString = date.toISOString().split('T')[0];
+ let operator: string | null;
+
+ switch (filter.operator) {
+ case 'is_equal_to':
+ operator = '=';
+ break;
+ case 'is_not_equal_to':
+ operator = '!=';
+ break;
+ case 'is_on_or_after':
+ operator = '>=';
+ break;
+ case 'is_on_or_before':
+ operator = '<=';
+ break;
+ case 'is_after':
+ operator = '>';
+ break;
+ case 'is_before':
+ operator = '<';
+ break;
+ default:
+ return null;
+ }
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `DATE(n.created_at) ${operator} '${dateString}'`;
+ };
+
+ private buildIsEmptyFilterQuery = (fieldId: string): string => {
+ return `json_extract(n.attributes, '$.${fieldId}') IS NULL`;
+ };
+
+ private buildIsNotEmptyFilterQuery = (fieldId: string): string => {
+ return `json_extract(n.attributes, '$.${fieldId}') IS NOT NULL`;
+ };
+
+ private joinIds = (ids: string[]): string => {
+ return ids.map((id) => `'${id}'`).join(',');
+ };
+
+ private buildSortOrdersQuery = (
+ sorts: ViewSort[],
+ fields: FieldNode[],
+ ): string => {
+ return sorts
+ .map((sort) => this.buildSortOrderQuery(sort, fields))
+ .filter((query) => query !== null && query.length > 0)
+ .join(', ');
+ };
+
+ private buildSortOrderQuery = (
+ sort: ViewSort,
+ fields: FieldNode[],
+ ): string | null => {
+ const field = fields.find((field) => field.id === sort.fieldId);
+ if (!field) {
+ return null;
+ }
+
+ if (field.dataType === 'created_at') {
+ return `n.created_at ${sort.direction}`;
+ }
+
+ if (field.dataType === 'created_by') {
+ return `n.created_by_id ${sort.direction}`;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${sort.direction}`;
+ };
+}
diff --git a/desktop/src/electron/queries/server-list.ts b/desktop/src/electron/queries/server-list.ts
new file mode 100644
index 00000000..e1b32e76
--- /dev/null
+++ b/desktop/src/electron/queries/server-list.ts
@@ -0,0 +1,63 @@
+import { ServerListQueryInput } from '@/types/queries/server-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { mapServer } from '@/lib/servers';
+import { SelectServer } from '../schemas/app';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class ServerListQueryHandler
+ implements QueryHandler<ServerListQueryInput>
+{
+ async handleQuery(
+ _: ServerListQueryInput,
+ ): Promise<QueryResult<ServerListQueryInput>> {
+ const rows = await this.fetchServers();
+ return {
+ output: rows.map(mapServer),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ async checkForChanges(
+ changes: MutationChange[],
+ _: ServerListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<ServerListQueryInput>> {
+ if (
+ !changes.some(
+ (change) => change.type === 'app' && change.table === 'servers',
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchServers();
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: rows.map(mapServer),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private fetchServers(): Promise<SelectServer[]> {
+ return databaseContext.appDatabase
+ .selectFrom('servers')
+ .selectAll()
+ .execute();
+ }
+}
diff --git a/desktop/src/electron/queries/sidebar-chat-list.ts b/desktop/src/electron/queries/sidebar-chat-list.ts
new file mode 100644
index 00000000..063506e1
--- /dev/null
+++ b/desktop/src/electron/queries/sidebar-chat-list.ts
@@ -0,0 +1,155 @@
+import { SidebarChatListQueryInput } from '@/types/queries/sidebar-chat-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { SidebarChatNode } from '@/types/workspaces';
+import { mapNode } from '@/lib/nodes';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+type ChatRow = SelectNode & {
+ collaborators: string;
+};
+
+export class SidebarChatListQueryHandler
+ implements QueryHandler<SidebarChatListQueryInput>
+{
+ public async handleQuery(
+ input: SidebarChatListQueryInput,
+ ): Promise<QueryResult<SidebarChatListQueryInput>> {
+ const rows = await this.fetchChats(input);
+ return {
+ output: this.buildSidebarChatNodes(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: SidebarChatListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<SidebarChatListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ (change.table === 'nodes' || change.table === 'node_collaborators') &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchChats(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildSidebarChatNodes(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchChats(
+ input: SidebarChatListQueryInput,
+ ): Promise<ChatRow[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<ChatRow>`
+ WITH chat_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE parent_id IS NULL AND type = ${NodeTypes.Chat}
+ ),
+ collaborator_nodes AS (
+ SELECT *
+ FROM nodes
+ WHERE id IN
+ (
+ SELECT collaborator_id
+ FROM node_collaborators
+ WHERE collaborator_id != ${input.userId}
+ AND node_id IN
+ (
+ SELECT id
+ FROM chat_nodes
+ )
+ )
+ ),
+ all_nodes AS (
+ SELECT * FROM chat_nodes
+ UNION ALL
+ SELECT * FROM collaborator_nodes
+ ),
+ chat_collaborators AS (
+ SELECT
+ nc.node_id,
+ json_group_array(nc.collaborator_id) AS collaborators
+ FROM node_collaborators nc
+ WHERE nc.node_id IN (SELECT id FROM chat_nodes)
+ AND nc.collaborator_id != ${input.userId}
+ GROUP BY nc.node_id
+ )
+ SELECT
+ n.*,
+ COALESCE(cc.collaborators, json('[]')) AS collaborators
+ FROM all_nodes n
+ LEFT JOIN chat_collaborators cc ON n.id = cc.node_id
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildSidebarChatNodes = (rows: ChatRow[]): SidebarChatNode[] => {
+ const chats: SidebarChatNode[] = [];
+
+ for (const row of rows) {
+ if (row.type !== NodeTypes.Chat) {
+ continue;
+ }
+
+ const chatNode = mapNode(row);
+ const collaboratorIds = JSON.parse(row.collaborators) as string[];
+ if (!collaboratorIds || collaboratorIds.length === 0) {
+ continue;
+ }
+
+ const collaboratorId = collaboratorIds[0];
+ const collaboratorRow = rows.find((r) => r.id === collaboratorId);
+ if (!collaboratorRow) {
+ continue;
+ }
+
+ const collaboratorNode = mapNode(collaboratorRow);
+ chats.push({
+ id: chatNode.id,
+ type: chatNode.type,
+ name: collaboratorNode.attributes.name,
+ avatar: chatNode.attributes.avatar,
+ });
+ }
+
+ return chats;
+ };
+}
diff --git a/desktop/src/electron/queries/sidebar-space-list.ts b/desktop/src/electron/queries/sidebar-space-list.ts
new file mode 100644
index 00000000..899deffc
--- /dev/null
+++ b/desktop/src/electron/queries/sidebar-space-list.ts
@@ -0,0 +1,132 @@
+import { SidebarSpaceListQueryInput } from '@/types/queries/sidebar-space-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { SidebarNode, SidebarSpaceNode } from '@/types/workspaces';
+import { mapNode } from '@/lib/nodes';
+import { LocalNode } from '@/types/nodes';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class SidebarSpaceListQueryHandler
+ implements QueryHandler<SidebarSpaceListQueryInput>
+{
+ public async handleQuery(
+ input: SidebarSpaceListQueryInput,
+ ): Promise<QueryResult<SidebarSpaceListQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildSidebarSpaceNodes(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: SidebarSpaceListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<SidebarSpaceListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildSidebarSpaceNodes(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: SidebarSpaceListQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ 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)
+ )
+ SELECT * FROM space_nodes
+ UNION ALL
+ SELECT * FROM space_children_nodes;
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildSidebarSpaceNodes = (rows: SelectNode[]): SidebarSpaceNode[] => {
+ const nodes: LocalNode[] = rows.map(mapNode);
+ const spaces: SidebarSpaceNode[] = [];
+
+ for (const node of nodes) {
+ if (node.type !== NodeTypes.Space) {
+ continue;
+ }
+
+ const children = nodes.filter((n) => n.parentId === node.id);
+ spaces.push(this.buildSpaceNode(node, children));
+ }
+
+ return spaces;
+ };
+
+ private buildSpaceNode = (
+ node: LocalNode,
+ children: LocalNode[],
+ ): SidebarSpaceNode => {
+ return {
+ id: node.id,
+ type: node.type,
+ name: node.attributes?.name ?? null,
+ avatar: node.attributes?.avatar ?? null,
+ children: children.map(this.buildSidearNode),
+ };
+ };
+
+ private buildSidearNode = (node: LocalNode): SidebarNode => {
+ return {
+ id: node.id,
+ type: node.type,
+ name: node.attributes.name ?? null,
+ avatar: node.attributes.avatar ?? null,
+ };
+ };
+}
diff --git a/desktop/src/electron/queries/user-search.ts b/desktop/src/electron/queries/user-search.ts
new file mode 100644
index 00000000..4901510f
--- /dev/null
+++ b/desktop/src/electron/queries/user-search.ts
@@ -0,0 +1,104 @@
+import { UserSearchQueryInput } from '@/types/queries/user-search';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { sql } from 'kysely';
+import { SelectNode } from '@/electron/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { UserNode } from '@/types/users';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class UserSearchQueryHandler
+ implements QueryHandler<UserSearchQueryInput>
+{
+ public async handleQuery(
+ input: UserSearchQueryInput,
+ ): Promise<QueryResult<UserSearchQueryInput>> {
+ if (input.searchQuery.length === 0) {
+ return {
+ output: [],
+ state: {
+ rows: [],
+ },
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildUserNodes(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: UserSearchQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<UserSearchQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildUserNodes(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(input: UserSearchQueryInput): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const query = sql<SelectNode>`
+ SELECT n.*
+ FROM nodes n
+ JOIN node_names nn ON n.id = nn.id
+ WHERE n.type = ${NodeTypes.User}
+ AND n.id != ${input.userId}
+ AND nn.name MATCH ${input.searchQuery + '*'}
+ `.compile(workspaceDatabase);
+
+ const result = await workspaceDatabase.executeQuery(query);
+ return result.rows;
+ }
+
+ private buildUserNodes = (rows: SelectNode[]): UserNode[] => {
+ return rows.map((row) => {
+ const attributes = JSON.parse(row.attributes);
+ return {
+ id: row.id,
+ name: attributes.name,
+ email: attributes.email,
+ avatar: attributes.avatar,
+ };
+ });
+ };
+}
diff --git a/desktop/src/electron/queries/workspace-list.ts b/desktop/src/electron/queries/workspace-list.ts
new file mode 100644
index 00000000..54d8ca04
--- /dev/null
+++ b/desktop/src/electron/queries/workspace-list.ts
@@ -0,0 +1,88 @@
+import { WorkspaceListQueryInput } from '@/types/queries/workspace-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { Workspace, WorkspaceRole } from '@/types/workspaces';
+import { SelectWorkspace } from '../schemas/app';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class WorkspaceListQueryHandler
+ implements QueryHandler<WorkspaceListQueryInput>
+{
+ public async handleQuery(
+ input: WorkspaceListQueryInput,
+ ): Promise<QueryResult<WorkspaceListQueryInput>> {
+ const rows = await this.fetchWorkspaces();
+
+ return {
+ output: this.buildWorkspaces(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: WorkspaceListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<WorkspaceListQueryInput>> {
+ if (
+ !changes.some(
+ (change) => change.type === 'app' && change.table === 'accounts',
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchWorkspaces();
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildWorkspaces(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private fetchWorkspaces(): Promise<SelectWorkspace[]> {
+ return databaseContext.appDatabase
+ .selectFrom('workspaces')
+ .selectAll()
+ .where(
+ 'account_id',
+ 'in',
+ databaseContext.appDatabase
+ .selectFrom('accounts')
+ .where('status', '=', 'active')
+ .select('id'),
+ )
+ .execute();
+ }
+
+ private buildWorkspaces(rows: SelectWorkspace[]): Workspace[] {
+ return rows.map((row) => {
+ return {
+ id: row.workspace_id,
+ name: row.name,
+ description: row.description,
+ avatar: row.avatar,
+ versionId: row.version_id,
+ accountId: row.account_id,
+ role: row.role as WorkspaceRole,
+ userId: row.user_id,
+ synced: row.synced === 1,
+ };
+ });
+ }
+}
diff --git a/desktop/src/electron/queries/workspace-user-list.ts b/desktop/src/electron/queries/workspace-user-list.ts
new file mode 100644
index 00000000..c48e144c
--- /dev/null
+++ b/desktop/src/electron/queries/workspace-user-list.ts
@@ -0,0 +1,89 @@
+import { WorkspaceUserListQueryInput } from '@/types/queries/workspace-user-list';
+import { databaseContext } from '@/electron/database-context';
+import { ChangeCheckResult, QueryHandler, QueryResult } from '@/types/queries';
+import { NodeTypes } from '@/lib/constants';
+import { mapNode } from '@/lib/nodes';
+import { SelectNode } from '../schemas/workspace';
+import { LocalNode } from '@/types/nodes';
+import { MutationChange } from '@/types/mutations';
+import { isEqual } from 'lodash';
+
+export class WorkspaceUserListQueryHandler
+ implements QueryHandler<WorkspaceUserListQueryInput>
+{
+ public async handleQuery(
+ input: WorkspaceUserListQueryInput,
+ ): Promise<QueryResult<WorkspaceUserListQueryInput>> {
+ const rows = await this.fetchNodes(input);
+ return {
+ output: this.buildWorkspaceUserNodes(rows),
+ state: {
+ rows,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: WorkspaceUserListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<WorkspaceUserListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ change.table === 'nodes' &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const rows = await this.fetchNodes(input);
+ if (isEqual(rows, state.rows)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildWorkspaceUserNodes(rows),
+ state: {
+ rows,
+ },
+ },
+ };
+ }
+
+ private async fetchNodes(
+ input: WorkspaceUserListQueryInput,
+ ): Promise<SelectNode[]> {
+ const workspaceDatabase = await databaseContext.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ if (workspaceDatabase === null) {
+ throw new Error('Workspace database not found.');
+ }
+
+ const offset = input.page * input.count;
+ const rows = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('type', '=', NodeTypes.User)
+ .orderBy('created_at asc')
+ .offset(offset)
+ .limit(input.count)
+ .execute();
+
+ return rows;
+ }
+
+ private buildWorkspaceUserNodes = (rows: SelectNode[]): LocalNode[] => {
+ return rows.map(mapNode);
+ };
+}
diff --git a/desktop/src/electron/schemas/app.ts b/desktop/src/electron/schemas/app.ts
index 672f0bfb..c1c7d42e 100644
--- a/desktop/src/electron/schemas/app.ts
+++ b/desktop/src/electron/schemas/app.ts
@@ -30,14 +30,14 @@ export type CreateAccount = Insertable<AccountTable>;
export type UpdateAccount = Updateable<AccountTable>;
interface WorkspaceTable {
- id: ColumnType<string, string, never>;
+ user_id: ColumnType<string, string, never>;
+ workspace_id: ColumnType<string, string, never>;
account_id: ColumnType<string, string, never>;
name: ColumnType<string, string, string>;
description: ColumnType<string | null, string | null, string | null>;
avatar: ColumnType<string | null, string | null, string | null>;
version_id: ColumnType<string, string, string>;
role: ColumnType<string, string, string>;
- user_id: ColumnType<string, string, never>;
synced: ColumnType<number, number, number>;
}
diff --git a/desktop/src/electron/schemas/workspace.ts b/desktop/src/electron/schemas/workspace.ts
index af3ea52a..8614344d 100644
--- a/desktop/src/electron/schemas/workspace.ts
+++ b/desktop/src/electron/schemas/workspace.ts
@@ -41,7 +41,7 @@ export type UpdateNodeCollaborator = Updateable<NodeCollaboratorTable>;
interface NodeReactionTable {
node_id: ColumnType<string, string, never>;
- reactor_id: ColumnType<string, string, never>;
+ actor_id: ColumnType<string, string, never>;
reaction: ColumnType<string, string, never>;
created_at: ColumnType<string, string, never>;
server_created_at: ColumnType<string | null, string | null, string | null>;
diff --git a/desktop/src/electron/workspace-manager.ts b/desktop/src/electron/workspace-manager.ts
index 2cceda4b..d70753be 100644
--- a/desktop/src/electron/workspace-manager.ts
+++ b/desktop/src/electron/workspace-manager.ts
@@ -18,7 +18,6 @@ import {
extractTablesFromSql,
resultHasChanged,
} from '@/electron/utils';
-import { SubscribedQueryContext, SubscribedQueryResult } from '@/types/queries';
import {
ServerExecuteMutationsResponse,
ServerMutation,
@@ -40,7 +39,6 @@ export class WorkspaceManager {
private readonly workspace: Workspace;
private readonly axios: AxiosInstance;
private readonly database: Kysely<WorkspaceDatabaseSchema>;
- private readonly subscribers: Map<string, SubscribedQueryResult<unknown>>;
private readonly backoffCalculator: BackoffCalculator;
private readonly debouncedNotifyQuerySubscribers: (
affectedTables: string[],
@@ -49,7 +47,6 @@ export class WorkspaceManager {
constructor(workspace: Workspace, axios: AxiosInstance, accountPath: string) {
this.workspace = workspace;
this.axios = axios;
- this.subscribers = new Map();
this.backoffCalculator = new BackoffCalculator();
const workspaceDir = `${accountPath}/${workspace.id}`;
@@ -92,28 +89,6 @@ export class WorkspaceManager {
return result;
}
- public async executeQueryAndSubscribe<T>(
- context: SubscribedQueryContext<T>,
- ): Promise<QueryResult<T>> {
- const result = await this.database.executeQuery(context.query);
-
- // only mutations should have side effects
- if (result.numAffectedRows > 0) {
- throw new Error('Query should not have any side effects');
- }
-
- const queryId = context.key.join('|') + context.page;
- const selectedTables = extractTablesFromSql(context.query.sql);
- const subscriberData: SubscribedQueryResult<T> = {
- context,
- tables: selectedTables,
- result: result,
- };
- this.subscribers.set(queryId, subscriberData);
-
- return result;
- }
-
public async executeMutation(
mutation: CompiledQuery | CompiledQuery[],
): Promise<void> {
@@ -153,44 +128,31 @@ export class WorkspaceManager {
}
}
- public unsubscribeQuery(queryKey: string[]): void {
- var queryIds = [...this.subscribers.keys()];
- for (const queryId of queryIds) {
- const subscriberData = this.subscribers.get(queryId);
- if (isEqual(subscriberData.context.key, queryKey)) {
- this.subscribers.delete(queryId);
- }
- }
- }
-
private async notifyQuerySubscribers(
affectedTables: string[],
): Promise<void> {
- for (const subscriber of this.subscribers.values()) {
- const hasAffectedTables = affectedTables.some((table) =>
- subscriber.tables.includes(table),
- );
-
- if (!hasAffectedTables) {
- continue;
- }
-
- const newResult = await this.database.executeQuery(
- subscriber.context.query,
- );
-
- if (resultHasChanged(subscriber.result, newResult)) {
- subscriber.result = newResult;
- eventBus.publish({
- event: 'workspace_query_updated',
- payload: {
- key: subscriber.context.key,
- page: subscriber.context.page,
- result: newResult,
- },
- });
- }
- }
+ // for (const subscriber of this.subscribers.values()) {
+ // const hasAffectedTables = affectedTables.some((table) =>
+ // subscriber.tables.includes(table),
+ // );
+ // if (!hasAffectedTables) {
+ // continue;
+ // }
+ // const newResult = await this.database.executeQuery(
+ // subscriber.context.query,
+ // );
+ // if (resultHasChanged(subscriber.result, newResult)) {
+ // subscriber.result = newResult;
+ // eventBus.publish({
+ // event: 'workspace_query_updated',
+ // payload: {
+ // key: subscriber.context.key,
+ // page: subscriber.context.page,
+ // result: newResult,
+ // },
+ // });
+ // }
+ // }
}
public async sendMutations(): Promise<void> {
@@ -322,7 +284,7 @@ export class WorkspaceManager {
.where((eb) =>
eb.and([
eb('node_id', '=', mutation.before.node_id),
- eb('reactor_id', '=', mutation.before.reactor_id),
+ eb('actor_id', '=', mutation.before.actor_id),
eb('reaction', '=', mutation.before.reaction),
]),
)
@@ -394,7 +356,7 @@ export class WorkspaceManager {
data.nodeReactions.map((nodeReaction) => {
return {
node_id: nodeReaction.nodeId,
- reactor_id: nodeReaction.reactorId,
+ actor_id: nodeReaction.actorId,
reaction: nodeReaction.reaction,
created_at: nodeReaction.createdAt,
server_created_at: nodeReaction.serverCreatedAt,
@@ -568,7 +530,7 @@ export class WorkspaceManager {
.insertInto('node_reactions')
.values({
node_id: nodeReaction.nodeId,
- reactor_id: nodeReaction.reactorId,
+ actor_id: nodeReaction.actorId,
reaction: nodeReaction.reaction,
created_at: nodeReaction.createdAt,
server_created_at: nodeReaction.serverCreatedAt,
diff --git a/desktop/src/hooks/use-infinite-query.tsx b/desktop/src/hooks/use-infinite-query.tsx
new file mode 100644
index 00000000..865fc722
--- /dev/null
+++ b/desktop/src/hooks/use-infinite-query.tsx
@@ -0,0 +1,141 @@
+import React from 'react';
+import { QueryInput, QueryMap } from '@/types/queries';
+import { sha256 } from 'js-sha256';
+import { useEventBus } from '@/hooks/use-event-bus';
+import { NeuronId } from '@/lib/id';
+
+export const useInfiniteQuery = <T extends QueryInput>({
+ initialPageInput,
+ getNextPageInput,
+}: {
+ initialPageInput: T;
+ getNextPageInput: (
+ page: number,
+ pages: Array<QueryMap[T['type']]['output']>,
+ ) => T | undefined;
+}) => {
+ const eventBus = useEventBus();
+
+ const [pages, setPages] = React.useState<
+ Array<QueryMap[T['type']]['output']>
+ >([]);
+ const [isPending, setIsPending] = React.useState(true);
+ const [isFetchingNextPage, setIsFetchingNextPage] = React.useState(false);
+ const [hasNextPage, setHasNextPage] = React.useState(true);
+
+ const subscriberIdsRef = React.useRef<
+ Array<{ queryId: string; subscriberId: string }>
+ >([]);
+
+ const initialInputHash = sha256(JSON.stringify(initialPageInput));
+
+ // Function to clean up existing subscriptions
+ const cleanupSubscriptions = React.useCallback(() => {
+ subscriberIdsRef.current.forEach(({ queryId, subscriberId }) => {
+ window.neuron.unsubscribeQuery(queryId);
+ eventBus.unsubscribe(subscriberId);
+ });
+ subscriberIdsRef.current = [];
+ }, []);
+
+ // Function to subscribe to query result updates
+ const subscribeToQueryResult = React.useCallback(
+ (queryId: string, pageIndex: number) => {
+ const subscriberId = eventBus.subscribe((event) => {
+ if (
+ event.event === 'query_result_updated' &&
+ event.payload?.id === queryId &&
+ event.payload?.result
+ ) {
+ setPages((prevPages) => {
+ const newPages = [...prevPages];
+ newPages[pageIndex] = event.payload.result;
+ return newPages;
+ });
+ }
+ });
+ subscriberIdsRef.current.push({ queryId, subscriberId });
+ },
+ [eventBus],
+ );
+
+ // Function to fetch a page
+ const fetchPage = React.useCallback(
+ async (input: T, pageIndex: number) => {
+ const queryId = NeuronId.generate(NeuronId.Type.Query);
+
+ try {
+ const result = await window.neuron.executeQuery(queryId, input);
+
+ // Update pages state
+ setPages((prevPages) => {
+ const newPages = [...prevPages];
+ newPages[pageIndex] = result;
+ return newPages;
+ });
+
+ // Check for the next page
+ const futureNextPageInput = getNextPageInput(pageIndex + 1, [
+ ...pages,
+ result,
+ ]);
+ setHasNextPage(!!futureNextPageInput);
+
+ // Subscribe to updates for this query
+ subscribeToQueryResult(queryId, pageIndex);
+ } catch (error) {
+ console.error('Error executing query:', error);
+ }
+ },
+ [pages, getNextPageInput, subscribeToQueryResult],
+ );
+
+ // Fetch the initial page
+ const fetchInitialPage = React.useCallback(async () => {
+ setPages([]);
+ setIsPending(true);
+ setHasNextPage(false);
+
+ cleanupSubscriptions();
+
+ await fetchPage(initialPageInput, 0);
+
+ setIsPending(false);
+ }, [initialPageInput, fetchPage]);
+
+ React.useEffect(() => {
+ fetchInitialPage();
+
+ return () => {
+ cleanupSubscriptions();
+ };
+ }, [initialInputHash]);
+
+ // Function to fetch the next page
+ const fetchNextPage = React.useCallback(async () => {
+ if (!hasNextPage || isFetchingNextPage) return;
+
+ setIsFetchingNextPage(true);
+
+ const nextPageNumber = pages.length;
+ const nextPageInput = getNextPageInput(nextPageNumber, pages);
+
+ if (!nextPageInput) {
+ setIsFetchingNextPage(false);
+ setHasNextPage(false);
+ return;
+ }
+
+ await fetchPage(nextPageInput, nextPageNumber);
+
+ setIsFetchingNextPage(false);
+ }, [pages, hasNextPage, isFetchingNextPage, getNextPageInput, fetchPage]);
+
+ return {
+ data: pages,
+ isPending,
+ hasNextPage,
+ isFetchingNextPage,
+ fetchNextPage,
+ };
+};
diff --git a/desktop/src/hooks/use-mutation.tsx b/desktop/src/hooks/use-mutation.tsx
new file mode 100644
index 00000000..dd3a1c7b
--- /dev/null
+++ b/desktop/src/hooks/use-mutation.tsx
@@ -0,0 +1,34 @@
+import React from 'react';
+import { MutationInput, MutationMap } from '@/types/mutations';
+
+interface MutationOptions<T extends MutationInput> {
+ input: T;
+ onSuccess?: (output: MutationMap[T['type']]['output']) => void;
+ onError?: (error: Error) => void;
+}
+
+export const useMutation = () => {
+ const [isPending, setIsPending] = React.useState(false);
+
+ const mutate = React.useCallback(
+ async <T extends MutationInput>(options: MutationOptions<T>) => {
+ setIsPending(true);
+ try {
+ const output = await window.neuron.executeMutation(options.input);
+ options.onSuccess?.(output);
+ return output;
+ } catch (error) {
+ options.onError?.(error as Error);
+ throw error;
+ } finally {
+ setIsPending(false);
+ }
+ },
+ [],
+ );
+
+ return {
+ isPending,
+ mutate: mutate,
+ };
+};
diff --git a/desktop/src/hooks/use-query.tsx b/desktop/src/hooks/use-query.tsx
new file mode 100644
index 00000000..97c06f0e
--- /dev/null
+++ b/desktop/src/hooks/use-query.tsx
@@ -0,0 +1,53 @@
+import React from 'react';
+import { QueryInput, QueryMap } from '@/types/queries';
+import { sha256 } from 'js-sha256';
+import { useEventBus } from './use-event-bus';
+import { NeuronId } from '@/lib/id';
+
+export const useQuery = <T extends QueryInput>(input: T) => {
+ const eventBus = useEventBus();
+
+ const inputJson = JSON.stringify(input);
+ const hash = sha256(inputJson);
+
+ const [isPending, setIsPending] = React.useState(true);
+ const [data, setData] = React.useState<
+ QueryMap[T['type']]['output'] | undefined
+ >(undefined);
+
+ React.useEffect(() => {
+ const queryId = NeuronId.generate(NeuronId.Type.Query);
+ const fetchData = async () => {
+ try {
+ const result = await window.neuron.executeQuery(queryId, input);
+ setData(result);
+ } catch (error) {
+ console.error('Error executing query:', error);
+ } finally {
+ setIsPending(false);
+ }
+ };
+
+ fetchData();
+
+ const subscriberId = eventBus.subscribe((event) => {
+ if (
+ event.event === 'query_result_updated' &&
+ event.payload?.id === queryId &&
+ event.payload?.result
+ ) {
+ setData(event.payload.result);
+ }
+ });
+
+ return () => {
+ window.neuron.unsubscribeQuery(queryId);
+ eventBus.unsubscribe(subscriberId);
+ };
+ }, [hash]);
+
+ return {
+ isPending,
+ data,
+ };
+};
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index c587ba92..2f44f1b5 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -39,6 +39,7 @@ enum IdType {
SelectOption = 'so',
ViewFilter = 'vf',
ViewSort = 'vs',
+ Query = 'qu',
}
export class NeuronId {
diff --git a/desktop/src/lib/nodes.ts b/desktop/src/lib/nodes.ts
index 080ccdfa..67a688d2 100644
--- a/desktop/src/lib/nodes.ts
+++ b/desktop/src/lib/nodes.ts
@@ -51,7 +51,7 @@ export const buildNodeInsertMutation = (
return schema.insertInto('nodes').values(nodes).compile();
};
-const buildCreateNode = (
+export const buildCreateNode = (
input: NodeInsertInput,
userId: string,
): CreateNode => {
diff --git a/desktop/src/lib/servers.ts b/desktop/src/lib/servers.ts
index a261fcaf..cf5f46c1 100644
--- a/desktop/src/lib/servers.ts
+++ b/desktop/src/lib/servers.ts
@@ -1,3 +1,4 @@
+import { SelectServer } from '@/electron/schemas/app';
import { Server } from '@/types/servers';
export const buildApiBaseUrl = (server: Server): string => {
@@ -9,3 +10,15 @@ export const buildSynapseUrl = (server: Server, deviceId: string) => {
const protocol = server.attributes?.insecure ? 'ws' : 'wss';
return `${protocol}://${server.domain}/v1/synapse?device_id=${deviceId}`;
};
+
+export const mapServer = (row: SelectServer): Server => {
+ return {
+ domain: row.domain,
+ name: row.name,
+ avatar: row.avatar,
+ attributes: JSON.parse(row.attributes),
+ version: row.version,
+ createdAt: new Date(row.created_at),
+ lastSyncedAt: row.last_synced_at ? new Date(row.last_synced_at) : null,
+ };
+};
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 275c6a93..0b9d008d 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -1,9 +1,11 @@
import { app, ipcMain, BrowserWindow } from 'electron';
import path from 'path';
import { eventBus } from '@/lib/event-bus';
-import { appManager } from '@/electron/app-manager';
-import { CompiledQuery, QueryResult } from 'kysely';
-import { SubscribedQueryContext } from '@/types/queries';
+import { MutationInput, MutationMap } from '@/types/mutations';
+import { QueryInput, QueryMap } from '@/types/queries';
+import { mediator } from '@/electron/mediator';
+import { databaseContext } from './electron/database-context';
+
let subscriptionId: string | null = null;
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
@@ -11,7 +13,9 @@ if (require('electron-squirrel-startup')) {
app.quit();
}
-const createWindow = () => {
+const createWindow = async () => {
+ await databaseContext.init();
+
// Create the browser window.
const mainWindow = new BrowserWindow({
fullscreen: true,
@@ -65,122 +69,27 @@ app.on('before-quit', () => {
}
});
-// inter process handlers
-ipcMain.handle('init', async () => appManager.init());
-ipcMain.handle('logout', async (_, accountId) => appManager.logout(accountId));
-
-ipcMain.handle(
- 'execute-app-mutation',
- async (_, mutation: CompiledQuery | CompiledQuery[]): Promise<void> => {
- await appManager.executeMutation(mutation);
- },
-);
-
ipcMain.handle(
- 'execute-app-query',
- async (_, query: CompiledQuery<unknown>): Promise<QueryResult<unknown>> => {
- return await appManager.executeQuery(query);
+ 'execute-mutation',
+ async <T extends MutationInput>(
+ _: unknown,
+ input: T,
+ ): Promise<MutationMap[T['type']]['output']> => {
+ return mediator.handleMutation(input);
},
);
ipcMain.handle(
- 'execute-app-query-and-subscribe',
- async (
- _,
- context: SubscribedQueryContext<unknown>,
- ): Promise<QueryResult<unknown>> => {
- return await appManager.executeQueryAndSubscribe(context);
+ 'execute-query',
+ async <T extends QueryInput>(
+ _: unknown,
+ id: string,
+ input: T,
+ ): Promise<QueryMap[T['type']]['output']> => {
+ return mediator.handleQuery(id, input);
},
);
-ipcMain.handle('unsubscribe-app-query', (_, queryKey: string[]): void => {
- appManager.unsubscribeQuery(queryKey);
+ipcMain.handle('unsubscribe-query', (_: unknown, id: string): void => {
+ mediator.unsubscribeQuery(id);
});
-
-ipcMain.handle(
- 'execute-workspace-mutation',
- async (
- _,
- accountId: string,
- workspaceId: string,
- mutation: CompiledQuery | CompiledQuery[],
- ): Promise<void> => {
- const accountManager = await appManager.getAccount(accountId);
- if (!accountManager) {
- throw new Error(`Account not found: ${accountId}`);
- }
-
- const workspaceManager = accountManager.getWorkspace(workspaceId);
- if (!workspaceManager) {
- throw new Error(`Workspace not found: ${workspaceId}`);
- }
-
- return await workspaceManager.executeMutation(mutation);
- },
-);
-
-ipcMain.handle(
- 'execute-workspace-query',
- async (
- _,
- accountId: string,
- workspaceId: string,
- query: CompiledQuery<unknown>,
- ): Promise<QueryResult<unknown>> => {
- const accountManager = await appManager.getAccount(accountId);
- if (!accountManager) {
- throw new Error(`Account not found: ${accountId}`);
- }
-
- const workspaceManager = accountManager.getWorkspace(workspaceId);
- if (!workspaceManager) {
- throw new Error(`Workspace not found: ${workspaceId}`);
- }
-
- return await workspaceManager.executeQuery(query);
- },
-);
-
-ipcMain.handle(
- 'execute-workspace-query-and-subscribe',
- async (
- _,
- accountId: string,
- workspaceId: string,
- context: SubscribedQueryContext<unknown>,
- ): Promise<QueryResult<unknown>> => {
- const accountManager = await appManager.getAccount(accountId);
- if (!accountManager) {
- throw new Error(`Account not found: ${accountId}`);
- }
-
- const workspaceManager = accountManager.getWorkspace(workspaceId);
- if (!workspaceManager) {
- throw new Error(`Workspace not found: ${workspaceId}`);
- }
-
- return await workspaceManager.executeQueryAndSubscribe(context);
- },
-);
-
-ipcMain.handle(
- 'unsubscribe-workspace-query',
- async (
- _,
- accountId: string,
- workspaceId: string,
- queryKey: string[],
- ): Promise<void> => {
- const accountManager = await appManager.getAccount(accountId);
- if (!accountManager) {
- throw new Error(`Account not found: ${accountId}`);
- }
-
- const workspaceManager = accountManager.getWorkspace(workspaceId);
- if (!workspaceManager) {
- throw new Error(`Workspace not found: ${workspaceId}`);
- }
-
- workspaceManager.unsubscribeQuery(queryKey);
- },
-);
diff --git a/desktop/src/mutations/use-board-view-create-mutation.tsx b/desktop/src/mutations/use-board-view-create-mutation.tsx
deleted file mode 100644
index 543ed347..00000000
--- a/desktop/src/mutations/use-board-view-create-mutation.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { useMutation } from '@tanstack/react-query';
-
-interface BoardViewCreateInput {
- databaseId: string;
- name: string;
- groupBy: string;
-}
-
-export const useBoardViewCreateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: BoardViewCreateInput) => {
- const siblingsQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .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.BoardView);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.BoardView,
- parentId: input.databaseId,
- index: generateNodeIndex(maxIndex, null),
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-calendar-view-create-mutation.tsx b/desktop/src/mutations/use-calendar-view-create-mutation.tsx
deleted file mode 100644
index 82894055..00000000
--- a/desktop/src/mutations/use-calendar-view-create-mutation.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { useMutation } from '@tanstack/react-query';
-
-interface CalendarViewCreateInput {
- databaseId: string;
- name: string;
- groupBy: string;
-}
-
-export const useCalendarViewCreateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: CalendarViewCreateInput) => {
- const siblingsQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .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.CalendarView);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.CalendarView,
- parentId: input.databaseId,
- index: generateNodeIndex(maxIndex, null),
- name: input.name,
- groupBy: input.groupBy,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-channel-create-mutation.tsx b/desktop/src/mutations/use-channel-create-mutation.tsx
deleted file mode 100644
index f51d02ef..00000000
--- a/desktop/src/mutations/use-channel-create-mutation.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 id = NeuronId.generate(NeuronId.Type.Channel);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.Channel,
- parentId: input.spaceId,
- index: generateNodeIndex(maxIndex, null),
- name: input.name,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-chat-create-mutation.tsx b/desktop/src/mutations/use-chat-create-mutation.tsx
deleted file mode 100644
index 1d091e6f..00000000
--- a/desktop/src/mutations/use-chat-create-mutation.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
-
-interface CreateChatInput {
- userId: string;
-}
-
-export const useChatCreateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: CreateChatInput) => {
- const existingChats = workspace.schema
- .selectFrom('nodes')
- .where('type', '=', NodeTypes.Chat)
- .where(
- 'id',
- 'in',
- workspace.schema
- .selectFrom('node_collaborators')
- .select('node_id')
- .where('collaborator_id', 'in', [workspace.userId, input.userId])
- .groupBy('node_id')
- .having(workspace.schema.fn.count('collaborator_id'), '=', 2),
- )
- .selectAll()
- .compile();
-
- const result = await workspace.query(existingChats);
- if (result.rows.length > 0) {
- const chat = result.rows[0];
- return chat.id;
- }
-
- const id = NeuronId.generate(NeuronId.Type.Chat);
- const insertChatQuery = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.Chat,
- },
- },
- );
-
- const insertCollaboratorsQuery = workspace.schema
- .insertInto('node_collaborators')
- .values([
- {
- node_id: id,
- collaborator_id: workspace.userId,
- role: 'owner',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: id,
- collaborator_id: input.userId,
- role: 'owner',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
-
- await workspace.mutate([insertChatQuery, insertCollaboratorsQuery]);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-database-create-mutation.tsx b/desktop/src/mutations/use-database-create-mutation.tsx
deleted file mode 100644
index 0f5dc784..00000000
--- a/desktop/src/mutations/use-database-create-mutation.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- [
- {
- id: databaseId,
- attributes: {
- type: NodeTypes.Database,
- parentId: input.spaceId,
- index: generateNodeIndex(maxIndex, null),
- name: input.name,
- },
- },
- {
- id: tableViewId,
- attributes: {
- type: NodeTypes.TableView,
- parentId: databaseId,
- index: generateNodeIndex(null, null),
- name: 'Default',
- },
- },
- {
- id: fieldId,
- attributes: {
- type: NodeTypes.Field,
- parentId: databaseId,
- index: generateNodeIndex(null, null),
- name: 'Comment',
- dataType: 'text',
- },
- },
- ],
- );
-
- await workspace.mutate(query);
- return databaseId;
- },
- });
-};
diff --git a/desktop/src/mutations/use-email-login-mutation.tsx b/desktop/src/mutations/use-email-login-mutation.tsx
deleted file mode 100644
index 25996362..00000000
--- a/desktop/src/mutations/use-email-login-mutation.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import axios from 'axios';
-import { useAppDatabase } from '@/contexts/app-database';
-import { LoginOutput } from '@/types/accounts';
-import { useMutation } from '@tanstack/react-query';
-import { Server } from '@/types/servers';
-import { buildLoginMutationQueries } from '@/lib/accounts';
-
-interface EmailLoginInput {
- server: Server;
- email: string;
- password: string;
-}
-
-export const useEmailLoginMutation = () => {
- const appDatabase = useAppDatabase();
-
- return useMutation({
- mutationFn: async (input: EmailLoginInput) => {
- const { data } = await axios.post<LoginOutput>(
- `http://${input.server.domain}/v1/accounts/login/email`,
- {
- email: input.email,
- password: input.password,
- },
- );
-
- const queries = buildLoginMutationQueries(
- appDatabase.database,
- data,
- input.server,
- );
-
- await appDatabase.mutate(queries);
- },
- });
-};
diff --git a/desktop/src/mutations/use-email-register-mutation.tsx b/desktop/src/mutations/use-email-register-mutation.tsx
deleted file mode 100644
index 7865a69e..00000000
--- a/desktop/src/mutations/use-email-register-mutation.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import axios from 'axios';
-import { useAppDatabase } from '@/contexts/app-database';
-import { LoginOutput } from '@/types/accounts';
-import { useMutation } from '@tanstack/react-query';
-import { Server } from '@/types/servers';
-import { buildLoginMutationQueries } from '@/lib/accounts';
-
-interface EmailRegisterInput {
- server: Server;
- name: string;
- email: string;
- password: string;
-}
-
-export const useEmailRegisterMutation = () => {
- const appDatabase = useAppDatabase();
-
- return useMutation({
- mutationFn: async (input: EmailRegisterInput) => {
- const { data } = await axios.post<LoginOutput>(
- `http://${input.server.domain}/v1/accounts/register/email`,
- {
- name: input.name,
- email: input.email,
- password: input.password,
- },
- );
-
- const queries = buildLoginMutationQueries(
- appDatabase.database,
- data,
- input.server,
- );
-
- await appDatabase.mutate(queries);
- },
- });
-};
diff --git a/desktop/src/mutations/use-field-create-mutation.tsx b/desktop/src/mutations/use-field-create-mutation.tsx
deleted file mode 100644
index 7b00461b..00000000
--- a/desktop/src/mutations/use-field-create-mutation.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 id = NeuronId.generate(NeuronId.Type.Field);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.Field,
- parentId: values.databaseId,
- index: generateNodeIndex(maxIndex, null),
- name: values.name,
- dataType: values.dataType,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-message-create-mutation.tsx b/desktop/src/mutations/use-message-create-mutation.tsx
deleted file mode 100644
index 39b55296..00000000
--- a/desktop/src/mutations/use-message-create-mutation.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { mapContentsToEditorNodes } from '@/editor/mappers';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-import { JSONContent } from '@tiptap/core';
-import { LocalNode, NodeInsertInput } from '@/types/nodes';
-import { buildNodeInsertMutation } from '@/lib/nodes';
-
-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, LocalNode>(),
- );
-
- if (editorNodes.length === 0) {
- return;
- }
-
- const nodeInsertInputs: NodeInsertInput[] = [
- {
- id: messageId,
- attributes: {
- type: NodeTypes.Message,
- parentId: input.conversationId,
- index: null,
- },
- },
- ];
-
- for (const node of editorNodes) {
- nodeInsertInputs.push({
- id: node.id,
- attributes: node.attributes,
- });
- }
-
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- nodeInsertInputs,
- );
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-node-attribute-delete-mutation.tsx b/desktop/src/mutations/use-node-attribute-delete-mutation.tsx
deleted file mode 100644
index 518c7a4d..00000000
--- a/desktop/src/mutations/use-node-attribute-delete-mutation.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import * as Y from 'yjs';
-
-interface NodeAttributeDeleteInput {
- nodeId: string;
- key: string;
-}
-
-export const useNodeAttributeDeleteMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: NodeAttributeDeleteInput) => {
- const selectQuery = workspace.schema
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .compile();
-
- const result = await workspace.query(selectQuery);
- if (result.rows.length === 0) {
- throw new Error('Node not found');
- }
-
- const node = result.rows[0];
- const doc = new Y.Doc({
- guid: node.id,
- });
-
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- const attributesMap = doc.getMap('attributes');
- attributesMap.delete(input.key);
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const updateQuery = workspace.schema
- .updateTable('nodes')
- .set({
- state: encodedState,
- attributes: attributes,
- updated_at: new Date().toISOString(),
- updated_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .where('id', '=', input.nodeId)
- .compile();
-
- await workspace.mutate(updateQuery);
- },
- });
-};
diff --git a/desktop/src/mutations/use-node-attribute-set-mutation.tsx b/desktop/src/mutations/use-node-attribute-set-mutation.tsx
deleted file mode 100644
index 673405aa..00000000
--- a/desktop/src/mutations/use-node-attribute-set-mutation.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-import { fromUint8Array, toUint8Array } from 'js-base64';
-import * as Y from 'yjs';
-
-interface NodeAttributeSetInput {
- nodeId: string;
- key: string;
- value: any;
-}
-
-export const useNodeAttributeSetMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: NodeAttributeSetInput) => {
- const selectQuery = workspace.schema
- .selectFrom('nodes')
- .where('id', '=', input.nodeId)
- .selectAll()
- .compile();
-
- const result = await workspace.query(selectQuery);
- if (result.rows.length === 0) {
- throw new Error('Node not found');
- }
-
- const node = result.rows[0];
- const doc = new Y.Doc({
- guid: node.id,
- });
-
- Y.applyUpdate(doc, toUint8Array(node.state));
-
- const attributesMap = doc.getMap('attributes');
- attributesMap.set(input.key, input.value);
-
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
-
- const updateQuery = workspace.schema
- .updateTable('nodes')
- .set({
- state: encodedState,
- attributes: attributes,
- updated_at: new Date().toISOString(),
- updated_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .where('id', '=', input.nodeId)
- .compile();
-
- await workspace.mutate(updateQuery);
- },
- });
-};
diff --git a/desktop/src/mutations/use-node-collaborator-create-mutation.tsx b/desktop/src/mutations/use-node-collaborator-create-mutation.tsx
deleted file mode 100644
index 6d93c44f..00000000
--- a/desktop/src/mutations/use-node-collaborator-create-mutation.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { CreateNodeCollaborator } from '@/electron/schemas/workspace';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-
-interface ReactionCreateInput {
- nodeId: string;
- collaboratorIds: string[];
- role: string;
-}
-
-export const useNodeCollaboratorCreateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: ReactionCreateInput) => {
- if (input.collaboratorIds.length === 0) {
- return;
- }
-
- const nodeCollaboratorsToCreate: CreateNodeCollaborator[] =
- input.collaboratorIds.map((collaboratorId) => {
- return {
- node_id: input.nodeId,
- collaborator_id: collaboratorId,
- role: input.role,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- };
- });
-
- const query = workspace.schema
- .insertInto('node_collaborators')
- .values(nodeCollaboratorsToCreate)
- .onConflict((b) => b.doNothing())
- .compile();
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-node-collaborator-delete-mutation.tsx b/desktop/src/mutations/use-node-collaborator-delete-mutation.tsx
deleted file mode 100644
index 961ccbd0..00000000
--- a/desktop/src/mutations/use-node-collaborator-delete-mutation.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
-
-interface NodeCollaboratorDeleteInput {
- nodeId: string;
- collaboratorId: string;
-}
-
-export const useNodeCollaboratorDeleteMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: NodeCollaboratorDeleteInput) => {
- const mutation = workspace.schema
- .deleteFrom('node_collaborators')
- .where((eb) =>
- eb.and([
- eb('node_id', '=', input.nodeId),
- eb('collaborator_id', '=', input.collaboratorId),
- ]),
- )
- .compile();
-
- await workspace.mutate(mutation);
- },
- });
-};
diff --git a/desktop/src/mutations/use-node-collaborator-update-mutation.tsx b/desktop/src/mutations/use-node-collaborator-update-mutation.tsx
deleted file mode 100644
index 9592f1dd..00000000
--- a/desktop/src/mutations/use-node-collaborator-update-mutation.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-
-interface NodeCollaboratorUpdateInput {
- nodeId: string;
- collaboratorId: string;
- role: string;
-}
-
-export const useNodeCollaboratorUpdateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: NodeCollaboratorUpdateInput) => {
- const mutation = workspace.schema
- .updateTable('node_collaborators')
- .set({
- role: input.role,
- updated_at: new Date().toISOString(),
- updated_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .where((eb) =>
- eb.and([
- eb('node_id', '=', input.nodeId),
- eb('collaborator_id', '=', input.collaboratorId),
- ]),
- )
- .compile();
-
- await workspace.mutate(mutation);
- },
- });
-};
diff --git a/desktop/src/mutations/use-node-delete-mutation.tsx b/desktop/src/mutations/use-node-delete-mutation.tsx
deleted file mode 100644
index cd856fe8..00000000
--- a/desktop/src/mutations/use-node-delete-mutation.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-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-page-create-mutation.tsx b/desktop/src/mutations/use-page-create-mutation.tsx
deleted file mode 100644
index abadcd3b..00000000
--- a/desktop/src/mutations/use-page-create-mutation.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.Page,
- parentId: input.spaceId,
- index: index,
- name: input.name,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-reaction-create-mutation.tsx b/desktop/src/mutations/use-reaction-create-mutation.tsx
deleted file mode 100644
index a43e47d3..00000000
--- a/desktop/src/mutations/use-reaction-create-mutation.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
-
-interface ReactionCreateInput {
- nodeId: string;
- reaction: string;
-}
-
-export const useReactionCreateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: ReactionCreateInput) => {
- const query = workspace.schema
- .insertInto('node_reactions')
- .values({
- node_id: input.nodeId,
- reactor_id: workspace.userId,
- reaction: input.reaction,
- created_at: new Date().toISOString(),
- })
- .onConflict((b) => b.doNothing())
- .compile();
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-reaction-delete-mutation.tsx b/desktop/src/mutations/use-reaction-delete-mutation.tsx
deleted file mode 100644
index 95e1bef0..00000000
--- a/desktop/src/mutations/use-reaction-delete-mutation.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { useMutation } from '@tanstack/react-query';
-
-interface ReactionDeleteInput {
- nodeId: string;
- reaction: string;
-}
-
-export const useReactionDeleteMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: ReactionDeleteInput) => {
- const query = workspace.schema
- .deleteFrom('node_reactions')
- .where('node_id', '=', input.nodeId)
- .where('reactor_id', '=', workspace.userId)
- .where('reaction', '=', input.reaction)
- .compile();
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-record-create-mutation.tsx b/desktop/src/mutations/use-record-create-mutation.tsx
deleted file mode 100644
index 4176bf49..00000000
--- a/desktop/src/mutations/use-record-create-mutation.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 id = NeuronId.generate(NeuronId.Type.Record);
- const index = generateNodeIndex(maxIndex, null);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.Record,
- parentId: input.databaseId,
- index: index,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-select-option-create-mutation.tsx b/desktop/src/mutations/use-select-option-create-mutation.tsx
deleted file mode 100644
index 448413b8..00000000
--- a/desktop/src/mutations/use-select-option-create-mutation.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 id = NeuronId.generate(NeuronId.Type.SelectOption);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.SelectOption,
- parentId: input.fieldId,
- index: generateNodeIndex(maxIndex, null),
- name: input.name,
- color: input.color,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-server-create-mutation.tsx b/desktop/src/mutations/use-server-create-mutation.tsx
deleted file mode 100644
index 5d175f6d..00000000
--- a/desktop/src/mutations/use-server-create-mutation.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import axios from 'axios';
-import { useAppDatabase } from '@/contexts/app-database';
-import { ServerConfig } from '@/types/servers';
-import { useMutation } from '@tanstack/react-query';
-
-interface ServerCreateInput {
- domain: string;
-}
-
-export const useServerCreateMutation = () => {
- const appDatabase = useAppDatabase();
-
- return useMutation({
- mutationFn: async (input: ServerCreateInput) => {
- const { data } = await axios.get<ServerConfig>(
- `http://${input.domain}/v1/config`,
- );
-
- const query = appDatabase.database
- .insertInto('servers')
- .values({
- domain: input.domain,
- name: data.name,
- avatar: data.avatar,
- attributes: JSON.stringify(data.attributes),
- version: data.version,
- created_at: new Date().toISOString(),
- })
- .compile();
-
- await appDatabase.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-space-create-mutation.tsx b/desktop/src/mutations/use-space-create-mutation.tsx
deleted file mode 100644
index e5595ee0..00000000
--- a/desktop/src/mutations/use-space-create-mutation.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeRole, NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, 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 = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- [
- {
- id: spaceId,
- attributes: {
- type: NodeTypes.Space,
- name: values.name,
- description: values.description,
- },
- },
- {
- id: pageId,
- attributes: {
- type: NodeTypes.Page,
- parentId: spaceId,
- index: pageIndex,
- name: 'Home',
- },
- },
- {
- id: channelId,
- attributes: {
- type: NodeTypes.Channel,
- parentId: spaceId,
- index: channelIndex,
- name: 'Discussions',
- },
- },
- ],
- );
-
- const insertCollaboratorQuery = workspace.schema
- .insertInto('node_collaborators')
- .values({
- node_id: spaceId,
- collaborator_id: workspace.userId,
- role: NodeRole.Owner,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- await workspace.mutate([insertNodesQuery, insertCollaboratorQuery]);
- return spaceId;
- },
- });
-};
diff --git a/desktop/src/mutations/use-table-view-create-mutation.tsx b/desktop/src/mutations/use-table-view-create-mutation.tsx
deleted file mode 100644
index 49a6e4d9..00000000
--- a/desktop/src/mutations/use-table-view-create-mutation.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { useMutation } from '@tanstack/react-query';
-
-interface TableViewCreateInput {
- databaseId: string;
- name: string;
-}
-
-export const useTableViewCreateMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: TableViewCreateInput) => {
- const siblingsQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and([
- eb('parent_id', '=', input.databaseId),
- eb('type', 'in', ViewNodeTypes),
- ]),
- )
- .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.TableView);
- const query = buildNodeInsertMutation(
- workspace.schema,
- workspace.userId,
- {
- id: id,
- attributes: {
- type: NodeTypes.TableView,
- parentId: input.databaseId,
- index: generateNodeIndex(maxIndex, null),
- name: input.name,
- },
- },
- );
-
- await workspace.mutate(query);
- return id;
- },
- });
-};
diff --git a/desktop/src/mutations/use-workspace-account-role-update-mutation.tsx b/desktop/src/mutations/use-workspace-account-role-update-mutation.tsx
deleted file mode 100644
index ec908bc4..00000000
--- a/desktop/src/mutations/use-workspace-account-role-update-mutation.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { useAxios } from '@/contexts/axios';
-import { useWorkspace } from '@/contexts/workspace';
-import { WorkspaceAccountRoleUpdateOutput } from '@/types/workspaces';
-import { useMutation } from '@tanstack/react-query';
-
-interface UpdateWorkspaceAccountRoleInput {
- accountId: string;
- role: string;
-}
-
-export const useWorkspaceAccountRoleUpdateMutation = () => {
- const workspace = useWorkspace();
- const axios = useAxios();
-
- return useMutation({
- mutationFn: async (input: UpdateWorkspaceAccountRoleInput) => {
- const { data } = await axios.put<WorkspaceAccountRoleUpdateOutput>(
- `v1/workspaces/${workspace.id}/accounts/${input.accountId}`,
- {
- role: input.role,
- },
- );
-
- const query = workspace.schema
- .updateTable('nodes')
- .set({
- attributes: JSON.stringify(data.user.attributes),
- updated_at: data.user.updatedAt,
- updated_by: data.user.updatedBy,
- version_id: data.user.versionId,
- server_updated_at: data.user.updatedAt,
- server_version_id: data.user.versionId,
- })
- .where('id', '=', data.user.id)
- .compile();
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-workspace-accounts-invite-mutation.tsx b/desktop/src/mutations/use-workspace-accounts-invite-mutation.tsx
deleted file mode 100644
index d98eb260..00000000
--- a/desktop/src/mutations/use-workspace-accounts-invite-mutation.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { useAxios } from '@/contexts/axios';
-import { useWorkspace } from '@/contexts/workspace';
-import { CreateNode } from '@/electron/schemas/workspace';
-import { WorkspaceAccountsInviteOutput } from '@/types/workspaces';
-import { useMutation } from '@tanstack/react-query';
-
-interface InviteWorkspaceAccountsInput {
- emails: string[];
-}
-
-export const useWorkspaceAccountsInviteMutation = () => {
- const workspace = useWorkspace();
- const axios = useAxios();
-
- return useMutation({
- mutationFn: async (input: InviteWorkspaceAccountsInput) => {
- const { data } = await axios.post<WorkspaceAccountsInviteOutput>(
- `v1/workspaces/${workspace.id}/accounts`,
- input,
- );
-
- const usersToCreate: CreateNode[] = data.users.map((user) => {
- return {
- id: user.id,
- attributes: JSON.stringify(user.attributes),
- state: user.state,
- created_at: user.createdAt,
- created_by: user.createdBy,
- updated_at: user.updatedAt,
- updated_by: user.updatedBy,
- server_created_at: user.serverCreatedAt,
- server_updated_at: user.serverUpdatedAt,
- server_version_id: user.versionId,
- version_id: user.versionId,
- };
- });
-
- const query = workspace.schema
- .insertInto('nodes')
- .values(usersToCreate)
- .onConflict((cb) => cb.doNothing())
- .compile();
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-workspace-create-mutation.tsx b/desktop/src/mutations/use-workspace-create-mutation.tsx
deleted file mode 100644
index cca63cdb..00000000
--- a/desktop/src/mutations/use-workspace-create-mutation.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useAppDatabase } from '@/contexts/app-database';
-import { useAxios } from '@/contexts/axios';
-import { Workspace } from '@/types/workspaces';
-import { useMutation } from '@tanstack/react-query';
-
-interface CreateWorkspaceInput {
- name: string;
- description: string;
-}
-
-export const useWorkspaceCreateMutation = () => {
- const appDatabase = useAppDatabase();
- const axios = useAxios();
-
- return useMutation({
- mutationFn: async (input: CreateWorkspaceInput) => {
- const { data } = await axios.post<Workspace>('v1/workspaces', input);
- const insertWorkspaceQuery = appDatabase.database
- .insertInto('workspaces')
- .values({
- id: data.id,
- account_id: data.accountId,
- name: data.name,
- description: data.description,
- avatar: data.avatar,
- role: data.role,
- synced: 0,
- user_id: data.userId,
- version_id: data.versionId,
- })
- .compile();
-
- await appDatabase.mutate(insertWorkspaceQuery);
- },
- });
-};
diff --git a/desktop/src/mutations/use-workspace-update-mutation.tsx b/desktop/src/mutations/use-workspace-update-mutation.tsx
deleted file mode 100644
index af120032..00000000
--- a/desktop/src/mutations/use-workspace-update-mutation.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useAppDatabase } from '@/contexts/app-database';
-import { useAxios } from '@/contexts/axios';
-import { Workspace } from '@/types/workspaces';
-import { useMutation } from '@tanstack/react-query';
-
-interface UpdateWorkspaceInput {
- id: string;
- name: string;
- description: string;
-}
-
-export const useWorkspaceUpdateMutation = () => {
- const appDatabase = useAppDatabase();
- const axios = useAxios();
-
- return useMutation({
- mutationFn: async (input: UpdateWorkspaceInput) => {
- const { data } = await axios.put<Workspace>(`v1/workspaces/${input.id}`, {
- name: input.name,
- description: input.description,
- });
- const updateWorkspaceQuery = appDatabase.database
- .updateTable('workspaces')
- .set({
- name: data.name,
- description: data.description,
- avatar: data.avatar,
- role: data.role,
- version_id: data.versionId,
- })
- .compile();
-
- await appDatabase.mutate(updateWorkspaceQuery);
- },
- });
-};
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index d9de0cb1..b05dc4c3 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -1,74 +1,28 @@
import { contextBridge, ipcRenderer } from 'electron';
import { eventBus, Event } from '@/lib/event-bus';
-import { CompiledQuery, QueryResult } from 'kysely';
+import { MutationInput, MutationMap } from '@/types/mutations';
+import { QueryInput, QueryMap } from '@/types/queries';
contextBridge.exposeInMainWorld('neuron', {
init: () => ipcRenderer.invoke('init'),
logout: (accountId: string) => ipcRenderer.invoke('logout', accountId),
- executeAppQuery: <R>(query: CompiledQuery<R>): Promise<QueryResult<R>> =>
- ipcRenderer.invoke('execute-app-query', query),
- executeAppQueryAndSubscribe: <R>(
- queryId: string,
- query: CompiledQuery<R>,
- ): Promise<QueryResult<R>> =>
- ipcRenderer.invoke('execute-app-query-and-subscribe', queryId, query),
- executeAppMutation: (
- mutation: CompiledQuery | CompiledQuery[],
- ): Promise<void> => ipcRenderer.invoke('execute-app-mutation', mutation),
-
- unsubscribeAppQuery: (queryId: string): Promise<void> =>
- ipcRenderer.invoke('unsubscribe-app-query', queryId),
-
- executeWorkspaceMutation: (
- accountId: string,
- workspaceId: string,
- mutation: CompiledQuery | CompiledQuery[],
- ): Promise<void> =>
- ipcRenderer.invoke(
- 'execute-workspace-mutation',
- accountId,
- workspaceId,
- mutation,
- ),
-
- executeWorkspaceQuery: <R>(
- accountId: string,
- workspaceId: string,
- query: CompiledQuery<R>,
- ): Promise<QueryResult<R>> =>
- ipcRenderer.invoke(
- 'execute-workspace-query',
- accountId,
- workspaceId,
- query,
- ),
-
- executeWorkspaceQueryAndSubscribe: <R>(
- accountId: string,
- workspaceId: string,
- queryId: string,
- query: CompiledQuery<R>,
- ): Promise<QueryResult<R>> =>
- ipcRenderer.invoke(
- 'execute-workspace-query-and-subscribe',
- accountId,
- workspaceId,
- queryId,
- query,
- ),
-
- unsubscribeWorkspaceQuery: (
- accountId: string,
- workspaceId: string,
- queryId: string,
- ) =>
- ipcRenderer.invoke(
- 'unsubscribe-workspace-query',
- accountId,
- workspaceId,
- queryId,
- ),
+ executeMutation: <T extends MutationInput>(
+ input: T,
+ ): Promise<MutationMap[T['type']]['output']> => {
+ return ipcRenderer.invoke('execute-mutation', input);
+ },
+
+ executeQuery: <T extends QueryInput>(
+ id: string,
+ input: T,
+ ): Promise<QueryMap[T['type']]['output']> => {
+ return ipcRenderer.invoke('execute-query', id, input);
+ },
+
+ unsubscribeQuery: (id: string): Promise<void> => {
+ return ipcRenderer.invoke('unsubscribe-query', id);
+ },
});
contextBridge.exposeInMainWorld('eventBus', {
diff --git a/desktop/src/queries/use-accounts-query.tsx b/desktop/src/queries/use-accounts-query.tsx
deleted file mode 100644
index d9ed3d68..00000000
--- a/desktop/src/queries/use-accounts-query.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useAppDatabase } from '@/contexts/app-database';
-import { SelectAccount, SelectServer } from '@/electron/schemas/app';
-import { Account } from '@/types/accounts';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult } from 'kysely';
-
-export const useAccountsQuery = () => {
- const appDatabase = useAppDatabase();
- return useQuery<QueryResult<SelectAccount>, Error, Account[], string[]>({
- queryKey: ['accounts'],
- queryFn: async ({ queryKey }) => {
- const query = appDatabase.database
- .selectFrom('accounts')
- .selectAll()
- .where('status', '=', 'active')
- .compile();
-
- return await window.neuron.executeAppQueryAndSubscribe({
- key: queryKey,
- query: query,
- });
- },
- select: (data: QueryResult<SelectAccount>): Account[] => {
- const rows = data?.rows ?? [];
- return rows.map(mapAccount);
- },
- });
-};
-
-const mapAccount = (row: SelectAccount): Account => {
- return {
- id: row.id,
- name: row.name,
- avatar: row.avatar,
- token: row.token,
- email: row.email,
- deviceId: row.device_id,
- status: row.status,
- server: row.server,
- };
-};
diff --git a/desktop/src/queries/use-breadcrumb-query.tsx b/desktop/src/queries/use-breadcrumb-query.tsx
deleted file mode 100644
index da636a24..00000000
--- a/desktop/src/queries/use-breadcrumb-query.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { mapNode } 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<SelectNode>, Error, BreadcrumbNode[], string[]>({
- queryKey: ['breadcrumb', nodeId],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- 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.*
- FROM breadcrumb_nodes n;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): BreadcrumbNode[] => {
- const rows = data?.rows ?? [];
- return buildBreadcrumbNodes(nodeId, rows);
- },
- });
-};
-
-const buildBreadcrumbNodes = (
- nodeId: string,
- rows: SelectNode[],
-): 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: SelectNode): BreadcrumbNode => {
- const node = mapNode(row);
-
- const name = node.attributes.name;
- const avatar = node.attributes.avatar;
-
- return {
- id: node.id,
- type: node.type,
- name,
- avatar,
- };
-};
diff --git a/desktop/src/queries/use-database-query.tsx b/desktop/src/queries/use-database-query.tsx
deleted file mode 100644
index 52869751..00000000
--- a/desktop/src/queries/use-database-query.tsx
+++ /dev/null
@@ -1,225 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import {
- DatabaseNode,
- FieldDataType,
- FieldNode,
- SelectOptionNode,
-} from '@/types/databases';
-import { LocalNode } 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<SelectNode>,
- Error,
- DatabaseNode | null,
- string[]
- >({
- queryKey: ['database', databaseId],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- WITH database_node AS (
- SELECT *
- FROM nodes
- WHERE id = ${databaseId}
- ),
- field_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${databaseId} AND type = ${NodeTypes.Field}
- ),
- select_option_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IN
- (
- SELECT id
- FROM field_nodes
- )
- AND type = ${NodeTypes.SelectOption}
- )
- SELECT * FROM database_node
- UNION ALL
- SELECT * FROM field_nodes
- UNION ALL
- SELECT * FROM select_option_nodes
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): DatabaseNode | null => {
- const rows = data?.rows ?? [];
- return buildDatabaseNode(rows);
- },
- });
-};
-
-const buildDatabaseNode = (rows: SelectNode[]): DatabaseNode | null => {
- const nodes = rows.map((row) => mapNode(row));
-
- const databaseLocalNode = nodes.find(
- (node) => node.type === NodeTypes.Database,
- );
- if (!databaseLocalNode) {
- return null;
- }
-
- const name = databaseLocalNode.attributes.name;
- const fieldsNodes = nodes.filter((node) => node.type === NodeTypes.Field);
- const groupedSelectOptions = nodes
- .filter((node) => node.type === NodeTypes.SelectOption)
- .reduce(
- (acc, node) => {
- if (!acc[node.parentId]) {
- acc[node.parentId] = [];
- }
- acc[node.parentId].push(node);
- return acc;
- },
- {} as Record<string, LocalNode[]>,
- );
-
- const fields: FieldNode[] = [];
- for (const fieldNode of fieldsNodes) {
- const selectOptions = groupedSelectOptions[fieldNode.id] ?? [];
- const field = buildFieldNode(fieldNode, selectOptions);
- if (field) {
- fields.push(field);
- }
- }
-
- return {
- id: databaseLocalNode.id,
- name: name,
- fields,
- };
-};
-
-const buildFieldNode = (
- node: LocalNode,
- selectOptions: LocalNode[],
-): FieldNode | null => {
- const name = node.attributes.name;
- const dataType = node.attributes.dataType as FieldDataType;
-
- if (!dataType) {
- return null;
- }
-
- switch (dataType) {
- case 'boolean':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'collaborator':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'created_at':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'created_by':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'date':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'email':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'file':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- };
- case 'multi_select':
- return {
- id: node.id,
- name,
- dataType,
- index: node.index,
- options: selectOptions.map(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;
- }
-};
-
-const buildSelectOption = (node: LocalNode): SelectOptionNode => {
- const name = node.attributes.name;
- const color = node.attributes.color;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- color: color ?? 'gray',
- };
-};
diff --git a/desktop/src/queries/use-database-views-query.tsx b/desktop/src/queries/use-database-views-query.tsx
deleted file mode 100644
index 656093f4..00000000
--- a/desktop/src/queries/use-database-views-query.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import {
- BoardViewNode,
- CalendarViewNode,
- TableViewNode,
- ViewNode,
-} from '@/types/databases';
-import { LocalNode } from '@/types/nodes';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-export const useDatabaseViewsQuery = (databaseId: string) => {
- const workspace = useWorkspace();
- return useQuery<QueryResult<SelectNode>, Error, ViewNode[], string[]>({
- queryKey: ['database-views', databaseId],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- SELECT *
- FROM nodes
- WHERE parent_id = ${databaseId} AND type IN (${sql.join(ViewNodeTypes)})
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): ViewNode[] => {
- const rows = data?.rows ?? [];
- return buildViewNodes(rows);
- },
- });
-};
-
-const buildViewNodes = (rows: SelectNode[]): ViewNode[] => {
- const nodes = rows.map((row) => mapNode(row));
- const views: ViewNode[] = [];
- for (const node of nodes) {
- const view = buildViewNode(node);
- if (view) {
- views.push(view);
- }
- }
-
- return views;
-};
-
-const buildViewNode = (node: LocalNode): ViewNode | null => {
- if (node.type === NodeTypes.TableView) {
- return buildTableViewNode(node);
- } else if (node.type === NodeTypes.BoardView) {
- return buildBoardViewNode(node);
- } else if (node.type === NodeTypes.CalendarView) {
- return buildCalendarViewNode(node);
- }
-
- return null;
-};
-
-const buildTableViewNode = (node: LocalNode): TableViewNode => {
- const name = node.attributes.name;
- const hiddenFields = node.attributes.hiddenFields;
- const fieldIndexes = node.attributes.fieldIndexes;
- const fieldWidths = node.attributes.fieldWidths;
- const nameWidth = node.attributes.nameWidth;
-
- const viewFilters = node.attributes.filters;
- const viewSorts = node.attributes.sorts;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- type: 'table_view',
- hiddenFields,
- fieldIndexes,
- fieldWidths,
- nameWidth: nameWidth,
- versionId: node.versionId,
- filters: viewFilters ?? [],
- sorts: viewSorts ?? [],
- };
-};
-
-const buildBoardViewNode = (node: LocalNode): BoardViewNode => {
- const name = node.attributes.name;
- const groupBy = node.attributes.groupBy;
- const viewFilters = node.attributes.filters;
- const viewSorts = node.attributes.sorts;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- type: 'board_view',
- filters: viewFilters ?? [],
- sorts: viewSorts ?? [],
- groupBy,
- };
-};
-
-const buildCalendarViewNode = (node: LocalNode): CalendarViewNode => {
- const name = node.attributes.name;
- const groupBy = node.attributes.groupBy;
-
- const viewFilters = node.attributes.filters;
- const viewSorts = node.attributes.sorts;
-
- return {
- id: node.id,
- name: name ?? 'Unnamed',
- type: 'calendar_view',
- filters: viewFilters ?? [],
- sorts: viewSorts ?? [],
- groupBy,
- };
-};
diff --git a/desktop/src/queries/use-document-query.tsx b/desktop/src/queries/use-document-query.tsx
deleted file mode 100644
index 98452aba..00000000
--- a/desktop/src/queries/use-document-query.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-import { LocalNode } from '@/types/nodes';
-import { mapNode } from '@/lib/nodes';
-
-export const useDocumentQuery = (id: string) => {
- const workspace = useWorkspace();
-
- return useQuery<
- QueryResult<SelectNode>,
- Error,
- Map<string, LocalNode>,
- string[]
- >({
- queryKey: ['document', id],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- 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 *
- FROM document_nodes
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- query,
- key: queryKey,
- });
- },
- select: (data) => buildMap(data?.rows ?? []),
- });
-};
-
-const buildMap = (rows: SelectNode[]): Map<string, LocalNode> => {
- const map = new Map<string, LocalNode>();
- rows.forEach((row) => {
- map.set(row.id, mapNode(row));
- });
- return map;
-};
diff --git a/desktop/src/queries/use-messages-query.tsx b/desktop/src/queries/use-messages-query.tsx
deleted file mode 100644
index 3c1b879a..00000000
--- a/desktop/src/queries/use-messages-query.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { buildNodeWithChildren, mapNode } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
-import { MessageNode, MessageReactionCount } from '@/types/messages';
-import { UserNode } from '@/types/users';
-import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-const MESSAGES_PER_PAGE = 50;
-
-type MessageRow = SelectNode & {
- reaction_counts: string | null;
- user_reactions: string | null;
-};
-
-export const useMessagesQuery = (conversationId: string) => {
- const workspace = useWorkspace();
-
- return useInfiniteQuery<
- QueryResult<MessageRow>,
- 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<MessageRow>`
- 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
- ),
- message_reaction_counts AS (
- SELECT
- mrc.node_id,
- json_group_array(
- json_object(
- 'reaction', mrc.'reaction',
- 'count', mrc.'count'
- )
- ) AS reaction_counts
- FROM (
- SELECT node_id, reaction, COUNT(*) as count
- FROM node_reactions
- WHERE node_id IN (SELECT id FROM message_nodes)
- GROUP BY node_id, reaction
- ) mrc
- GROUP BY mrc.node_id
- ),
- user_reactions AS (
- SELECT
- ur.node_id,
- json_group_array(ur.reaction) AS user_reactions
- FROM node_reactions ur
- WHERE ur.node_id IN (SELECT id FROM message_nodes) AND ur.reactor_id = ${workspace.userId}
- GROUP BY ur.node_id
- )
- SELECT
- n.*,
- COALESCE(mrc.reaction_counts, json('[]')) AS reaction_counts,
- COALESCE(ur.user_reactions, json('[]')) AS user_reactions
- FROM all_nodes n
- LEFT JOIN message_reaction_counts mrc ON n.id = mrc.node_id
- LEFT JOIN user_reactions ur ON n.id = ur.node_id;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- page: pageParam,
- query,
- });
- },
- select: (data: InfiniteData<QueryResult<MessageRow>>): MessageNode[] => {
- const pages = data?.pages ?? [];
- const rows = pages.map((page) => page.rows).flat();
- return buildMessages(rows);
- },
- });
-};
-
-const buildMessages = (rows: MessageRow[]): MessageNode[] => {
- const messageRows = rows.filter((row) => row.type === NodeTypes.Message);
- const authorRows = rows.filter((row) => row.type === NodeTypes.User);
- const contentNodes = rows
- .filter(
- (row) => row.type !== NodeTypes.User && row.type !== NodeTypes.Message,
- )
- .map(mapNode);
-
- const messages: MessageNode[] = [];
- const authorMap = new Map<string, UserNode>();
- for (const authorRow of authorRows) {
- const authorNode = mapNode(authorRow);
- const name = authorNode.attributes.name;
- const email = authorNode.attributes.email;
- const avatar = authorNode.attributes.avatar;
-
- authorMap.set(authorRow.id, {
- id: authorRow.id,
- name: name ?? 'Unknown User',
- email,
- avatar,
- });
- }
-
- for (const messageRow of messageRows) {
- const messageNode = mapNode(messageRow);
- const author = authorMap.get(messageNode.createdBy);
- const children = contentNodes
- .filter((n) => n.parentId === messageNode.id)
- .map((n) => buildNodeWithChildren(n, contentNodes));
-
- const reactionCounts: MessageReactionCount[] = JSON.parse(
- messageRow.reaction_counts,
- );
- const userReactions: string[] = JSON.parse(messageRow.user_reactions);
-
- const message: MessageNode = {
- id: messageNode.id,
- createdAt: messageNode.createdAt,
- author: author ?? {
- id: messageNode.createdBy,
- name: 'Unknown User',
- email: '[email protected]',
- avatar: null,
- },
- content: children,
- reactionCounts,
- userReactions,
- };
-
- messages.push(message);
- }
-
- return messages.sort((a, b) => compareString(a.id, b.id));
-};
diff --git a/desktop/src/queries/use-node-collaborator-search-query.tsx b/desktop/src/queries/use-node-collaborator-search-query.tsx
deleted file mode 100644
index 04040fa0..00000000
--- a/desktop/src/queries/use-node-collaborator-search-query.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { NodeCollaboratorNode } from '@/types/nodes';
-import { useQuery } from '@tanstack/react-query';
-import { sha256 } from 'js-sha256';
-import { QueryResult, sql } from 'kysely';
-
-export const useNodeCollaboratorSearchQuery = (
- searchQuery: string,
- excluded: string[],
-) => {
- const workspace = useWorkspace();
- const hash = sha256(`${searchQuery}-${excluded.sort().join(',')}`);
- return useQuery<
- QueryResult<SelectNode>,
- Error,
- NodeCollaboratorNode[],
- string[]
- >({
- queryKey: ['collaborator-search', hash],
- enabled: searchQuery.length > 0,
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- SELECT n.*
- FROM nodes n
- JOIN node_names nn ON n.id = nn.id
- WHERE n.type = ${NodeTypes.User}
- AND nn.name MATCH ${searchQuery + '*'}
- ${
- excluded.length > 0
- ? sql`AND n.id NOT IN (${sql.join(
- excluded.map((id) => sql`${id}`),
- sql`, `,
- )})`
- : sql``
- }
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): NodeCollaboratorNode[] => {
- const rows = data?.rows ?? [];
- return rows.map((row) => {
- const attributes = JSON.parse(row.attributes);
- return {
- id: row.id,
- name: attributes.name,
- email: attributes.email,
- avatar: attributes.avatar,
- role: 'collaborator',
- };
- });
- },
- });
-};
diff --git a/desktop/src/queries/use-node-collaborators-query.tsx b/desktop/src/queries/use-node-collaborators-query.tsx
deleted file mode 100644
index 427ebbba..00000000
--- a/desktop/src/queries/use-node-collaborators-query.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NodeTypes } from '@/lib/constants';
-import {
- InheritNodeCollaboratorsGroup,
- NodeCollaboratorNode,
- NodeCollaboratorsWrapper,
-} from '@/types/nodes';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-type NodeCollaboratorRow = {
- node_id: string;
- node_level: number;
- node_attributes: string;
- node_parent_id: string | null;
- collaborator_id: string;
- collaborator_attributes: string;
- role: string;
-};
-
-export const useNodeCollaboratorsQuery = (nodeId: string) => {
- const workspace = useWorkspace();
- return useQuery<
- QueryResult<NodeCollaboratorRow>,
- Error,
- NodeCollaboratorsWrapper,
- string[]
- >({
- queryKey: ['collaborators', nodeId],
- queryFn: async ({ queryKey }) => {
- const query = sql<NodeCollaboratorRow>`
- WITH RECURSIVE ancestors(id, parent_id, level) AS (
- SELECT id, parent_id, 0 AS level
- FROM nodes
- WHERE id = ${nodeId}
- UNION ALL
- SELECT n.id, n.parent_id, a.level + 1
- FROM nodes n
- INNER JOIN ancestors a ON n.id = a.parent_id
- )
- SELECT
- nc.node_id,
- a.level AS node_level,
- nn.attributes AS node_attributes,
- nn.parent_id AS node_parent_id,
- nc.collaborator_id,
- cn.attributes AS collaborator_attributes,
- nc.role
- FROM node_collaborators nc
- JOIN ancestors a ON nc.node_id = a.id
- JOIN nodes nn ON nc.node_id = nn.id
- JOIN nodes cn ON nc.collaborator_id = cn.id
- WHERE cn.type = ${NodeTypes.User};
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (
- data: QueryResult<NodeCollaboratorRow>,
- ): NodeCollaboratorsWrapper => {
- const rows = data?.rows ?? [];
- return buildNodeCollaborators(nodeId, rows);
- },
- });
-};
-
-const buildNodeCollaborators = (
- nodeId: string,
- rows: NodeCollaboratorRow[],
-): NodeCollaboratorsWrapper => {
- const direct: NodeCollaboratorNode[] = [];
- const inheritCollaboratorMap: Map<string, NodeCollaboratorRow> = new Map();
-
- for (const row of rows) {
- if (row.node_id === nodeId) {
- const collaboratorAttributes = JSON.parse(row.collaborator_attributes);
-
- const collaborator: NodeCollaboratorNode = {
- id: row.collaborator_id,
- name: collaboratorAttributes.name,
- email: collaboratorAttributes.email,
- avatar: collaboratorAttributes.avatar || null,
- role: row.role,
- };
-
- direct.push(collaborator);
- } else {
- if (!inheritCollaboratorMap.has(row.collaborator_id)) {
- inheritCollaboratorMap.set(row.collaborator_id, row);
- } else {
- const existingRow = inheritCollaboratorMap.get(row.collaborator_id);
- if (!existingRow || existingRow.node_level < row.node_level) {
- inheritCollaboratorMap.set(row.collaborator_id, row);
- }
- }
- }
- }
-
- const inheritLeveledMap: Map<number, InheritNodeCollaboratorsGroup> =
- new Map();
-
- for (const row of inheritCollaboratorMap.values()) {
- if (!inheritLeveledMap.has(row.node_level)) {
- const nodeAttributes = JSON.parse(row.node_attributes);
- inheritLeveledMap.set(row.node_level, {
- id: row.node_id,
- name: nodeAttributes.name,
- avatar: nodeAttributes.avatar,
- collaborators: [],
- });
- }
-
- const group = inheritLeveledMap.get(row.node_level);
- const collaboratorAttributes = JSON.parse(row.collaborator_attributes);
- group.collaborators.push({
- id: row.collaborator_id,
- name: collaboratorAttributes.name,
- avatar: collaboratorAttributes.avatar,
- email: collaboratorAttributes.email,
- role: row.role,
- });
- }
-
- return {
- direct,
- inherit: Array.from(inheritLeveledMap.values()),
- };
-};
diff --git a/desktop/src/queries/use-node-query.tsx b/desktop/src/queries/use-node-query.tsx
deleted file mode 100644
index 86c31a70..00000000
--- a/desktop/src/queries/use-node-query.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { useQuery } from '@tanstack/react-query';
-
-export const useNodeQuery = (nodeId: string) => {
- const workspace = useWorkspace();
-
- return useQuery({
- queryKey: ['node', nodeId],
- queryFn: async ({ queryKey }) => {
- const query = workspace.schema
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', nodeId)
- .compile();
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- });
-};
diff --git a/desktop/src/queries/use-record-query.tsx b/desktop/src/queries/use-record-query.tsx
deleted file mode 100644
index 63e4173b..00000000
--- a/desktop/src/queries/use-record-query.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import { RecordNode } from '@/types/databases';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-export const useRecordQuery = (recordId: string) => {
- const workspace = useWorkspace();
-
- return useQuery<QueryResult<SelectNode>, Error, RecordNode | null, string[]>({
- queryKey: ['record', recordId],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- WITH record_node AS (
- SELECT *
- FROM nodes
- WHERE id = ${recordId}
- ),
- author_node AS (
- SELECT *
- FROM nodes
- WHERE id IN (SELECT DISTINCT created_by FROM record_node)
- )
- SELECT * FROM record_node
- UNION ALL
- SELECT * FROM author_node
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): RecordNode | null => {
- const rows = data?.rows ?? [];
- return buildRecord(recordId, rows);
- },
- });
-};
-
-const buildRecord = (
- recordId: string,
- rows: SelectNode[],
-): RecordNode | null => {
- const nodes = rows.map(mapNode);
- const recordNode = nodes.find((node) => node.id === recordId);
- if (!recordNode) {
- return null;
- }
-
- const recordName = recordNode.attributes.name;
- const authorNode = nodes.find((node) => node.type === NodeTypes.User);
- const author = authorNode
- ? {
- id: authorNode.id,
- name: authorNode.attributes.name,
- avatar: authorNode.attributes.avatar,
- email: authorNode.attributes.email,
- }
- : {
- id: recordNode.createdBy,
- name: 'Unknown User',
- avatar: null,
- email: '[email protected]',
- };
-
- return {
- id: recordNode.id,
- parentId: recordNode.parentId,
- name: recordName ?? null,
- index: recordNode.index,
- attributes: recordNode.attributes,
- createdAt: new Date(recordNode.createdAt),
- createdBy: author,
- versionId: recordNode.versionId,
- };
-};
diff --git a/desktop/src/queries/use-records-query.tsx b/desktop/src/queries/use-records-query.tsx
deleted file mode 100644
index 62eb56c3..00000000
--- a/desktop/src/queries/use-records-query.tsx
+++ /dev/null
@@ -1,734 +0,0 @@
-import { useDatabase } from '@/contexts/database';
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import { isStringArray } from '@/lib/utils';
-import {
- BooleanFieldNode,
- CreatedAtFieldNode,
- DateFieldNode,
- EmailFieldNode,
- FieldNode,
- MultiSelectFieldNode,
- NumberFieldNode,
- PhoneFieldNode,
- RecordNode,
- SelectFieldNode,
- TextFieldNode,
- UrlFieldNode,
- ViewFieldFilter,
- ViewFilter,
- ViewSort,
-} from '@/types/databases';
-import { UserNode } from '@/types/users';
-import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
-import { sha256 } from 'js-sha256';
-import { QueryResult, sql } from 'kysely';
-
-const RECORDS_PER_PAGE = 50;
-
-export const useRecordsQuery = (
- databaseId: string,
- filters: ViewFilter[],
- sorts: ViewSort[],
-) => {
- const workspace = useWorkspace();
- const database = useDatabase();
-
- let hash = '';
- if (filters.length > 0 || sorts.length > 0) {
- const json = JSON.stringify({ filters, sorts });
- hash = sha256(json);
- }
-
- return useInfiniteQuery<
- QueryResult<SelectNode>,
- Error,
- RecordNode[],
- string[],
- number
- >({
- queryKey: ['records', databaseId, hash],
- 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 filterQuery = buildFiltersQuery(filters, database.fields);
- const orderByQuery = `ORDER BY ${sorts.length > 0 ? buildSortOrdersQuery(sorts, database.fields) : 'n."index" ASC'}`;
-
- const query = sql<SelectNode>`
- WITH record_nodes AS (
- SELECT n.*, ROW_NUMBER() OVER (${sql.raw(orderByQuery)}) AS order_number
- FROM nodes n
- WHERE n.parent_id = ${databaseId} AND n.type = ${NodeTypes.Record} ${sql.raw(filterQuery)}
- ${sql.raw(orderByQuery)}
- LIMIT ${sql.lit(RECORDS_PER_PAGE)}
- OFFSET ${sql.lit(offset)}
- ),
- author_nodes AS (
- SELECT *, NULL AS order_number
- FROM nodes
- WHERE id IN (SELECT DISTINCT created_by FROM record_nodes)
- ),
- all_nodes as (
- SELECT * FROM record_nodes
- UNION ALL
- SELECT * FROM author_nodes
- )
- SELECT n.*
- FROM all_nodes n
- ORDER BY n.order_number ASC
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- page: pageParam,
- query,
- });
- },
- select: (data: InfiniteData<QueryResult<SelectNode>>): RecordNode[] => {
- const pages = data?.pages ?? [];
- const rows = pages.map((page) => page.rows).flat();
- return buildRecords(rows);
- },
- });
-};
-
-const buildRecords = (rows: SelectNode[]): RecordNode[] => {
- const nodes = rows.map(mapNode);
- const recordNodes = nodes.filter((node) => node.type === NodeTypes.Record);
-
- const authorNodes = nodes.filter((node) => node.type === NodeTypes.User);
- const records: RecordNode[] = [];
- const authorMap = new Map<string, UserNode>();
-
- for (const author of authorNodes) {
- const name = author.attributes.name;
- const avatar = author.attributes.avatar;
- const email = author.attributes.email;
-
- authorMap.set(author.id, {
- id: author.id,
- name: name ?? 'Unknown User',
- email,
- avatar,
- });
- }
-
- for (const node of recordNodes) {
- const name = node.attributes.name;
- const author = authorMap.get(node.createdBy);
- const record: RecordNode = {
- id: node.id,
- parentId: node.parentId,
- name: name ?? null,
- index: node.index,
- attributes: node.attributes,
- createdAt: new Date(node.createdAt),
- createdBy: author ?? {
- id: node.createdBy,
- name: 'Unknown User',
- email: '[email protected]',
- avatar: null,
- },
- versionId: node.versionId,
- };
-
- records.push(record);
- }
-
- return records;
-};
-
-const buildFiltersQuery = (
- filters: ViewFilter[],
- fields: FieldNode[],
-): string => {
- if (filters.length === 0) {
- return '';
- }
-
- const filterQueries = filters
- .map((filter) => buildFilterQuery(filter, fields))
- .filter((query) => query !== null);
-
- if (filterQueries.length === 0) {
- return '';
- }
-
- return `AND (${filterQueries.join(' AND ')})`;
-};
-
-const buildFilterQuery = (
- filter: ViewFilter,
- fields: FieldNode[],
-): string | null => {
- if (filter.type === 'group') {
- return null;
- }
-
- const field = fields.find((field) => field.id === filter.fieldId);
- if (!field) {
- return null;
- }
-
- switch (field.dataType) {
- case 'boolean':
- return buildBooleanFilterQuery(filter, field);
- case 'collaborator':
- return null;
- case 'created_at':
- return buildCreatedAtFilterQuery(filter, field);
- case 'created_by':
- return null;
- case 'date':
- return buildDateFilterQuery(filter, field);
- case 'email':
- return buildEmailFilterQuery(filter, field);
- case 'file':
- return null;
- case 'multi_select':
- return buildMultiSelectFilterQuery(filter, field);
- case 'number':
- return buildNumberFilterQuery(filter, field);
- case 'phone':
- return buildPhoneFilterQuery(filter, field);
- case 'select':
- return buildSelectFilterQuery(filter, field);
- case 'text':
- return buildTextFilterQuery(filter, field);
- case 'url':
- return buildUrlFilterQuery(filter, field);
- default:
- return null;
- }
-};
-
-const buildBooleanFilterQuery = (
- filter: ViewFieldFilter,
- field: BooleanFieldNode,
-): string | null => {
- if (filter.operator === 'is_true') {
- return `json_extract(n.attributes, '$.${field.id}') = true`;
- }
-
- if (filter.operator === 'is_false') {
- return `(json_extract(n.attributes, '$.${field.id}') = false OR json_extract(n.attributes, '$.${field.id}') IS NULL)`;
- }
-
- return null;
-};
-
-const buildNumberFilterQuery = (
- filter: ViewFieldFilter,
- field: NumberFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'number') {
- return null;
- }
-
- const value = filter.value as number;
- let operator: string | null;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'is_greater_than':
- operator = '>';
- break;
- case 'is_less_than':
- operator = '<';
- break;
- case 'is_greater_than_or_equal_to':
- operator = '>=';
- break;
- case 'is_less_than_or_equal_to':
- operator = '<=';
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `json_extract(n.attributes, '$.${field.id}') ${operator} ${value}`;
-};
-
-const buildTextFilterQuery = (
- filter: ViewFieldFilter,
- field: TextFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'string') {
- return null;
- }
-
- const value = filter.value as string;
- let operator: string | null;
- let formattedValue = value;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'contains':
- operator = 'LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'does_not_contain':
- operator = 'NOT LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'starts_with':
- operator = 'LIKE';
- formattedValue = `${value}%`;
- break;
- case 'ends_with':
- operator = 'LIKE';
- formattedValue = `%${value}`;
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
-};
-
-const buildEmailFilterQuery = (
- filter: ViewFilter,
- field: EmailFieldNode,
-): string | null => {
- if (filter.type === 'group') {
- return null;
- }
-
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'string') {
- return null;
- }
-
- const value = filter.value as string;
- let operator: string | null;
- let formattedValue = value;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'contains':
- operator = 'LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'does_not_contain':
- operator = 'NOT LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'starts_with':
- operator = 'LIKE';
- formattedValue = `${value}%`;
- break;
- case 'ends_with':
- operator = 'LIKE';
- formattedValue = `%${value}`;
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
-};
-
-const buildPhoneFilterQuery = (
- filter: ViewFieldFilter,
- field: PhoneFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'string') {
- return null;
- }
-
- const value = filter.value as string;
- let operator: string | null;
- let formattedValue = value;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'contains':
- operator = 'LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'does_not_contain':
- operator = 'NOT LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'starts_with':
- operator = 'LIKE';
- formattedValue = `${value}%`;
- break;
- case 'ends_with':
- operator = 'LIKE';
- formattedValue = `%${value}`;
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
-};
-
-const buildUrlFilterQuery = (
- filter: ViewFieldFilter,
- field: UrlFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'string') {
- return null;
- }
-
- const value = filter.value as string;
- let operator: string | null;
- let formattedValue = value;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'contains':
- operator = 'LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'does_not_contain':
- operator = 'NOT LIKE';
- formattedValue = `%${value}%`;
- break;
- case 'starts_with':
- operator = 'LIKE';
- formattedValue = `${value}%`;
- break;
- case 'ends_with':
- operator = 'LIKE';
- formattedValue = `%${value}`;
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `json_extract(n.attributes, '$.${field.id}') ${operator} '${formattedValue}'`;
-};
-
-const buildSelectFilterQuery = (
- filter: ViewFieldFilter,
- field: SelectFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (!isStringArray(filter.value)) {
- return null;
- }
-
- const values = joinIds(filter.value);
- switch (filter.operator) {
- case 'is_in':
- return `json_extract(n.attributes, '$.${field.id}') IN (${values})`;
- case 'is_not_in':
- return `json_extract(n.attributes, '$.${field.id}') NOT IN (${values})`;
- default:
- return null;
- }
-};
-
-const buildMultiSelectFilterQuery = (
- filter: ViewFieldFilter,
- field: MultiSelectFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return `json_extract(n.attributes, '$.${field.id}') IS NULL OR json_array_length(json_extract(n.attributes, '$.${field.id}')) = 0`;
- }
-
- if (filter.operator === 'is_not_empty') {
- return `json_extract(n.attributes, '$.${field.id}') IS NOT NULL AND json_array_length(json_extract(n.attributes, '$.${field.id}')) > 0`;
- }
-
- if (!isStringArray(filter.value)) {
- return null;
- }
-
- const values = joinIds(filter.value);
- switch (filter.operator) {
- case 'is_in':
- return `EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.${field.id}')) WHERE json_each.value IN (${values}))`;
- case 'is_not_in':
- return `NOT EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.${field.id}')) WHERE json_each.value IN (${values}))`;
- default:
- return null;
- }
-};
-
-const buildDateFilterQuery = (
- filter: ViewFieldFilter,
- field: DateFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(field.id);
- }
-
- if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(field.id);
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'string') {
- return null;
- }
-
- const date = new Date(filter.value);
- if (isNaN(date.getTime())) {
- return null;
- }
-
- const dateString = date.toISOString().split('T')[0];
- let operator: string | null;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'is_on_or_after':
- operator = '>=';
- break;
- case 'is_on_or_before':
- operator = '<=';
- break;
- case 'is_after':
- operator = '>';
- break;
- case 'is_before':
- operator = '<';
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `DATE(json_extract(n.attributes, '$.${field.id}')) ${operator} '${dateString}'`;
-};
-
-const buildCreatedAtFilterQuery = (
- filter: ViewFieldFilter,
- field: CreatedAtFieldNode,
-): string | null => {
- if (filter.operator === 'is_empty') {
- return `n.created_at IS NULL`;
- }
-
- if (filter.operator === 'is_not_empty') {
- return `n.created_at IS NOT NULL`;
- }
-
- if (filter.value === null) {
- return null;
- }
-
- if (typeof filter.value !== 'string') {
- return null;
- }
-
- const date = new Date(filter.value);
- if (isNaN(date.getTime())) {
- return null;
- }
-
- const dateString = date.toISOString().split('T')[0];
- let operator: string | null;
-
- switch (filter.operator) {
- case 'is_equal_to':
- operator = '=';
- break;
- case 'is_not_equal_to':
- operator = '!=';
- break;
- case 'is_on_or_after':
- operator = '>=';
- break;
- case 'is_on_or_before':
- operator = '<=';
- break;
- case 'is_after':
- operator = '>';
- break;
- case 'is_before':
- operator = '<';
- break;
- default:
- return null;
- }
-
- if (operator === null) {
- return null;
- }
-
- return `DATE(n.created_at) ${operator} '${dateString}'`;
-};
-
-const buildIsEmptyFilterQuery = (fieldId: string): string => {
- return `json_extract(n.attributes, '$.${fieldId}') IS NULL`;
-};
-
-const buildIsNotEmptyFilterQuery = (fieldId: string): string => {
- return `json_extract(n.attributes, '$.${fieldId}') IS NOT NULL`;
-};
-
-const joinIds = (ids: string[]): string => {
- return ids.map((id) => `'${id}'`).join(',');
-};
-
-const buildSortOrdersQuery = (
- sorts: ViewSort[],
- fields: FieldNode[],
-): string => {
- return sorts
- .map((sort) => buildSortOrderQuery(sort, fields))
- .filter((query) => query !== null && query.length > 0)
- .join(', ');
-};
-
-const buildSortOrderQuery = (
- sort: ViewSort,
- fields: FieldNode[],
-): string | null => {
- const field = fields.find((field) => field.id === sort.fieldId);
- if (!field) {
- return null;
- }
-
- if (field.dataType === 'created_at') {
- return `n.created_at ${sort.direction}`;
- }
-
- if (field.dataType === 'created_by') {
- return `n.created_by_id ${sort.direction}`;
- }
-
- return `json_extract(n.attributes, '$.${field.id}') ${sort.direction}`;
-};
diff --git a/desktop/src/queries/use-servers-query.tsx b/desktop/src/queries/use-servers-query.tsx
deleted file mode 100644
index 58294b95..00000000
--- a/desktop/src/queries/use-servers-query.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useAppDatabase } from '@/contexts/app-database';
-import { SelectServer } from '@/electron/schemas/app';
-import { Server } from '@/types/servers';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult } from 'kysely';
-
-export const useServersQuery = () => {
- const appDatabase = useAppDatabase();
- return useQuery<QueryResult<SelectServer>, Error, Server[], string[]>({
- queryKey: ['servers'],
- queryFn: async ({ queryKey }) => {
- const query = appDatabase.database
- .selectFrom('servers')
- .selectAll()
- .compile();
-
- const servers = await appDatabase.queryAndSubscribe({
- key: ['servers'],
- query: query,
- });
-
- return servers;
- },
- select: (data: QueryResult<SelectServer>): Server[] => {
- const rows = data?.rows ?? [];
- return rows.map(mapServer);
- },
- });
-};
-
-const mapServer = (row: SelectServer): Server => {
- return {
- domain: row.domain,
- name: row.name,
- avatar: row.avatar,
- attributes: JSON.parse(row.attributes),
- version: row.version,
- createdAt: new Date(row.created_at),
- lastSyncedAt: row.last_synced_at ? new Date(row.last_synced_at) : null,
- };
-};
diff --git a/desktop/src/queries/use-sidebar-chats-query.tsx b/desktop/src/queries/use-sidebar-chats-query.tsx
deleted file mode 100644
index b806ad9c..00000000
--- a/desktop/src/queries/use-sidebar-chats-query.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import { SidebarChatNode } from '@/types/workspaces';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-type ChatRow = SelectNode & {
- collaborators: string;
-};
-
-export const useSidebarChatsQuery = () => {
- const workspace = useWorkspace();
-
- return useQuery<QueryResult<ChatRow>, Error, SidebarChatNode[], string[]>({
- queryKey: ['sidebar-chats', workspace.id],
- queryFn: async ({ queryKey }) => {
- const query = sql<ChatRow>`
- WITH chat_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IS NULL AND type = ${NodeTypes.Chat}
- ),
- collaborator_nodes AS (
- SELECT *
- FROM nodes
- WHERE id IN
- (
- SELECT collaborator_id
- FROM node_collaborators
- WHERE collaborator_id != ${workspace.userId}
- AND node_id IN
- (
- SELECT id
- FROM chat_nodes
- )
- )
- ),
- all_nodes AS (
- SELECT * FROM chat_nodes
- UNION ALL
- SELECT * FROM collaborator_nodes
- ),
- chat_collaborators AS (
- SELECT
- nc.node_id,
- json_group_array(nc.collaborator_id) AS collaborators
- FROM node_collaborators nc
- WHERE nc.node_id IN (SELECT id FROM chat_nodes)
- AND nc.collaborator_id != ${workspace.userId}
- GROUP BY nc.node_id
- )
- SELECT
- n.*,
- COALESCE(cc.collaborators, json('[]')) AS collaborators
- FROM all_nodes n
- LEFT JOIN chat_collaborators cc ON n.id = cc.node_id
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<ChatRow>): SidebarChatNode[] => {
- const rows = data?.rows ?? [];
- return buildSidebarSpaceNodes(rows);
- },
- });
-};
-
-const buildSidebarSpaceNodes = (rows: ChatRow[]): SidebarChatNode[] => {
- const chats: SidebarChatNode[] = [];
-
- for (const row of rows) {
- if (row.type !== NodeTypes.Chat) {
- continue;
- }
-
- const chatNode = mapNode(row);
- const collaboratorIds = JSON.parse(row.collaborators) as string[];
- if (!collaboratorIds || collaboratorIds.length === 0) {
- continue;
- }
-
- const collaboratorId = collaboratorIds[0];
- const collaboratorRow = rows.find((r) => r.id === collaboratorId);
- if (!collaboratorRow) {
- continue;
- }
-
- const collaboratorNode = mapNode(collaboratorRow);
- chats.push({
- id: chatNode.id,
- type: chatNode.type,
- name: collaboratorNode.attributes.name,
- avatar: chatNode.attributes.avatar,
- });
- }
-
- return chats;
-};
diff --git a/desktop/src/queries/use-sidebar-spaces-query.tsx b/desktop/src/queries/use-sidebar-spaces-query.tsx
deleted file mode 100644
index c2f30deb..00000000
--- a/desktop/src/queries/use-sidebar-spaces-query.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import { LocalNode } from '@/types/nodes';
-import { SidebarNode, SidebarSpaceNode } from '@/types/workspaces';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-export const useSidebarSpacesQuery = () => {
- const workspace = useWorkspace();
-
- return useQuery<QueryResult<SelectNode>, Error, SidebarSpaceNode[], string[]>(
- {
- queryKey: ['sidebar-spaces', workspace.id],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- 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)
- )
- SELECT * FROM space_nodes
- UNION ALL
- SELECT * FROM space_children_nodes;
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): SidebarSpaceNode[] => {
- const rows = data?.rows ?? [];
- return buildSidebarSpaceNodes(rows);
- },
- },
- );
-};
-
-const buildSidebarSpaceNodes = (rows: SelectNode[]): SidebarSpaceNode[] => {
- const nodes: LocalNode[] = rows.map(mapNode);
- const spaces: SidebarSpaceNode[] = [];
-
- for (const node of nodes) {
- if (node.type !== NodeTypes.Space) {
- continue;
- }
-
- const children = nodes.filter((n) => n.parentId === node.id);
- spaces.push(buildSpaceNode(node, children));
- }
-
- return spaces;
-};
-
-const buildSpaceNode = (
- node: LocalNode,
- children: LocalNode[],
-): SidebarSpaceNode => {
- return {
- id: node.id,
- type: node.type,
- name: node.attributes?.name ?? null,
- avatar: node.attributes?.avatar ?? null,
- children: children.map(buildSidearNode),
- };
-};
-
-const buildSidearNode = (node: LocalNode): SidebarNode => {
- return {
- id: node.id,
- type: node.type,
- name: node.attributes.name ?? null,
- avatar: node.attributes.avatar ?? null,
- };
-};
diff --git a/desktop/src/queries/use-user-search-query.tsx b/desktop/src/queries/use-user-search-query.tsx
deleted file mode 100644
index acb45483..00000000
--- a/desktop/src/queries/use-user-search-query.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { UserNode } from '@/types/users';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult, sql } from 'kysely';
-
-export const useUserSearchQuery = (searchQuery: string) => {
- const workspace = useWorkspace();
-
- return useQuery<QueryResult<SelectNode>, Error, UserNode[], string[]>({
- queryKey: ['user-search', searchQuery],
- enabled: searchQuery.length > 0,
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNode>`
- SELECT n.*
- FROM nodes n
- JOIN node_names nn ON n.id = nn.id
- WHERE n.type = ${NodeTypes.User}
- AND n.id != ${workspace.userId}
- AND nn.name MATCH ${searchQuery + '*'}
- `.compile(workspace.schema);
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (data: QueryResult<SelectNode>): UserNode[] => {
- const rows = data?.rows ?? [];
- return rows.map((row) => {
- const attributes = JSON.parse(row.attributes);
- return {
- id: row.id,
- name: attributes.name,
- email: attributes.email,
- avatar: attributes.avatar,
- };
- });
- },
- });
-};
diff --git a/desktop/src/queries/use-workspace-users-query.tsx b/desktop/src/queries/use-workspace-users-query.tsx
deleted file mode 100644
index b97e47f4..00000000
--- a/desktop/src/queries/use-workspace-users-query.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode } from '@/electron/schemas/workspace';
-import { NodeTypes } from '@/lib/constants';
-import { mapNode } from '@/lib/nodes';
-import { LocalNode } from '@/types/nodes';
-import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
-import { QueryResult } from 'kysely';
-
-const USERS_PER_PAGE = 50;
-
-export const useWorkspaceUsersQuery = () => {
- const workspace = useWorkspace();
-
- return useInfiniteQuery<
- QueryResult<SelectNode>,
- Error,
- LocalNode[],
- string[],
- number
- >({
- queryKey: ['workspace', 'users', workspace.id],
- initialPageParam: 0,
- getNextPageParam: (
- lastPage: QueryResult<SelectNode>,
- pages,
- ): number | undefined => {
- if (lastPage && lastPage.rows) {
- const userCount = lastPage.rows.length;
-
- if (userCount >= USERS_PER_PAGE) {
- return pages.length;
- }
- }
- return undefined;
- },
- queryFn: async ({ queryKey, pageParam }) => {
- const offset = pageParam * USERS_PER_PAGE;
- const query = workspace.schema
- .selectFrom('nodes')
- .selectAll()
- .where('type', '=', NodeTypes.User)
- .orderBy('created_at asc')
- .offset(offset)
- .limit(USERS_PER_PAGE)
- .compile();
-
- return await workspace.queryAndSubscribe({
- key: queryKey,
- page: pageParam,
- query,
- });
- },
- select: (data: InfiniteData<QueryResult<SelectNode>>): LocalNode[] => {
- const pages = data?.pages ?? [];
- const rows = pages.map((page) => page.rows).flat();
- return rows.map(mapNode);
- },
- });
-};
diff --git a/desktop/src/queries/use-workspaces-query.tsx b/desktop/src/queries/use-workspaces-query.tsx
deleted file mode 100644
index 5055c141..00000000
--- a/desktop/src/queries/use-workspaces-query.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useAppDatabase } from '@/contexts/app-database';
-import { SelectWorkspace } from '@/electron/schemas/app';
-import { Workspace, WorkspaceRole } from '@/types/workspaces';
-import { useQuery } from '@tanstack/react-query';
-import { QueryResult } from 'kysely';
-
-export const useWorkspacesQuery = () => {
- const appDatabase = useAppDatabase();
- return useQuery<QueryResult<SelectWorkspace>, Error, Workspace[], string[]>({
- queryKey: ['workspaces'],
- queryFn: async ({ queryKey }) => {
- const query = appDatabase.database
- .selectFrom('workspaces')
- .selectAll()
- .where(
- 'account_id',
- 'in',
- appDatabase.database
- .selectFrom('accounts')
- .where('status', '=', 'active')
- .select('id'),
- )
-
- .compile();
-
- return await window.neuron.executeAppQueryAndSubscribe({
- key: queryKey,
- query: query,
- });
- },
- select: (data: QueryResult<SelectWorkspace>): Workspace[] => {
- const rows = data?.rows ?? [];
- return rows.map(mapWorkspaces);
- },
- });
-};
-
-const mapWorkspaces = (row: SelectWorkspace): Workspace => {
- return {
- id: row.id,
- name: row.name,
- description: row.description,
- avatar: row.avatar,
- versionId: row.version_id,
- accountId: row.account_id,
- role: row.role as WorkspaceRole,
- userId: row.user_id,
- synced: row.synced === 1,
- };
-};
diff --git a/desktop/src/types/mutations.ts b/desktop/src/types/mutations.ts
deleted file mode 100644
index 91b7772a..00000000
--- a/desktop/src/types/mutations.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type ServerMutation = {
- id: string;
- table: string;
- action: string;
- workspaceId: string;
- before: any | null;
- after: any | null;
-};
-
-export type ServerExecuteMutationsResponse = {
- results: ServerExecuteMutationResult[];
-};
-
-export type ServerExecuteMutationResult = {
- id: number;
- status: ServerExecuteMutationStatus;
-};
-
-export type ServerExecuteMutationStatus = 'success' | 'error';
diff --git a/desktop/src/types/mutations/board-view-create.ts b/desktop/src/types/mutations/board-view-create.ts
new file mode 100644
index 00000000..eb20e97e
--- /dev/null
+++ b/desktop/src/types/mutations/board-view-create.ts
@@ -0,0 +1,20 @@
+export type BoardViewCreateMutationInput = {
+ type: 'board_view_create';
+ userId: string;
+ databaseId: string;
+ name: string;
+ groupBy: string;
+};
+
+export type BoardViewCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ board_view_create: {
+ input: BoardViewCreateMutationInput;
+ output: BoardViewCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/calendar-view-create.ts b/desktop/src/types/mutations/calendar-view-create.ts
new file mode 100644
index 00000000..6403d7a5
--- /dev/null
+++ b/desktop/src/types/mutations/calendar-view-create.ts
@@ -0,0 +1,20 @@
+export type CalendarViewCreateMutationInput = {
+ type: 'calendar_view_create';
+ userId: string;
+ databaseId: string;
+ name: string;
+ groupBy: string;
+};
+
+export type CalendarViewCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ calendar_view_create: {
+ input: CalendarViewCreateMutationInput;
+ output: CalendarViewCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/channel-create.ts b/desktop/src/types/mutations/channel-create.ts
new file mode 100644
index 00000000..e111afc7
--- /dev/null
+++ b/desktop/src/types/mutations/channel-create.ts
@@ -0,0 +1,19 @@
+export type ChannelCreateMutationInput = {
+ type: 'channel_create';
+ userId: string;
+ spaceId: string;
+ name: string;
+};
+
+export type ChannelCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ channel_create: {
+ input: ChannelCreateMutationInput;
+ output: ChannelCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/chat-create.ts b/desktop/src/types/mutations/chat-create.ts
new file mode 100644
index 00000000..727e3666
--- /dev/null
+++ b/desktop/src/types/mutations/chat-create.ts
@@ -0,0 +1,18 @@
+export type ChatCreateMutationInput = {
+ type: 'chat_create';
+ userId: string;
+ otherUserId: string;
+};
+
+export type ChatCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ chat_create: {
+ input: ChatCreateMutationInput;
+ output: ChatCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/database-create.ts b/desktop/src/types/mutations/database-create.ts
new file mode 100644
index 00000000..a5a8e11f
--- /dev/null
+++ b/desktop/src/types/mutations/database-create.ts
@@ -0,0 +1,19 @@
+export type DatabaseCreateMutationInput = {
+ type: 'database_create';
+ userId: string;
+ spaceId: string;
+ name: string;
+};
+
+export type DatabaseCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ database_create: {
+ input: DatabaseCreateMutationInput;
+ output: DatabaseCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/email-login.ts b/desktop/src/types/mutations/email-login.ts
new file mode 100644
index 00000000..030ada35
--- /dev/null
+++ b/desktop/src/types/mutations/email-login.ts
@@ -0,0 +1,19 @@
+export type EmailLoginMutationInput = {
+ type: 'email_login';
+ server: string;
+ email: string;
+ password: string;
+};
+
+export type EmailLoginMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ email_login: {
+ input: EmailLoginMutationInput;
+ output: EmailLoginMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/email-register.ts b/desktop/src/types/mutations/email-register.ts
new file mode 100644
index 00000000..478449f4
--- /dev/null
+++ b/desktop/src/types/mutations/email-register.ts
@@ -0,0 +1,20 @@
+export type EmailRegisterMutationInput = {
+ type: 'email_register';
+ server: string;
+ name: string;
+ email: string;
+ password: string;
+};
+
+export type EmailRegisterMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ email_register: {
+ input: EmailRegisterMutationInput;
+ output: EmailRegisterMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/field-create.ts b/desktop/src/types/mutations/field-create.ts
new file mode 100644
index 00000000..8f03f3c9
--- /dev/null
+++ b/desktop/src/types/mutations/field-create.ts
@@ -0,0 +1,20 @@
+export type FieldCreateMutationInput = {
+ type: 'field_create';
+ databaseId: string;
+ name: string;
+ dataType: string;
+ userId: string;
+};
+
+export type FieldCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ field_create: {
+ input: FieldCreateMutationInput;
+ output: FieldCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/index.ts b/desktop/src/types/mutations/index.ts
new file mode 100644
index 00000000..6457b82f
--- /dev/null
+++ b/desktop/src/types/mutations/index.ts
@@ -0,0 +1,48 @@
+import { AppDatabaseSchema } from '@/electron/schemas/app';
+import { WorkspaceDatabaseSchema } from '@/electron/schemas/workspace';
+
+export interface MutationMap {}
+
+export type MutationInput = MutationMap[keyof MutationMap]['input'];
+
+export interface MutationHandler<T extends MutationInput> {
+ handleMutation: (input: T) => Promise<MutationResult<T>>;
+}
+
+export type MutationResult<T extends MutationInput> = {
+ output: MutationMap[T['type']]['output'];
+ changedTables?: MutationChange[];
+};
+
+export type MutationChange = AppMutationChange | WorkspaceMutationChange;
+
+export type AppMutationChange = {
+ type: 'app';
+ table: keyof AppDatabaseSchema;
+};
+
+export type WorkspaceMutationChange = {
+ type: 'workspace';
+ table: keyof WorkspaceDatabaseSchema;
+ userId: string;
+};
+
+export type ServerMutation = {
+ id: string;
+ table: string;
+ action: string;
+ workspaceId: string;
+ before: any | null;
+ after: any | null;
+};
+
+export type ServerExecuteMutationsResponse = {
+ results: ServerExecuteMutationResult[];
+};
+
+export type ServerExecuteMutationResult = {
+ id: number;
+ status: ServerExecuteMutationStatus;
+};
+
+export type ServerExecuteMutationStatus = 'success' | 'error';
diff --git a/desktop/src/types/mutations/message-create.ts b/desktop/src/types/mutations/message-create.ts
new file mode 100644
index 00000000..03ba0809
--- /dev/null
+++ b/desktop/src/types/mutations/message-create.ts
@@ -0,0 +1,21 @@
+import { JSONContent } from '@tiptap/core';
+
+export type MessageCreateMutationInput = {
+ type: 'message_create';
+ userId: string;
+ conversationId: string;
+ content: JSONContent;
+};
+
+export type MessageCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ message_create: {
+ input: MessageCreateMutationInput;
+ output: MessageCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-attribute-delete.ts b/desktop/src/types/mutations/node-attribute-delete.ts
new file mode 100644
index 00000000..29682b7d
--- /dev/null
+++ b/desktop/src/types/mutations/node-attribute-delete.ts
@@ -0,0 +1,19 @@
+export type NodeAttributeDeleteMutationInput = {
+ type: 'node_attribute_delete';
+ userId: string;
+ nodeId: string;
+ attribute: string;
+};
+
+export type NodeAttributeDeleteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_attribute_delete: {
+ input: NodeAttributeDeleteMutationInput;
+ output: NodeAttributeDeleteMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-attribute-set.ts b/desktop/src/types/mutations/node-attribute-set.ts
new file mode 100644
index 00000000..3bbe0359
--- /dev/null
+++ b/desktop/src/types/mutations/node-attribute-set.ts
@@ -0,0 +1,20 @@
+export type NodeAttributeSetMutationInput = {
+ type: 'node_attribute_set';
+ userId: string;
+ nodeId: string;
+ attribute: string;
+ value: any;
+};
+
+export type NodeAttributeSetMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_attribute_set: {
+ input: NodeAttributeSetMutationInput;
+ output: NodeAttributeSetMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-collaborator-create.ts b/desktop/src/types/mutations/node-collaborator-create.ts
new file mode 100644
index 00000000..e06ae958
--- /dev/null
+++ b/desktop/src/types/mutations/node-collaborator-create.ts
@@ -0,0 +1,20 @@
+export type NodeCollaboratorCreateMutationInput = {
+ type: 'node_collaborator_create';
+ userId: string;
+ nodeId: string;
+ collaboratorIds: string[];
+ role: string;
+};
+
+export type NodeCollaboratorCreateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_collaborator_create: {
+ input: NodeCollaboratorCreateMutationInput;
+ output: NodeCollaboratorCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-collaborator-delete.ts b/desktop/src/types/mutations/node-collaborator-delete.ts
new file mode 100644
index 00000000..278dd7d9
--- /dev/null
+++ b/desktop/src/types/mutations/node-collaborator-delete.ts
@@ -0,0 +1,19 @@
+export type NodeCollaboratorDeleteMutationInput = {
+ type: 'node_collaborator_delete';
+ userId: string;
+ nodeId: string;
+ collaboratorId: string;
+};
+
+export type NodeCollaboratorDeleteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_collaborator_delete: {
+ input: NodeCollaboratorDeleteMutationInput;
+ output: NodeCollaboratorDeleteMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-collaborator-update.ts b/desktop/src/types/mutations/node-collaborator-update.ts
new file mode 100644
index 00000000..b70b5645
--- /dev/null
+++ b/desktop/src/types/mutations/node-collaborator-update.ts
@@ -0,0 +1,20 @@
+export type NodeCollaboratorUpdateMutationInput = {
+ type: 'node_collaborator_update';
+ userId: string;
+ nodeId: string;
+ collaboratorId: string;
+ role: string;
+};
+
+export type NodeCollaboratorUpdateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_collaborator_update: {
+ input: NodeCollaboratorUpdateMutationInput;
+ output: NodeCollaboratorUpdateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-delete.ts b/desktop/src/types/mutations/node-delete.ts
new file mode 100644
index 00000000..c19bf782
--- /dev/null
+++ b/desktop/src/types/mutations/node-delete.ts
@@ -0,0 +1,18 @@
+export type NodeDeleteMutationInput = {
+ type: 'node_delete';
+ userId: string;
+ nodeId: string;
+};
+
+export type NodeDeleteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_delete: {
+ input: NodeDeleteMutationInput;
+ output: NodeDeleteMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-reaction-create.ts b/desktop/src/types/mutations/node-reaction-create.ts
new file mode 100644
index 00000000..bad25dbf
--- /dev/null
+++ b/desktop/src/types/mutations/node-reaction-create.ts
@@ -0,0 +1,19 @@
+export type NodeReactionCreateMutationInput = {
+ type: 'node_reaction_create';
+ userId: string;
+ nodeId: string;
+ reaction: string;
+};
+
+export type NodeReactionCreateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_reaction_create: {
+ input: NodeReactionCreateMutationInput;
+ output: NodeReactionCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/node-reaction-delete.ts b/desktop/src/types/mutations/node-reaction-delete.ts
new file mode 100644
index 00000000..158f6221
--- /dev/null
+++ b/desktop/src/types/mutations/node-reaction-delete.ts
@@ -0,0 +1,19 @@
+export type NodeReactionDeleteMutationInput = {
+ type: 'node_reaction_delete';
+ userId: string;
+ nodeId: string;
+ reaction: string;
+};
+
+export type NodeReactionDeleteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ node_reaction_delete: {
+ input: NodeReactionDeleteMutationInput;
+ output: NodeReactionDeleteMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/page-create.ts b/desktop/src/types/mutations/page-create.ts
new file mode 100644
index 00000000..6b3a4fa9
--- /dev/null
+++ b/desktop/src/types/mutations/page-create.ts
@@ -0,0 +1,19 @@
+export type PageCreateMutationInput = {
+ type: 'page_create';
+ userId: string;
+ spaceId: string;
+ name: string;
+};
+
+export type PageCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ page_create: {
+ input: PageCreateMutationInput;
+ output: PageCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/record-create.ts b/desktop/src/types/mutations/record-create.ts
new file mode 100644
index 00000000..3ad355d6
--- /dev/null
+++ b/desktop/src/types/mutations/record-create.ts
@@ -0,0 +1,18 @@
+export type RecordCreateMutationInput = {
+ type: 'record_create';
+ userId: string;
+ databaseId: string;
+};
+
+export type RecordCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ record_create: {
+ input: RecordCreateMutationInput;
+ output: RecordCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/select-option-create.ts b/desktop/src/types/mutations/select-option-create.ts
new file mode 100644
index 00000000..1f1505fd
--- /dev/null
+++ b/desktop/src/types/mutations/select-option-create.ts
@@ -0,0 +1,20 @@
+export type SelectOptionCreateMutationInput = {
+ type: 'select_option_create';
+ userId: string;
+ fieldId: string;
+ name: string;
+ color: string;
+};
+
+export type SelectOptionCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ select_option_create: {
+ input: SelectOptionCreateMutationInput;
+ output: SelectOptionCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/server-create.ts b/desktop/src/types/mutations/server-create.ts
new file mode 100644
index 00000000..056f59ac
--- /dev/null
+++ b/desktop/src/types/mutations/server-create.ts
@@ -0,0 +1,17 @@
+export type ServerCreateMutationInput = {
+ type: 'server_create';
+ domain: string;
+};
+
+export type ServerCreateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ server_create: {
+ input: ServerCreateMutationInput;
+ output: ServerCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/space-create.ts b/desktop/src/types/mutations/space-create.ts
new file mode 100644
index 00000000..1fc34ec4
--- /dev/null
+++ b/desktop/src/types/mutations/space-create.ts
@@ -0,0 +1,19 @@
+export type SpaceCreateMutationInput = {
+ type: 'space_create';
+ userId: string;
+ name: string;
+ description: string;
+};
+
+export type SpaceCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ space_create: {
+ input: SpaceCreateMutationInput;
+ output: SpaceCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/table-view-create.ts b/desktop/src/types/mutations/table-view-create.ts
new file mode 100644
index 00000000..d62f1902
--- /dev/null
+++ b/desktop/src/types/mutations/table-view-create.ts
@@ -0,0 +1,19 @@
+export type TableViewCreateMutationInput = {
+ type: 'table_view_create';
+ userId: string;
+ databaseId: string;
+ name: string;
+};
+
+export type TableViewCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ table_view_create: {
+ input: TableViewCreateMutationInput;
+ output: TableViewCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/workspace-account-role-update.ts b/desktop/src/types/mutations/workspace-account-role-update.ts
new file mode 100644
index 00000000..4eb527f0
--- /dev/null
+++ b/desktop/src/types/mutations/workspace-account-role-update.ts
@@ -0,0 +1,19 @@
+export type WorkspaceAccountRoleUpdateMutationInput = {
+ type: 'workspace_account_role_update';
+ accountId: string;
+ role: string;
+ userId: string;
+};
+
+export type WorkspaceAccountRoleUpdateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ workspace_account_role_update: {
+ input: WorkspaceAccountRoleUpdateMutationInput;
+ output: WorkspaceAccountRoleUpdateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/workspace-accounts-invite.ts b/desktop/src/types/mutations/workspace-accounts-invite.ts
new file mode 100644
index 00000000..eca7e0c7
--- /dev/null
+++ b/desktop/src/types/mutations/workspace-accounts-invite.ts
@@ -0,0 +1,18 @@
+export type WorkspaceAccountsInviteMutationInput = {
+ type: 'workspace_accounts_invite';
+ emails: string[];
+ userId: string;
+};
+
+export type WorkspaceAccountsInviteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ workspace_accounts_invite: {
+ input: WorkspaceAccountsInviteMutationInput;
+ output: WorkspaceAccountsInviteMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/workspace-create.ts b/desktop/src/types/mutations/workspace-create.ts
new file mode 100644
index 00000000..267813e8
--- /dev/null
+++ b/desktop/src/types/mutations/workspace-create.ts
@@ -0,0 +1,19 @@
+export type WorkspaceCreateMutationInput = {
+ type: 'workspace_create';
+ name: string;
+ description: string;
+ accountId: string;
+};
+
+export type WorkspaceCreateMutationOutput = {
+ id: string;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ workspace_create: {
+ input: WorkspaceCreateMutationInput;
+ output: WorkspaceCreateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/mutations/workspace-update.ts b/desktop/src/types/mutations/workspace-update.ts
new file mode 100644
index 00000000..756c0f19
--- /dev/null
+++ b/desktop/src/types/mutations/workspace-update.ts
@@ -0,0 +1,20 @@
+export type WorkspaceUpdateMutationInput = {
+ type: 'workspace_update';
+ id: string;
+ name: string;
+ description: string;
+ accountId: string;
+};
+
+export type WorkspaceUpdateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/types/mutations' {
+ interface MutationMap {
+ workspace_update: {
+ input: WorkspaceUpdateMutationInput;
+ output: WorkspaceUpdateMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/nodes.ts b/desktop/src/types/nodes.ts
index e4aff6fd..ab912583 100644
--- a/desktop/src/types/nodes.ts
+++ b/desktop/src/types/nodes.ts
@@ -78,7 +78,7 @@ export type ServerNodeCollaborator = {
export type ServerNodeReaction = {
nodeId: string;
- reactorId: string;
+ actorId: string;
reaction: string;
workspaceId: string;
createdAt: string;
diff --git a/desktop/src/types/queries.ts b/desktop/src/types/queries.ts
deleted file mode 100644
index b5a13c0a..00000000
--- a/desktop/src/types/queries.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { CompiledQuery, QueryResult } from 'kysely';
-
-export type SubscribedQueryContext<T> = {
- key: string[];
- page?: number;
- query: CompiledQuery<T>;
-};
-
-export type SubscribedQueryResult<T> = {
- context: SubscribedQueryContext<T>;
- tables: string[];
- result: QueryResult<T>;
-};
diff --git a/desktop/src/types/queries/account-list.ts b/desktop/src/types/queries/account-list.ts
new file mode 100644
index 00000000..ee9e3bfd
--- /dev/null
+++ b/desktop/src/types/queries/account-list.ts
@@ -0,0 +1,14 @@
+import { Account } from '@/types/accounts';
+
+export type AccountListQueryInput = {
+ type: 'account_list';
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ account_list: {
+ input: AccountListQueryInput;
+ output: Account[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/breadcrumb-list.ts b/desktop/src/types/queries/breadcrumb-list.ts
new file mode 100644
index 00000000..4be1b9fd
--- /dev/null
+++ b/desktop/src/types/queries/breadcrumb-list.ts
@@ -0,0 +1,16 @@
+import { BreadcrumbNode } from '@/types/workspaces';
+
+export type BreadcrumbListQueryInput = {
+ type: 'breadcrumb_list';
+ nodeId: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ breadcrumb_list: {
+ input: BreadcrumbListQueryInput;
+ output: BreadcrumbNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/database-get.ts b/desktop/src/types/queries/database-get.ts
new file mode 100644
index 00000000..3f46d295
--- /dev/null
+++ b/desktop/src/types/queries/database-get.ts
@@ -0,0 +1,16 @@
+import { DatabaseNode } from '@/types/databases';
+
+export type DatabaseGetQueryInput = {
+ type: 'database_get';
+ databaseId: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ database_get: {
+ input: DatabaseGetQueryInput;
+ output: DatabaseNode;
+ };
+ }
+}
diff --git a/desktop/src/types/queries/database-view-list.ts b/desktop/src/types/queries/database-view-list.ts
new file mode 100644
index 00000000..3c393c9d
--- /dev/null
+++ b/desktop/src/types/queries/database-view-list.ts
@@ -0,0 +1,16 @@
+import { ViewNode } from '@/types/databases';
+
+export type DatabaseViewListQueryInput = {
+ type: 'database_view_list';
+ databaseId: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ database_view_list: {
+ input: DatabaseViewListQueryInput;
+ output: ViewNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/document-get.ts b/desktop/src/types/queries/document-get.ts
new file mode 100644
index 00000000..87df5b4a
--- /dev/null
+++ b/desktop/src/types/queries/document-get.ts
@@ -0,0 +1,20 @@
+import { LocalNode } from '@/types/nodes';
+
+export type DocumentGetQueryInput = {
+ type: 'document_get';
+ nodeId: string;
+ userId: string;
+};
+
+export type DocumentGetQueryOutput = {
+ nodes: Map<string, LocalNode>;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ document_get: {
+ input: DocumentGetQueryInput;
+ output: DocumentGetQueryOutput;
+ };
+ }
+}
diff --git a/desktop/src/types/queries/index.ts b/desktop/src/types/queries/index.ts
new file mode 100644
index 00000000..057fb0d0
--- /dev/null
+++ b/desktop/src/types/queries/index.ts
@@ -0,0 +1,29 @@
+import { MutationChange } from '@/types/mutations';
+
+export interface QueryMap {}
+
+export type QueryInput = QueryMap[keyof QueryMap]['input'];
+
+export interface QueryHandler<T extends QueryInput> {
+ handleQuery: (input: T) => Promise<QueryResult<T>>;
+ checkForChanges: (
+ changes: MutationChange[],
+ input: T,
+ state: Record<string, any>,
+ ) => Promise<ChangeCheckResult<T>>;
+}
+
+export type QueryResult<T extends QueryInput> = {
+ output: QueryMap[T['type']]['output'];
+ state: Record<string, any>;
+};
+
+export type SubscribedQuery<T extends QueryInput> = {
+ input: T;
+ result: QueryResult<T>;
+};
+
+export type ChangeCheckResult<T extends QueryInput> = {
+ hasChanges: boolean;
+ result?: QueryResult<T>;
+};
diff --git a/desktop/src/types/queries/message-list.ts b/desktop/src/types/queries/message-list.ts
new file mode 100644
index 00000000..0f4caa00
--- /dev/null
+++ b/desktop/src/types/queries/message-list.ts
@@ -0,0 +1,18 @@
+import { MessageNode } from '@/types/messages';
+
+export type MessageListQueryInput = {
+ type: 'message_list';
+ conversationId: string;
+ page: number;
+ count: number;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ message_list: {
+ input: MessageListQueryInput;
+ output: MessageNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/node-collaborator-list.ts b/desktop/src/types/queries/node-collaborator-list.ts
new file mode 100644
index 00000000..7bea875e
--- /dev/null
+++ b/desktop/src/types/queries/node-collaborator-list.ts
@@ -0,0 +1,16 @@
+import { NodeCollaboratorsWrapper } from '@/types/nodes';
+
+export type NodeCollaboratorListQueryInput = {
+ type: 'node_collaborator_list';
+ nodeId: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ node_collaborator_list: {
+ input: NodeCollaboratorListQueryInput;
+ output: NodeCollaboratorsWrapper;
+ };
+ }
+}
diff --git a/desktop/src/types/queries/node-collaborator-search.ts b/desktop/src/types/queries/node-collaborator-search.ts
new file mode 100644
index 00000000..257d613d
--- /dev/null
+++ b/desktop/src/types/queries/node-collaborator-search.ts
@@ -0,0 +1,17 @@
+import { NodeCollaboratorNode } from '@/types/nodes';
+
+export type NodeCollaboratorSearchQueryInput = {
+ type: 'node_collaborator_search';
+ searchQuery: string;
+ excluded: string[];
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ node_collaborator_search: {
+ input: NodeCollaboratorSearchQueryInput;
+ output: NodeCollaboratorNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/node-get.ts b/desktop/src/types/queries/node-get.ts
new file mode 100644
index 00000000..87832420
--- /dev/null
+++ b/desktop/src/types/queries/node-get.ts
@@ -0,0 +1,16 @@
+import { LocalNode } from '@/types/nodes';
+
+export type NodeGetQueryInput = {
+ type: 'node_get';
+ nodeId: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ node_get: {
+ input: NodeGetQueryInput;
+ output: LocalNode;
+ };
+ }
+}
diff --git a/desktop/src/types/queries/record-get.ts b/desktop/src/types/queries/record-get.ts
new file mode 100644
index 00000000..1f7a6f39
--- /dev/null
+++ b/desktop/src/types/queries/record-get.ts
@@ -0,0 +1,16 @@
+import { RecordNode } from '@/types/databases';
+
+export type RecordGetQueryInput = {
+ type: 'record_get';
+ recordId: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ record_get: {
+ input: RecordGetQueryInput;
+ output: RecordNode;
+ };
+ }
+}
diff --git a/desktop/src/types/queries/record-list.ts b/desktop/src/types/queries/record-list.ts
new file mode 100644
index 00000000..182ad5cc
--- /dev/null
+++ b/desktop/src/types/queries/record-list.ts
@@ -0,0 +1,20 @@
+import { RecordNode, ViewFilter, ViewSort } from '@/types/databases';
+
+export type RecordListQueryInput = {
+ type: 'record_list';
+ databaseId: string;
+ filters: ViewFilter[];
+ sorts: ViewSort[];
+ page: number;
+ count: number;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ record_list: {
+ input: RecordListQueryInput;
+ output: RecordNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/server-list.ts b/desktop/src/types/queries/server-list.ts
new file mode 100644
index 00000000..0123dff2
--- /dev/null
+++ b/desktop/src/types/queries/server-list.ts
@@ -0,0 +1,14 @@
+import { Server } from '@/types/servers';
+
+export type ServerListQueryInput = {
+ type: 'server_list';
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ server_list: {
+ input: ServerListQueryInput;
+ output: Server[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/sidebar-chat-list.ts b/desktop/src/types/queries/sidebar-chat-list.ts
new file mode 100644
index 00000000..161c46fc
--- /dev/null
+++ b/desktop/src/types/queries/sidebar-chat-list.ts
@@ -0,0 +1,15 @@
+import { SidebarChatNode } from '@/types/workspaces';
+
+export type SidebarChatListQueryInput = {
+ type: 'sidebar_chat_list';
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ sidebar_chat_list: {
+ input: SidebarChatListQueryInput;
+ output: SidebarChatNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/sidebar-space-list.ts b/desktop/src/types/queries/sidebar-space-list.ts
new file mode 100644
index 00000000..b8144de5
--- /dev/null
+++ b/desktop/src/types/queries/sidebar-space-list.ts
@@ -0,0 +1,15 @@
+import { SidebarSpaceNode } from '@/types/workspaces';
+
+export type SidebarSpaceListQueryInput = {
+ type: 'sidebar_space_list';
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ sidebar_space_list: {
+ input: SidebarSpaceListQueryInput;
+ output: SidebarSpaceNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/user-search.ts b/desktop/src/types/queries/user-search.ts
new file mode 100644
index 00000000..3464b5dd
--- /dev/null
+++ b/desktop/src/types/queries/user-search.ts
@@ -0,0 +1,16 @@
+import { UserNode } from '@/types/users';
+
+export type UserSearchQueryInput = {
+ type: 'user_search';
+ searchQuery: string;
+ userId: string;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ user_search: {
+ input: UserSearchQueryInput;
+ output: UserNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/workspace-list.ts b/desktop/src/types/queries/workspace-list.ts
new file mode 100644
index 00000000..14442311
--- /dev/null
+++ b/desktop/src/types/queries/workspace-list.ts
@@ -0,0 +1,14 @@
+import { Workspace } from '@/types/workspaces';
+
+export type WorkspaceListQueryInput = {
+ type: 'workspace_list';
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ workspace_list: {
+ input: WorkspaceListQueryInput;
+ output: Workspace[];
+ };
+ }
+}
diff --git a/desktop/src/types/queries/workspace-user-list.ts b/desktop/src/types/queries/workspace-user-list.ts
new file mode 100644
index 00000000..41593a93
--- /dev/null
+++ b/desktop/src/types/queries/workspace-user-list.ts
@@ -0,0 +1,17 @@
+import { LocalNode } from '@/types/nodes';
+
+export type WorkspaceUserListQueryInput = {
+ type: 'workspace_user_list';
+ userId: string;
+ page: number;
+ count: number;
+};
+
+declare module '@/types/queries' {
+ interface QueryMap {
+ workspace_user_list: {
+ input: WorkspaceUserListQueryInput;
+ output: LocalNode[];
+ };
+ }
+}
diff --git a/desktop/src/types/window.d.ts b/desktop/src/types/window.d.ts
index 5e551b79..f96399e1 100644
--- a/desktop/src/types/window.d.ts
+++ b/desktop/src/types/window.d.ts
@@ -2,6 +2,8 @@ import { EventBus } from '@/lib/event-bus';
import { CompiledQuery, QueryResult } from 'kysely';
import { LocalMutationInput } from '@/types/mutations';
import { SubscribedQueryContext } from '@/types/queries';
+import { MutationMap, MutationInput } from '@/types/mutations';
+import { QueryMap, QueryInput } from '@/types/queries';
interface NeuronApi {
init: () => Promise<void>;
@@ -38,6 +40,17 @@ interface NeuronApi {
workspaceId: string,
queryKey: string[],
) => Promise<void>;
+
+ executeMutation: <T extends MutationInput>(
+ input: T,
+ ) => Promise<MutationMap[T['type']]['output']>;
+
+ executeQuery: <T extends QueryInput>(
+ id: string,
+ input: T,
+ ) => Promise<QueryMap[T['type']]['output']>;
+
+ unsubscribeQuery: (id: string) => Promise<void>;
}
declare global {
diff --git a/server/src/consumers/node-reaction-changes.ts b/server/src/consumers/node-reaction-changes.ts
index f1dd389b..61e3fde8 100644
--- a/server/src/consumers/node-reaction-changes.ts
+++ b/server/src/consumers/node-reaction-changes.ts
@@ -123,7 +123,7 @@ const mapNodeReaction = (
): ServerNodeReaction => {
return {
nodeId: reaction.node_id,
- reactorId: reaction.reactor_id,
+ reactorId: reaction.actor_id,
reaction: reaction.reaction,
workspaceId: reaction.workspace_id,
createdAt: new Date(reaction.created_at),
diff --git a/server/src/data/migrations.ts b/server/src/data/migrations.ts
index 0532d1b1..eb5ca496 100644
--- a/server/src/data/migrations.ts
+++ b/server/src/data/migrations.ts
@@ -142,7 +142,7 @@ const createNodeReactionsTable: Migration = {
.addColumn('node_id', 'varchar(30)', (col) =>
col.notNull().references('nodes.id').onDelete('cascade'),
)
- .addColumn('reactor_id', 'varchar(30)', (col) =>
+ .addColumn('actor_id', 'varchar(30)', (col) =>
col.notNull().references('nodes.id').onDelete('cascade'),
)
.addColumn('reaction', 'varchar(30)', (col) => col.notNull())
@@ -151,7 +151,7 @@ const createNodeReactionsTable: Migration = {
.addColumn('server_created_at', 'timestamptz', (col) => col.notNull())
.addPrimaryKeyConstraint('node_reactions_pkey', [
'node_id',
- 'reactor_id',
+ 'actor_id',
'reaction',
])
.execute();
diff --git a/server/src/data/schema.ts b/server/src/data/schema.ts
index 052ba94b..9a2b8698 100644
--- a/server/src/data/schema.ts
+++ b/server/src/data/schema.ts
@@ -121,7 +121,7 @@ export type UpdateNodeCollaborator = Updateable<NodeCollaboratorTable>;
interface NodeReactionTable {
node_id: ColumnType<string, string, never>;
- reactor_id: ColumnType<string, string, never>;
+ actor_id: ColumnType<string, string, never>;
reaction: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
created_at: ColumnType<Date, Date, never>;
diff --git a/server/src/mutations/node-reactions.ts b/server/src/mutations/node-reactions.ts
index 02495c2a..4c482f40 100644
--- a/server/src/mutations/node-reactions.ts
+++ b/server/src/mutations/node-reactions.ts
@@ -39,7 +39,7 @@ const handleCreateNodeReactionMutation = async (
mutation.after,
) as LocalNodeReactionMutationData;
- if (nodeReactionData.reactor_id !== workspaceAccount.user_id) {
+ if (nodeReactionData.actor_id !== workspaceAccount.user_id) {
return {
status: 'error',
};
@@ -60,7 +60,7 @@ const handleCreateNodeReactionMutation = async (
.insertInto('node_reactions')
.values({
node_id: nodeReactionData.node_id,
- reactor_id: nodeReactionData.reactor_id,
+ actor_id: nodeReactionData.actor_id,
reaction: nodeReactionData.reaction,
created_at: new Date(nodeReactionData.created_at),
workspace_id: workspaceAccount.workspace_id,
@@ -88,7 +88,7 @@ const handleDeleteNodeReactionMutation = async (
mutation.before,
) as LocalNodeReactionMutationData;
- if (nodeReactionData.reactor_id !== workspaceAccount.user_id) {
+ if (nodeReactionData.actor_id !== workspaceAccount.user_id) {
return {
status: 'error',
};
@@ -99,7 +99,7 @@ const handleDeleteNodeReactionMutation = async (
.where((eb) =>
eb.and([
eb('node_id', '=', nodeReactionData.node_id),
- eb('reactor_id', '=', nodeReactionData.reactor_id),
+ eb('actor_id', '=', nodeReactionData.actor_id),
eb('reaction', '=', nodeReactionData.reaction),
]),
)
diff --git a/server/src/routes/sync.ts b/server/src/routes/sync.ts
index cb152ac4..a8ad02d0 100644
--- a/server/src/routes/sync.ts
+++ b/server/src/routes/sync.ts
@@ -31,7 +31,7 @@ syncRouter.get(
(nodeReaction) => {
return {
nodeId: nodeReaction.node_id,
- reactorId: nodeReaction.reactor_id,
+ reactorId: nodeReaction.actor_id,
reaction: nodeReaction.reaction,
workspaceId: nodeReaction.workspace_id,
createdAt: nodeReaction.created_at,
diff --git a/server/src/synapse.ts b/server/src/synapse.ts
index 833f1903..ca9ddf00 100644
--- a/server/src/synapse.ts
+++ b/server/src/synapse.ts
@@ -1,7 +1,7 @@
import { WebSocket } from 'ws';
import { IncomingMessage } from 'http';
import { SocketMessage } from '@/types/sockets';
-import { database } from './data/database';
+import { database } from '@/data/database';
import { sql } from 'kysely';
import { SelectMutation } from '@/data/schema';
import { ServerMutation } from '@/types/mutations';
diff --git a/server/src/types/changes.ts b/server/src/types/changes.ts
index ffdcdb6c..36e6b668 100644
--- a/server/src/types/changes.ts
+++ b/server/src/types/changes.ts
@@ -69,7 +69,7 @@ export type NodeCollaboratorChangeData = {
export type NodeReactionChangeData = {
node_id: string;
- reactor_id: string;
+ actor_id: string;
reaction: string;
workspace_id: string;
created_at: string;
diff --git a/server/src/types/mutations.ts b/server/src/types/mutations.ts
index 347b2124..40756bcd 100644
--- a/server/src/types/mutations.ts
+++ b/server/src/types/mutations.ts
@@ -53,7 +53,7 @@ export type LocalNodeCollaboratorMutationData = {
export type LocalNodeReactionMutationData = {
node_id: string;
- reactor_id: string;
+ actor_id: string;
reaction: string;
created_at: string;
};