Skip to content

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

Implement new structure for nodes with CRDT

Hakan Shehu4499420ce387
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 0cac9588..567c436f 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -64,6 +64,7 @@
"electron-squirrel-startup": "^1.0.1",
"fractional-indexing-jittered": "^0.9.1",
"is-hotkey": "^0.2.0",
+ "js-base64": "^3.7.7",
"js-sha256": "^0.11.0",
"kysely": "^0.27.4",
"lodash": "^4.17.21",
@@ -84,6 +85,7 @@
"ts-pattern": "^5.3.1",
"ulid": "^2.3.0",
"ws": "^8.18.0",
+ "yjs": "^13.6.19",
"zod": "^3.23.8"
},
"devDependencies": {
@@ -8985,6 +8987,16 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
+ "node_modules/isomorphic.js": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz",
+ "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==",
+ "license": "MIT",
+ "funding": {
+ "type": "GitHub Sponsors ❤",
+ "url": "https://github.com/sponsors/dmonad"
+ }
+ },
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
@@ -9009,6 +9021,12 @@
"jiti": "bin/jiti.js"
}
},
+ "node_modules/js-base64": {
+ "version": "3.7.7",
+ "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.7.tgz",
+ "integrity": "sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/js-sha256": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/js-sha256/-/js-sha256-0.11.0.tgz",
@@ -9139,6 +9157,27 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/lib0": {
+ "version": "0.2.97",
+ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.97.tgz",
+ "integrity": "sha512-Q4d1ekgvufi9FiHkkL46AhecfNjznSL9MRNoJRQ76gBHS9OqU2ArfQK0FvBpuxgWeJeNI0LVgAYMIpsGeX4gYg==",
+ "license": "MIT",
+ "dependencies": {
+ "isomorphic.js": "^0.2.4"
+ },
+ "bin": {
+ "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js",
+ "0gentesthtml": "bin/gentesthtml.js",
+ "0serve": "bin/0serve.js"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "type": "GitHub Sponsors ❤",
+ "url": "https://github.com/sponsors/dmonad"
+ }
+ },
"node_modules/lilconfig": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz",
@@ -14229,6 +14268,23 @@
"fd-slicer": "~1.1.0"
}
},
+ "node_modules/yjs": {
+ "version": "13.6.19",
+ "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.19.tgz",
+ "integrity": "sha512-GNKw4mEUn5yWU2QPHRx8jppxmCm9KzbBhB4qJLUJFiiYD0g/tDVgXQ7aPkyh01YO28kbs2J/BEbWBagjuWyejw==",
+ "license": "MIT",
+ "dependencies": {
+ "lib0": "^0.2.86"
+ },
+ "engines": {
+ "node": ">=16.0.0",
+ "npm": ">=8.0.0"
+ },
+ "funding": {
+ "type": "GitHub Sponsors ❤",
+ "url": "https://github.com/sponsors/dmonad"
+ }
+ },
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
diff --git a/desktop/package.json b/desktop/package.json
index a793cb60..cd0773a9 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -105,6 +105,7 @@
"electron-squirrel-startup": "^1.0.1",
"fractional-indexing-jittered": "^0.9.1",
"is-hotkey": "^0.2.0",
+ "js-base64": "^3.7.7",
"js-sha256": "^0.11.0",
"kysely": "^0.27.4",
"lodash": "^4.17.21",
@@ -125,6 +126,7 @@
"ts-pattern": "^5.3.1",
"ulid": "^2.3.0",
"ws": "^8.18.0",
+ "yjs": "^13.6.19",
"zod": "^3.23.8"
}
}
diff --git a/desktop/src/components/databases/boards/board-view-card.tsx b/desktop/src/components/databases/boards/board-view-card.tsx
index 53929647..ab6c7f80 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 { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import {
RecordNode,
SelectFieldNode,
@@ -20,7 +20,7 @@ interface DragResult {
export const BoardViewCard = ({ record }: BoardViewCardProps) => {
const workspace = useWorkspace();
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate, isPending } = useNodeAttributeSetMutation();
const [, drag] = useDrag({
type: 'board-record',
@@ -32,9 +32,9 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
const optionId = dropResult.option.id;
const fieldId = dropResult.field.id;
- const currentOptionId = record.attributes?.find(
- (v) => v.type === fieldId && v.foreignNodeId === optionId,
- )?.foreignNodeId;
+ const currentOptionId = record.attributes[fieldId] as
+ | string
+ | undefined;
if (currentOptionId === optionId) {
return;
@@ -42,11 +42,8 @@ export const BoardViewCard = ({ record }: BoardViewCardProps) => {
mutate({
nodeId: record.id,
- type: fieldId,
- key: '1',
- foreignNodeId: optionId,
- textValue: null,
- numberValue: null,
+ key: fieldId,
+ value: optionId,
});
}
},
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 9204a53d..26dec3ac 100644
--- a/desktop/src/components/databases/boards/board-view-column-records.tsx
+++ b/desktop/src/components/databases/boards/board-view-column-records.tsx
@@ -5,6 +5,7 @@ import {
BoardViewNode,
SelectFieldNode,
SelectOptionNode,
+ ViewFilter,
} from '@/types/databases';
import { BoardViewCard } from '@/components/databases/boards/board-view-card';
@@ -21,19 +22,14 @@ export const BoardViewColumnRecords = ({
}: BoardViewColumnRecordsProps) => {
const database = useDatabase();
- const filters = [
+ const filters: ViewFilter[] = [
...view.filters,
{
id: '1',
+ type: 'field',
fieldId: field.id,
operator: 'is_in',
- values: [
- {
- textValue: null,
- numberValue: null,
- foreignNodeId: option.id,
- },
- ],
+ value: [option.id],
},
];
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
diff --git a/desktop/src/components/databases/boards/board-view.tsx b/desktop/src/components/databases/boards/board-view.tsx
index a02a52ae..973e799b 100644
--- a/desktop/src/components/databases/boards/board-view.tsx
+++ b/desktop/src/components/databases/boards/board-view.tsx
@@ -3,9 +3,10 @@ import { BoardViewNode } from '@/types/databases';
import { ViewTabs } from '@/components/databases/view-tabs';
import { useDatabase } from '@/contexts/database';
import { BoardViewColumn } from '@/components/databases/boards/board-view-column';
-import { ViewSortsAndFilters } from '@/components/databases/view-sorts-and-filters';
-import { ViewSortButton } from '@/components/databases/sorts/view-sort-button';
-import { ViewFilterButton } from '@/components/databases/filters/view-filter.button';
+import { ViewSearchBar } from '@/components/databases/search/view-search-bar';
+import { ViewSortButton } from '@/components/databases/search/view-sort-button';
+import { ViewFilterButton } from '@/components/databases/search/view-filter-button';
+import { ViewSearchProvider } from '@/components/databases/search/view-search-provider';
interface BoardViewProps {
node: BoardViewNode;
@@ -13,7 +14,6 @@ interface BoardViewProps {
export const BoardView = ({ node }: BoardViewProps) => {
const database = useDatabase();
- const [openSortsAndFilters, setOpenSortsAndFilters] = React.useState(true);
const groupByField = database.fields.find(
(field) => field.id === node.groupBy,
@@ -24,31 +24,15 @@ export const BoardView = ({ node }: BoardViewProps) => {
}
return (
- <React.Fragment>
+ <ViewSearchProvider id={node.id} filters={node.filters} sorts={node.sorts}>
<div className="mt-2 flex flex-row justify-between border-b">
<ViewTabs />
<div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
- <ViewSortButton
- viewId={node.id}
- sorts={node.sorts}
- open={openSortsAndFilters}
- setOpen={setOpenSortsAndFilters}
- />
- <ViewFilterButton
- viewId={node.id}
- filters={node.filters}
- open={openSortsAndFilters}
- setOpen={setOpenSortsAndFilters}
- />
+ <ViewSortButton />
+ <ViewFilterButton />
</div>
</div>
- {openSortsAndFilters && (
- <ViewSortsAndFilters
- viewId={node.id}
- filters={node.filters}
- sorts={node.sorts}
- />
- )}
+ <ViewSearchBar />
<div className="mt-2 flex w-full min-w-full max-w-full flex-row gap-2 overflow-auto pr-5">
{groupByField.options.map((option) => {
return (
@@ -61,6 +45,6 @@ export const BoardView = ({ node }: BoardViewProps) => {
);
})}
</div>
- </React.Fragment>
+ </ViewSearchProvider>
);
};
diff --git a/desktop/src/components/databases/calendars/calendar-view-grid.tsx b/desktop/src/components/databases/calendars/calendar-view-grid.tsx
index bc9aec75..ef7f5d4b 100644
--- a/desktop/src/components/databases/calendars/calendar-view-grid.tsx
+++ b/desktop/src/components/databases/calendars/calendar-view-grid.tsx
@@ -4,7 +4,7 @@ import { Icon } from '@/components/ui/icon';
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, ViewFilterNode } from '@/types/databases';
+import { CalendarViewNode, FieldNode, ViewFilter } from '@/types/databases';
import { useRecordsQuery } from '@/queries/use-records-query';
import { useDatabase } from '@/contexts/database';
import { filterRecords } from '@/lib/databases';
@@ -22,31 +22,21 @@ export const CalendarViewGrid = ({ view, field }: CalendarViewGridProps) => {
const [month, setMonth] = React.useState(new Date());
const { first, last } = getDisplayedDates(month);
- const filters = [
+ const filters: ViewFilter[] = [
...view.filters,
{
id: 'start_date',
+ type: 'field',
fieldId: field.id,
operator: 'is_on_or_after',
- values: [
- {
- textValue: first.toISOString(),
- numberValue: null,
- foreignNodeId: null,
- },
- ],
+ value: first.toISOString(),
},
{
id: 'end_date',
+ type: 'field',
fieldId: field.id,
operator: 'is_on_or_before',
- values: [
- {
- textValue: last.toISOString(),
- numberValue: null,
- foreignNodeId: null,
- },
- ],
+ value: last.toISOString(),
},
];
@@ -98,17 +88,12 @@ export const CalendarViewGrid = ({ view, field }: CalendarViewGridProps) => {
<Icon name="arrow-right-s-line" className="h-4 w-4" {...props} />
),
Day: (props: DayProps) => {
- const filter: ViewFilterNode = {
+ const filter: ViewFilter = {
id: 'calendar_filter',
+ type: 'field',
fieldId: field.id,
operator: 'is_equal_to',
- values: [
- {
- textValue: props.date.toISOString(),
- numberValue: null,
- foreignNodeId: null,
- },
- ],
+ value: props.date.toISOString(),
};
const dayRecords = filterRecords(
diff --git a/desktop/src/components/databases/calendars/calendar-view.tsx b/desktop/src/components/databases/calendars/calendar-view.tsx
index c4c22788..477913e6 100644
--- a/desktop/src/components/databases/calendars/calendar-view.tsx
+++ b/desktop/src/components/databases/calendars/calendar-view.tsx
@@ -3,9 +3,10 @@ import { CalendarViewNode } from '@/types/databases';
import { ViewTabs } from '@/components/databases/view-tabs';
import { useDatabase } from '@/contexts/database';
import { CalendarViewGrid } from '@/components/databases/calendars/calendar-view-grid';
-import { ViewSortsAndFilters } from '@/components/databases/view-sorts-and-filters';
-import { ViewSortButton } from '@/components/databases/sorts/view-sort-button';
-import { ViewFilterButton } from '@/components/databases/filters/view-filter.button';
+import { ViewSearchBar } from '@/components/databases/search/view-search-bar';
+import { ViewSortButton } from '@/components/databases/search/view-sort-button';
+import { ViewFilterButton } from '@/components/databases/search/view-filter-button';
+import { ViewSearchProvider } from '@/components/databases/search/view-search-provider';
interface CalendarViewProps {
node: CalendarViewNode;
@@ -14,8 +15,6 @@ interface CalendarViewProps {
export const CalendarView = ({ node }: CalendarViewProps) => {
const database = useDatabase();
- const [openSortsAndFilters, setOpenSortsAndFilters] = React.useState(true);
-
const groupByField = database.fields.find(
(field) => field.id === node.groupBy,
);
@@ -25,34 +24,18 @@ export const CalendarView = ({ node }: CalendarViewProps) => {
}
return (
- <React.Fragment>
+ <ViewSearchProvider id={node.id} filters={node.filters} sorts={node.sorts}>
<div className="mt-2 flex flex-row justify-between border-b">
<ViewTabs />
<div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
- <ViewSortButton
- viewId={node.id}
- sorts={node.sorts}
- open={openSortsAndFilters}
- setOpen={setOpenSortsAndFilters}
- />
- <ViewFilterButton
- viewId={node.id}
- filters={node.filters}
- open={openSortsAndFilters}
- setOpen={setOpenSortsAndFilters}
- />
+ <ViewSortButton />
+ <ViewFilterButton />
</div>
</div>
- {openSortsAndFilters && (
- <ViewSortsAndFilters
- viewId={node.id}
- filters={node.filters}
- sorts={node.sorts}
- />
- )}
+ <ViewSearchBar />
<div className="mt-2 w-full min-w-full max-w-full overflow-auto pr-5">
<CalendarViewGrid view={node} field={groupByField} />
</div>
- </React.Fragment>
+ </ViewSearchProvider>
);
};
diff --git a/desktop/src/components/databases/fields/field-rename-input.tsx b/desktop/src/components/databases/fields/field-rename-input.tsx
index a26adb5d..5d4b21d0 100644
--- a/desktop/src/components/databases/fields/field-rename-input.tsx
+++ b/desktop/src/components/databases/fields/field-rename-input.tsx
@@ -1,15 +1,14 @@
import React from 'react';
import { FieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { AttributeTypes } from '@/lib/constants';
interface FieldRenameInputProps {
field: FieldNode;
}
export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate, isPending } = useNodeAttributeSetMutation();
return (
<div className="w-full p-1">
@@ -21,11 +20,8 @@ export const FieldRenameInput = ({ field }: FieldRenameInputProps) => {
mutate({
nodeId: field.id,
- type: AttributeTypes.Name,
- key: '1',
- textValue: newName,
- numberValue: null,
- foreignNodeId: null,
+ key: 'name',
+ value: newName,
});
}}
/>
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 485bb809..c1c00948 100644
--- a/desktop/src/components/databases/fields/select-option-settings-popover.tsx
+++ b/desktop/src/components/databases/fields/select-option-settings-popover.tsx
@@ -11,9 +11,8 @@ 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 { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { AttributeTypes } from '@/lib/constants';
interface SelectOptionSettingsPopoverProps {
option: SelectOptionNode;
@@ -22,7 +21,7 @@ interface SelectOptionSettingsPopoverProps {
export const SelectOptionSettingsPopover = ({
option,
}: SelectOptionSettingsPopoverProps) => {
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate, isPending } = useNodeAttributeSetMutation();
const [openSetttingsPopover, setOpenSetttingsPopover] = React.useState(false);
const [openDeleteDialog, setOpenDeleteDialog] = React.useState(false);
@@ -47,11 +46,8 @@ export const SelectOptionSettingsPopover = ({
mutate({
nodeId: option.id,
- type: AttributeTypes.Name,
- key: '1',
- textValue: newName,
- numberValue: null,
- foreignNodeId: null,
+ key: 'name',
+ value: newName,
});
}}
/>
@@ -67,11 +63,8 @@ export const SelectOptionSettingsPopover = ({
if (isPending) return;
mutate({
nodeId: option.id,
- type: AttributeTypes.Color,
- key: '1',
- textValue: color.value,
- numberValue: null,
- foreignNodeId: null,
+ key: 'color',
+ value: color.value,
});
}}
>
diff --git a/desktop/src/components/databases/filters/view-filter.button.tsx b/desktop/src/components/databases/filters/view-filter.button.tsx
deleted file mode 100644
index be3080bc..00000000
--- a/desktop/src/components/databases/filters/view-filter.button.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import React from 'react';
-import { ViewFilterNode } from '@/types/databases';
-import { ViewFilterAddPopover } from '@/components/databases/filters/view-filter-add-popover';
-import { Icon } from '@/components/ui/icon';
-
-interface ViewFilterButtonProps {
- viewId: string;
- filters: ViewFilterNode[];
- open: boolean;
- setOpen: (open: boolean) => void;
-}
-
-export const ViewFilterButton = ({
- viewId,
- filters,
- open,
- setOpen,
-}: ViewFilterButtonProps) => {
- if (filters.length > 0) {
- return (
- <button
- className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50"
- onClick={() => setOpen(!open)}
- >
- <Icon name="filter-line" />
- </button>
- );
- }
-
- return (
- <ViewFilterAddPopover
- viewId={viewId}
- existingFilters={filters}
- onCreate={() => setOpen(true)}
- >
- <button className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50">
- <Icon name="filter-line" />
- </button>
- </ViewFilterAddPopover>
- );
-};
diff --git a/desktop/src/components/databases/filters/view-boolean-field-filter.tsx b/desktop/src/components/databases/search/view-boolean-field-filter.tsx
similarity index 73%
rename from desktop/src/components/databases/filters/view-boolean-field-filter.tsx
rename to desktop/src/components/databases/search/view-boolean-field-filter.tsx
index 095c9a7b..e6b00afe 100644
--- a/desktop/src/components/databases/filters/view-boolean-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-boolean-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { BooleanFieldNode, ViewFilterNode } from '@/types/databases';
+import { BooleanFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -14,22 +14,18 @@ import {
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, booleanFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewBooleanFieldFilterProps {
field: BooleanFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewBooleanFieldFilter = ({
field,
filter,
}: ViewBooleanFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
booleanFieldFilterOperators.find(
@@ -37,7 +33,16 @@ export const ViewBooleanFieldFilter = ({
) ?? booleanFieldFilterOperators[0];
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={(open) => {
+ if (open) {
+ viewSearch.openFieldFilter(filter.id);
+ } else {
+ viewSearch.closeFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -68,13 +73,9 @@ export const ViewBooleanFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
});
}}
>
@@ -87,7 +88,7 @@ export const ViewBooleanFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
diff --git a/desktop/src/components/databases/filters/view-created-at-field-fitler.tsx b/desktop/src/components/databases/search/view-created-at-field-fitler.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-created-at-field-fitler.tsx
rename to desktop/src/components/databases/search/view-created-at-field-fitler.tsx
index 63c98e91..346cd859 100644
--- a/desktop/src/components/databases/filters/view-created-at-field-fitler.tsx
+++ b/desktop/src/components/databases/search/view-created-at-field-fitler.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { CreatedAtFieldNode, ViewFilterNode } from '@/types/databases';
+import { CreatedAtFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -14,37 +14,39 @@ import {
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, dateFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
import { DatePicker } from '@/components/ui/date-picker';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewCreatedAtFieldFilterProps {
field: CreatedAtFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewCreatedAtFieldFilter = ({
field,
filter,
}: ViewCreatedAtFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
dateFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? dateFieldFilterOperators[0];
- const dateTextValue =
- filter.values.length > 0 ? filter.values[0].textValue : null;
+ const dateTextValue = (filter.value as string) ?? null;
const dateValue = dateTextValue ? new Date(dateTextValue) : null;
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -75,25 +77,17 @@ export const ViewCreatedAtFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : dateValue?.toISOString();
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -105,7 +99,7 @@ export const ViewCreatedAtFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -115,19 +109,14 @@ export const ViewCreatedAtFieldFilter = ({
value={dateValue}
onChange={(newValue) => {
if (newValue === null || newValue === undefined) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: null,
});
} else {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: newValue.toISOString(),
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: newValue.toISOString(),
});
}
}}
diff --git a/desktop/src/components/databases/filters/view-date-field-filter.tsx b/desktop/src/components/databases/search/view-date-field-filter.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-date-field-filter.tsx
rename to desktop/src/components/databases/search/view-date-field-filter.tsx
index 6d9103f3..f2ec9dd1 100644
--- a/desktop/src/components/databases/filters/view-date-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-date-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { DateFieldNode, ViewFilterNode } from '@/types/databases';
+import { DateFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -14,40 +14,42 @@ import {
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, dateFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
import { DatePicker } from '@/components/ui/date-picker';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewDateFieldFilterProps {
field: DateFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewDateFieldFilter = ({
field,
filter,
}: ViewDateFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
dateFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? dateFieldFilterOperators[0];
- const dateTextValue =
- filter.values.length > 0 ? filter.values[0].textValue : null;
+ const dateTextValue = filter.value as string | null;
const dateValue = dateTextValue ? new Date(dateTextValue) : null;
const hideInput =
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -78,25 +80,17 @@ export const ViewDateFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : dateValue?.toISOString();
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -108,7 +102,7 @@ export const ViewDateFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -119,19 +113,14 @@ export const ViewDateFieldFilter = ({
value={dateValue}
onChange={(newValue) => {
if (newValue === null || newValue === undefined) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: null,
});
} else {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: newValue.toISOString(),
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: newValue.toISOString(),
});
}
}}
diff --git a/desktop/src/components/databases/filters/view-email-field-filter.tsx b/desktop/src/components/databases/search/view-email-field-filter.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-email-field-filter.tsx
rename to desktop/src/components/databases/search/view-email-field-filter.tsx
index f6c4729a..a5183cb1 100644
--- a/desktop/src/components/databases/filters/view-email-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-email-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { EmailFieldNode, ViewFilterNode } from '@/types/databases';
+import { EmailFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -15,38 +15,40 @@ import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, emailFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewEmailFieldFilterProps {
field: EmailFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewEmailFieldFilter = ({
field,
filter,
}: ViewEmailFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
emailFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? emailFieldFilterOperators[0];
- const textValue =
- filter.values.length > 0 ? filter.values[0].textValue : null;
+ const textValue = filter.value as string | null;
const hideInput =
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -77,25 +79,17 @@ export const ViewEmailFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : textValue;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -107,7 +101,7 @@ export const ViewEmailFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -117,13 +111,9 @@ export const ViewEmailFieldFilter = ({
<SmartTextInput
value={textValue}
onChange={(value) => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: value,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: value,
});
}}
/>
diff --git a/desktop/src/components/databases/filters/view-filter-add-popover.tsx b/desktop/src/components/databases/search/view-filter-add-popover.tsx
similarity index 60%
rename from desktop/src/components/databases/filters/view-filter-add-popover.tsx
rename to desktop/src/components/databases/search/view-filter-add-popover.tsx
index fe2bdb71..258f19c5 100644
--- a/desktop/src/components/databases/filters/view-filter-add-popover.tsx
+++ b/desktop/src/components/databases/search/view-filter-add-popover.tsx
@@ -14,29 +14,25 @@ import {
CommandList,
} from '@/components/ui/command';
import { useDatabase } from '@/contexts/database';
-import { ViewFilterNode } from '@/types/databases';
-import { getFieldFilterOperators, getFieldIcon } from '@/lib/databases';
-import { useViewFilterCreateMutation } from '@/mutations/use-view-filter-create-mutation';
+import { getFieldIcon } from '@/lib/databases';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewFilterAddPopoverProps {
- viewId: string;
- existingFilters: ViewFilterNode[];
children: React.ReactNode;
- onCreate?: () => void;
}
export const ViewFilterAddPopover = ({
- viewId,
- existingFilters,
children,
- onCreate,
}: ViewFilterAddPopoverProps) => {
const database = useDatabase();
- const { mutate, isPending } = useViewFilterCreateMutation();
+ const viewSearch = useViewSearch();
const [open, setOpen] = React.useState(false);
const fieldsWithoutFilters = database.fields.filter(
- (field) => !existingFilters.some((filter) => filter.fieldId === field.id),
+ (field) =>
+ !viewSearch.filters.some(
+ (filter) => filter.type === 'field' && filter.fieldId === field.id,
+ ),
);
if (fieldsWithoutFilters.length === 0) {
@@ -56,24 +52,8 @@ export const ViewFilterAddPopover = ({
<CommandItem
key={field.id}
onSelect={() => {
- if (isPending) {
- return;
- }
-
- const operators = getFieldFilterOperators(field.dataType);
- mutate(
- {
- viewId,
- fieldId: field.id,
- operator: operators[0].value,
- },
- {
- onSuccess: (data) => {
- onCreate?.();
- setOpen(false);
- },
- },
- );
+ viewSearch.initFieldFilter(field.id);
+ setOpen(false);
}}
>
<div className="flex w-full flex-row items-center gap-2">
diff --git a/desktop/src/components/databases/search/view-filter-button.tsx b/desktop/src/components/databases/search/view-filter-button.tsx
new file mode 100644
index 00000000..e4bd0740
--- /dev/null
+++ b/desktop/src/components/databases/search/view-filter-button.tsx
@@ -0,0 +1,27 @@
+import React from 'react';
+import { ViewFilterAddPopover } from '@/components/databases/search/view-filter-add-popover';
+import { Icon } from '@/components/ui/icon';
+import { useViewSearch } from '@/contexts/view-search';
+
+export const ViewFilterButton = () => {
+ const viewSearch = useViewSearch();
+
+ if (viewSearch.filters.length > 0) {
+ return (
+ <button
+ className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50"
+ onClick={() => viewSearch.openSearchBar()}
+ >
+ <Icon name="filter-line" />
+ </button>
+ );
+ }
+
+ return (
+ <ViewFilterAddPopover>
+ <button className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50">
+ <Icon name="filter-line" />
+ </button>
+ </ViewFilterAddPopover>
+ );
+};
diff --git a/desktop/src/components/databases/filters/view-filters.tsx b/desktop/src/components/databases/search/view-filters.tsx
similarity index 72%
rename from desktop/src/components/databases/filters/view-filters.tsx
rename to desktop/src/components/databases/search/view-filters.tsx
index fd9f9656..0f2388d4 100644
--- a/desktop/src/components/databases/filters/view-filters.tsx
+++ b/desktop/src/components/databases/search/view-filters.tsx
@@ -1,31 +1,31 @@
import React from 'react';
-import { ViewFilterNode } from '@/types/databases';
import { useDatabase } from '@/contexts/database';
-import { ViewTextFieldFilter } from '@/components/databases/filters/view-text-field-filter';
-import { ViewNumberFieldFilter } from '@/components/databases/filters/view-number-field-filter';
-import { ViewEmailFieldFilter } from '@/components/databases/filters/view-email-field-filter';
-import { ViewUrlFieldFilter } from '@/components/databases/filters/view-url-field-filter';
-import { ViewPhoneFieldFilter } from '@/components/databases/filters/view-phone-field-filter';
-import { ViewBooleanFieldFilter } from '@/components/databases/filters/view-boolean-field-filter';
-import { ViewSelectFieldFilter } from '@/components/databases/filters/view-select-field-filter';
-import { ViewMultiSelectFieldFilter } from '@/components/databases/filters/view-multi-select-field-filter';
-import { ViewDateFieldFilter } from '@/components/databases/filters/view-date-field-filter';
-import { ViewCreatedAtFieldFilter } from '@/components/databases/filters/view-created-at-field-fitler';
-import { ViewFilterAddPopover } from '@/components/databases/filters/view-filter-add-popover';
+import { ViewTextFieldFilter } from '@/components/databases/search/view-text-field-filter';
+import { ViewNumberFieldFilter } from '@/components/databases/search/view-number-field-filter';
+import { ViewEmailFieldFilter } from '@/components/databases/search/view-email-field-filter';
+import { ViewUrlFieldFilter } from '@/components/databases/search/view-url-field-filter';
+import { ViewPhoneFieldFilter } from '@/components/databases/search/view-phone-field-filter';
+import { ViewBooleanFieldFilter } from '@/components/databases/search/view-boolean-field-filter';
+import { ViewSelectFieldFilter } from '@/components/databases/search/view-select-field-filter';
+import { ViewMultiSelectFieldFilter } from '@/components/databases/search/view-multi-select-field-filter';
+import { ViewDateFieldFilter } from '@/components/databases/search/view-date-field-filter';
+import { ViewCreatedAtFieldFilter } from '@/components/databases/search/view-created-at-field-fitler';
+import { ViewFilterAddPopover } from '@/components/databases/search/view-filter-add-popover';
import { Icon } from '@/components/ui/icon';
+import { useViewSearch } from '@/contexts/view-search';
-interface ViewFiltersProps {
- viewId: string;
- filters: ViewFilterNode[];
-}
-
-export const ViewFilters = ({ viewId, filters }: ViewFiltersProps) => {
+export const ViewFilters = () => {
const database = useDatabase();
+ const viewSearch = useViewSearch();
return (
<div className="flex flex-row items-center gap-2">
- {filters &&
- filters.map((filter) => {
+ {viewSearch.filters &&
+ viewSearch.filters.map((filter) => {
+ if (filter.type === 'group') {
+ return null;
+ }
+
const field = database.fields.find(
(field) => field.id === filter.fieldId,
);
@@ -127,7 +127,7 @@ export const ViewFilters = ({ viewId, filters }: ViewFiltersProps) => {
return null;
}
})}
- <ViewFilterAddPopover viewId={viewId} existingFilters={filters}>
+ <ViewFilterAddPopover>
<button className="flex cursor-pointer flex-row items-center gap-1 rounded-lg p-1 text-sm text-muted-foreground hover:bg-gray-50">
<Icon name="add-line" />
Add filter
diff --git a/desktop/src/components/databases/filters/view-multi-select-field-filter.tsx b/desktop/src/components/databases/search/view-multi-select-field-filter.tsx
similarity index 65%
rename from desktop/src/components/databases/filters/view-multi-select-field-filter.tsx
rename to desktop/src/components/databases/search/view-multi-select-field-filter.tsx
index d54ffc72..42caa61c 100644
--- a/desktop/src/components/databases/filters/view-multi-select-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-multi-select-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { MultiSelectFieldNode, ViewFilterNode } from '@/types/databases';
+import { MultiSelectFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -14,33 +14,27 @@ import {
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, selectFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
import { SelectOptionBadge } from '@/components/databases/fields/select-option-badge';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewMultiSelectFieldFilterProps {
field: MultiSelectFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewMultiSelectFieldFilter = ({
field,
filter,
}: ViewMultiSelectFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
selectFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? selectFieldFilterOperators[0];
- const selectOptionIds = filter.values.map((value) => value.foreignNodeId);
+ const selectOptionIds = (filter.value as string[]) ?? [];
const selectedOptions = field.options.filter((option) =>
selectOptionIds.includes(option.id),
);
@@ -49,7 +43,16 @@ export const ViewMultiSelectFieldFilter = ({
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -80,25 +83,17 @@ export const ViewMultiSelectFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? []
+ : selectOptionIds;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -110,7 +105,7 @@ export const ViewMultiSelectFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -134,22 +129,14 @@ export const ViewMultiSelectFieldFilter = ({
field={field}
values={selectOptionIds}
onSelect={(id) => {
- if (selectOptionIds.includes(id)) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: id,
- });
- } else {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: id,
- foreignNodeId: id,
- textValue: null,
- numberValue: null,
- });
- }
+ const values = selectOptionIds.includes(id)
+ ? selectOptionIds.filter((value) => value !== id)
+ : [...selectOptionIds, id];
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: values,
+ });
}}
allowAdd={false}
/>
diff --git a/desktop/src/components/databases/filters/view-number-field-filter.tsx b/desktop/src/components/databases/search/view-number-field-filter.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-number-field-filter.tsx
rename to desktop/src/components/databases/search/view-number-field-filter.tsx
index 93445e43..84565a20 100644
--- a/desktop/src/components/databases/filters/view-number-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-number-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { NumberFieldNode, ViewFilterNode } from '@/types/databases';
+import { NumberFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -14,39 +14,41 @@ import {
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, numberFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
import { SmartNumberInput } from '@/components/ui/smart-number-input';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewNumberFieldFilterProps {
field: NumberFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewNumberFieldFilter = ({
field,
filter,
}: ViewNumberFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
numberFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? numberFieldFilterOperators[0];
- const numberValue =
- filter.values.length > 0 ? filter.values[0].numberValue : null;
+ const numberValue = filter.value as number | null;
const hideInput =
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -77,25 +79,17 @@ export const ViewNumberFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : numberValue;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -107,7 +101,7 @@ export const ViewNumberFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -117,13 +111,9 @@ export const ViewNumberFieldFilter = ({
<SmartNumberInput
value={numberValue ?? null}
onChange={(value) => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: null,
- numberValue: value,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: value,
});
}}
/>
diff --git a/desktop/src/components/databases/filters/view-phone-field-filter.tsx b/desktop/src/components/databases/search/view-phone-field-filter.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-phone-field-filter.tsx
rename to desktop/src/components/databases/search/view-phone-field-filter.tsx
index ac9c263c..30bbc699 100644
--- a/desktop/src/components/databases/filters/view-phone-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-phone-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { PhoneFieldNode, ViewFilterNode } from '@/types/databases';
+import { PhoneFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -15,38 +15,40 @@ import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { phoneFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewPhoneFieldFilterProps {
field: PhoneFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewPhoneFieldFilter = ({
field,
filter,
}: ViewPhoneFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
phoneFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? phoneFieldFilterOperators[0];
- const phoneValue =
- filter.values.length > 0 ? filter.values[0].textValue : null;
+ const phoneValue = filter.value as string | null;
const hideInput =
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -77,25 +79,17 @@ export const ViewPhoneFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : phoneValue;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -107,7 +101,7 @@ export const ViewPhoneFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -117,13 +111,9 @@ export const ViewPhoneFieldFilter = ({
<SmartTextInput
value={phoneValue}
onChange={(value) => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: value,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: value,
});
}}
/>
diff --git a/desktop/src/components/databases/search/view-search-bar.tsx b/desktop/src/components/databases/search/view-search-bar.tsx
new file mode 100644
index 00000000..d9d3733d
--- /dev/null
+++ b/desktop/src/components/databases/search/view-search-bar.tsx
@@ -0,0 +1,25 @@
+import React from 'react';
+import { ViewSorts } from '@/components/databases/search/view-sorts';
+import { ViewFilters } from '@/components/databases/search/view-filters';
+import { Separator } from '@/components/ui/separator';
+import { useViewSearch } from '@/contexts/view-search';
+
+export const ViewSearchBar = () => {
+ const viewSearch = useViewSearch();
+
+ if (!viewSearch.isSearchBarOpened) {
+ return null;
+ }
+
+ return (
+ <div className="mt-3 flex flex-row items-center gap-2">
+ {viewSearch.sorts.length > 0 && (
+ <React.Fragment>
+ <ViewSorts />
+ <Separator orientation="vertical" className="mx-1 h-4" />
+ </React.Fragment>
+ )}
+ <ViewFilters />
+ </div>
+ );
+};
diff --git a/desktop/src/components/databases/search/view-search-provider.tsx b/desktop/src/components/databases/search/view-search-provider.tsx
new file mode 100644
index 00000000..6b9f05aa
--- /dev/null
+++ b/desktop/src/components/databases/search/view-search-provider.tsx
@@ -0,0 +1,210 @@
+import React from 'react';
+import { ViewSearchContext } from '@/contexts/view-search';
+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';
+
+interface ViewSearchProviderProps {
+ id: string;
+ filters: ViewFilter[];
+ sorts: ViewSort[];
+ children: React.ReactNode;
+}
+
+export const ViewSearchProvider = ({
+ id,
+ filters,
+ sorts,
+ children,
+}: ViewSearchProviderProps) => {
+ const database = useDatabase();
+ const { mutate: setNodeAttribute, isPending: isSetingNodeAttribute } =
+ useNodeAttributeSetMutation();
+
+ const [isSearchBarOpened, setIsSearchBarOpened] = React.useState(false);
+ const [isSortsOpened, setIsSortsOpened] = React.useState(false);
+ const [openedFieldFilters, setOpenedFieldFilters] = React.useState<string[]>(
+ [],
+ );
+
+ return (
+ <ViewSearchContext.Provider
+ value={{
+ id,
+ filters: filters,
+ sorts: sorts,
+ isSaving: isSetingNodeAttribute,
+ isSearchBarOpened: isSearchBarOpened,
+ isSortsOpened: isSortsOpened,
+ isFieldFilterOpened: (fieldId: string) =>
+ openedFieldFilters.includes(fieldId),
+ initFieldFilter: (fieldId: string) => {
+ const field = database.fields.find((field) => field.id === fieldId);
+ if (!field) {
+ return;
+ }
+
+ const existingFieldFilter = filters.find(
+ (filter) => filter.type === 'field' && filter.fieldId === fieldId,
+ );
+
+ if (existingFieldFilter) {
+ if (!openedFieldFilters.includes(fieldId)) {
+ setOpenedFieldFilters((prev) => [...prev, fieldId]);
+ }
+ return;
+ }
+
+ const operators = getFieldFilterOperators(field.dataType);
+ const filter: ViewFieldFilter = {
+ type: 'field',
+ id: NeuronId.generate(NeuronId.Type.ViewFilter),
+ fieldId,
+ operator: operators[0].value,
+ value: null,
+ };
+
+ const newFilters = [...filters, filter];
+ setNodeAttribute(
+ {
+ nodeId: id,
+ key: 'filters',
+ value: newFilters,
+ },
+ {
+ onSuccess: () => {
+ setOpenedFieldFilters((prev) => [...prev, filter.id]);
+ setIsSearchBarOpened(true);
+ },
+ },
+ );
+ },
+ updateFilter: (filterId: string, newFilter: ViewFieldFilter) => {
+ const newFilters = filters.map((filter) =>
+ filter.type === 'field' && filter.id === filterId
+ ? newFilter
+ : filter,
+ );
+
+ setNodeAttribute(
+ {
+ nodeId: id,
+ key: 'filters',
+ value: newFilters,
+ },
+ {
+ onSuccess: () => {
+ setIsSearchBarOpened(true);
+ },
+ },
+ );
+ },
+ removeFilter: (filterId: string) => {
+ const newFilters = filters.filter((filter) => filter.id !== filterId);
+
+ setNodeAttribute(
+ {
+ nodeId: id,
+ key: 'filters',
+ value: newFilters,
+ },
+ {
+ onSuccess: () => {
+ setOpenedFieldFilters((prev) =>
+ prev.filter((id) => id !== filterId),
+ );
+ setIsSearchBarOpened(true);
+ },
+ },
+ );
+ },
+ initFieldSort: (fieldId: string) => {
+ const field = database.fields.find((field) => field.id === fieldId);
+ if (!field) {
+ return;
+ }
+
+ const existingFieldSort = sorts.find(
+ (sort) => sort.fieldId === fieldId,
+ );
+
+ if (existingFieldSort) {
+ if (!isSortsOpened) {
+ setIsSortsOpened(true);
+ setIsSearchBarOpened(true);
+ }
+ return;
+ }
+
+ const sort: ViewSort = {
+ id: NeuronId.generate(NeuronId.Type.ViewFilter),
+ fieldId,
+ direction: 'asc',
+ };
+
+ const newSorts = [...sorts, sort];
+ setNodeAttribute(
+ {
+ nodeId: id,
+ key: 'sorts',
+ value: newSorts,
+ },
+ {
+ onSuccess: () => {
+ setIsSearchBarOpened(true);
+ setIsSortsOpened(true);
+ },
+ },
+ );
+ },
+ updateSort: (sortId: string, newSort: ViewSort) => {
+ const newSorts = sorts.map((sort) =>
+ sort.id === sortId ? newSort : sort,
+ );
+
+ setNodeAttribute(
+ {
+ nodeId: id,
+ key: 'sorts',
+ value: newSorts,
+ },
+ {
+ onSuccess: () => {
+ setIsSortsOpened(true);
+ setIsSearchBarOpened(true);
+ },
+ },
+ );
+ },
+ removeSort: (sortId: string) => {
+ const newSorts = sorts.filter((sort) => sort.id !== sortId);
+
+ setNodeAttribute(
+ {
+ nodeId: id,
+ key: 'sorts',
+ value: newSorts,
+ },
+ {
+ onSuccess: () => {
+ setIsSearchBarOpened(true);
+ },
+ },
+ );
+ },
+ openSearchBar: () => setIsSearchBarOpened(true),
+ closeSearchBar: () => setIsSearchBarOpened(false),
+ openSorts: () => setIsSortsOpened(true),
+ closeSorts: () => setIsSortsOpened(false),
+ openFieldFilter: (fieldId: string) =>
+ setOpenedFieldFilters((prev) => [...prev, fieldId]),
+ closeFieldFilter: (fieldId: string) =>
+ setOpenedFieldFilters((prev) => prev.filter((id) => id !== fieldId)),
+ }}
+ >
+ {children}
+ </ViewSearchContext.Provider>
+ );
+};
diff --git a/desktop/src/components/databases/filters/view-select-field-filter.tsx b/desktop/src/components/databases/search/view-select-field-filter.tsx
similarity index 65%
rename from desktop/src/components/databases/filters/view-select-field-filter.tsx
rename to desktop/src/components/databases/search/view-select-field-filter.tsx
index c244c939..7c7a7cf9 100644
--- a/desktop/src/components/databases/filters/view-select-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-select-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { SelectFieldNode, ViewFilterNode } from '@/types/databases';
+import { SelectFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -14,33 +14,27 @@ import {
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, selectFieldFilterOperators } from '@/lib/databases';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
import { SelectOptionBadge } from '@/components/databases/fields/select-option-badge';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewSelectFieldFilterProps {
field: SelectFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewSelectFieldFilter = ({
field,
filter,
}: ViewSelectFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
selectFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? selectFieldFilterOperators[0];
- const selectOptionIds = filter.values.map((value) => value.foreignNodeId);
+ const selectOptionIds = (filter.value as string[]) ?? [];
const selectedOptions = field.options.filter((option) =>
selectOptionIds.includes(option.id),
);
@@ -49,7 +43,16 @@ export const ViewSelectFieldFilter = ({
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={() => {
+ if (viewSearch.isFieldFilterOpened(filter.id)) {
+ viewSearch.closeFieldFilter(filter.id);
+ } else {
+ viewSearch.openFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -80,25 +83,17 @@ export const ViewSelectFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? []
+ : selectOptionIds;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -110,7 +105,7 @@ export const ViewSelectFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -134,22 +129,14 @@ export const ViewSelectFieldFilter = ({
field={field}
values={selectOptionIds}
onSelect={(id) => {
- if (selectOptionIds.includes(id)) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: id,
- });
- } else {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: id,
- foreignNodeId: id,
- textValue: null,
- numberValue: null,
- });
- }
+ const value = selectOptionIds.includes(id)
+ ? selectOptionIds.filter((optionId) => optionId !== id)
+ : [...selectOptionIds, id];
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: value,
+ });
}}
allowAdd={false}
/>
diff --git a/desktop/src/components/databases/sorts/view-sort-add-popover.tsx b/desktop/src/components/databases/search/view-sort-add-popover.tsx
similarity index 62%
rename from desktop/src/components/databases/sorts/view-sort-add-popover.tsx
rename to desktop/src/components/databases/search/view-sort-add-popover.tsx
index e2d0e746..60294876 100644
--- a/desktop/src/components/databases/sorts/view-sort-add-popover.tsx
+++ b/desktop/src/components/databases/search/view-sort-add-popover.tsx
@@ -15,31 +15,21 @@ import {
} from '@/components/ui/command';
import { useDatabase } from '@/contexts/database';
import { getFieldIcon, isSortableField } from '@/lib/databases';
-import { useViewSortCreateMutation } from '@/mutations/use-view-sort-create-mutation';
-import { SortDirections } from '@/lib/constants';
-import { ViewSortNode } from '@/types/databases';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewSortAddPopoverProps {
- viewId: string;
- existingSorts: ViewSortNode[];
children: React.ReactNode;
- onCreate?: () => void;
}
-export const ViewSortAddPopover = ({
- viewId,
- existingSorts,
- onCreate,
- children,
-}: ViewSortAddPopoverProps) => {
+export const ViewSortAddPopover = ({ children }: ViewSortAddPopoverProps) => {
const database = useDatabase();
- const { mutate, isPending } = useViewSortCreateMutation();
+ const viewSearch = useViewSearch();
const [open, setOpen] = React.useState(false);
const sortableFields = database.fields.filter(
(field) =>
isSortableField(field) &&
- !existingSorts.some((sort) => sort.fieldId === field.id),
+ !viewSearch.sorts.some((sort) => sort.fieldId === field.id),
);
if (sortableFields.length === 0) {
@@ -59,23 +49,8 @@ export const ViewSortAddPopover = ({
<CommandItem
key={field.id}
onSelect={() => {
- if (isPending) {
- return;
- }
-
- mutate(
- {
- viewId,
- fieldId: field.id,
- direction: SortDirections.Ascending,
- },
- {
- onSuccess: () => {
- onCreate?.();
- setOpen(false);
- },
- },
- );
+ viewSearch.initFieldSort(field.id);
+ setOpen(false);
}}
>
<div className="flex w-full flex-row items-center gap-2">
diff --git a/desktop/src/components/databases/search/view-sort-button.tsx b/desktop/src/components/databases/search/view-sort-button.tsx
new file mode 100644
index 00000000..4c8f92de
--- /dev/null
+++ b/desktop/src/components/databases/search/view-sort-button.tsx
@@ -0,0 +1,27 @@
+import React from 'react';
+import { Icon } from '@/components/ui/icon';
+import { ViewSortAddPopover } from '@/components/databases/search/view-sort-add-popover';
+import { useViewSearch } from '@/contexts/view-search';
+
+export const ViewSortButton = () => {
+ const viewSearch = useViewSearch();
+
+ if (viewSearch.sorts.length > 0) {
+ return (
+ <button
+ className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50"
+ onClick={() => viewSearch.openSearchBar()}
+ >
+ <Icon name="sort-desc" />
+ </button>
+ );
+ }
+
+ return (
+ <ViewSortAddPopover>
+ <button className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50">
+ <Icon name="sort-desc" />
+ </button>
+ </ViewSortAddPopover>
+ );
+};
diff --git a/desktop/src/components/databases/sorts/view-sort.tsx b/desktop/src/components/databases/search/view-sort-row.tsx
similarity index 61%
rename from desktop/src/components/databases/sorts/view-sort.tsx
rename to desktop/src/components/databases/search/view-sort-row.tsx
index 2a7bcde0..dbb7653e 100644
--- a/desktop/src/components/databases/sorts/view-sort.tsx
+++ b/desktop/src/components/databases/search/view-sort-row.tsx
@@ -1,6 +1,6 @@
import { Icon } from '@/components/ui/icon';
import { getFieldIcon } from '@/lib/databases';
-import { FieldNode, ViewSortNode } from '@/types/databases';
+import { FieldNode, ViewSort } from '@/types/databases';
import {
DropdownMenu,
DropdownMenuContent,
@@ -9,18 +9,16 @@ import {
} from '@/components/ui/dropdown-menu';
import React from 'react';
import { Button } from '@/components/ui/button';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
-import { AttributeTypes, SortDirections } from '@/lib/constants';
+import { SortDirections } from '@/lib/constants';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewSortProps {
- sort: ViewSortNode;
+ sort: ViewSort;
field: FieldNode;
}
-export const ViewSort = ({ sort, field }: ViewSortProps) => {
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteSort } = useNodeDeleteMutation();
+export const ViewSortRow = ({ sort, field }: ViewSortProps) => {
+ const viewSearch = useViewSearch();
return (
<div className="flex flex-row items-center gap-3 text-sm">
@@ -45,13 +43,9 @@ export const ViewSort = ({ sort, field }: ViewSortProps) => {
<DropdownMenuContent>
<DropdownMenuItem
onClick={() => {
- upsertAttribute({
- nodeId: sort.id,
- type: AttributeTypes.Direction,
- key: '1',
- textValue: SortDirections.Ascending,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateSort(sort.id, {
+ ...sort,
+ direction: 'asc',
});
}}
>
@@ -59,13 +53,9 @@ export const ViewSort = ({ sort, field }: ViewSortProps) => {
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
- upsertAttribute({
- nodeId: sort.id,
- type: AttributeTypes.Direction,
- key: '1',
- textValue: SortDirections.Descending,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateSort(sort.id, {
+ ...sort,
+ direction: 'desc',
});
}}
>
@@ -77,7 +67,7 @@ export const ViewSort = ({ sort, field }: ViewSortProps) => {
variant="ghost"
size="icon"
onClick={() => {
- deleteSort(sort.id);
+ viewSearch.removeSort(sort.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
diff --git a/desktop/src/components/databases/sorts/view-sorts.tsx b/desktop/src/components/databases/search/view-sorts.tsx
similarity index 59%
rename from desktop/src/components/databases/sorts/view-sorts.tsx
rename to desktop/src/components/databases/search/view-sorts.tsx
index a908b650..0a1f68b9 100644
--- a/desktop/src/components/databases/sorts/view-sorts.tsx
+++ b/desktop/src/components/databases/search/view-sorts.tsx
@@ -1,50 +1,50 @@
import React from 'react';
-import { ViewSortNode } from '@/types/databases';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
-import { ViewSort } from '@/components/databases/sorts/view-sort';
+import { ViewSortRow } from '@/components/databases/search/view-sort-row';
import { useDatabase } from '@/contexts/database';
-import { ViewSortAddPopover } from './view-sort-add-popover';
+import { ViewSortAddPopover } from '@/components/databases/search/view-sort-add-popover';
import { Icon } from '@/components/ui/icon';
+import { useViewSearch } from '@/contexts/view-search';
-interface ViewSortsProps {
- viewId: string;
- sorts: ViewSortNode[];
-}
-
-export const ViewSorts = ({ viewId, sorts }: ViewSortsProps) => {
+export const ViewSorts = () => {
const database = useDatabase();
- const [open, setOpen] = React.useState(false);
+ const viewSearch = useViewSearch();
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isSortsOpened}
+ onOpenChange={(open) => {
+ if (open) {
+ viewSearch.openSorts();
+ } else {
+ viewSearch.closeSorts();
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
size="sm"
className="border-dashed text-xs text-muted-foreground"
>
- Sorts ({sorts.length})
+ Sorts ({viewSearch.sorts.length})
</Button>
</PopoverTrigger>
<PopoverContent className="flex flex-col gap-2 p-2">
- {sorts.map((sort) => {
+ {viewSearch.sorts.map((sort) => {
const field = database.fields.find(
(field) => field.id === sort.fieldId,
);
if (!field) return null;
- return <ViewSort key={sort.id} sort={sort} field={field} />;
+ return <ViewSortRow key={sort.id} sort={sort} field={field} />;
})}
- <ViewSortAddPopover
- viewId={viewId}
- existingSorts={sorts}
- onCreate={() => setOpen(true)}
- >
+ <ViewSortAddPopover>
<button className="flex cursor-pointer flex-row items-center gap-1 rounded-lg p-1 text-sm text-muted-foreground hover:bg-gray-50">
<Icon name="add-line" />
Add sort
diff --git a/desktop/src/components/databases/filters/view-text-field-filter.tsx b/desktop/src/components/databases/search/view-text-field-filter.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-text-field-filter.tsx
rename to desktop/src/components/databases/search/view-text-field-filter.tsx
index 0a2874e9..ded513cd 100644
--- a/desktop/src/components/databases/filters/view-text-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-text-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { TextFieldNode, ViewFilterNode } from '@/types/databases';
+import { TextFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -15,38 +15,40 @@ import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { getFieldIcon, textFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewTextFieldFilterProps {
field: TextFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewTextFieldFilter = ({
field,
filter,
}: ViewTextFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
textFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? textFieldFilterOperators[0];
- const textValue =
- filter.values.length > 0 ? filter.values[0].textValue : null;
+ const textValue = filter.value as string | null;
const hideInput =
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={(open) => {
+ if (open) {
+ viewSearch.openFieldFilter(filter.id);
+ } else {
+ viewSearch.closeFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -77,25 +79,17 @@ export const ViewTextFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : textValue;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -107,7 +101,7 @@ export const ViewTextFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -117,13 +111,9 @@ export const ViewTextFieldFilter = ({
<SmartTextInput
value={textValue}
onChange={(value) => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: value,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: value,
});
}}
/>
diff --git a/desktop/src/components/databases/filters/view-url-field-filter.tsx b/desktop/src/components/databases/search/view-url-field-filter.tsx
similarity index 63%
rename from desktop/src/components/databases/filters/view-url-field-filter.tsx
rename to desktop/src/components/databases/search/view-url-field-filter.tsx
index 728be35c..14c0b8e4 100644
--- a/desktop/src/components/databases/filters/view-url-field-filter.tsx
+++ b/desktop/src/components/databases/search/view-url-field-filter.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { UrlFieldNode, ViewFilterNode } from '@/types/databases';
+import { UrlFieldNode, ViewFieldFilter } from '@/types/databases';
import {
Popover,
PopoverContent,
@@ -15,37 +15,40 @@ import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { urlFieldFilterOperators } from '@/lib/databases';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { useNodeDeleteMutation } from '@/mutations/use-node-delete-mutation';
+import { useViewSearch } from '@/contexts/view-search';
interface ViewUrlFieldFilterProps {
field: UrlFieldNode;
- filter: ViewFilterNode;
+ filter: ViewFieldFilter;
}
export const ViewUrlFieldFilter = ({
field,
filter,
}: ViewUrlFieldFilterProps) => {
- const [open, setOpen] = React.useState(false);
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
- const { mutate: deleteFilter } = useNodeDeleteMutation();
+ const viewSearch = useViewSearch();
const operator =
urlFieldFilterOperators.find(
(operator) => operator.value === filter.operator,
) ?? urlFieldFilterOperators[0];
- const urlValue = filter.values.length > 0 ? filter.values[0].textValue : null;
+ const urlValue = filter.value as string | null;
const hideInput =
operator.value === 'is_empty' || operator.value === 'is_not_empty';
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover
+ open={viewSearch.isFieldFilterOpened(filter.id)}
+ onOpenChange={(open) => {
+ if (open) {
+ viewSearch.openFieldFilter(filter.id);
+ } else {
+ viewSearch.closeFieldFilter(filter.id);
+ }
+ }}
+ >
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -76,25 +79,17 @@ export const ViewUrlFieldFilter = ({
<DropdownMenuItem
key={operator.value}
onSelect={() => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Operator,
- key: '1',
- textValue: operator.value,
- numberValue: null,
- foreignNodeId: null,
- });
-
- if (
+ const value =
operator.value === 'is_empty' ||
operator.value === 'is_not_empty'
- ) {
- deleteAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- });
- }
+ ? null
+ : urlValue;
+
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ operator: operator.value,
+ value: value,
+ });
}}
>
{operator.label}
@@ -106,7 +101,7 @@ export const ViewUrlFieldFilter = ({
variant="ghost"
size="icon"
onClick={() => {
- deleteFilter(filter.id);
+ viewSearch.removeFilter(filter.id);
}}
>
<Icon name="delete-bin-line" className="h-4 w-4" />
@@ -116,13 +111,9 @@ export const ViewUrlFieldFilter = ({
<SmartTextInput
value={urlValue}
onChange={(value) => {
- upsertAttribute({
- nodeId: filter.id,
- type: AttributeTypes.Value,
- key: '1',
- textValue: value,
- numberValue: null,
- foreignNodeId: null,
+ viewSearch.updateFilter(filter.id, {
+ ...filter,
+ value: value,
});
}}
/>
diff --git a/desktop/src/components/databases/sorts/view-sort-button.tsx b/desktop/src/components/databases/sorts/view-sort-button.tsx
deleted file mode 100644
index 34d94c10..00000000
--- a/desktop/src/components/databases/sorts/view-sort-button.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import React from 'react';
-import { ViewSortNode } from '@/types/databases';
-import { Icon } from '@/components/ui/icon';
-import { ViewSortAddPopover } from '@/components/databases/sorts/view-sort-add-popover';
-
-interface ViewSortButtonProps {
- viewId: string;
- sorts: ViewSortNode[];
- open: boolean;
- setOpen: (open: boolean) => void;
-}
-
-export const ViewSortButton = ({
- viewId,
- sorts,
- open,
- setOpen,
-}: ViewSortButtonProps) => {
- if (sorts.length > 0) {
- return (
- <button
- className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50"
- onClick={() => setOpen(!open)}
- >
- <Icon name="sort-desc" />
- </button>
- );
- }
-
- return (
- <ViewSortAddPopover
- viewId={viewId}
- existingSorts={sorts}
- onCreate={() => setOpen(true)}
- >
- <button className="flex cursor-pointer items-center rounded-md p-1.5 hover:bg-gray-50">
- <Icon name="sort-desc" />
- </button>
- </ViewSortAddPopover>
- );
-};
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 067d7656..4872af0d 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,21 +1,9 @@
import React from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { BooleanFieldNode, RecordNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-const getBooleanValue = (
- record: RecordNode,
- field: BooleanFieldNode,
-): boolean => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- if (!attribute) {
- return false;
- }
-
- return attribute.numberValue === 1;
-};
-
interface TableViewBooleanCellProps {
record: RecordNode;
field: BooleanFieldNode;
@@ -25,20 +13,20 @@ export const TableViewBooleanCell = ({
record,
field,
}: TableViewBooleanCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const canEdit = true;
const [input, setInput] = React.useState<boolean>(
- getBooleanValue(record, field),
+ (record.attributes[field.id] as boolean) ?? false,
);
React.useEffect(() => {
- setInput(getBooleanValue(record, field));
+ setInput((record.attributes[field.id] as boolean) ?? false);
}, [record.versionId]);
return (
@@ -54,19 +42,15 @@ export const TableViewBooleanCell = ({
setInput(e.valueOf());
const checked = e.valueOf();
if (checked) {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: checked,
});
} else {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
}
}
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 6176d11b..b603ae57 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,17 +1,9 @@
import React from 'react';
import { RecordNode, EmailFieldNode, DateFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
import { DatePicker } from '@/components/ui/date-picker';
-const getDateValue = (
- record: RecordNode,
- field: DateFieldNode,
-): Date | null => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ? new Date(attribute.textValue) : null;
-};
-
interface TableViewDateCellProps {
record: RecordNode;
field: DateFieldNode;
@@ -21,17 +13,17 @@ export const TableViewDateCell = ({
record,
field,
}: TableViewDateCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<DatePicker
- value={getDateValue(record, field)}
+ value={record.attributes[field.id]}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
@@ -39,17 +31,13 @@ export const TableViewDateCell = ({
if (newValue === null || newValue === undefined) {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- textValue: newValue.toISOString(),
- numberValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue.toISOString(),
});
}
}}
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 0947c120..4889e4e3 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,14 +1,9 @@
import React from 'react';
import { RecordNode, EmailFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getEmailValue = (record: RecordNode, field: EmailFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface TableViewEmailCellProps {
record: RecordNode;
field: EmailFieldNode;
@@ -18,17 +13,17 @@ export const TableViewEmailCell = ({
record,
field,
}: TableViewEmailCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
- value={getEmailValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
@@ -37,17 +32,13 @@ export const TableViewEmailCell = ({
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- textValue: newValue,
- numberValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
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 735f6946..0976fe41 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,17 +7,9 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-const getMultiSelectValues = (
- record: RecordNode,
- field: MultiSelectFieldNode,
-): string[] => {
- const attributes = record.attributes.filter((attr) => attr.type === field.id);
- return attributes.map((attr) => attr.foreignNodeId);
-};
-
interface TableViewMultiSelectCellProps {
record: RecordNode;
field: MultiSelectFieldNode;
@@ -27,20 +19,20 @@ export const TableViewMultiSelectCell = ({
record,
field,
}: TableViewMultiSelectCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState(
- getMultiSelectValues(record, field),
+ (record.attributes[field.id] as string[]) ?? [],
);
React.useEffect(() => {
- setSelectedValues(getMultiSelectValues(record, field));
+ setSelectedValues((record.attributes[field.id] as string[]) ?? []);
}, [record.versionId]);
const selectedOptions = field.options?.filter((option) =>
@@ -72,18 +64,15 @@ export const TableViewMultiSelectCell = ({
setSelectedValues(selectedValues.filter((v) => v !== id));
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: id,
+ key: field.id,
});
} else {
- setSelectedValues([...selectedValues, id]);
- upsertNodeAttribute({
+ const values = [...selectedValues, id];
+ setSelectedValues(values);
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: id,
- foreignNodeId: id,
- numberValue: null,
- textValue: null,
+ key: field.id,
+ value: values,
});
}
}}
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 3545ba14..a1d352d7 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,18 +1,10 @@
import React from 'react';
import { RecordNode } from '@/types/databases';
import { NumberFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getNumberValue = (
- record: RecordNode,
- field: NumberFieldNode,
-): number | null => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.numberValue ?? null;
-};
-
interface TableViewNumberCellProps {
record: RecordNode;
field: NumberFieldNode;
@@ -22,40 +14,36 @@ export const TableViewNumberCell = ({
record,
field,
}: TableViewNumberCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartNumberInput
- value={getNumberValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
- if (newValue === getNumberValue(record, field)) {
+ if (newValue === record.attributes[field.id]) {
return;
}
if (newValue === null) {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: newValue,
- textValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
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 6d33aa2a..fc36b3eb 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,14 +1,9 @@
import React from 'react';
import { RecordNode, PhoneFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getPhoneValue = (record: RecordNode, field: PhoneFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface TableViewPhoneCellProps {
record: RecordNode;
field: PhoneFieldNode;
@@ -18,40 +13,36 @@ export const TableViewPhoneCell = ({
record,
field,
}: TableViewPhoneCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
- value={getPhoneValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
- if (newValue === getPhoneValue(record, field)) {
+ if (newValue === record.attributes[field.id]) {
return;
}
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: newValue,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
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 3d7918c0..43d34003 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,17 +7,9 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-const getSelectValue = (
- record: RecordNode,
- field: SelectFieldNode,
-): string | null => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.foreignNodeId ?? null;
-};
-
interface TableViewSelectCellProps {
record: RecordNode;
field: SelectFieldNode;
@@ -27,20 +19,20 @@ export const TableViewSelectCell = ({
record,
field,
}: TableViewSelectCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(
- getSelectValue(record, field) ?? '',
+ record.attributes[field.id] ?? '',
);
React.useEffect(() => {
- setSelectedValue(getSelectValue(record, field) ?? '');
+ setSelectedValue(record.attributes[field.id] ?? '');
}, [record.versionId]);
const selectedOption = field.options?.find(
@@ -75,18 +67,14 @@ export const TableViewSelectCell = ({
setSelectedValue('');
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute(
+ setNodeAttribute(
{
nodeId: record.id,
- type: field.id,
- key: '1',
- foreignNodeId: id,
- textValue: null,
- numberValue: null,
+ key: field.id,
+ value: id,
},
{
onSuccess: () => {
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 22cdd711..6204e6e7 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,14 +1,9 @@
import React from 'react';
import { RecordNode, TextFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getTextValue = (record: RecordNode, field: TextFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface TableViewTextCellProps {
record: RecordNode;
field: TextFieldNode;
@@ -18,40 +13,36 @@ export const TableViewTextCell = ({
record,
field,
}: TableViewTextCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
- value={getTextValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
- if (newValue === getTextValue(record, field)) {
+ if (newValue === record.attributes[field.id]) {
return;
}
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: newValue,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
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 c3978737..1b82dec4 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,29 +7,24 @@ import {
HoverCardTrigger,
} from '@/components/ui/hover-card';
import { Icon } from '@/components/ui/icon';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getUrlValue = (record: RecordNode, field: UrlFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface TableViewUrlCellProps {
record: RecordNode;
field: UrlFieldNode;
}
export const TableViewUrlCell = ({ record, field }: TableViewUrlCellProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
- const text = getUrlValue(record, field);
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const text = record.attributes[field.id];
const isUrl = text.length > 0 && isValidUrl(text);
return (
@@ -49,17 +44,13 @@ export const TableViewUrlCell = ({ record, field }: TableViewUrlCellProps) => {
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: newValue,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
diff --git a/desktop/src/components/databases/tables/table-view-body.tsx b/desktop/src/components/databases/tables/table-view-body.tsx
index 04cf61fc..0512f52f 100644
--- a/desktop/src/components/databases/tables/table-view-body.tsx
+++ b/desktop/src/components/databases/tables/table-view-body.tsx
@@ -4,14 +4,14 @@ 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 { useTableView } from '@/contexts/table-view';
+import { useViewSearch } from '@/contexts/view-search';
export const TableViewBody = () => {
const database = useDatabase();
- const tableView = useTableView();
+ const viewSearch = useViewSearch();
const { data, isPending, isFetchingNextPage, fetchNextPage, hasNextPage } =
- useRecordsQuery(database.id, tableView.filters, tableView.sorts);
+ useRecordsQuery(database.id, viewSearch.filters, viewSearch.sorts);
const records = data ?? [];
return (
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 01cdeb16..19da3e75 100644
--- a/desktop/src/components/databases/tables/table-view-name-cell.tsx
+++ b/desktop/src/components/databases/tables/table-view-name-cell.tsx
@@ -4,8 +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 { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
-import { AttributeTypes } from '@/lib/constants';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
interface NameEditorProps {
initialValue: string;
@@ -55,7 +54,7 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
const workspace = useWorkspace();
const [isEditing, setIsEditing] = React.useState(false);
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate, isPending } = useNodeAttributeSetMutation();
const canEdit = true;
const hasName = record.name && record.name.length > 0;
@@ -63,11 +62,8 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
mutate(
{
nodeId: record.id,
- type: AttributeTypes.Name,
- key: '1',
- textValue: newName,
- numberValue: null,
- foreignNodeId: null,
+ key: 'name',
+ value: newName,
},
{
onSuccess: () => {
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 e6888397..cb09b1ee 100644
--- a/desktop/src/components/databases/tables/table-view-settings-popover.tsx
+++ b/desktop/src/components/databases/tables/table-view-settings-popover.tsx
@@ -16,15 +16,14 @@ import {
TooltipTrigger,
} from '@/components/ui/tooltip';
import { FieldDeleteDialog } from '@/components/databases/fields/field-delete-dialog';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { ViewDeleteDialog } from '@/components/databases/view-delete-dialog';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { AttributeTypes } from '@/lib/constants';
export const TableViewSettingsPopover = () => {
const tableView = useTableView();
const database = useDatabase();
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate, isPending } = useNodeAttributeSetMutation();
const [open, setOpen] = React.useState(false);
const [openDelete, setOpenDelete] = React.useState(false);
@@ -51,11 +50,8 @@ export const TableViewSettingsPopover = () => {
mutate({
nodeId: tableView.id,
- type: AttributeTypes.Name,
- key: '1',
- textValue: newName,
- numberValue: null,
- foreignNodeId: null,
+ key: 'name',
+ value: newName,
});
}}
/>
diff --git a/desktop/src/components/databases/tables/table-view.tsx b/desktop/src/components/databases/tables/table-view.tsx
index ba403f92..0c3b3b50 100644
--- a/desktop/src/components/databases/tables/table-view.tsx
+++ b/desktop/src/components/databases/tables/table-view.tsx
@@ -10,12 +10,12 @@ 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 { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-import { AttributeTypes } from '@/lib/constants';
-import { ViewSortsAndFilters } from '@/components/databases/view-sorts-and-filters';
-import { ViewFilterButton } from '@/components/databases/filters/view-filter.button';
-import { ViewSortButton } from '@/components/databases/sorts/view-sort-button';
+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';
interface TableViewProps {
node: TableViewNode;
@@ -24,8 +24,8 @@ interface TableViewProps {
export const TableView = ({ node }: TableViewProps) => {
const database = useDatabase();
- const { mutate: upsertAttribute } = useNodeAttributeUpsertMutation();
- const { mutate: deleteAttribute } = useNodeAttributeDeleteMutation();
+ const { mutate: setNodeAttribute } = useNodeAttributeSetMutation();
+ const { mutate: deleteNodeAttribute } = useNodeAttributeDeleteMutation();
const [hiddenFields, setHiddenFields] = React.useState<string[]>(
node.hiddenFields ?? [],
@@ -40,8 +40,6 @@ export const TableView = ({ node }: TableViewProps) => {
node.nameWidth ?? getDefaultNameWidth(),
);
- const [openSortsAndFilters, setOpenSortsAndFilters] = React.useState(false);
-
React.useEffect(() => {
setHiddenFields(node.hiddenFields ?? []);
setFieldIndexes(node.fieldIndexes ?? {});
@@ -66,21 +64,17 @@ export const TableView = ({ node }: TableViewProps) => {
id: node.id,
name: node.name,
fields,
- filters: node.filters,
- sorts: node.sorts,
hideField: (id: string) => {
if (hiddenFields.includes(id)) {
return;
}
- setHiddenFields([...hiddenFields, id]);
- upsertAttribute({
+ const newHiddenFields = [...hiddenFields, id];
+ setHiddenFields(newHiddenFields);
+ setNodeAttribute({
nodeId: node.id,
- type: AttributeTypes.HiddenField,
- key: id,
- textValue: id,
- numberValue: null,
- foreignNodeId: id,
+ key: 'hiddenFields',
+ value: newHiddenFields,
});
},
showField: (id: string) => {
@@ -88,24 +82,21 @@ export const TableView = ({ node }: TableViewProps) => {
return;
}
- setHiddenFields((prev) => prev.filter((f) => f !== id));
- deleteAttribute({
+ const newHiddenFields = hiddenFields.filter((f) => f !== id);
+ setHiddenFields(newHiddenFields);
+ deleteNodeAttribute({
nodeId: node.id,
- type: AttributeTypes.HiddenField,
- key: id,
+ key: 'hiddenFields',
});
},
isHiddenField: (id: string) => hiddenFields.includes(id),
getNameWidth: () => nameWidth,
resizeName: (width: number) => {
setNameWidth(width);
- upsertAttribute({
+ setNodeAttribute({
nodeId: node.id,
- type: AttributeTypes.NameWidth,
- key: '1',
- numberValue: width,
- foreignNodeId: null,
- textValue: null,
+ key: 'nameWidth',
+ value: width,
});
},
getFieldWidth: (id: string, type: FieldDataType) => {
@@ -113,13 +104,10 @@ export const TableView = ({ node }: TableViewProps) => {
},
resizeField: (id, width) => {
setFieldWidths({ ...fieldWidths, [id]: width });
- upsertAttribute({
+ setNodeAttribute({
nodeId: node.id,
- type: AttributeTypes.FieldWidth,
- key: id,
- numberValue: width,
- foreignNodeId: id,
- textValue: null,
+ key: 'fieldWidths',
+ value: { ...fieldWidths, [id]: width },
});
},
moveField: (id, after) => {
@@ -190,47 +178,34 @@ export const TableView = ({ node }: TableViewProps) => {
...fieldIndexes,
[id]: newIndex,
});
- upsertAttribute({
+ setNodeAttribute({
nodeId: node.id,
- type: AttributeTypes.FieldIndex,
- key: id,
- textValue: newIndex,
- foreignNodeId: id,
- numberValue: null,
+ key: 'fieldIndexes',
+ value: { ...fieldIndexes, [id]: newIndex },
});
},
}}
>
- <div className="mt-2 flex flex-row justify-between border-b">
- <ViewTabs />
- <div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
- <TableViewSettingsPopover />
- <ViewSortButton
- viewId={node.id}
- sorts={node.sorts}
- open={openSortsAndFilters}
- setOpen={setOpenSortsAndFilters}
- />
- <ViewFilterButton
- viewId={node.id}
- filters={node.filters}
- open={openSortsAndFilters}
- setOpen={setOpenSortsAndFilters}
- />
+ <ViewSearchProvider
+ id={node.id}
+ filters={node.filters}
+ sorts={node.sorts}
+ >
+ <div className="mt-2 flex flex-row justify-between border-b">
+ <ViewTabs />
+ <div className="invisible flex flex-row items-center justify-end group-hover/database:visible">
+ <TableViewSettingsPopover />
+ <ViewSortButton />
+ <ViewFilterButton />
+ </div>
+ </div>
+ <ViewSearchBar />
+ <div className="mt-2 w-full min-w-full max-w-full overflow-auto pr-5">
+ <TableViewHeader />
+ <TableViewBody />
+ <TableViewRecordCreateRow />
</div>
- </div>
- {openSortsAndFilters && (
- <ViewSortsAndFilters
- viewId={node.id}
- filters={node.filters}
- sorts={node.sorts}
- />
- )}
- <div className="mt-2 w-full min-w-full max-w-full overflow-auto pr-5">
- <TableViewHeader />
- <TableViewBody />
- <TableViewRecordCreateRow />
- </div>
+ </ViewSearchProvider>
</TableViewContext.Provider>
);
};
diff --git a/desktop/src/components/databases/view-sorts-and-filters.tsx b/desktop/src/components/databases/view-sorts-and-filters.tsx
deleted file mode 100644
index dcccb665..00000000
--- a/desktop/src/components/databases/view-sorts-and-filters.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import React from 'react';
-import { ViewSorts } from '@/components/databases/sorts/view-sorts';
-import { ViewFilters } from '@/components/databases/filters/view-filters';
-import { ViewFilterNode, ViewSortNode } from '@/types/databases';
-import { Separator } from '@/components/ui/separator';
-
-interface ViewSortsAndFiltersProps {
- viewId: string;
- filters: ViewFilterNode[];
- sorts: ViewSortNode[];
-}
-
-export const ViewSortsAndFilters = ({
- viewId,
- filters,
- sorts,
-}: ViewSortsAndFiltersProps) => {
- return (
- <div className="mt-3 flex flex-row items-center gap-2">
- {sorts.length > 0 && (
- <React.Fragment>
- <ViewSorts viewId={viewId} sorts={sorts} />
- <Separator orientation="vertical" className="mx-1 h-4" />
- </React.Fragment>
- )}
- <ViewFilters viewId={viewId} filters={filters} />
- </div>
- );
-};
diff --git a/desktop/src/components/documents/document-editor.tsx b/desktop/src/components/documents/document-editor.tsx
index 44fb83ae..9da26a7d 100644
--- a/desktop/src/components/documents/document-editor.tsx
+++ b/desktop/src/components/documents/document-editor.tsx
@@ -49,13 +49,13 @@ import {
} from '@/editor/extensions';
import { EditorBubbleMenu } from '@/editor/menu/bubble-menu';
-import { LocalNode, LocalNodeWithAttributes } from '@/types/nodes';
+import { LocalNode } from '@/types/nodes';
import { useWorkspace } from '@/contexts/workspace';
import { EditorObserver } from '@/editor/observer';
interface DocumentEditorProps {
node: LocalNode;
- nodes: Map<string, LocalNodeWithAttributes>;
+ nodes: Map<string, LocalNode>;
}
export const DocumentEditor = ({ node, nodes }: DocumentEditorProps) => {
diff --git a/desktop/src/components/records/record-name.tsx b/desktop/src/components/records/record-name.tsx
index 0b4dcc19..35d59a92 100644
--- a/desktop/src/components/records/record-name.tsx
+++ b/desktop/src/components/records/record-name.tsx
@@ -1,15 +1,14 @@
import React from 'react';
import { RecordNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { AttributeTypes } from '@/lib/constants';
interface RecordNameProps {
record: RecordNode;
}
export const RecordName = ({ record }: RecordNameProps) => {
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate, isPending } = useNodeAttributeSetMutation();
return (
<SmartTextInput
@@ -25,11 +24,8 @@ export const RecordName = ({ record }: RecordNameProps) => {
mutate({
nodeId: record.id,
- type: AttributeTypes.Name,
- key: '1',
- textValue: value,
- numberValue: null,
- foreignNodeId: null,
+ key: 'name',
+ value: value,
});
}}
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 d8ec7d8c..1bc538c6 100644
--- a/desktop/src/components/records/values/record-boolean-value.tsx
+++ b/desktop/src/components/records/values/record-boolean-value.tsx
@@ -1,21 +1,9 @@
import React from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { BooleanFieldNode, RecordNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-const getBooleanValue = (
- record: RecordNode,
- field: BooleanFieldNode,
-): boolean => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- if (!attribute) {
- return false;
- }
-
- return attribute.numberValue === 1;
-};
-
interface RecordBooleanValueProps {
record: RecordNode;
field: BooleanFieldNode;
@@ -25,20 +13,20 @@ export const RecordBooleanValue = ({
record,
field,
}: RecordBooleanValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const canEdit = true;
const [input, setInput] = React.useState<boolean>(
- getBooleanValue(record, field),
+ (record.attributes[field.id] as boolean) ?? false,
);
React.useEffect(() => {
- setInput(getBooleanValue(record, field));
+ setInput((record.attributes[field.id] as boolean) ?? false);
}, [record.versionId]);
return (
@@ -54,19 +42,15 @@ export const RecordBooleanValue = ({
setInput(e.valueOf());
const checked = e.valueOf();
if (checked) {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: checked,
});
} else {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
}
}
diff --git a/desktop/src/components/records/values/record-email-value.tsx b/desktop/src/components/records/values/record-email-value.tsx
index 96f07854..530779d5 100644
--- a/desktop/src/components/records/values/record-email-value.tsx
+++ b/desktop/src/components/records/values/record-email-value.tsx
@@ -1,31 +1,26 @@
import React from 'react';
import { RecordNode, EmailFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getEmailValue = (record: RecordNode, field: EmailFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface RecordEmailValueProps {
record: RecordNode;
field: EmailFieldNode;
}
export const RecordEmailValue = ({ record, field }: RecordEmailValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
- value={getEmailValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
@@ -34,17 +29,13 @@ export const RecordEmailValue = ({ record, field }: RecordEmailValueProps) => {
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- textValue: newValue,
- numberValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
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 3b8f1363..8b14d839 100644
--- a/desktop/src/components/records/values/record-multi-select-value.tsx
+++ b/desktop/src/components/records/values/record-multi-select-value.tsx
@@ -7,17 +7,9 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-const getMultiSelectValues = (
- record: RecordNode,
- field: MultiSelectFieldNode,
-): string[] => {
- const attributes = record.attributes.filter((attr) => attr.type === field.id);
- return attributes.map((attr) => attr.foreignNodeId);
-};
-
interface RecordMultiSelectValueProps {
record: RecordNode;
field: MultiSelectFieldNode;
@@ -27,20 +19,20 @@ export const RecordMultiSelectValue = ({
record,
field,
}: RecordMultiSelectValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState(
- getMultiSelectValues(record, field),
+ (record.attributes[field.id] as string[]) ?? [],
);
React.useEffect(() => {
- setSelectedValues(getMultiSelectValues(record, field));
+ setSelectedValues((record.attributes[field.id] as string[]) ?? []);
}, [record.versionId]);
const selectedOptions = field.options?.filter((option) =>
@@ -69,21 +61,19 @@ export const RecordMultiSelectValue = ({
if (isPending) return;
if (selectedValues.includes(id)) {
- setSelectedValues(selectedValues.filter((v) => v !== id));
+ const values = selectedValues.filter((v) => v !== id);
+ setSelectedValues(values);
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: id,
+ key: field.id,
});
} else {
- setSelectedValues([...selectedValues, id]);
- upsertNodeAttribute({
+ const values = [...selectedValues, id];
+ setSelectedValues(values);
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: id,
- foreignNodeId: id,
- numberValue: null,
- textValue: null,
+ key: field.id,
+ value: values,
});
}
}}
diff --git a/desktop/src/components/records/values/record-number-value.tsx b/desktop/src/components/records/values/record-number-value.tsx
index b7bd647e..406acb54 100644
--- a/desktop/src/components/records/values/record-number-value.tsx
+++ b/desktop/src/components/records/values/record-number-value.tsx
@@ -1,18 +1,10 @@
import React from 'react';
import { RecordNode } from '@/types/databases';
import { NumberFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getNumberValue = (
- record: RecordNode,
- field: NumberFieldNode,
-): number | null => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.numberValue ?? null;
-};
-
interface RecordNumberValueProps {
record: RecordNode;
field: NumberFieldNode;
@@ -22,40 +14,36 @@ export const RecordNumberValue = ({
record,
field,
}: RecordNumberValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartNumberInput
- value={getNumberValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
- if (newValue === getNumberValue(record, field)) {
+ if (newValue === record.attributes[field.id]) {
return;
}
if (newValue === null) {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: newValue,
- textValue: null,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
diff --git a/desktop/src/components/records/values/record-phone-value.tsx b/desktop/src/components/records/values/record-phone-value.tsx
index bd3f0205..0c42a11b 100644
--- a/desktop/src/components/records/values/record-phone-value.tsx
+++ b/desktop/src/components/records/values/record-phone-value.tsx
@@ -1,54 +1,45 @@
import React from 'react';
import { RecordNode, PhoneFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getPhoneValue = (record: RecordNode, field: PhoneFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface RecordPhoneValueProps {
record: RecordNode;
field: PhoneFieldNode;
}
export const RecordPhoneValue = ({ record, field }: RecordPhoneValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
- value={getPhoneValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
- if (newValue === getPhoneValue(record, field)) {
+ if (newValue === record.attributes[field.id]) {
return;
}
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: newValue,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
diff --git a/desktop/src/components/records/values/record-select-value.tsx b/desktop/src/components/records/values/record-select-value.tsx
index b9604623..b06e9f0a 100644
--- a/desktop/src/components/records/values/record-select-value.tsx
+++ b/desktop/src/components/records/values/record-select-value.tsx
@@ -7,17 +7,9 @@ import {
PopoverContent,
} from '@/components/ui/popover';
import { SelectFieldOptions } from '@/components/databases/fields/select-field-options';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { useNodeAttributeDeleteMutation } from '@/mutations/use-node-attribute-delete-mutation';
-const getSelectValue = (
- record: RecordNode,
- field: SelectFieldNode,
-): string | null => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.foreignNodeId ?? null;
-};
-
interface RecordSelectValueProps {
record: RecordNode;
field: SelectFieldNode;
@@ -27,20 +19,20 @@ export const RecordSelectValue = ({
record,
field,
}: RecordSelectValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(
- getSelectValue(record, field) ?? '',
+ record.attributes[field.id] ?? '',
);
React.useEffect(() => {
- setSelectedValue(getSelectValue(record, field) ?? '');
+ setSelectedValue(record.attributes[field.id] ?? '');
}, [record.versionId]);
const selectedOption = field.options?.find(
@@ -74,18 +66,14 @@ export const RecordSelectValue = ({
setSelectedValue('');
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute(
+ setNodeAttribute(
{
nodeId: record.id,
- type: field.id,
- key: '1',
- foreignNodeId: id,
- textValue: null,
- numberValue: null,
+ key: field.id,
+ value: id,
},
{
onSuccess: () => {
diff --git a/desktop/src/components/records/values/record-text-value.tsx b/desktop/src/components/records/values/record-text-value.tsx
index 9f407ee5..1ddc4875 100644
--- a/desktop/src/components/records/values/record-text-value.tsx
+++ b/desktop/src/components/records/values/record-text-value.tsx
@@ -1,54 +1,45 @@
import React from 'react';
import { RecordNode, TextFieldNode } from '@/types/databases';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getTextValue = (record: RecordNode, field: TextFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface RecordTextValueProps {
record: RecordNode;
field: TextFieldNode;
}
export const RecordTextValue = ({ record, field }: RecordTextValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
return (
<SmartTextInput
- value={getTextValue(record, field)}
+ value={record.attributes[field.id]}
readOnly={!canEdit || isPending}
onChange={(newValue) => {
if (isPending) return;
if (!canEdit) return;
- if (newValue === getTextValue(record, field)) {
+ if (newValue === record.attributes[field.id]) {
return;
}
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: newValue,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
diff --git a/desktop/src/components/records/values/record-url-value.tsx b/desktop/src/components/records/values/record-url-value.tsx
index 28fca28b..4b49b704 100644
--- a/desktop/src/components/records/values/record-url-value.tsx
+++ b/desktop/src/components/records/values/record-url-value.tsx
@@ -7,29 +7,24 @@ import {
HoverCardTrigger,
} from '@/components/ui/hover-card';
import { Icon } from '@/components/ui/icon';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+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';
-const getUrlValue = (record: RecordNode, field: UrlFieldNode): string => {
- const attribute = record.attributes.find((attr) => attr.type === field.id);
- return attribute?.textValue ?? '';
-};
-
interface RecordUrlValueProps {
record: RecordNode;
field: UrlFieldNode;
}
export const RecordUrlValue = ({ record, field }: RecordUrlValueProps) => {
- const { mutate: upsertNodeAttribute, isPending: isUpsertingNodeAttribute } =
- useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
const { mutate: deleteNodeAttribute, isPending: isDeletingNodeAttribute } =
useNodeAttributeDeleteMutation();
const canEdit = true;
- const isPending = isUpsertingNodeAttribute || isDeletingNodeAttribute;
- const text = getUrlValue(record, field);
+ const isPending = isSettingNodeAttribute || isDeletingNodeAttribute;
+ const text = record.attributes[field.id];
const isUrl = text.length > 0 && isValidUrl(text);
return (
@@ -49,17 +44,13 @@ export const RecordUrlValue = ({ record, field }: RecordUrlValueProps) => {
if (newValue === null || newValue === '') {
deleteNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
+ key: field.id,
});
} else {
- upsertNodeAttribute({
+ setNodeAttribute({
nodeId: record.id,
- type: field.id,
- key: '1',
- numberValue: 1,
- textValue: newValue,
- foreignNodeId: null,
+ key: field.id,
+ value: newValue,
});
}
}}
diff --git a/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx b/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
index 1c60c1ee..712759fd 100644
--- a/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
+++ b/desktop/src/components/workspaces/containers/breadcrumb-item-editor.tsx
@@ -1,31 +1,28 @@
import React from 'react';
import { BreadcrumbNode } from '@/types/workspaces';
-import { useNodeAttributeUpsertMutation } from '@/mutations/use-node-attribute-upsert-mutation';
+import { useNodeAttributeSetMutation } from '@/mutations/use-node-attribute-set-mutation';
import { SmartTextInput } from '@/components/ui/smart-text-input';
-import { AttributeTypes } from '@/lib/constants';
interface BreadcrumbItemEditorProps {
node: BreadcrumbNode;
}
export const BreadcrumbItemEditor = ({ node }: BreadcrumbItemEditorProps) => {
- const { mutate, isPending } = useNodeAttributeUpsertMutation();
+ const { mutate: setNodeAttribute, isPending: isSettingNodeAttribute } =
+ useNodeAttributeSetMutation();
return (
<div>
<SmartTextInput
value={node.name}
onChange={(newName) => {
- if (isPending) return;
+ if (isSettingNodeAttribute) return;
if (newName === node.name) return;
- mutate({
+ setNodeAttribute({
nodeId: node.id,
- type: AttributeTypes.Name,
- key: '1',
- textValue: newName,
- numberValue: null,
- foreignNodeId: null,
+ key: 'name',
+ value: newName,
});
}}
/>
diff --git a/desktop/src/contexts/table-view.ts b/desktop/src/contexts/table-view.ts
index 3bf8486a..8ebca77f 100644
--- a/desktop/src/contexts/table-view.ts
+++ b/desktop/src/contexts/table-view.ts
@@ -1,17 +1,10 @@
-import {
- FieldNode,
- FieldDataType,
- ViewFilterNode,
- ViewSortNode,
-} from '@/types/databases';
+import { FieldNode, FieldDataType } from '@/types/databases';
import { createContext, useContext } from 'react';
interface TableViewContext {
id: string;
name: string;
fields: FieldNode[];
- filters: ViewFilterNode[];
- sorts: ViewSortNode[];
hideField: (id: string) => void;
showField: (id: string) => void;
isHiddenField: (id: string) => boolean;
diff --git a/desktop/src/contexts/view-search.ts b/desktop/src/contexts/view-search.ts
new file mode 100644
index 00000000..f7d5d472
--- /dev/null
+++ b/desktop/src/contexts/view-search.ts
@@ -0,0 +1,30 @@
+import { ViewFilter, ViewSort } from '@/types/databases';
+import { createContext, useContext } from 'react';
+
+interface ViewSearchContext {
+ id: string;
+ filters: ViewFilter[];
+ sorts: ViewSort[];
+ isSaving: boolean;
+ isSearchBarOpened: boolean;
+ isSortsOpened: boolean;
+ isFieldFilterOpened: (fieldId: string) => boolean;
+ initFieldFilter: (fieldId: string) => void;
+ updateFilter: (id: string, filter: ViewFilter) => void;
+ removeFilter: (id: string) => void;
+ initFieldSort: (fieldId: string) => void;
+ updateSort: (id: string, sort: ViewSort) => void;
+ removeSort: (id: string) => void;
+ openSearchBar: () => void;
+ closeSearchBar: () => void;
+ openSorts: () => void;
+ closeSorts: () => void;
+ openFieldFilter: (fieldId: string) => void;
+ closeFieldFilter: (fieldId: string) => void;
+}
+
+export const ViewSearchContext = createContext<ViewSearchContext>(
+ {} as ViewSearchContext,
+);
+
+export const useViewSearch = () => useContext(ViewSearchContext);
diff --git a/desktop/src/data/migrations/workspace.ts b/desktop/src/data/migrations/workspace.ts
index 4b1441ef..05235c8d 100644
--- a/desktop/src/data/migrations/workspace.ts
+++ b/desktop/src/data/migrations/workspace.ts
@@ -2,27 +2,27 @@ import { Migration, sql } from 'kysely';
const createNodesTable: Migration = {
up: async (db) => {
- await db.schema
- .createTable('nodes')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('parent_id', 'text', (col) =>
- col.references('nodes.id').onDelete('cascade'),
+ await sql`
+ CREATE TABLE nodes (
+ id TEXT PRIMARY KEY NOT NULL,
+ type TEXT GENERATED ALWAYS AS (json_extract(attributes, '$.type')) STORED NOT NULL,
+ parent_id TEXT GENERATED ALWAYS AS (json_extract(attributes, '$.parentId')) STORED REFERENCES nodes(id) ON DELETE CASCADE,
+ "index" TEXT GENERATED ALWAYS AS (json_extract(attributes, '$.index')) STORED,
+ attributes TEXT NOT NULL,
+ state TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT,
+ created_by TEXT NOT NULL,
+ updated_by TEXT,
+ version_id TEXT NOT NULL,
+ server_created_at TEXT,
+ server_updated_at TEXT,
+ server_version_id TEXT
)
- .addColumn('type', 'text', (col) => col.notNull())
- .addColumn('index', 'text')
- .addColumn('content', 'text')
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('updated_by', 'text')
- .addColumn('version_id', 'text', (col) => col.notNull())
- .addColumn('server_created_at', 'text')
- .addColumn('server_updated_at', 'text')
- .addColumn('server_version_id', 'text')
- .execute();
+ `.execute(db);
},
down: async (db) => {
- await db.schema.dropTable('nodes').execute();
+ await sql`DROP TABLE IF EXISTS nodes`.execute(db);
},
};
@@ -37,40 +37,6 @@ const createNodesParentIdAndTypeIndex: Migration = {
},
};
-const createNodeAttributesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('node_attributes')
- .addColumn('node_id', 'text', (col) =>
- col.references('nodes.id').onDelete('cascade'),
- )
- .addColumn('type', 'text', (col) => col.notNull())
- .addColumn('key', 'text', (col) => col.notNull())
- .addColumn('text_value', 'text')
- .addColumn('number_value', 'real')
- .addColumn('foreign_node_id', 'text', (col) =>
- col.references('nodes.id').onDelete('cascade'),
- )
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('updated_by', 'text')
- .addColumn('version_id', 'text', (col) => col.notNull())
- .addColumn('server_created_at', 'text')
- .addColumn('server_updated_at', 'text')
- .addColumn('server_version_id', 'text')
- .addPrimaryKeyConstraint('node_attributes_pkey', [
- 'node_id',
- 'type',
- 'key',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('node_attributes').execute();
- },
-};
-
const createNodeReactionsTable: Migration = {
up: async (db) => {
await db.schema
@@ -127,10 +93,11 @@ const createNodesInsertTrigger: Migration = {
'nodes',
json_object(
'id', NEW.'id',
- 'parent_id', NEW.'parent_id',
'type', NEW.'type',
+ 'parent_id', NEW.'parent_id',
'index', NEW.'index',
- 'content', NEW.'content',
+ 'attributes', NEW.'attributes',
+ 'state', NEW.'state',
'created_at', NEW.'created_at',
'updated_at', NEW.'updated_at',
'created_by', NEW.'created_by',
@@ -164,10 +131,11 @@ const createNodesUpdateTrigger: Migration = {
'nodes',
json_object(
'id', OLD.'id',
- 'parent_id', OLD.'parent_id',
'type', OLD.'type',
+ 'parent_id', OLD.'parent_id',
'index', OLD.'index',
- 'content', OLD.'content',
+ 'attributes', OLD.'attributes',
+ 'state', OLD.'state',
'created_at', OLD.'created_at',
'updated_at', OLD.'updated_at',
'created_by', OLD.'created_by',
@@ -179,10 +147,11 @@ const createNodesUpdateTrigger: Migration = {
),
json_object(
'id', NEW.'id',
- 'parent_id', NEW.'parent_id',
'type', NEW.'type',
+ 'parent_id', NEW.'parent_id',
'index', NEW.'index',
- 'content', NEW.'content',
+ 'attributes', NEW.'attributes',
+ 'state', NEW.'state',
'created_at', NEW.'created_at',
'updated_at', NEW.'updated_at',
'created_by', NEW.'created_by',
@@ -215,10 +184,11 @@ const createDeleteNodesTrigger: Migration = {
'nodes',
json_object(
'id', OLD.'id',
- 'parent_id', OLD.'parent_id',
'type', OLD.'type',
+ 'parent_id', OLD.'parent_id',
'index', OLD.'index',
- 'content', OLD.'content',
+ 'attributes', OLD.'attributes',
+ 'state', OLD.'state',
'created_at', OLD.'created_at',
'updated_at', OLD.'updated_at',
'created_by', OLD.'created_by',
@@ -238,133 +208,6 @@ const createDeleteNodesTrigger: Migration = {
},
};
-const createNodeAttributesInsertTrigger: Migration = {
- up: async (db) => {
- await sql`
- CREATE TRIGGER after_insert_node_attributes
- AFTER INSERT ON node_attributes
- FOR EACH ROW
- BEGIN
- INSERT INTO mutations ('action', 'table', 'after', 'created_at')
- VALUES (
- 'insert',
- 'node_attributes',
- json_object(
- 'node_id', NEW.'node_id',
- 'type', NEW.'type',
- 'key', NEW.'key',
- 'text_value', NEW.'text_value',
- 'number_value', NEW.'number_value',
- 'foreign_node_id', NEW.'foreign_node_id',
- 'created_at', NEW.'created_at',
- 'updated_at', NEW.'updated_at',
- 'created_by', NEW.'created_by',
- 'updated_by', NEW.'updated_by',
- 'version_id', NEW.'version_id',
- 'server_created_at', NEW.'server_created_at',
- 'server_updated_at', NEW.'server_updated_at',
- 'server_version_id', NEW.'server_version_id'
- ),
- datetime('now')
- );
- END;
- `.execute(db);
- },
- down: async (db) => {
- await sql`DROP TRIGGER after_insert_node_attributes`.execute(db);
- },
-};
-
-const createNodeAttributesUpdateTrigger: Migration = {
- up: async (db) => {
- await sql`
- CREATE TRIGGER after_update_node_attributes
- AFTER UPDATE ON node_attributes
- FOR EACH ROW
- BEGIN
- INSERT INTO mutations ('action', 'table', 'before', 'after', 'created_at')
- VALUES (
- 'update',
- 'node_attributes',
- json_object(
- 'node_id', OLD.'node_id',
- 'type', OLD.'type',
- 'key', OLD.'key',
- 'text_value', OLD.'text_value',
- 'number_value', OLD.'number_value',
- 'foreign_node_id', OLD.'foreign_node_id',
- 'created_at', OLD.'created_at',
- 'updated_at', OLD.'updated_at',
- 'created_by', OLD.'created_by',
- 'updated_by', OLD.'updated_by',
- 'version_id', OLD.'version_id',
- 'server_created_at', OLD.'server_created_at',
- 'server_updated_at', OLD.'server_updated_at',
- 'server_version_id', OLD.'server_version_id'
- ),
- json_object(
- 'node_id', NEW.'node_id',
- 'type', NEW.'type',
- 'key', NEW.'key',
- 'text_value', NEW.'text_value',
- 'number_value', NEW.'number_value',
- 'foreign_node_id', NEW.'foreign_node_id',
- 'created_at', NEW.'created_at',
- 'updated_at', NEW.'updated_at',
- 'created_by', NEW.'created_by',
- 'updated_by', NEW.'updated_by',
- 'version_id', NEW.'version_id',
- 'server_created_at', NEW.'server_created_at',
- 'server_updated_at', NEW.'server_updated_at',
- 'server_version_id', NEW.'server_version_id'
- ),
- datetime('now')
- );
- END;
- `.execute(db);
- },
- down: async (db) => {
- await sql`DROP TRIGGER after_update_node_attributes`.execute(db);
- },
-};
-
-const createNodeAttributesDeleteTrigger: Migration = {
- up: async (db) => {
- await sql`
- CREATE TRIGGER after_delete_node_attributes
- AFTER DELETE ON node_attributes
- FOR EACH ROW
- BEGIN
- INSERT INTO mutations ('action', 'table', 'before', 'created_at')
- VALUES (
- 'delete',
- 'node_attributes',
- json_object(
- 'node_id', OLD.'node_id',
- 'type', OLD.'type',
- 'key', OLD.'key',
- 'text_value', OLD.'text_value',
- 'number_value', OLD.'number_value',
- 'foreign_node_id', OLD.'foreign_node_id',
- 'created_at', OLD.'created_at',
- 'updated_at', OLD.'updated_at',
- 'created_by', OLD.'created_by',
- 'updated_by', OLD.'updated_by',
- 'version_id', OLD.'version_id',
- 'server_created_at', OLD.'server_created_at',
- 'server_updated_at', OLD.'server_updated_at',
- 'server_version_id', OLD.'server_version_id'
- ),
- datetime('now')
- );
- END;
- `.execute(db);
- },
- down: async (db) => {
- await sql`DROP TRIGGER after_delete_node_attributes`.execute(db);
- },
-};
-
const createNodeReactionsInsertTrigger: Migration = {
up: async (db) => {
await sql`
@@ -426,20 +269,13 @@ export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00001_create_nodes_table': createNodesTable,
'00002_create_nodes_parent_id_and_type_index':
createNodesParentIdAndTypeIndex,
- '00003_create_node_attributes_table': createNodeAttributesTable,
- '00004_create_mutations_table': createMutationsTable,
- '00005_create_node_insert_trigger': createNodesInsertTrigger,
- '00006_create_node_update_trigger': createNodesUpdateTrigger,
- '00007_create_node_delete_trigger': createDeleteNodesTrigger,
- '00008_create_node_attributes_insert_trigger':
- createNodeAttributesInsertTrigger,
- '00009_create_node_attributes_update_trigger':
- createNodeAttributesUpdateTrigger,
- '00010_create_node_attributes_delete_trigger':
- createNodeAttributesDeleteTrigger,
- '00011_create_node_reactions_table': createNodeReactionsTable,
- '00012_create_node_reactions_insert_trigger':
+ '00003_create_mutations_table': createMutationsTable,
+ '00004_create_node_insert_trigger': createNodesInsertTrigger,
+ '00005_create_node_update_trigger': createNodesUpdateTrigger,
+ '00006_create_node_delete_trigger': createDeleteNodesTrigger,
+ '00007_create_node_reactions_table': createNodeReactionsTable,
+ '00008_create_node_reactions_insert_trigger':
createNodeReactionsInsertTrigger,
- '00013_create_node_reactions_delete_trigger':
+ '00009_create_node_reactions_delete_trigger':
createNodeReactionsDeleteTrigger,
};
diff --git a/desktop/src/data/schemas/workspace.ts b/desktop/src/data/schemas/workspace.ts
index eba3fab5..c326ba36 100644
--- a/desktop/src/data/schemas/workspace.ts
+++ b/desktop/src/data/schemas/workspace.ts
@@ -2,10 +2,11 @@ import { ColumnType, Insertable, Selectable, Updateable } from 'kysely';
interface NodeTable {
id: ColumnType<string, string, never>;
- parent_id: ColumnType<string, string, string>;
- type: ColumnType<string, string, string>;
- index: ColumnType<string | null, string | null, string | null>;
- content: ColumnType<string | null, string | null, string | null>;
+ parent_id: ColumnType<string | null, never, never>;
+ type: ColumnType<string, never, never>;
+ index: ColumnType<string | null, never, never>;
+ attributes: ColumnType<string, string, string>;
+ state: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
created_by: ColumnType<string, string, never>;
@@ -19,30 +20,6 @@ interface NodeTable {
export type SelectNode = Selectable<NodeTable>;
export type CreateNode = Insertable<NodeTable>;
export type UpdateNode = Updateable<NodeTable>;
-export type SelectNodeWithAttributes = SelectNode & {
- attributes: string;
-};
-
-interface NodeAttributeTable {
- node_id: ColumnType<string, string, never>;
- type: ColumnType<string, string, never>;
- key: ColumnType<string, string, never>;
- text_value: ColumnType<string | null, string | null, string | null>;
- number_value: ColumnType<number | null, number | null, number | null>;
- foreign_node_id: ColumnType<string | null, string | null, string | null>;
- created_at: ColumnType<string, string, never>;
- updated_at: ColumnType<string | null, string | null, string | null>;
- created_by: ColumnType<string, string, never>;
- updated_by: ColumnType<string | null, string | null, string | null>;
- version_id: ColumnType<string, string, string>;
- server_created_at: ColumnType<string | null, string | null, string | null>;
- server_updated_at: ColumnType<string | null, string | null, string | null>;
- server_version_id: ColumnType<string | null, string | null, string | null>;
-}
-
-export type SelectNodeAttribute = Selectable<NodeAttributeTable>;
-export type CreateNodeAttribute = Insertable<NodeAttributeTable>;
-export type UpdateNodeAttribute = Updateable<NodeAttributeTable>;
interface NodeReactionTable {
node_id: ColumnType<string, string, never>;
@@ -71,7 +48,6 @@ export type UpdateMutation = Updateable<MutationTable>;
export interface WorkspaceDatabaseSchema {
nodes: NodeTable;
- node_attributes: NodeAttributeTable;
mutations: MutationTable;
node_reactions: NodeReactionTable;
}
diff --git a/desktop/src/data/workspace-manager.ts b/desktop/src/data/workspace-manager.ts
index b16d629f..4e6b98e5 100644
--- a/desktop/src/data/workspace-manager.ts
+++ b/desktop/src/data/workspace-manager.ts
@@ -8,10 +8,7 @@ import {
SqliteDialect,
} from 'kysely';
import { Workspace, WorkspaceSyncData } from '@/types/workspaces';
-import {
- SelectNodeAttribute,
- WorkspaceDatabaseSchema,
-} from '@/data/schemas/workspace';
+import { WorkspaceDatabaseSchema } from '@/data/schemas/workspace';
import { workspaceDatabaseMigrations } from '@/data/migrations/workspace';
import {
buildSqlite,
@@ -23,7 +20,7 @@ import { ServerMutation } from '@/types/mutations';
import { eventBus } from '@/lib/event-bus';
import { AxiosInstance } from 'axios';
import { debounce, isEqual } from 'lodash';
-import { ServerNode, ServerNodeAttribute } from '@/types/nodes';
+import { ServerNode } from '@/types/nodes';
import { SelectNode } from '@/data/schemas/workspace';
export class WorkspaceManager {
@@ -214,8 +211,6 @@ export class WorkspaceManager {
public async executeServerMutation(mutation: ServerMutation): Promise<void> {
if (mutation.table === 'nodes') {
await this.executeNodeServerMutation(mutation);
- } else if (mutation.table === 'node_attributes') {
- await this.executeNodeAttributeServerMutation(mutation);
}
//other cases in the future
@@ -238,29 +233,6 @@ export class WorkspaceManager {
}
}
- private async executeNodeAttributeServerMutation(
- mutation: ServerMutation,
- ): Promise<void> {
- if (mutation.action === 'insert' && mutation.after) {
- await this.syncNodeAttributeFromServer(mutation.after);
- } else if (mutation.action === 'update' && mutation.after) {
- await this.syncNodeAttributeFromServer(mutation.after);
- } else if (mutation.action === 'delete' && mutation.before) {
- await this.database
- .deleteFrom('node_attributes')
- .where((eb) =>
- eb.and([
- eb('node_id', '=', mutation.before.nodeId),
- eb('type', '=', mutation.before.type),
- eb('key', '=', mutation.before.key),
- ]),
- )
- .execute();
-
- this.debouncedNotifyQuerySubscribers(['node_attributes']);
- }
- }
-
public isSynced(): boolean {
return this.workspace.synced;
}
@@ -282,10 +254,6 @@ export class WorkspaceManager {
await this.syncNodeFromServer(node);
}
- for (const nodeAttribute of data.nodeAttributes) {
- await this.syncNodeAttributeFromServer(nodeAttribute);
- }
-
this.workspace.synced = true;
return true;
}
@@ -302,10 +270,8 @@ export class WorkspaceManager {
.insertInto('nodes')
.values({
id: node.id,
- type: node.type,
- parent_id: node.parentId,
- index: node.index,
- content: node.content ? JSON.stringify(node.content) : null,
+ attributes: node.attributes ? JSON.stringify(node.attributes) : null,
+ state: node.state,
created_at: node.createdAt,
created_by: node.createdBy,
updated_by: node.updatedBy,
@@ -325,10 +291,8 @@ export class WorkspaceManager {
await this.database
.updateTable('nodes')
.set({
- type: node.type,
- parent_id: node.parentId,
- index: node.index,
- content: node.content ? JSON.stringify(node.content) : null,
+ attributes: node.attributes ? JSON.stringify(node.attributes) : null,
+ state: node.state,
updated_at: node.updatedAt,
updated_by: node.updatedBy,
version_id: node.versionId,
@@ -343,78 +307,6 @@ export class WorkspaceManager {
}
}
- private async syncNodeAttributeFromServer(
- nodeAttribute: ServerNodeAttribute,
- ): Promise<void> {
- const existingNodeAttribute = await this.database
- .selectFrom('node_attributes')
- .selectAll()
- .where((eb) =>
- eb.and([
- eb('node_id', '=', nodeAttribute.nodeId),
- eb('type', '=', nodeAttribute.type),
- eb('key', '=', nodeAttribute.key),
- ]),
- )
- .executeTakeFirst();
-
- if (!existingNodeAttribute) {
- await this.database
- .insertInto('node_attributes')
- .values({
- node_id: nodeAttribute.nodeId,
- type: nodeAttribute.type,
- key: nodeAttribute.key,
- text_value: nodeAttribute.textValue,
- number_value: nodeAttribute.numberValue,
- foreign_node_id: nodeAttribute.foreignNodeId,
- created_at: nodeAttribute.createdAt,
- created_by: nodeAttribute.createdBy,
- updated_by: nodeAttribute.updatedBy,
- updated_at: nodeAttribute.updatedAt,
- version_id: nodeAttribute.versionId,
- server_created_at: nodeAttribute.serverCreatedAt,
- server_updated_at: nodeAttribute.serverUpdatedAt,
- server_version_id: nodeAttribute.versionId,
- })
- .execute();
-
- this.debouncedNotifyQuerySubscribers(['node_attributes']);
- return;
- }
-
- if (
- this.shouldUpdateNodeAttributeFromServer(
- existingNodeAttribute,
- nodeAttribute,
- )
- ) {
- await this.database
- .updateTable('node_attributes')
- .set({
- text_value: nodeAttribute.textValue,
- number_value: nodeAttribute.numberValue,
- foreign_node_id: nodeAttribute.foreignNodeId,
- updated_at: nodeAttribute.updatedAt,
- updated_by: nodeAttribute.updatedBy,
- version_id: nodeAttribute.versionId,
- server_created_at: nodeAttribute.serverCreatedAt,
- server_updated_at: nodeAttribute.serverUpdatedAt,
- server_version_id: nodeAttribute.versionId,
- })
- .where((eb) =>
- eb.and([
- eb('node_id', '=', nodeAttribute.nodeId),
- eb('type', '=', nodeAttribute.type),
- eb('key', '=', nodeAttribute.key),
- ]),
- )
- .execute();
-
- this.debouncedNotifyQuerySubscribers(['node_attributes']);
- }
- }
-
public shouldUpdateNodeFromServer(
localNode: SelectNode,
serverNode: ServerNode,
@@ -439,32 +331,6 @@ export class WorkspaceManager {
return true;
}
- private shouldUpdateNodeAttributeFromServer(
- localNodeAttribute: SelectNodeAttribute,
- serverNodeAttribute: ServerNodeAttribute,
- ): boolean {
- if (
- localNodeAttribute.server_version_id === serverNodeAttribute.versionId
- ) {
- return false;
- }
-
- if (localNodeAttribute.updated_at) {
- if (!serverNodeAttribute.updatedAt) {
- return false;
- }
-
- const localUpdatedAt = new Date(localNodeAttribute.updated_at);
- const serverUpdatedAt = new Date(serverNodeAttribute.updatedAt);
-
- if (localUpdatedAt > serverUpdatedAt) {
- return false;
- }
- }
-
- return true;
- }
-
private async migrate(): Promise<void> {
const migrator = new Migrator({
db: this.database,
diff --git a/desktop/src/editor/mappers.ts b/desktop/src/editor/mappers.ts
index f6304e12..ac18050b 100644
--- a/desktop/src/editor/mappers.ts
+++ b/desktop/src/editor/mappers.ts
@@ -1,15 +1,15 @@
-import { AttributeTypes, EditorNodeTypes, NodeTypes } from '@/lib/constants';
+import { EditorNodeTypes, NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
import { generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { EditorNode } from '@/types/editor';
-import { LocalNodeWithAttributes, NodeBlock } from '@/types/nodes';
+import { LocalNode, NodeBlock } from '@/types/nodes';
import { JSONContent } from '@tiptap/core';
export const mapContentsToEditorNodes = (
contents: JSONContent[],
parentId: string,
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): EditorNode[] => {
const editorNodes: EditorNode[] = [];
mapAndPushContentsToNodes(contents, parentId, editorNodes, nodesMap);
@@ -21,7 +21,7 @@ const mapAndPushContentsToNodes = (
contents: JSONContent[] | null | undefined,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
if (!contents) {
return;
@@ -34,7 +34,7 @@ const mapAndPushContentsToNodes = (
export const mapNodesToContents = (
parentId: string,
- nodes: LocalNodeWithAttributes[],
+ nodes: LocalNode[],
): JSONContent[] => {
const contents: JSONContent[] = [];
const children = nodes
@@ -51,29 +51,30 @@ const validateNodesIndexes = (editorNodes: EditorNode[]) => {
//group by parentId
const groupedNodes: { [key: string]: EditorNode[] } = {};
for (const node of editorNodes) {
- if (!groupedNodes[node.parentId]) {
- groupedNodes[node.parentId] = [];
+ if (!groupedNodes[node.attributes.parentId]) {
+ groupedNodes[node.attributes.parentId] = [];
}
- groupedNodes[node.parentId].push(node);
+ groupedNodes[node.attributes.parentId].push(node);
}
for (const parentId in groupedNodes) {
const nodes = groupedNodes[parentId];
for (let i = 0; i < nodes.length; i++) {
- const currentIndex = nodes[i].index;
- const beforeIndex = i === 0 ? null : nodes[i - 1].index;
+ const currentIndex = nodes[i].attributes.index;
+ const beforeIndex = i === 0 ? null : nodes[i - 1].attributes.index;
// find the lowest index after the current node
// we do this because sometimes nodes can be ordered in such a way that
// the current node's index is higher than one of its siblings
// after the next sibling
// for example: 1, {current}, 4, 3
- let afterIndex = i === nodes.length - 1 ? null : nodes[i + 1].index;
+ let afterIndex =
+ i === nodes.length - 1 ? null : nodes[i + 1].attributes.index;
for (let j = i + 1; j < nodes.length; j++) {
- if (nodes[j].index < afterIndex) {
- afterIndex = nodes[j].index;
+ if (nodes[j].attributes.index < afterIndex) {
+ afterIndex = nodes[j].attributes.index;
break;
}
}
@@ -91,7 +92,7 @@ const validateNodesIndexes = (editorNodes: EditorNode[]) => {
currentIndex <= beforeIndex ||
currentIndex > afterIndex
) {
- nodes[i].index = generateNodeIndex(beforeIndex, afterIndex);
+ nodes[i].attributes.index = generateNodeIndex(beforeIndex, afterIndex);
}
}
}
@@ -101,7 +102,7 @@ const mapAndPushContentToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
switch (content.type) {
case EditorNodeTypes.Paragraph:
@@ -146,10 +147,7 @@ const mapAndPushContentToNode = (
}
};
-const mapNodeToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
-): JSONContent => {
+const mapNodeToContent = (node: LocalNode, nodes: LocalNode[]): JSONContent => {
switch (node.type) {
case NodeTypes.Paragraph:
return mapParagraphToContent(node);
@@ -184,27 +182,28 @@ const mapParagraphToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.Paragraph,
- parentId: parentId,
- index: index,
- attributes: [],
- content: mapContentsToNodeBlocks(content.content),
+ attributes: {
+ type: NodeTypes.Paragraph,
+ parentId: parentId,
+ index: index,
+ content: mapContentsToNodeBlocks(content.content),
+ },
});
};
-const mapParagraphToContent = (node: LocalNodeWithAttributes): JSONContent => {
+const mapParagraphToContent = (node: LocalNode): JSONContent => {
return {
type: EditorNodeTypes.Paragraph,
attrs: {
id: node.id,
},
- content: mapNodeBlocksToContents(node.content),
+ content: mapNodeBlocksToContents(node.attributes.content),
};
};
@@ -212,27 +211,28 @@ const mapHeading1ToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.Heading1,
- parentId: parentId,
- index: index,
- attributes: [],
- content: mapContentsToNodeBlocks(content.content),
+ attributes: {
+ type: NodeTypes.Heading1,
+ parentId: parentId,
+ index: index,
+ content: mapContentsToNodeBlocks(content.content),
+ },
});
};
-const mapHeading1ToContent = (node: LocalNodeWithAttributes): JSONContent => {
+const mapHeading1ToContent = (node: LocalNode): JSONContent => {
return {
type: EditorNodeTypes.Heading1,
attrs: {
id: node.id,
},
- content: mapNodeBlocksToContents(node.content),
+ content: mapNodeBlocksToContents(node.attributes.content),
};
};
@@ -240,27 +240,28 @@ const mapHeading2ToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.Heading2,
- parentId: parentId,
- index: index,
- attributes: [],
- content: mapContentsToNodeBlocks(content.content),
+ attributes: {
+ type: NodeTypes.Heading2,
+ parentId: parentId,
+ index: index,
+ content: mapContentsToNodeBlocks(content.content),
+ },
});
};
-const mapHeading2ToContent = (node: LocalNodeWithAttributes): JSONContent => {
+const mapHeading2ToContent = (node: LocalNode): JSONContent => {
return {
type: EditorNodeTypes.Heading2,
attrs: {
id: node.id,
},
- content: mapNodeBlocksToContents(node.content),
+ content: mapNodeBlocksToContents(node.attributes.content),
};
};
@@ -268,27 +269,28 @@ const mapHeading3ToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.Heading3,
- parentId: parentId,
- index: index,
- attributes: [],
- content: mapContentsToNodeBlocks(content.content),
+ attributes: {
+ type: NodeTypes.Heading3,
+ parentId: parentId,
+ index: index,
+ content: mapContentsToNodeBlocks(content.content),
+ },
});
};
-const mapHeading3ToContent = (node: LocalNodeWithAttributes): JSONContent => {
+const mapHeading3ToContent = (node: LocalNode): JSONContent => {
return {
type: EditorNodeTypes.Heading3,
attrs: {
id: node.id,
},
- content: mapNodeBlocksToContents(node.content),
+ content: mapNodeBlocksToContents(node.attributes.content),
};
};
@@ -296,26 +298,26 @@ const mapBulletListToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.BulletList,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.BulletList,
+ parentId: parentId,
+ index: index,
+ },
});
mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
};
const mapBulletListToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
+ node: LocalNode,
+ nodes: LocalNode[],
): JSONContent => {
return {
type: EditorNodeTypes.BulletList,
@@ -330,25 +332,25 @@ const mapOrderedListToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.OrderedList,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.OrderedList,
+ parentId: parentId,
+ index: index,
+ },
});
mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
};
const mapOrderedListToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
+ node: LocalNode,
+ nodes: LocalNode[],
): JSONContent => {
return {
type: EditorNodeTypes.OrderedList,
@@ -363,25 +365,25 @@ const mapListItemToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.ListItem,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.ListItem,
+ parentId: parentId,
+ index: index,
+ },
});
mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
};
const mapListItemToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
+ node: LocalNode,
+ nodes: LocalNode[],
): JSONContent => {
return {
type: EditorNodeTypes.ListItem,
@@ -396,25 +398,25 @@ const mapBlockquoteToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.Blockquote,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.Blockquote,
+ parentId: parentId,
+ index: index,
+ },
});
mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
};
const mapBlockquoteToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
+ node: LocalNode,
+ nodes: LocalNode[],
): JSONContent => {
return {
type: EditorNodeTypes.Blockquote,
@@ -429,7 +431,7 @@ const mapCodeBlockToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
@@ -437,35 +439,25 @@ const mapCodeBlockToNode = (
const language = content.attrs?.language;
editorNodes.push({
id: id,
- type: NodeTypes.CodeBlock,
- parentId: parentId,
- index: index,
- attributes: [
- {
- nodeId: id,
- type: AttributeTypes.Language,
- key: AttributeTypes.Language,
- numberValue: null,
- textValue: language,
- foreignNodeId: null,
- },
- ],
- content: mapContentsToNodeBlocks(content.content),
+ attributes: {
+ type: NodeTypes.CodeBlock,
+ parentId: parentId,
+ index: index,
+ language: language,
+ content: mapContentsToNodeBlocks(content.content),
+ },
});
};
-const mapCodeBlockToContent = (node: LocalNodeWithAttributes): JSONContent => {
- const language = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Language,
- )?.textValue;
-
+const mapCodeBlockToContent = (node: LocalNode): JSONContent => {
+ const language = node.attributes.language;
return {
type: EditorNodeTypes.CodeBlock,
attrs: {
id: node.id,
language: language,
},
- content: mapNodeBlocksToContents(node.content),
+ content: mapNodeBlocksToContents(node.attributes.content),
};
};
@@ -473,23 +465,21 @@ const mapHorizontalRuleToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.HorizontalRule,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.HorizontalRule,
+ parentId: parentId,
+ index: index,
+ },
});
};
-const mapHorizontalRuleToContent = (
- node: LocalNodeWithAttributes,
-): JSONContent => {
+const mapHorizontalRuleToContent = (node: LocalNode): JSONContent => {
return {
type: EditorNodeTypes.HorizontalRule,
attrs: {
@@ -503,25 +493,25 @@ const mapTaskListToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.TaskList,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.TaskList,
+ parentId: parentId,
+ index: index,
+ },
});
mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
};
const mapTaskListToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
+ node: LocalNode,
+ nodes: LocalNode[],
): JSONContent => {
return {
type: EditorNodeTypes.TaskList,
@@ -536,40 +526,28 @@ const mapTaskItemToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.TaskItem,
- parentId: parentId,
- index: index,
- attributes: [
- {
- nodeId: id,
- type: AttributeTypes.Checked,
- key: '1',
- numberValue: content.attrs?.checked ? 1 : 0,
- textValue: null,
- foreignNodeId: null,
- },
- ],
- content: null,
+ attributes: {
+ type: NodeTypes.TaskItem,
+ parentId: parentId,
+ index: index,
+ checked: content.attrs?.checked ?? false,
+ },
});
mapAndPushContentsToNodes(content.content, id, editorNodes, nodesMap);
};
const mapTaskItemToContent = (
- node: LocalNodeWithAttributes,
- nodes: LocalNodeWithAttributes[],
+ node: LocalNode,
+ nodes: LocalNode[],
): JSONContent => {
- const checkedAttribute = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Checked,
- );
-
- const checked = checkedAttribute?.numberValue === 1;
+ const checked = node.attributes.checked === true;
return {
type: EditorNodeTypes.TaskItem,
attrs: {
@@ -584,36 +562,28 @@ const mapPageToNode = (
content: JSONContent,
parentId: string,
editorNodes: EditorNode[],
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
): void => {
const id = getIdFromContent(content);
const index = nodesMap.get(id)?.index;
editorNodes.push({
id: id,
- type: NodeTypes.Page,
- parentId: parentId,
- index: index,
- attributes: [],
- content: null,
+ attributes: {
+ type: NodeTypes.Page,
+ parentId: parentId,
+ index: index,
+ },
});
};
-const mapPageToContent = (node: LocalNodeWithAttributes): JSONContent => {
- const name = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Avatar,
- )?.textValue;
-
+const mapPageToContent = (node: LocalNode): JSONContent => {
return {
type: EditorNodeTypes.Page,
attrs: {
id: node.id,
- name: name,
- avatar: avatar,
+ name: node.attributes.name,
+ avatar: node.attributes.avatar,
},
content: null,
};
diff --git a/desktop/src/editor/observer.ts b/desktop/src/editor/observer.ts
index 9737d381..baa6bc83 100644
--- a/desktop/src/editor/observer.ts
+++ b/desktop/src/editor/observer.ts
@@ -1,22 +1,20 @@
import { WorkspaceDatabaseSchema } from '@/data/schemas/workspace';
import { NeuronId } from '@/lib/id';
-import {
- LocalNode,
- LocalNodeAttribute,
- LocalNodeWithAttributes,
-} from '@/types/nodes';
+import { LocalNode } from '@/types/nodes';
import { Workspace } from '@/types/workspaces';
import { Editor, JSONContent } from '@tiptap/core';
import { CompiledQuery, Kysely } from 'kysely';
import { debounce, isEqual } from 'lodash';
import { mapContentsToEditorNodes, mapNodesToContents } from '@/editor/mappers';
-import { EditorNode, EditorNodeAttribute } from '@/types/editor';
+import { EditorNode } from '@/types/editor';
+import * as Y from 'yjs';
+import { fromUint8Array, toUint8Array } from 'js-base64';
export class EditorObserver {
private readonly workspace: Workspace;
private readonly database: Kysely<WorkspaceDatabaseSchema>;
private readonly rootNode: LocalNode;
- private readonly nodesMap: Map<string, LocalNodeWithAttributes>;
+ private readonly nodesMap: Map<string, LocalNode>;
private editorContent: JSONContent;
private readonly onEditorUpdateDebounced: () => void;
@@ -29,7 +27,7 @@ export class EditorObserver {
workspace: Workspace,
database: Kysely<WorkspaceDatabaseSchema>,
rootNode: LocalNode,
- nodesMap: Map<string, LocalNodeWithAttributes>,
+ nodesMap: Map<string, LocalNode>,
) {
this.workspace = workspace;
this.database = database;
@@ -98,12 +96,30 @@ export class EditorObserver {
const editorNode = editorNodesMap.get(nodeId);
if (!existingNode) {
- const newNode: LocalNodeWithAttributes = {
+ const doc = new Y.Doc({
+ guid: editorNode.id,
+ });
+
+ const attributesMap = doc.getMap('attributes');
+
+ doc.transact(() => {
+ for (const [key, value] of Object.entries(editorNode.attributes)) {
+ if (value !== undefined) {
+ attributesMap.set(key, value);
+ }
+ }
+ });
+
+ const attributes = attributesMap.toJSON();
+ const state = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ const newNode: LocalNode = {
id: editorNode.id,
- type: editorNode.type,
- parentId: editorNode.parentId,
- index: editorNode.index,
- content: editorNode.content,
+ type: editorNode.attributes.type,
+ parentId: editorNode.attributes.parentId,
+ index: editorNode.attributes.index,
+ attributes: editorNode.attributes,
+ state: state,
createdAt: new Date().toISOString(),
createdBy: this.workspace.userId,
versionId: NeuronId.generate(NeuronId.Type.Version),
@@ -112,19 +128,14 @@ export class EditorObserver {
serverCreatedAt: null,
serverUpdatedAt: null,
serverVersionId: null,
- attributes: [],
};
const insertNodeQuery = this.database
.insertInto('nodes')
.values({
id: editorNode.id,
- type: editorNode.type,
- parent_id: editorNode.parentId,
- index: editorNode.index,
- content: editorNode.content
- ? JSON.stringify(editorNode.content)
- : null,
+ attributes: JSON.stringify(attributes),
+ state: state,
created_at: new Date().toISOString(),
created_by: this.workspace.userId,
version_id: NeuronId.generate(NeuronId.Type.Version),
@@ -133,46 +144,6 @@ export class EditorObserver {
insertQueries.push(insertNodeQuery);
this.nodesMap.set(newNode.id, newNode);
-
- if (editorNode.attributes && editorNode.attributes.length > 0) {
- for (const attribute of editorNode.attributes) {
- const nodeAttribute: LocalNodeAttribute = {
- nodeId: newNode.id,
- type: attribute.type,
- key: attribute.key,
- textValue: attribute.textValue,
- numberValue: attribute.numberValue,
- foreignNodeId: attribute.foreignNodeId,
- createdAt: new Date().toISOString(),
- createdBy: this.workspace.userId,
- versionId: NeuronId.generate(NeuronId.Type.Version),
- updatedAt: null,
- updatedBy: null,
- serverCreatedAt: null,
- serverUpdatedAt: null,
- serverVersionId: null,
- };
-
- newNode.attributes.push(nodeAttribute);
-
- const insertNodeAttributeQuery = this.database
- .insertInto('node_attributes')
- .values({
- node_id: newNode.id,
- type: nodeAttribute.type,
- key: nodeAttribute.key,
- text_value: nodeAttribute.textValue,
- number_value: nodeAttribute.numberValue,
- foreign_node_id: nodeAttribute.foreignNodeId,
- created_at: new Date().toISOString(),
- created_by: this.workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- insertQueries.push(insertNodeAttributeQuery);
- }
- }
} else if (!editorNode) {
const query = this.database
.deleteFrom('nodes')
@@ -182,11 +153,73 @@ export class EditorObserver {
deleteQueries.push(query);
this.nodesMap.delete(existingNode.id);
} else {
- if (!this.nodeContentEquals(existingNode, editorNode)) {
- existingNode.type = editorNode.type;
- existingNode.parentId = editorNode.parentId;
- existingNode.index = editorNode.index;
- existingNode.content = editorNode.content;
+ if (!isEqual(existingNode.attributes, editorNode.attributes)) {
+ const doc = new Y.Doc({
+ guid: existingNode.id,
+ });
+
+ Y.applyUpdate(doc, toUint8Array(existingNode.state));
+ const attributesMap = doc.getMap('attributes');
+
+ let hasChanges = false;
+ doc.transact(() => {
+ if (existingNode.attributes.type !== editorNode.attributes.type) {
+ attributesMap.set('type', editorNode.attributes.type);
+ hasChanges = true;
+ }
+
+ if (
+ existingNode.attributes.parentId !==
+ editorNode.attributes.parentId
+ ) {
+ attributesMap.set('parentId', editorNode.attributes.parentId);
+ hasChanges = true;
+ }
+
+ if (existingNode.attributes.index !== editorNode.attributes.index) {
+ attributesMap.set('index', editorNode.attributes.index);
+ hasChanges = true;
+ }
+
+ if (
+ !isEqual(
+ existingNode.attributes.content,
+ editorNode.attributes.content,
+ )
+ ) {
+ attributesMap.set('content', editorNode.attributes.content);
+ hasChanges = true;
+ }
+
+ for (const [key, value] of Object.entries(editorNode.attributes)) {
+ const existingValue = attributesMap.get(key);
+ if (!isEqual(existingValue, value)) {
+ attributesMap.set(key, value);
+ hasChanges = true;
+ }
+ }
+
+ const existingAttributes = existingNode.attributes;
+ const editorAttributes = editorNode.attributes;
+ for (const key of Object.keys(existingAttributes)) {
+ if (!(key in editorAttributes)) {
+ attributesMap.delete(key);
+ hasChanges = true;
+ }
+ }
+ });
+
+ if (!hasChanges) {
+ continue;
+ }
+
+ const attributes = attributesMap.toJSON();
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
+ existingNode.type = editorNode.attributes.type;
+ existingNode.parentId = editorNode.attributes.parentId;
+ existingNode.index = editorNode.attributes.index;
+ existingNode.attributes = editorNode.attributes;
existingNode.updatedAt = new Date().toISOString();
existingNode.updatedBy = this.workspace.userId;
existingNode.versionId = NeuronId.generate(NeuronId.Type.Version);
@@ -194,12 +227,8 @@ export class EditorObserver {
const query = this.database
.updateTable('nodes')
.set({
- type: existingNode.type,
- parent_id: existingNode.parentId,
- index: existingNode.index,
- content: existingNode.content
- ? JSON.stringify(existingNode.content)
- : null,
+ attributes: JSON.stringify(attributes),
+ state: encodedState,
updated_at: existingNode.updatedAt,
updated_by: existingNode.updatedBy,
version_id: existingNode.versionId,
@@ -209,98 +238,6 @@ export class EditorObserver {
updateQueries.push(query);
}
-
- for (const attribute of editorNode.attributes) {
- const existingAttribute = existingNode.attributes.find(
- (attr) =>
- attr.nodeId === existingNode.id &&
- attr.type === attribute.type &&
- attr.key === attribute.key,
- );
-
- if (!existingAttribute) {
- const newAttribute: LocalNodeAttribute = {
- nodeId: existingNode.id,
- type: attribute.type,
- key: attribute.key,
- textValue: attribute.textValue,
- numberValue: attribute.numberValue,
- foreignNodeId: attribute.foreignNodeId,
- createdAt: new Date().toISOString(),
- createdBy: this.workspace.userId,
- versionId: NeuronId.generate(NeuronId.Type.Version),
- updatedAt: null,
- updatedBy: null,
- serverCreatedAt: null,
- serverUpdatedAt: null,
- serverVersionId: null,
- };
-
- existingNode.attributes.push(newAttribute);
-
- const insertNodeAttributeQuery = this.database
- .insertInto('node_attributes')
- .values({
- node_id: existingNode.id,
- type: newAttribute.type,
- key: newAttribute.key,
- text_value: newAttribute.textValue,
- number_value: newAttribute.numberValue,
- foreign_node_id: newAttribute.foreignNodeId,
- created_at: newAttribute.createdAt,
- created_by: newAttribute.createdBy,
- version_id: newAttribute.versionId,
- })
- .compile();
-
- insertQueries.push(insertNodeAttributeQuery);
- } else if (!this.nodeAttributesEqual(existingAttribute, attribute)) {
- const updateNodeAttributeQuery = this.database
- .updateTable('node_attributes')
- .set({
- text_value: attribute.textValue,
- number_value: attribute.numberValue,
- foreign_node_id: attribute.foreignNodeId,
- updated_at: new Date().toISOString(),
- updated_by: this.workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .where((eb) =>
- eb.and([
- eb('node_id', '=', existingAttribute.nodeId),
- eb('type', '=', existingAttribute.type),
- eb('key', '=', existingAttribute.key),
- ]),
- )
- .compile();
-
- updateQueries.push(updateNodeAttributeQuery);
- }
- }
-
- for (const attribute of existingNode.attributes) {
- const editorAttribute = editorNode.attributes.find(
- (attr) =>
- attr.nodeId === existingNode.id &&
- attr.type === attribute.type &&
- attr.key === attribute.key,
- );
-
- if (!editorAttribute) {
- const deleteNodeAttributeQuery = this.database
- .deleteFrom('node_attributes')
- .where((eb) =>
- eb.and([
- eb('node_id', '=', existingNode.id),
- eb('type', '=', attribute.type),
- eb('key', '=', attribute.key),
- ]),
- )
- .compile();
-
- deleteQueries.push(deleteNodeAttributeQuery);
- }
- }
}
}
@@ -319,7 +256,7 @@ export class EditorObserver {
}
private checkNodesChanges(
- newNodesMap: Map<string, LocalNodeWithAttributes>,
+ newNodesMap: Map<string, LocalNode>,
editor: Editor,
) {
const allNodeIds = new Set([
@@ -339,7 +276,7 @@ export class EditorObserver {
this.nodesMap.delete(oldNode.id);
hasChanges = true;
} else if (
- !this.nodeContentEquals(oldNode, newNode) &&
+ !isEqual(oldNode, newNode) &&
oldNode.updatedAt !== null &&
newNode.updatedAt !== null
) {
@@ -366,54 +303,4 @@ export class EditorObserver {
}
}
}
-
- private nodeContentEquals(
- existingNode: EditorNode,
- editorNode: EditorNode,
- ): boolean {
- if (existingNode.index !== editorNode.index) {
- return false;
- }
-
- if (existingNode.parentId !== editorNode.parentId) {
- return false;
- }
-
- if (existingNode.type !== editorNode.type) {
- return false;
- }
-
- if (!isEqual(existingNode.content, editorNode.content)) {
- return false;
- }
-
- return true;
- }
-
- private nodeAttributesEqual(
- existingAttribute: EditorNodeAttribute,
- editorAttribute: EditorNodeAttribute,
- ): boolean {
- if (existingAttribute.key !== editorAttribute.key) {
- return false;
- }
-
- if (existingAttribute.type !== editorAttribute.type) {
- return false;
- }
-
- if (existingAttribute.textValue !== editorAttribute.textValue) {
- return false;
- }
-
- if (existingAttribute.numberValue !== editorAttribute.numberValue) {
- return false;
- }
-
- if (existingAttribute.foreignNodeId !== editorAttribute.foreignNodeId) {
- return false;
- }
-
- return true;
- }
}
diff --git a/desktop/src/editor/renderers/blockquote.tsx b/desktop/src/editor/renderers/blockquote.tsx
index 409f532e..55792e1c 100644
--- a/desktop/src/editor/renderers/blockquote.tsx
+++ b/desktop/src/editor/renderers/blockquote.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface BlockquoteRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/bullet-list.tsx b/desktop/src/editor/renderers/bullet-list.tsx
index 32cc453a..fdb9d9a6 100644
--- a/desktop/src/editor/renderers/bullet-list.tsx
+++ b/desktop/src/editor/renderers/bullet-list.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface BulletListRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/code-block.tsx b/desktop/src/editor/renderers/code-block.tsx
index 00e98214..40d454fc 100644
--- a/desktop/src/editor/renderers/code-block.tsx
+++ b/desktop/src/editor/renderers/code-block.tsx
@@ -2,12 +2,11 @@ import React from 'react';
import { Icon } from '@/components/ui/icon';
import { defaultClasses } from '@/editor/classes';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
import { highlightCode, languages } from '@/lib/lowlight';
-import { AttributeTypes } from '@/lib/constants';
interface CodeBlockRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
@@ -15,13 +14,11 @@ export const CodeBlockRenderer = ({
node,
keyPrefix,
}: CodeBlockRendererProps) => {
- const language = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Language,
- )?.textValue;
+ const language = node.attributes.language;
const [copied, setCopied] = React.useState(false);
- const code = node.content?.[0].text ?? '';
+ const code = node.attributes.content?.[0].text ?? '';
if (!code) {
return null;
}
diff --git a/desktop/src/editor/renderers/document.tsx b/desktop/src/editor/renderers/document.tsx
index 6b6e3185..fa90a32c 100644
--- a/desktop/src/editor/renderers/document.tsx
+++ b/desktop/src/editor/renderers/document.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface DocumentRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/heading1.tsx b/desktop/src/editor/renderers/heading1.tsx
index f7be9259..b8be0a34 100644
--- a/desktop/src/editor/renderers/heading1.tsx
+++ b/desktop/src/editor/renderers/heading1.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface Heading1RendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/heading2.tsx b/desktop/src/editor/renderers/heading2.tsx
index 5d466635..8cb2285d 100644
--- a/desktop/src/editor/renderers/heading2.tsx
+++ b/desktop/src/editor/renderers/heading2.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface Heading2RendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/heading3.tsx b/desktop/src/editor/renderers/heading3.tsx
index d67600d0..78332427 100644
--- a/desktop/src/editor/renderers/heading3.tsx
+++ b/desktop/src/editor/renderers/heading3.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface Heading3RendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/list-item.tsx b/desktop/src/editor/renderers/list-item.tsx
index 72f72a5d..5389edc9 100644
--- a/desktop/src/editor/renderers/list-item.tsx
+++ b/desktop/src/editor/renderers/list-item.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface ListItemRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/message.tsx b/desktop/src/editor/renderers/message.tsx
index 743e73fd..2bafae83 100644
--- a/desktop/src/editor/renderers/message.tsx
+++ b/desktop/src/editor/renderers/message.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface MessageRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/node-children.tsx b/desktop/src/editor/renderers/node-children.tsx
index c493708e..793f40c8 100644
--- a/desktop/src/editor/renderers/node-children.tsx
+++ b/desktop/src/editor/renderers/node-children.tsx
@@ -1,11 +1,11 @@
import React from 'react';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
import { NodeBlockRenderer } from '@/editor/renderers/node-block';
import { NodeRenderer } from '@/editor/renderers/node';
interface NodeChildrenRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
@@ -25,7 +25,7 @@ export const NodeChildrenRenderer = ({
return (
<React.Fragment>
- {node.content.map((nodeBlock, index) => (
+ {node.attributes.content?.map((nodeBlock, index) => (
<NodeBlockRenderer node={nodeBlock} keyPrefix={keyPrefix} key={index} />
))}
</React.Fragment>
diff --git a/desktop/src/editor/renderers/node.tsx b/desktop/src/editor/renderers/node.tsx
index 72707b27..2b9e63b7 100644
--- a/desktop/src/editor/renderers/node.tsx
+++ b/desktop/src/editor/renderers/node.tsx
@@ -13,11 +13,11 @@ import { ParagraphRenderer } from '@/editor/renderers/paragraph';
import { TaskItemRenderer } from '@/editor/renderers/task-item';
import { TaskListRenderer } from '@/editor/renderers/task-list';
import { TextRenderer } from '@/editor/renderers/text';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
import { match } from 'ts-pattern';
interface NodeRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/ordered-list.tsx b/desktop/src/editor/renderers/ordered-list.tsx
index 7ebaf9dd..6df470dd 100644
--- a/desktop/src/editor/renderers/ordered-list.tsx
+++ b/desktop/src/editor/renderers/ordered-list.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface OrderedListRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/paragraph.tsx b/desktop/src/editor/renderers/paragraph.tsx
index 31e139cf..73702913 100644
--- a/desktop/src/editor/renderers/paragraph.tsx
+++ b/desktop/src/editor/renderers/paragraph.tsx
@@ -1,11 +1,11 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
import { cn } from '@/lib/utils';
interface ParagraphRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
@@ -13,7 +13,7 @@ export const ParagraphRenderer = ({
node,
keyPrefix,
}: ParagraphRendererProps) => {
- if (!node.content || node.content.length === 0) {
+ if (!node.attributes.content || node.attributes.content.length === 0) {
return null;
}
diff --git a/desktop/src/editor/renderers/task-item.tsx b/desktop/src/editor/renderers/task-item.tsx
index 29e7de47..09f3b1c8 100644
--- a/desktop/src/editor/renderers/task-item.tsx
+++ b/desktop/src/editor/renderers/task-item.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface TaskItemRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/editor/renderers/task-list.tsx b/desktop/src/editor/renderers/task-list.tsx
index 75591fb9..1e14023b 100644
--- a/desktop/src/editor/renderers/task-list.tsx
+++ b/desktop/src/editor/renderers/task-list.tsx
@@ -1,10 +1,10 @@
import React from 'react';
import { defaultClasses } from '@/editor/classes';
import { NodeChildrenRenderer } from '@/editor/renderers/node-children';
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
interface TaskListRendererProps {
- node: LocalNodeWithAttributesAndChildren;
+ node: LocalNodeWithChildren;
keyPrefix: string | null;
}
diff --git a/desktop/src/lib/constants.ts b/desktop/src/lib/constants.ts
index 682ed136..c6d965af 100644
--- a/desktop/src/lib/constants.ts
+++ b/desktop/src/lib/constants.ts
@@ -26,8 +26,6 @@ export const NodeTypes = {
CalendarView: 'calendar_view',
Field: 'field',
SelectOption: 'select_option',
- ViewFilter: 'view_filter',
- ViewSort: 'view_sort',
};
export const EditorNodeTypes = {
@@ -68,25 +66,6 @@ export const ViewNodeTypes: string[] = [
NodeTypes.CalendarView,
];
-export const AttributeTypes = {
- Name: 'name',
- Description: 'description',
- Avatar: 'avatar',
- Color: 'color',
- DataType: 'data_type',
- Language: 'language',
- Checked: 'checked',
- HiddenField: 'hidden_field',
- FieldWidth: 'field_width',
- FieldIndex: 'field_index',
- NameWidth: 'name_width',
- FieldId: 'field_id',
- Operator: 'operator',
- Value: 'value',
- GroupBy: 'group_by',
- Direction: 'direction',
-};
-
export const SortDirections = {
Ascending: 'asc',
Descending: 'desc',
diff --git a/desktop/src/lib/databases.ts b/desktop/src/lib/databases.ts
index 8006fcc2..ad997b71 100644
--- a/desktop/src/lib/databases.ts
+++ b/desktop/src/lib/databases.ts
@@ -2,8 +2,10 @@ import {
FieldDataType,
FieldNode,
RecordNode,
- ViewFilterNode,
+ ViewFieldFilter,
+ ViewFilter,
} from '@/types/databases';
+import { isStringArray } from '@/lib/utils';
export const getFieldIcon = (type?: FieldDataType): string => {
if (!type) return '';
@@ -531,7 +533,7 @@ export const getFieldFilterOperators = (
export const filterRecords = (
records: RecordNode[],
- filter: ViewFilterNode,
+ filter: ViewFilter,
field: FieldNode,
currentUserId: string,
): RecordNode[] => {
@@ -542,10 +544,14 @@ export const filterRecords = (
const recordMatchesFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFilter,
field: FieldNode,
currentUserId: string,
) => {
+ if (filter.type === 'group') {
+ return false;
+ }
+
switch (field.dataType) {
case 'boolean':
return recordMatchesBooleanFilter(record, filter, field);
@@ -580,18 +586,16 @@ const recordMatchesFilter = (
const recordMatchesBooleanFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.numberValue;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_true') {
- return fieldValue === 1;
+ return fieldValue === true;
}
if (filter.operator === 'is_false') {
- return !fieldValue || fieldValue === 0;
+ return !fieldValue || fieldValue === false;
}
return false;
@@ -599,7 +603,7 @@ const recordMatchesBooleanFilter = (
const recordMatchesCollaboratorFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFilter,
field: FieldNode,
) => {
return false;
@@ -607,12 +611,15 @@ const recordMatchesCollaboratorFilter = (
const recordMatchesCreatedAtFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
) => {
- if (filter.values.length === 0) return false;
+ if (!filter.value) return false;
- const filterValue = filter.values[0].textValue;
- const filterDate = new Date(filterValue);
+ if (typeof filter.value !== 'string') {
+ return true;
+ }
+
+ const filterDate = new Date(filter.value);
filterDate.setHours(0, 0, 0, 0); // Set time to midnight
const recordDate = new Date(record.createdAt);
@@ -638,7 +645,7 @@ const recordMatchesCreatedAtFilter = (
const recordMatchesCreatedByFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
currentUserId: string,
) => {
const createdBy = record.createdBy?.id;
@@ -646,33 +653,42 @@ const recordMatchesCreatedByFilter = (
return false;
}
- const filterValues = filter.values.map((value) => value.foreignNodeId);
- if (filterValues.length === 0) {
+ if (filter.operator === 'is_me') {
+ return createdBy === currentUserId;
+ }
+
+ if (filter.operator === 'is_not_me') {
+ return createdBy !== currentUserId;
+ }
+
+ if (!isStringArray(filter.value)) {
return true;
}
- switch (filter.operator) {
- case 'is_me':
- return createdBy === currentUserId;
- case 'is_not_me':
- return createdBy !== currentUserId;
- case 'is_in':
- return filterValues.includes(createdBy);
- case 'is_not_in':
- return !filterValues.includes(createdBy);
- default:
- return false;
+ if (filter.operator === 'is_in') {
+ return filter.value.includes(createdBy);
+ }
+
+ if (filter.operator === 'is_not_in') {
+ return !filter.value.includes(createdBy);
}
+
+ return false;
};
const recordMatchesDateFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.textValue;
+ const fieldValue = record.attributes[field.id];
+ if (filter.operator === 'is_empty') {
+ return !fieldValue;
+ }
+
+ if (filter.operator === 'is_not_empty') {
+ return !!fieldValue;
+ }
if (!fieldValue) {
return false;
@@ -681,16 +697,11 @@ const recordMatchesDateFilter = (
const recordDate = new Date(fieldValue);
recordDate.setHours(0, 0, 0, 0); // Set time to midnight
- if (filter.values.length === 0) {
- return true;
- }
-
- const filterValue = filter.values[0].textValue;
- if (!filterValue) {
+ if (typeof filter.value !== 'string') {
return true;
}
- const filterDate = new Date(filterValue);
+ const filterDate = new Date(filter.value);
filterDate.setHours(0, 0, 0, 0); // Set time to midnight
switch (filter.operator) {
@@ -713,12 +724,10 @@ const recordMatchesDateFilter = (
const recordMatchesEmailFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.textValue;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -732,11 +741,11 @@ const recordMatchesEmailFilter = (
return false;
}
- if (filter.values.length === 0) {
+ if (typeof filter.value !== 'string') {
return true;
}
- const filterValue = filter.values[0].textValue;
+ const filterValue = filter.value;
if (!filterValue) {
return true;
}
@@ -757,7 +766,7 @@ const recordMatchesEmailFilter = (
const recordMatchesFileFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
return false;
@@ -765,12 +774,10 @@ const recordMatchesFileFilter = (
const recordMatchesMultiSelectFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValues = record.attributes
- .filter((attribute) => attribute.type === field.id)
- ?.map((attribute) => attribute.foreignNodeId);
+ const fieldValues = record.attributes[field.id] as string[];
if (filter.operator === 'is_empty') {
return fieldValues?.length === 0;
@@ -784,16 +791,15 @@ const recordMatchesMultiSelectFilter = (
return false;
}
- const selectOptionIds = filter.values.map((value) => value.foreignNodeId);
- if (selectOptionIds.length === 0) {
+ if (!isStringArray(filter.value)) {
return true;
}
switch (filter.operator) {
case 'is_in':
- return fieldValues.some((value) => selectOptionIds.includes(value));
+ return filter.value.some((value) => fieldValues.includes(value));
case 'is_not_in':
- return !fieldValues.some((value) => selectOptionIds.includes(value));
+ return !filter.value.some((value) => fieldValues.includes(value));
}
return false;
@@ -801,12 +807,10 @@ const recordMatchesMultiSelectFilter = (
const recordMatchesNumberFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.numberValue;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -820,11 +824,11 @@ const recordMatchesNumberFilter = (
return false;
}
- if (filter.values.length === 0) {
+ if (typeof filter.value !== 'number') {
return true;
}
- const filterValue = filter.values[0].numberValue;
+ const filterValue = filter.value;
if (!filterValue) {
return true;
}
@@ -849,12 +853,10 @@ const recordMatchesNumberFilter = (
const recordMatchesPhoneFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.textValue;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -868,11 +870,11 @@ const recordMatchesPhoneFilter = (
return false;
}
- if (filter.values.length === 0) {
+ if (typeof filter.value !== 'string') {
return true;
}
- const filterValue = filter.values[0].textValue;
+ const filterValue = filter.value;
if (!filterValue) {
return true;
}
@@ -893,12 +895,10 @@ const recordMatchesPhoneFilter = (
const recordMatchesSelectFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.foreignNodeId;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -912,20 +912,15 @@ const recordMatchesSelectFilter = (
return false;
}
- if (filter.values.length === 0) {
- return true;
- }
-
- const selectOptionIds = filter.values.map((value) => value.foreignNodeId);
- if (selectOptionIds.length === 0) {
+ if (!isStringArray(filter.value)) {
return true;
}
switch (filter.operator) {
case 'is_in':
- return selectOptionIds.includes(fieldValue);
+ return filter.value.includes(fieldValue);
case 'is_not_in':
- return !selectOptionIds.includes(fieldValue);
+ return !filter.value.includes(fieldValue);
}
return false;
@@ -933,12 +928,10 @@ const recordMatchesSelectFilter = (
const recordMatchesTextFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.textValue;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -952,11 +945,11 @@ const recordMatchesTextFilter = (
return false;
}
- if (filter.values.length === 0) {
+ if (typeof filter.value !== 'string') {
return true;
}
- const filterValue = filter.values[0].textValue;
+ const filterValue = filter.value;
if (!filterValue) {
return true;
}
@@ -977,12 +970,10 @@ const recordMatchesTextFilter = (
const recordMatchesUrlFilter = (
record: RecordNode,
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: FieldNode,
) => {
- const fieldValue = record.attributes.find(
- (attribute) => attribute.type === field.id,
- )?.textValue;
+ const fieldValue = record.attributes[field.id];
if (filter.operator === 'is_empty') {
return !fieldValue;
@@ -996,11 +987,11 @@ const recordMatchesUrlFilter = (
return false;
}
- if (filter.values.length === 0) {
+ if (typeof filter.value !== 'string') {
return true;
}
- const filterValue = filter.values[0].textValue;
+ const filterValue = filter.value;
if (!filterValue) {
return true;
}
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index fc185ecb..f8f4ced1 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -107,10 +107,6 @@ export class NeuronId {
return IdType.Field;
case NodeTypes.SelectOption:
return IdType.SelectOption;
- case NodeTypes.ViewFilter:
- return IdType.ViewFilter;
- case NodeTypes.ViewSort:
- return IdType.ViewSort;
default:
return IdType.Node;
}
diff --git a/desktop/src/lib/nodes.ts b/desktop/src/lib/nodes.ts
index 8ea645db..63eb32a0 100644
--- a/desktop/src/lib/nodes.ts
+++ b/desktop/src/lib/nodes.ts
@@ -1,17 +1,19 @@
import {
+ CreateNode,
SelectNode,
- SelectNodeAttribute,
- SelectNodeWithAttributes,
+ WorkspaceDatabaseSchema,
} from '@/data/schemas/workspace';
import {
LocalNode,
- LocalNodeAttribute,
- LocalNodeWithAttributes,
- LocalNodeWithAttributesAndChildren,
LocalNodeWithChildren,
+ NodeInsertInput,
} from '@/types/nodes';
import { generateKeyBetween } from 'fractional-indexing-jittered';
import { NodeTypes } from '@/lib/constants';
+import { CompiledQuery, Kysely } from 'kysely';
+import * as Y from 'yjs';
+import { NeuronId } from '@/lib/id';
+import { fromUint8Array } from 'js-base64';
export const buildNodeWithChildren = (
node: LocalNode,
@@ -27,20 +29,6 @@ export const buildNodeWithChildren = (
};
};
-export const buildNodeWithAttributesAndChildren = (
- node: LocalNodeWithAttributes,
- allNodes: LocalNodeWithAttributes[],
-): LocalNodeWithAttributesAndChildren => {
- const children: LocalNodeWithAttributesAndChildren[] = allNodes
- .filter((n) => n.parentId === node.id)
- .map((n) => buildNodeWithAttributesAndChildren(n, allNodes));
-
- return {
- ...node,
- children: children,
- };
-};
-
export const generateNodeIndex = (
previous?: string | null,
next?: string | null,
@@ -51,34 +39,57 @@ export const generateNodeIndex = (
return generateKeyBetween(lower, upper);
};
-export const mapNode = (row: SelectNode): LocalNode => {
+export const buildNodeInsertMutation = (
+ schema: Kysely<WorkspaceDatabaseSchema>,
+ userId: string,
+ input: NodeInsertInput | NodeInsertInput[],
+): CompiledQuery => {
+ const nodes = Array.isArray(input)
+ ? input.map((node) => buildCreateNode(node, userId))
+ : buildCreateNode(input, userId);
+
+ return schema.insertInto('nodes').values(nodes).compile();
+};
+
+const buildCreateNode = (
+ input: NodeInsertInput,
+ userId: string,
+): CreateNode => {
+ const doc = new Y.Doc({
+ guid: input.id,
+ });
+
+ const attributesMap = doc.getMap('attributes');
+
+ doc.transact(() => {
+ for (const [key, value] of Object.entries(input.attributes)) {
+ if (value !== undefined) {
+ attributesMap.set(key, value);
+ }
+ }
+ });
+
+ const attributes = JSON.stringify(attributesMap.toJSON());
+ const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+
return {
- id: row.id,
- type: row.type,
- index: row.index,
- parentId: row.parent_id,
- content: row.content ? JSON.parse(row.content) : null,
- createdAt: row.created_at,
- createdBy: row.created_by,
- updatedAt: row.updated_at,
- updatedBy: row.updated_by,
- versionId: row.version_id,
- serverCreatedAt: row.server_created_at,
- serverUpdatedAt: row.server_updated_at,
- serverVersionId: row.server_version_id,
+ id: input.id,
+ attributes: attributes,
+ state: encodedState,
+ created_at: new Date().toISOString(),
+ created_by: userId,
+ version_id: NeuronId.generate(NeuronId.Type.Version),
};
};
-export const mapNodeAttribute = (
- row: SelectNodeAttribute,
-): LocalNodeAttribute => {
+export const mapNode = (row: SelectNode): LocalNode => {
return {
- nodeId: row.node_id,
+ id: row.id,
type: row.type,
- key: row.key,
- textValue: row.text_value,
- numberValue: row.number_value,
- foreignNodeId: row.foreign_node_id,
+ index: row.index,
+ parentId: row.parent_id,
+ attributes: JSON.parse(row.attributes),
+ state: row.state,
createdAt: row.created_at,
createdBy: row.created_by,
updatedAt: row.updated_at,
@@ -90,19 +101,6 @@ export const mapNodeAttribute = (
};
};
-export const mapNodeWithAttributes = (
- row: SelectNodeWithAttributes,
-): LocalNodeWithAttributes => {
- const attributes: SelectNodeAttribute[] = row.attributes
- ? JSON.parse(row.attributes)
- : [];
-
- return {
- ...mapNode(row),
- attributes: attributes.map(mapNodeAttribute),
- };
-};
-
export const getDefaultNodeIcon = (type: string) => {
switch (type) {
case NodeTypes.Channel:
diff --git a/desktop/src/lib/utils.ts b/desktop/src/lib/utils.ts
index 1710357b..5a5a4d6b 100644
--- a/desktop/src/lib/utils.ts
+++ b/desktop/src/lib/utils.ts
@@ -187,3 +187,23 @@ export const toUTCDate = (dateParam: Date | string): Date => {
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()),
);
};
+
+export const isStringArray = (
+ value: unknown | null | undefined,
+): value is string[] => {
+ if (value == null) {
+ return false;
+ }
+
+ if (value === undefined) {
+ return false;
+ }
+
+ if (value === null) {
+ return false;
+ }
+
+ return (
+ Array.isArray(value) && value.every((item) => typeof item === 'string')
+ );
+};
diff --git a/desktop/src/mutations/use-board-view-create-mutation.tsx b/desktop/src/mutations/use-board-view-create-mutation.tsx
index 4a8ef2f3..543ed347 100644
--- a/desktop/src/mutations/use-board-view-create-mutation.tsx
+++ b/desktop/src/mutations/use-board-view-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { useMutation } from '@tanstack/react-query';
@@ -36,50 +36,22 @@ export const useBoardViewCreateMutation = () => {
].index
: null;
- const boardViewId = NeuronId.generate(NeuronId.Type.BoardView);
- const insertBoardViewQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: boardViewId,
- type: NodeTypes.BoardView,
- parent_id: input.databaseId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertBoardViewAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: boardViewId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ 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),
},
- {
- node_id: boardViewId,
- type: AttributeTypes.GroupBy,
- key: '1',
- foreign_node_id: input.groupBy,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
+ },
+ );
- await workspace.mutate([
- insertBoardViewQuery,
- insertBoardViewAttributesQuery,
- ]);
- return boardViewId;
+ 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
index 7be748fb..82894055 100644
--- a/desktop/src/mutations/use-calendar-view-create-mutation.tsx
+++ b/desktop/src/mutations/use-calendar-view-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { useMutation } from '@tanstack/react-query';
@@ -36,50 +36,24 @@ export const useCalendarViewCreateMutation = () => {
].index
: null;
- const calendarViewId = NeuronId.generate(NeuronId.Type.CalendarView);
- const insertCalendarViewQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: calendarViewId,
- type: NodeTypes.CalendarView,
- parent_id: input.databaseId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertCalendarViewAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: calendarViewId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ 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,
},
- {
- node_id: calendarViewId,
- type: AttributeTypes.GroupBy,
- key: '1',
- foreign_node_id: input.groupBy,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
+ },
+ );
- await workspace.mutate([
- insertCalendarViewQuery,
- insertCalendarViewAttributesQuery,
- ]);
- return calendarViewId;
+ 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
index 07d8837a..f51d02ef 100644
--- a/desktop/src/mutations/use-channel-create-mutation.tsx
+++ b/desktop/src/mutations/use-channel-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { useMutation } from '@tanstack/react-query';
@@ -12,6 +12,7 @@ interface ChannelCreateMutationInput {
export const useChannelCreateMutation = () => {
const workspace = useWorkspace();
+
return useMutation({
mutationFn: async (input: ChannelCreateMutationInput) => {
const siblingsQuery = workspace.schema
@@ -29,36 +30,23 @@ export const useChannelCreateMutation = () => {
].index
: null;
- const channelId = NeuronId.generate(NeuronId.Type.Channel);
- const insertChannelQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: channelId,
- type: NodeTypes.Channel,
- parent_id: input.spaceId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertChannelNameQuery = workspace.schema
- .insertInto('node_attributes')
- .values({
- node_id: channelId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
+ 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([insertChannelQuery, insertChannelNameQuery]);
- return channelId;
+ await workspace.mutate(query);
+ return id;
},
});
};
diff --git a/desktop/src/mutations/use-database-create-mutation.tsx b/desktop/src/mutations/use-database-create-mutation.tsx
index c214b196..0f5dc784 100644
--- a/desktop/src/mutations/use-database-create-mutation.tsx
+++ b/desktop/src/mutations/use-database-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { useMutation } from '@tanstack/react-query';
@@ -12,6 +12,7 @@ interface DatabaseCreateMutationInput {
export const useDatabaseCreateMutation = () => {
const workspace = useWorkspace();
+
return useMutation({
mutationFn: async (input: DatabaseCreateMutationInput) => {
const siblingsQuery = workspace.schema
@@ -32,85 +33,43 @@ export const useDatabaseCreateMutation = () => {
const databaseId = NeuronId.generate(NeuronId.Type.Database);
const tableViewId = NeuronId.generate(NeuronId.Type.TableView);
const fieldId = NeuronId.generate(NeuronId.Type.Field);
- const insertNodesQuery = workspace.schema
- .insertInto('nodes')
- .values([
+
+ const query = buildNodeInsertMutation(
+ workspace.schema,
+ workspace.userId,
+ [
{
id: databaseId,
- type: NodeTypes.Database,
- parent_id: input.spaceId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.Database,
+ parentId: input.spaceId,
+ index: generateNodeIndex(maxIndex, null),
+ name: input.name,
+ },
},
{
id: tableViewId,
- type: NodeTypes.TableView,
- parent_id: databaseId,
- index: generateNodeIndex(null, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.TableView,
+ parentId: databaseId,
+ index: generateNodeIndex(null, null),
+ name: 'Default',
+ },
},
{
id: fieldId,
- type: NodeTypes.Field,
- parent_id: databaseId,
- index: generateNodeIndex(null, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.Field,
+ parentId: databaseId,
+ index: generateNodeIndex(null, null),
+ name: 'Comment',
+ dataType: 'text',
+ },
},
- ])
- .compile();
-
- const insertAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: databaseId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: tableViewId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: 'Default',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: fieldId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: 'Comment',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: fieldId,
- type: AttributeTypes.DataType,
- key: '1',
- text_value: 'text',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
+ ],
+ );
- await workspace.mutate([insertNodesQuery, insertAttributesQuery]);
+ await workspace.mutate(query);
return databaseId;
},
});
diff --git a/desktop/src/mutations/use-field-create-mutation.tsx b/desktop/src/mutations/use-field-create-mutation.tsx
index aee9d3a6..7b00461b 100644
--- a/desktop/src/mutations/use-field-create-mutation.tsx
+++ b/desktop/src/mutations/use-field-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { useMutation } from '@tanstack/react-query';
interface FieldCreateMutationInput {
@@ -33,46 +33,24 @@ export const useFieldCreateMutation = () => {
result.rows && result.rows.length > 0 ? result.rows[0] : null;
const maxIndex = lastChild?.index ? lastChild.index : null;
- const fieldId = NeuronId.generate(NeuronId.Type.Field);
- const insertFieldQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: fieldId,
- type: NodeTypes.Field,
- parent_id: values.databaseId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertFieldAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: fieldId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: values.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: fieldId,
- type: AttributeTypes.DataType,
- key: '1',
- text_value: values.dataType,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ 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,
},
- ])
- .compile();
+ },
+ );
- await workspace.mutate([insertFieldQuery, insertFieldAttributesQuery]);
+ 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
index 9884de00..39b55296 100644
--- a/desktop/src/mutations/use-message-create-mutation.tsx
+++ b/desktop/src/mutations/use-message-create-mutation.tsx
@@ -1,12 +1,11 @@
import { useWorkspace } from '@/contexts/workspace';
-import { CreateNode, CreateNodeAttribute } from '@/data/schemas/workspace';
import { mapContentsToEditorNodes } from '@/editor/mappers';
import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { LocalNodeWithAttributes } from '@/types/nodes';
import { useMutation } from '@tanstack/react-query';
import { JSONContent } from '@tiptap/core';
-import { CompiledQuery } from 'kysely';
+import { LocalNode, NodeInsertInput } from '@/types/nodes';
+import { buildNodeInsertMutation } from '@/lib/nodes';
interface MessageCreateMutationInput {
conversationId: string;
@@ -21,66 +20,38 @@ export const useMessageCreateMutation = () => {
const editorNodes = mapContentsToEditorNodes(
input.content.content,
messageId,
- new Map<string, LocalNodeWithAttributes>(),
+ new Map<string, LocalNode>(),
);
if (editorNodes.length === 0) {
return;
}
- const nodesToCreate: CreateNode[] = [
+ const nodeInsertInputs: NodeInsertInput[] = [
{
id: messageId,
- type: NodeTypes.Message,
- parent_id: input.conversationId,
- index: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.Message,
+ parentId: input.conversationId,
+ index: null,
+ },
},
];
- const nodeAttributesToCreate: CreateNodeAttribute[] = [];
for (const node of editorNodes) {
- nodesToCreate.push({
+ nodeInsertInputs.push({
id: node.id,
- type: node.type,
- parent_id: node.parentId,
- index: node.index,
- content: node.content != null ? JSON.stringify(node.content) : null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: node.attributes,
});
-
- for (const attribute of node.attributes) {
- nodeAttributesToCreate.push({
- node_id: node.id,
- type: attribute.type,
- key: attribute.key,
- text_value: attribute.textValue,
- number_value: attribute.numberValue,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- });
- }
}
- const queries: CompiledQuery[] = [
- workspace.schema.insertInto('nodes').values(nodesToCreate).compile(),
- ];
-
- if (nodeAttributesToCreate.length > 0) {
- queries.push(
- workspace.schema
- .insertInto('node_attributes')
- .values(nodeAttributesToCreate)
- .compile(),
- );
- }
+ const query = buildNodeInsertMutation(
+ workspace.schema,
+ workspace.userId,
+ nodeInsertInputs,
+ );
- await workspace.mutate(queries);
+ 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
index aa66c01b..518c7a4d 100644
--- a/desktop/src/mutations/use-node-attribute-delete-mutation.tsx
+++ b/desktop/src/mutations/use-node-attribute-delete-mutation.tsx
@@ -1,9 +1,11 @@
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;
- type: string;
key: string;
}
@@ -12,18 +14,43 @@ export const useNodeAttributeDeleteMutation = () => {
return useMutation({
mutationFn: async (input: NodeAttributeDeleteInput) => {
- const query = workspace.schema
- .deleteFrom('node_attributes')
- .where((eb) =>
- eb.and([
- eb('node_id', '=', input.nodeId),
- eb('type', '=', input.type),
- eb('key', '=', input.key),
- ]),
- )
+ const selectQuery = workspace.schema
+ .selectFrom('nodes')
+ .where('id', '=', input.nodeId)
+ .selectAll()
.compile();
- await workspace.mutate(query);
+ 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
new file mode 100644
index 00000000..673405aa
--- /dev/null
+++ b/desktop/src/mutations/use-node-attribute-set-mutation.tsx
@@ -0,0 +1,57 @@
+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-attribute-upsert-mutation.tsx b/desktop/src/mutations/use-node-attribute-upsert-mutation.tsx
deleted file mode 100644
index 96122bba..00000000
--- a/desktop/src/mutations/use-node-attribute-upsert-mutation.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { NeuronId } from '@/lib/id';
-import { useMutation } from '@tanstack/react-query';
-
-interface NodeAttributeUpsertInput {
- nodeId: string;
- type: string;
- key: string;
- textValue: string | null;
- numberValue: number | null;
- foreignNodeId: string | null;
-}
-
-export const useNodeAttributeUpsertMutation = () => {
- const workspace = useWorkspace();
-
- return useMutation({
- mutationFn: async (input: NodeAttributeUpsertInput) => {
- const query = workspace.schema
- .insertInto('node_attributes')
- .values({
- node_id: input.nodeId,
- type: input.type,
- key: input.key,
- text_value: input.textValue,
- number_value: input.numberValue,
- foreign_node_id: input.foreignNodeId,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .onConflict((b) =>
- b.doUpdateSet({
- text_value: input.textValue,
- number_value: input.numberValue,
- foreign_node_id: input.foreignNodeId,
- updated_at: new Date().toISOString(),
- updated_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- }),
- )
- .compile();
-
- await workspace.mutate(query);
- },
- });
-};
diff --git a/desktop/src/mutations/use-page-create-mutation.tsx b/desktop/src/mutations/use-page-create-mutation.tsx
index ced2f779..abadcd3b 100644
--- a/desktop/src/mutations/use-page-create-mutation.tsx
+++ b/desktop/src/mutations/use-page-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { useMutation } from '@tanstack/react-query';
@@ -32,36 +32,21 @@ export const usePageCreateMutation = () => {
const id = NeuronId.generate(NeuronId.Type.Page);
const index = generateNodeIndex(maxIndex, null);
- const insertPageQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id,
- type: NodeTypes.Page,
- parent_id: input.spaceId,
- index,
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertPageAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: id,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ const query = buildNodeInsertMutation(
+ workspace.schema,
+ workspace.userId,
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Page,
+ parentId: input.spaceId,
+ index: index,
+ name: input.name,
},
- ])
- .compile();
+ },
+ );
- await workspace.mutate([insertPageQuery, insertPageAttributesQuery]);
+ await workspace.mutate(query);
return id;
},
});
diff --git a/desktop/src/mutations/use-record-create-mutation.tsx b/desktop/src/mutations/use-record-create-mutation.tsx
index 5f6e723a..4176bf49 100644
--- a/desktop/src/mutations/use-record-create-mutation.tsx
+++ b/desktop/src/mutations/use-record-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { useMutation } from '@tanstack/react-query';
interface RecordCreateInput {
@@ -26,24 +26,23 @@ export const useRecordCreateMutation = () => {
result.rows && result.rows.length > 0 ? result.rows[0] : null;
const maxIndex = lastChild?.index ? lastChild.index : null;
- const recordId = NeuronId.generate(NeuronId.Type.Record);
+ const id = NeuronId.generate(NeuronId.Type.Record);
const index = generateNodeIndex(maxIndex, null);
- const query = workspace.schema
- .insertInto('nodes')
- .values({
- id: recordId,
- type: NodeTypes.Record,
- parent_id: input.databaseId,
- index,
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
+ const query = buildNodeInsertMutation(
+ workspace.schema,
+ workspace.userId,
+ {
+ id: id,
+ attributes: {
+ type: NodeTypes.Record,
+ parentId: input.databaseId,
+ index: index,
+ },
+ },
+ );
await workspace.mutate(query);
- return recordId;
+ return id;
},
});
};
diff --git a/desktop/src/mutations/use-select-option-create-mutation.tsx b/desktop/src/mutations/use-select-option-create-mutation.tsx
index 70549e65..448413b8 100644
--- a/desktop/src/mutations/use-select-option-create-mutation.tsx
+++ b/desktop/src/mutations/use-select-option-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { useMutation } from '@tanstack/react-query';
interface CreateSelectOptionInput {
@@ -12,6 +12,7 @@ interface CreateSelectOptionInput {
export const useSelectOptionCreateMutation = () => {
const workspace = useWorkspace();
+
return useMutation({
mutationFn: async (input: CreateSelectOptionInput) => {
const lastChildQuery = workspace.schema
@@ -32,50 +33,24 @@ export const useSelectOptionCreateMutation = () => {
result.rows && result.rows.length > 0 ? result.rows[0] : null;
const maxIndex = lastChild?.index ? lastChild.index : null;
- const selectOptionId = NeuronId.generate(NeuronId.Type.SelectOption);
- const insertSelectOptionQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: selectOptionId,
- type: NodeTypes.SelectOption,
- parent_id: input.fieldId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertSelectOptionAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: selectOptionId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: selectOptionId,
- type: AttributeTypes.Color,
- key: '1',
- text_value: input.color,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ 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,
},
- ])
- .compile();
+ },
+ );
- await workspace.mutate([
- insertSelectOptionQuery,
- insertSelectOptionAttributesQuery,
- ]);
- return selectOptionId;
+ await workspace.mutate(query);
+ return id;
},
});
};
diff --git a/desktop/src/mutations/use-space-create-mutation.tsx b/desktop/src/mutations/use-space-create-mutation.tsx
index 5ed3b331..bfe53afb 100644
--- a/desktop/src/mutations/use-space-create-mutation.tsx
+++ b/desktop/src/mutations/use-space-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
+import { NodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { useMutation } from '@tanstack/react-query';
interface SpaceCreateMutationInput {
@@ -11,6 +11,7 @@ interface SpaceCreateMutationInput {
export const useSpaceCreateMutation = () => {
const workspace = useWorkspace();
+
return useMutation({
mutationFn: async (values: SpaceCreateMutationInput) => {
const spaceId = NeuronId.generate(NeuronId.Type.Space);
@@ -20,85 +21,40 @@ export const useSpaceCreateMutation = () => {
const pageIndex = generateNodeIndex(null, null);
const channelIndex = generateNodeIndex(pageIndex, null);
- const insertNodesQuery = workspace.schema
- .insertInto('nodes')
- .values([
+ const query = buildNodeInsertMutation(
+ workspace.schema,
+ workspace.userId,
+ [
{
id: spaceId,
- type: NodeTypes.Space,
- parent_id: null,
- index: null,
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.Space,
+ name: values.name,
+ description: values.description,
+ },
},
{
id: pageId,
- type: NodeTypes.Page,
- parent_id: spaceId,
- index: pageIndex,
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.Page,
+ parentId: spaceId,
+ index: pageIndex,
+ name: 'Home',
+ },
},
{
id: channelId,
- type: NodeTypes.Channel,
- parent_id: spaceId,
- index: channelIndex,
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
-
- const insertNodeAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: spaceId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: values.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: spaceId,
- type: AttributeTypes.Description,
- key: '1',
- text_value: values.description,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: pageId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: 'Home',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: channelId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: 'Discussions',
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
+ attributes: {
+ type: NodeTypes.Channel,
+ parentId: spaceId,
+ index: channelIndex,
+ name: 'Discussions',
+ },
},
- ])
- .compile();
+ ],
+ );
- await workspace.mutate([insertNodesQuery, insertNodeAttributesQuery]);
+ await workspace.mutate(query);
return spaceId;
},
});
diff --git a/desktop/src/mutations/use-table-view-create-mutation.tsx b/desktop/src/mutations/use-table-view-create-mutation.tsx
index 99e49828..49a6e4d9 100644
--- a/desktop/src/mutations/use-table-view-create-mutation.tsx
+++ b/desktop/src/mutations/use-table-view-create-mutation.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
+import { buildNodeInsertMutation, generateNodeIndex } from '@/lib/nodes';
import { compareString } from '@/lib/utils';
import { useMutation } from '@tanstack/react-query';
@@ -35,36 +35,23 @@ export const useTableViewCreateMutation = () => {
].index
: null;
- const tableViewId = NeuronId.generate(NeuronId.Type.TableView);
- const insertTableViewQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: tableViewId,
- type: NodeTypes.TableView,
- parent_id: input.databaseId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertTableViewNameQuery = workspace.schema
- .insertInto('node_attributes')
- .values({
- node_id: tableViewId,
- type: AttributeTypes.Name,
- key: '1',
- text_value: input.name,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
+ 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([insertTableViewQuery, insertTableViewNameQuery]);
- return tableViewId;
+ await workspace.mutate(query);
+ return id;
},
});
};
diff --git a/desktop/src/mutations/use-view-filter-create-mutation.tsx b/desktop/src/mutations/use-view-filter-create-mutation.tsx
deleted file mode 100644
index 64a837f9..00000000
--- a/desktop/src/mutations/use-view-filter-create-mutation.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
-
-interface CreateViewFilterInput {
- viewId: string;
- fieldId: string;
- operator: string;
-}
-
-export const useViewFilterCreateMutation = () => {
- const workspace = useWorkspace();
- return useMutation({
- mutationFn: async (input: CreateViewFilterInput) => {
- const lastChildQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and({
- parent_id: input.viewId,
- type: NodeTypes.ViewFilter,
- }),
- )
- .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 viewFilterId = NeuronId.generate(NeuronId.Type.ViewFilter);
- const insertViewFilterQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: viewFilterId,
- type: NodeTypes.ViewFilter,
- parent_id: input.viewId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertViewFilterAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: viewFilterId,
- type: AttributeTypes.FieldId,
- key: '1',
- foreign_node_id: input.fieldId,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: viewFilterId,
- type: AttributeTypes.Operator,
- key: '1',
- text_value: input.operator,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
-
- await workspace.mutate([
- insertViewFilterQuery,
- insertViewFilterAttributesQuery,
- ]);
- return viewFilterId;
- },
- });
-};
diff --git a/desktop/src/mutations/use-view-sort-create-mutation.tsx b/desktop/src/mutations/use-view-sort-create-mutation.tsx
deleted file mode 100644
index 5d4ddaab..00000000
--- a/desktop/src/mutations/use-view-sort-create-mutation.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { useWorkspace } from '@/contexts/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
-import { NeuronId } from '@/lib/id';
-import { generateNodeIndex } from '@/lib/nodes';
-import { useMutation } from '@tanstack/react-query';
-
-interface CreateViewSortInput {
- viewId: string;
- fieldId: string;
- direction: string;
-}
-
-export const useViewSortCreateMutation = () => {
- const workspace = useWorkspace();
- return useMutation({
- mutationFn: async (input: CreateViewSortInput) => {
- const lastViewSortQuery = workspace.schema
- .selectFrom('nodes')
- .where((eb) =>
- eb.and({
- parent_id: input.viewId,
- type: NodeTypes.ViewSort,
- }),
- )
- .selectAll()
- .orderBy('index', 'desc')
- .limit(1)
- .compile();
-
- const result = await workspace.query(lastViewSortQuery);
- const lastViewSort =
- result.rows && result.rows.length > 0 ? result.rows[0] : null;
- const maxIndex = lastViewSort?.index ? lastViewSort.index : null;
-
- const viewSortId = NeuronId.generate(NeuronId.Type.ViewSort);
- const insertViewSortQuery = workspace.schema
- .insertInto('nodes')
- .values({
- id: viewSortId,
- type: NodeTypes.ViewSort,
- parent_id: input.viewId,
- index: generateNodeIndex(maxIndex, null),
- content: null,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- })
- .compile();
-
- const insertViewSortAttributesQuery = workspace.schema
- .insertInto('node_attributes')
- .values([
- {
- node_id: viewSortId,
- type: AttributeTypes.FieldId,
- key: '1',
- foreign_node_id: input.fieldId,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- {
- node_id: viewSortId,
- type: AttributeTypes.Direction,
- key: '1',
- text_value: input.direction,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- version_id: NeuronId.generate(NeuronId.Type.Version),
- },
- ])
- .compile();
-
- await workspace.mutate([
- insertViewSortQuery,
- insertViewSortAttributesQuery,
- ]);
- return viewSortId;
- },
- });
-};
diff --git a/desktop/src/queries/use-breadcrumb-query.tsx b/desktop/src/queries/use-breadcrumb-query.tsx
index e2ba7ebd..cfb40ff9 100644
--- a/desktop/src/queries/use-breadcrumb-query.tsx
+++ b/desktop/src/queries/use-breadcrumb-query.tsx
@@ -1,22 +1,16 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes } from '@/lib/constants';
-import { mapNodeWithAttributes } from '@/lib/nodes';
+import { SelectNode } from '@/data/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<SelectNodeWithAttributes>,
- Error,
- BreadcrumbNode[],
- string[]
- >({
+ return useQuery<QueryResult<SelectNode>, Error, BreadcrumbNode[], string[]>({
queryKey: ['breadcrumb', nodeId],
queryFn: async ({ queryKey }) => {
- const query = sql<SelectNodeWithAttributes>`
+ const query = sql<SelectNode>`
WITH RECURSIVE breadcrumb_nodes AS (
SELECT *
FROM nodes
@@ -26,32 +20,8 @@ export const useBreadcrumbQuery = (nodeId: string) => {
FROM nodes n
INNER JOIN breadcrumb_nodes b ON n.id = b.parent_id
)
- SELECT
- n.*,
- CASE
- WHEN COUNT(na.node_id) = 0 THEN json('[]')
- ELSE json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.'updated_by',
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- )
- END as attributes
- FROM breadcrumb_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ SELECT n.*
+ FROM breadcrumb_nodes n;
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -59,7 +29,7 @@ export const useBreadcrumbQuery = (nodeId: string) => {
query,
});
},
- select: (data: QueryResult<SelectNodeWithAttributes>): BreadcrumbNode[] => {
+ select: (data: QueryResult<SelectNode>): BreadcrumbNode[] => {
const rows = data?.rows ?? [];
return buildBreadcrumbNodes(nodeId, rows);
},
@@ -68,7 +38,7 @@ export const useBreadcrumbQuery = (nodeId: string) => {
const buildBreadcrumbNodes = (
nodeId: string,
- rows: SelectNodeWithAttributes[],
+ rows: SelectNode[],
): BreadcrumbNode[] => {
const breadcrumbNodes: BreadcrumbNode[] = [];
@@ -85,20 +55,15 @@ const buildBreadcrumbNodes = (
return breadcrumbNodes.reverse();
};
-const buildBreadcrumbNode = (row: SelectNodeWithAttributes): BreadcrumbNode => {
- const nodeWithAttributes = mapNodeWithAttributes(row);
+const buildBreadcrumbNode = (row: SelectNode): BreadcrumbNode => {
+ const node = mapNode(row);
- const name = nodeWithAttributes.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = nodeWithAttributes.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue;
+ const name = node.attributes.name;
+ const avatar = node.attributes.avatar;
return {
- id: nodeWithAttributes.id,
- type: nodeWithAttributes.type,
+ 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
index 92299e5d..84ab0fe0 100644
--- a/desktop/src/queries/use-database-query.tsx
+++ b/desktop/src/queries/use-database-query.tsx
@@ -1,28 +1,28 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes, NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { mapNodeWithAttributes } from '@/lib/nodes';
+import { SelectNode } from '@/data/schemas/workspace';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { mapNode } from '@/lib/nodes';
import {
DatabaseNode,
FieldDataType,
FieldNode,
SelectOptionNode,
} from '@/types/databases';
-import { LocalNodeWithAttributes } from '@/types/nodes';
+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<SelectNodeWithAttributes>,
+ QueryResult<SelectNode>,
Error,
DatabaseNode | null,
string[]
>({
queryKey: ['database', databaseId],
queryFn: async ({ queryKey }) => {
- const query = sql<SelectNodeWithAttributes>`
+ const query = sql<SelectNode>`
WITH database_node AS (
SELECT *
FROM nodes
@@ -42,40 +42,12 @@ export const useDatabaseQuery = (databaseId: string) => {
FROM field_nodes
)
AND type = ${NodeTypes.SelectOption}
- ),
- all_nodes AS (
- SELECT * FROM database_node
- UNION ALL
- SELECT * FROM field_nodes
- UNION ALL
- SELECT * FROM select_option_nodes
)
- SELECT
- n.*,
- CASE
- WHEN COUNT(na.node_id) = 0 THEN json('[]')
- ELSE json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.'updated_by',
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- )
- END as attributes
- FROM all_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ SELECT * FROM database_node
+ UNION ALL
+ SELECT * FROM field_nodes
+ UNION ALL
+ SELECT * FROM select_option_nodes
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -83,19 +55,15 @@ export const useDatabaseQuery = (databaseId: string) => {
query,
});
},
- select: (
- data: QueryResult<SelectNodeWithAttributes>,
- ): DatabaseNode | null => {
+ select: (data: QueryResult<SelectNode>): DatabaseNode | null => {
const rows = data?.rows ?? [];
return buildDatabaseNode(rows);
},
});
};
-const buildDatabaseNode = (
- rows: SelectNodeWithAttributes[],
-): DatabaseNode | null => {
- const nodes = rows.map((row) => mapNodeWithAttributes(row));
+const buildDatabaseNode = (rows: SelectNode[]): DatabaseNode | null => {
+ const nodes = rows.map((row) => mapNode(row));
const databaseLocalNode = nodes.find(
(node) => node.type === NodeTypes.Database,
@@ -104,10 +72,7 @@ const buildDatabaseNode = (
return null;
}
- const name = databaseLocalNode.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
+ const name = databaseLocalNode.attributes.name;
const fieldsNodes = nodes.filter((node) => node.type === NodeTypes.Field);
const groupedSelectOptions = nodes
.filter((node) => node.type === NodeTypes.SelectOption)
@@ -119,7 +84,7 @@ const buildDatabaseNode = (
acc[node.parentId].push(node);
return acc;
},
- {} as Record<string, LocalNodeWithAttributes[]>,
+ {} as Record<string, LocalNode[]>,
);
const fields: FieldNode[] = [];
@@ -139,16 +104,11 @@ const buildDatabaseNode = (
};
const buildFieldNode = (
- node: LocalNodeWithAttributes,
- selectOptions: LocalNodeWithAttributes[],
+ node: LocalNode,
+ selectOptions: LocalNode[],
): FieldNode | null => {
- const name = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
- const dataType = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.DataType,
- )?.textValue as FieldDataType;
+ const name = node.attributes.name;
+ const dataType = node.attributes.dataType as FieldDataType;
if (!dataType) {
return null;
@@ -253,14 +213,9 @@ const buildFieldNode = (
}
};
-const buildSelectOption = (node: LocalNodeWithAttributes): SelectOptionNode => {
- const name = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
- const color = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Color,
- )?.textValue;
+const buildSelectOption = (node: LocalNode): SelectOptionNode => {
+ const name = node.attributes.name;
+ const color = node.attributes.color;
return {
id: node.id,
diff --git a/desktop/src/queries/use-database-views-query.tsx b/desktop/src/queries/use-database-views-query.tsx
index ee2f5fb1..898f004c 100644
--- a/desktop/src/queries/use-database-views-query.tsx
+++ b/desktop/src/queries/use-database-views-query.tsx
@@ -1,89 +1,26 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes, NodeTypes, ViewNodeTypes } from '@/lib/constants';
-import { mapNodeWithAttributes } from '@/lib/nodes';
+import { SelectNode } from '@/data/schemas/workspace';
+import { NodeTypes, ViewNodeTypes } from '@/lib/constants';
+import { mapNode } from '@/lib/nodes';
import {
BoardViewNode,
CalendarViewNode,
TableViewNode,
- ViewFilterNode,
- ViewFilterValueNode,
ViewNode,
- ViewSortNode,
} from '@/types/databases';
-import { LocalNodeWithAttributes } from '@/types/nodes';
+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<SelectNodeWithAttributes>,
- Error,
- ViewNode[],
- string[]
- >({
+ return useQuery<QueryResult<SelectNode>, Error, ViewNode[], string[]>({
queryKey: ['database-views', databaseId],
queryFn: async ({ queryKey }) => {
- const query = sql<SelectNodeWithAttributes>`
- WITH view_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id = ${databaseId} AND type IN (${sql.join(ViewNodeTypes)})
- ),
- view_filter_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IN
- (
- SELECT id
- FROM view_nodes
- )
- AND type = ${NodeTypes.ViewFilter}
- ),
- view_sort_nodes AS (
- SELECT *
- FROM nodes
- WHERE parent_id IN
- (
- SELECT id
- FROM view_nodes
- )
- AND type = ${NodeTypes.ViewSort}
- ),
- all_nodes AS (
- SELECT * FROM view_nodes
- UNION ALL
- SELECT * FROM view_filter_nodes
- UNION ALL
- SELECT * FROM view_sort_nodes
- )
- SELECT
- n.*,
- CASE
- WHEN COUNT(na.node_id) = 0 THEN json('[]')
- ELSE json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.'updated_by',
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- )
- END as attributes
- FROM all_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ const query = sql<SelectNode>`
+ SELECT *
+ FROM nodes
+ WHERE parent_id = ${databaseId} AND type IN (${sql.join(ViewNodeTypes)})
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -91,28 +28,18 @@ export const useDatabaseViewsQuery = (databaseId: string) => {
query,
});
},
- select: (data: QueryResult<SelectNodeWithAttributes>): ViewNode[] => {
+ select: (data: QueryResult<SelectNode>): ViewNode[] => {
const rows = data?.rows ?? [];
return buildViewNodes(rows);
},
});
};
-const buildViewNodes = (rows: SelectNodeWithAttributes[]): ViewNode[] => {
- const nodes = rows.map((row) => mapNodeWithAttributes(row));
-
- const viewNodes = nodes.filter((node) => ViewNodeTypes.includes(node.type));
+const buildViewNodes = (rows: SelectNode[]): ViewNode[] => {
+ const nodes = rows.map((row) => mapNode(row));
const views: ViewNode[] = [];
- for (const viewNode of viewNodes) {
- const viewFilters = nodes.filter(
- (node) =>
- node.type === NodeTypes.ViewFilter && node.parentId === viewNode.id,
- );
- const viewSorts = nodes.filter(
- (node) =>
- node.type === NodeTypes.ViewSort && node.parentId === viewNode.id,
- );
- const view = buildViewNode(viewNode, viewFilters, viewSorts);
+ for (const node of nodes) {
+ const view = buildViewNode(node);
if (view) {
views.push(view);
}
@@ -121,65 +48,27 @@ const buildViewNodes = (rows: SelectNodeWithAttributes[]): ViewNode[] => {
return views;
};
-const buildViewNode = (
- node: LocalNodeWithAttributes,
- filters: LocalNodeWithAttributes[],
- sorts: LocalNodeWithAttributes[],
-): ViewNode | null => {
+const buildViewNode = (node: LocalNode): ViewNode | null => {
if (node.type === NodeTypes.TableView) {
- return buildTableViewNode(node, filters, sorts);
+ return buildTableViewNode(node);
} else if (node.type === NodeTypes.BoardView) {
- return buildBoardViewNode(node, filters, sorts);
+ return buildBoardViewNode(node);
} else if (node.type === NodeTypes.CalendarView) {
- return buildCalendarViewNode(node, filters, sorts);
+ return buildCalendarViewNode(node);
}
return null;
};
-const buildTableViewNode = (
- node: LocalNodeWithAttributes,
- filters: LocalNodeWithAttributes[],
- sorts: LocalNodeWithAttributes[],
-): TableViewNode => {
- const name = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
- const hiddenFields = node.attributes
- .filter((attribute) => attribute.type === AttributeTypes.HiddenField)
- .map((attribute) => attribute.foreignNodeId);
-
- const fieldIndexes = node.attributes
- .filter((attribute) => attribute.type === AttributeTypes.FieldIndex)
- .reduce(
- (acc, attribute) => {
- if (attribute.foreignNodeId && attribute.textValue !== null) {
- acc[attribute.foreignNodeId] = attribute.textValue;
- }
- return acc;
- },
- {} as Record<string, string>,
- );
+const 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 fieldWidths = node.attributes
- .filter((attribute) => attribute.type === AttributeTypes.FieldWidth)
- .reduce(
- (acc, attribute) => {
- if (attribute.foreignNodeId && attribute.numberValue !== null) {
- acc[attribute.foreignNodeId] = attribute.numberValue;
- }
- return acc;
- },
- {} as Record<string, number>,
- );
-
- const nameWidth = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.NameWidth,
- )?.numberValue;
-
- const viewFilters = filters.map(buildViewFilterNode);
- const viewSorts = sorts.map(buildViewSortNode);
+ const viewFilters = node.attributes.filters;
+ const viewSorts = node.attributes.sorts;
return {
id: node.id,
@@ -190,100 +79,40 @@ const buildTableViewNode = (
fieldWidths,
nameWidth: nameWidth,
versionId: node.versionId,
- filters: viewFilters,
- sorts: viewSorts,
+ filters: viewFilters ?? [],
+ sorts: viewSorts ?? [],
};
};
-const buildBoardViewNode = (
- node: LocalNodeWithAttributes,
- filters: LocalNodeWithAttributes[],
- sorts: LocalNodeWithAttributes[],
-): BoardViewNode => {
- const name = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
- const groupBy = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.GroupBy,
- )?.foreignNodeId;
-
- const viewFilters = filters.map(buildViewFilterNode);
- const viewSorts = sorts.map(buildViewSortNode);
+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,
+ filters: viewFilters ?? [],
+ sorts: viewSorts ?? [],
groupBy,
};
};
-const buildCalendarViewNode = (
- node: LocalNodeWithAttributes,
- filters: LocalNodeWithAttributes[],
- sorts: LocalNodeWithAttributes[],
-): CalendarViewNode => {
- const name = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Name,
- )?.textValue;
-
- const groupBy = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.GroupBy,
- )?.foreignNodeId;
+const buildCalendarViewNode = (node: LocalNode): CalendarViewNode => {
+ const name = node.attributes.name;
+ const groupBy = node.attributes.groupBy;
- const viewFilters = filters.map(buildViewFilterNode);
- const viewSorts = sorts.map(buildViewSortNode);
+ const viewFilters = node.attributes.filters;
+ const viewSorts = node.attributes.sorts;
return {
id: node.id,
name: name ?? 'Unnamed',
type: 'calendar_view',
- filters: viewFilters,
- sorts: viewSorts,
+ filters: viewFilters ?? [],
+ sorts: viewSorts ?? [],
groupBy,
};
};
-
-const buildViewFilterNode = (node: LocalNodeWithAttributes): ViewFilterNode => {
- const fieldId = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.FieldId,
- )?.foreignNodeId;
-
- const operator = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Operator,
- )?.textValue;
-
- const values: ViewFilterValueNode[] = node.attributes
- .filter((attribute) => attribute.type === AttributeTypes.Value)
- .map((attribute) => ({
- textValue: attribute.textValue,
- numberValue: attribute.numberValue,
- foreignNodeId: attribute.foreignNodeId,
- }));
-
- return {
- id: node.id,
- fieldId,
- operator,
- values,
- };
-};
-
-const buildViewSortNode = (node: LocalNodeWithAttributes): ViewSortNode => {
- const fieldId = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.FieldId,
- )?.foreignNodeId;
-
- const direction = node.attributes.find(
- (attribute) => attribute.type === AttributeTypes.Direction,
- )?.textValue;
-
- return {
- id: node.id,
- fieldId,
- direction: direction as any,
- };
-};
diff --git a/desktop/src/queries/use-document-query.tsx b/desktop/src/queries/use-document-query.tsx
index dc00a716..cbd35986 100644
--- a/desktop/src/queries/use-document-query.tsx
+++ b/desktop/src/queries/use-document-query.tsx
@@ -1,23 +1,23 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
+import { SelectNode } from '@/data/schemas/workspace';
import { NodeTypes } from '@/lib/constants';
import { useQuery } from '@tanstack/react-query';
import { QueryResult, sql } from 'kysely';
-import { LocalNodeWithAttributes } from '@/types/nodes';
-import { mapNodeWithAttributes } from '@/lib/nodes';
+import { LocalNode } from '@/types/nodes';
+import { mapNode } from '@/lib/nodes';
export const useDocumentQuery = (id: string) => {
const workspace = useWorkspace();
return useQuery<
- QueryResult<SelectNodeWithAttributes>,
+ QueryResult<SelectNode>,
Error,
- Map<string, LocalNodeWithAttributes>,
+ Map<string, LocalNode>,
string[]
>({
queryKey: ['document', id],
queryFn: async ({ queryKey }) => {
- const query = sql<SelectNodeWithAttributes>`
+ const query = sql<SelectNode>`
WITH RECURSIVE document_nodes AS (
SELECT *
FROM nodes
@@ -30,29 +30,8 @@ export const useDocumentQuery = (id: string) => {
INNER JOIN document_nodes parent ON child.parent_id = parent.id
WHERE parent.type NOT IN (${NodeTypes.Page})
)
- SELECT
- n.*,
- json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.updated_by,
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- ) as attributes
- FROM document_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ SELECT *
+ FROM document_nodes
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -64,12 +43,10 @@ export const useDocumentQuery = (id: string) => {
});
};
-const buildMap = (
- rows: SelectNodeWithAttributes[],
-): Map<string, LocalNodeWithAttributes> => {
- const map = new Map<string, LocalNodeWithAttributes>();
+const buildMap = (rows: SelectNode[]): Map<string, LocalNode> => {
+ const map = new Map<string, LocalNode>();
rows.forEach((row) => {
- map.set(row.id, mapNodeWithAttributes(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
index f1e806a9..5946be09 100644
--- a/desktop/src/queries/use-messages-query.tsx
+++ b/desktop/src/queries/use-messages-query.tsx
@@ -1,10 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode, SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
-import {
- buildNodeWithAttributesAndChildren,
- mapNodeWithAttributes,
-} from '@/lib/nodes';
+import { SelectNode } from '@/data/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 { User } from '@/types/users';
@@ -13,7 +10,7 @@ import { QueryResult, sql } from 'kysely';
const MESSAGES_PER_PAGE = 50;
-type MessageRow = SelectNodeWithAttributes & {
+type MessageRow = SelectNode & {
reaction_counts: string | null;
user_reactions: string | null;
};
@@ -77,31 +74,6 @@ export const useMessagesQuery = (conversationId: string) => {
UNION ALL
SELECT * FROM author_nodes
),
- node_attributes_aggregated AS (
- SELECT
- na.node_id,
- json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.'updated_by',
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- ) AS attributes
- FROM node_attributes na
- WHERE na.node_id IN (SELECT id FROM all_nodes)
- GROUP BY na.node_id
- ),
message_reaction_counts AS (
SELECT
mrc.node_id,
@@ -129,11 +101,9 @@ export const useMessagesQuery = (conversationId: string) => {
)
SELECT
n.*,
- COALESCE(na.attributes, json('[]')) AS attributes,
COALESCE(mrc.reaction_counts, json('[]')) AS reaction_counts,
COALESCE(ur.user_reactions, json('[]')) AS user_reactions
FROM all_nodes n
- LEFT JOIN node_attributes_aggregated na ON n.id = na.node_id
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);
@@ -159,19 +129,14 @@ const buildMessages = (rows: MessageRow[]): MessageNode[] => {
.filter(
(row) => row.type !== NodeTypes.User && row.type !== NodeTypes.Message,
)
- .map(mapNodeWithAttributes);
+ .map(mapNode);
const messages: MessageNode[] = [];
const authorMap = new Map<string, User>();
for (const authorRow of authorRows) {
- const authorNode = mapNodeWithAttributes(authorRow);
- const name = authorNode.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = authorNode.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue;
+ const authorNode = mapNode(authorRow);
+ const name = authorNode.attributes.name;
+ const avatar = authorNode.attributes.avatar;
authorMap.set(authorRow.id, {
id: authorRow.id,
@@ -181,11 +146,11 @@ const buildMessages = (rows: MessageRow[]): MessageNode[] => {
}
for (const messageRow of messageRows) {
- const messageNode = mapNodeWithAttributes(messageRow);
+ const messageNode = mapNode(messageRow);
const author = authorMap.get(messageNode.createdBy);
const children = contentNodes
.filter((n) => n.parentId === messageNode.id)
- .map((n) => buildNodeWithAttributesAndChildren(n, contentNodes));
+ .map((n) => buildNodeWithChildren(n, contentNodes));
const reactionCounts: MessageReactionCount[] = JSON.parse(
messageRow.reaction_counts,
diff --git a/desktop/src/queries/use-record-query.tsx b/desktop/src/queries/use-record-query.tsx
index 39b17039..396149f7 100644
--- a/desktop/src/queries/use-record-query.tsx
+++ b/desktop/src/queries/use-record-query.tsx
@@ -1,7 +1,7 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
-import { mapNodeWithAttributes } from '@/lib/nodes';
+import { SelectNode } from '@/data/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';
@@ -9,15 +9,10 @@ import { QueryResult, sql } from 'kysely';
export const useRecordQuery = (recordId: string) => {
const workspace = useWorkspace();
- return useQuery<
- QueryResult<SelectNodeWithAttributes>,
- Error,
- RecordNode | null,
- string[]
- >({
+ return useQuery<QueryResult<SelectNode>, Error, RecordNode | null, string[]>({
queryKey: ['record', recordId],
queryFn: async ({ queryKey }) => {
- const query = sql<SelectNodeWithAttributes>`
+ const query = sql<SelectNode>`
WITH record_node AS (
SELECT *
FROM nodes
@@ -27,35 +22,10 @@ export const useRecordQuery = (recordId: string) => {
SELECT *
FROM nodes
WHERE id IN (SELECT DISTINCT created_by FROM record_node)
- ),
- all_nodes as (
- SELECT * FROM record_node
- UNION ALL
- SELECT * FROM author_node
)
- SELECT
- n.*,
- json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.updated_by,
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- ) as attributes
- FROM all_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ SELECT * FROM record_node
+ UNION ALL
+ SELECT * FROM author_node
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -63,9 +33,7 @@ export const useRecordQuery = (recordId: string) => {
query,
});
},
- select: (
- data: QueryResult<SelectNodeWithAttributes>,
- ): RecordNode | null => {
+ select: (data: QueryResult<SelectNode>): RecordNode | null => {
const rows = data?.rows ?? [];
return buildRecord(recordId, rows);
},
@@ -74,28 +42,21 @@ export const useRecordQuery = (recordId: string) => {
const buildRecord = (
recordId: string,
- rows: SelectNodeWithAttributes[],
+ rows: SelectNode[],
): RecordNode | null => {
- const nodes = rows.map(mapNodeWithAttributes);
+ const nodes = rows.map(mapNode);
const recordNode = nodes.find((node) => node.id === recordId);
if (!recordNode) {
return null;
}
- const recordName = recordNode.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
+ const recordName = recordNode.attributes.name;
const authorNode = nodes.find((node) => node.type === NodeTypes.User);
const author = authorNode
? {
id: authorNode.id,
- name: authorNode.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue,
- avatar: authorNode.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue,
+ name: authorNode.attributes.name,
+ avatar: authorNode.attributes.avatar,
}
: {
id: recordNode.createdBy,
diff --git a/desktop/src/queries/use-records-query.tsx b/desktop/src/queries/use-records-query.tsx
index 3ba10216..03d65313 100644
--- a/desktop/src/queries/use-records-query.tsx
+++ b/desktop/src/queries/use-records-query.tsx
@@ -1,9 +1,9 @@
import { useDatabase } from '@/contexts/database';
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNode, SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
-import { mapNodeWithAttributes } from '@/lib/nodes';
-import { compareString } from '@/lib/utils';
+import { SelectNode } from '@/data/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { mapNode } from '@/lib/nodes';
+import { isStringArray } from '@/lib/utils';
import {
BooleanFieldNode,
CreatedAtFieldNode,
@@ -17,8 +17,9 @@ import {
SelectFieldNode,
TextFieldNode,
UrlFieldNode,
- ViewFilterNode,
- ViewSortNode,
+ ViewFieldFilter,
+ ViewFilter,
+ ViewSort,
} from '@/types/databases';
import { User } from '@/types/users';
import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
@@ -29,8 +30,8 @@ const RECORDS_PER_PAGE = 50;
export const useRecordsQuery = (
databaseId: string,
- filters: ViewFilterNode[],
- sorts: ViewSortNode[],
+ filters: ViewFilter[],
+ sorts: ViewSort[],
) => {
const workspace = useWorkspace();
const database = useDatabase();
@@ -42,7 +43,7 @@ export const useRecordsQuery = (
}
return useInfiniteQuery<
- QueryResult<SelectNodeWithAttributes>,
+ QueryResult<SelectNode>,
Error,
RecordNode[],
string[],
@@ -66,14 +67,12 @@ export const useRecordsQuery = (
const offset = pageParam * RECORDS_PER_PAGE;
const filterQuery = buildFiltersQuery(filters, database.fields);
- const joinsQuery = buildSortJoinsQuery(sorts, database.fields);
const orderByQuery = `ORDER BY ${sorts.length > 0 ? buildSortOrdersQuery(sorts, database.fields) : 'n."index" ASC'}`;
- const query = sql<SelectNodeWithAttributes>`
+ const query = sql<SelectNode>`
WITH record_nodes AS (
SELECT n.*, ROW_NUMBER() OVER (${sql.raw(orderByQuery)}) AS order_number
FROM nodes n
- ${sql.raw(joinsQuery)}
WHERE n.parent_id = ${databaseId} AND n.type = ${NodeTypes.Record} ${sql.raw(filterQuery)}
${sql.raw(orderByQuery)}
LIMIT ${sql.lit(RECORDS_PER_PAGE)}
@@ -89,30 +88,9 @@ export const useRecordsQuery = (
UNION ALL
SELECT * FROM author_nodes
)
- SELECT
- n.*,
- json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.updated_by,
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- ) as attributes
- FROM all_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id
- ORDER BY n.order_number ASC
+ SELECT n.*
+ FROM all_nodes n
+ ORDER BY n.order_number ASC
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -121,9 +99,7 @@ export const useRecordsQuery = (
query,
});
},
- select: (
- data: InfiniteData<QueryResult<SelectNodeWithAttributes>>,
- ): RecordNode[] => {
+ select: (data: InfiniteData<QueryResult<SelectNode>>): RecordNode[] => {
const pages = data?.pages ?? [];
const rows = pages.map((page) => page.rows).flat();
return buildRecords(rows);
@@ -131,8 +107,8 @@ export const useRecordsQuery = (
});
};
-const buildRecords = (rows: SelectNodeWithAttributes[]): RecordNode[] => {
- const nodes = rows.map(mapNodeWithAttributes);
+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);
@@ -140,13 +116,8 @@ const buildRecords = (rows: SelectNodeWithAttributes[]): RecordNode[] => {
const authorMap = new Map<string, User>();
for (const author of authorNodes) {
- const name = author.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = author.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue;
+ const name = author.attributes.name;
+ const avatar = author.attributes.avatar;
authorMap.set(author.id, {
id: author.id,
@@ -156,10 +127,7 @@ const buildRecords = (rows: SelectNodeWithAttributes[]): RecordNode[] => {
}
for (const node of recordNodes) {
- const name = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
+ const name = node.attributes.name;
const author = authorMap.get(node.createdBy);
const record: RecordNode = {
id: node.id,
@@ -183,7 +151,7 @@ const buildRecords = (rows: SelectNodeWithAttributes[]): RecordNode[] => {
};
const buildFiltersQuery = (
- filters: ViewFilterNode[],
+ filters: ViewFilter[],
fields: FieldNode[],
): string => {
if (filters.length === 0) {
@@ -198,33 +166,17 @@ const buildFiltersQuery = (
return '';
}
- const joinQueries = filterQueries
- .map((query) => query.joinQuery)
- .filter((query) => query !== null && query.length > 0);
-
- const whereQueries = filterQueries
- .map((query) => query.whereQuery)
- .filter((query) => query !== null && query.length > 0);
-
- return `AND n.id IN
- (
- SELECT na.node_id
- FROM node_attributes na
- ${joinQueries.join(' ')}
- ${whereQueries.length > 0 ? `WHERE ${whereQueries.join(' AND ')}` : ''}
- )
- `;
+ return `AND (${filterQueries.join(' AND ')})`;
};
-interface FilterQuery {
- joinQuery: string;
- whereQuery: string | null;
-}
-
const buildFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFilter,
fields: FieldNode[],
-): FilterQuery | null => {
+): string | null => {
+ if (filter.type === 'group') {
+ return null;
+ }
+
const field = fields.find((field) => field.id === filter.fieldId);
if (!field) {
return null;
@@ -263,607 +215,493 @@ const buildFilterQuery = (
};
const buildBooleanFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: BooleanFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_true') {
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value = 1`,
- whereQuery: null,
- };
+ return `json_extract(n.attributes, '$.${field.id}') = true`;
}
if (filter.operator === 'is_false') {
- return {
- joinQuery: buildFilterLeftJoinNodeAttributesQuery(filter.id, field.id),
- whereQuery: `na_${filter.id}.node_id IS NULL OR na_${filter.id}.number_value = 0`,
- };
+ return `(json_extract(n.attributes, '$.${field.id}') = false OR json_extract(n.attributes, '$.${field.id}') IS NULL)`;
}
return null;
};
const buildNumberFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: NumberFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
+ return buildIsNotEmptyFilterQuery(field.id);
}
- if (filter.values.length === 0) {
+ if (filter.value === null) {
return null;
}
- const value = filter.values[0].numberValue;
- if (value === 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':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value = ${value}`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value != ${value}`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'is_greater_than':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value > ${value}`,
- whereQuery: null,
- };
+ operator = '>';
+ break;
case 'is_less_than':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value < ${value}`,
- whereQuery: null,
- };
+ operator = '<';
+ break;
case 'is_greater_than_or_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value >= ${value}`,
- whereQuery: null,
- };
+ operator = '>=';
+ break;
case 'is_less_than_or_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.number_value <= ${value}`,
- whereQuery: null,
- };
+ operator = '<=';
+ break;
default:
return null;
}
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `json_extract(n.attributes, '$.${field.id}') ${operator} ${value}`;
};
const buildTextFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: TextFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
+ return buildIsNotEmptyFilterQuery(field.id);
}
- if (filter.values.length === 0) {
+ if (filter.value === null) {
return null;
}
- const value = filter.values[0].textValue;
- if (value === 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':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value = '${value}'`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value != '${value}'`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'contains':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'does_not_contain':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value NOT LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'starts_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
case 'ends_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}'`,
- whereQuery: null,
- };
+ 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: ViewFilterNode,
+ filter: ViewFilter,
field: EmailFieldNode,
-): FilterQuery | null => {
+): string | null => {
+ if (filter.type === 'group') {
+ return null;
+ }
+
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
+ return buildIsNotEmptyFilterQuery(field.id);
}
- if (filter.values.length === 0) {
+ if (filter.value === null) {
return null;
}
- const value = filter.values[0].textValue;
- if (value === 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':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value = '${value}'`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value != '${value}'`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'contains':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'does_not_contain':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value NOT LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'starts_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
case 'ends_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}'`,
- whereQuery: null,
- };
+ 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: ViewFilterNode,
+ filter: ViewFieldFilter,
field: PhoneFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
+ return buildIsNotEmptyFilterQuery(field.id);
}
- if (filter.values.length === 0) {
+ if (filter.value === null) {
return null;
}
- const value = filter.values[0].textValue;
- if (value === 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':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value = '${value}'`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value != '${value}'`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'contains':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'does_not_contain':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value NOT LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'starts_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
case 'ends_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}'`,
- whereQuery: null,
- };
+ 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: ViewFilterNode,
+ filter: ViewFieldFilter,
field: UrlFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
+ return buildIsNotEmptyFilterQuery(field.id);
}
- if (filter.values.length === 0) {
+ if (filter.value === null) {
return null;
}
- const value = filter.values[0].textValue;
- if (value === 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':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value = '${value}'`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value != '${value}'`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'contains':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'does_not_contain':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value NOT LIKE '%${value}%'`,
- whereQuery: null,
- };
+ operator = 'NOT LIKE';
+ formattedValue = `%${value}%`;
+ break;
case 'starts_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '${value}%'`,
- whereQuery: null,
- };
+ operator = 'LIKE';
+ formattedValue = `${value}%`;
+ break;
case 'ends_with':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.text_value LIKE '%${value}'`,
- whereQuery: null,
- };
+ 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: ViewFilterNode,
+ filter: ViewFieldFilter,
field: SelectFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
- }
-
- if (filter.values.length === 0) {
- return null;
+ return buildIsNotEmptyFilterQuery(field.id);
}
- const ids = filter.values.map((value) => value.foreignNodeId);
- if (ids.length === 0) {
+ if (!isStringArray(filter.value)) {
return null;
}
+ const values = joinIds(filter.value);
switch (filter.operator) {
case 'is_in':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.foreign_node_id IN (${joinIds(ids)})`,
- whereQuery: null,
- };
+ return `json_extract(n.attributes, '$.${field.id}') IN (${values})`;
case 'is_not_in':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.foreign_node_id NOT IN (${joinIds(ids)})`,
- whereQuery: null,
- };
+ return `json_extract(n.attributes, '$.${field.id}') NOT IN (${values})`;
default:
return null;
}
};
const buildMultiSelectFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: MultiSelectFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
- }
-
- if (filter.values.length === 0) {
- return null;
+ return buildIsNotEmptyFilterQuery(field.id);
}
- const ids = filter.values.map((value) => value.foreignNodeId);
- if (ids.length === 0) {
+ if (!isStringArray(filter.value)) {
return null;
}
+ const values = joinIds(filter.value);
switch (filter.operator) {
case 'is_in':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.foreign_node_id IN (${joinIds(ids)})`,
- whereQuery: null,
- };
+ return `json_extract(n.attributes, '$.${field.id}') IN (${values})`;
case 'is_not_in':
- return {
- joinQuery: `${buildFilterLeftJoinNodeAttributesQuery(filter.id, field.id)} AND na_${filter.id}.foreign_node_id IN (${joinIds(ids)})`,
- whereQuery: `na_${filter.id}.node_id IS NULL`,
- };
+ return `json_extract(n.attributes, '$.${field.id}') NOT IN (${values})`;
default:
return null;
}
};
const buildDateFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: DateFieldNode,
-): FilterQuery | null => {
+): string | null => {
if (filter.operator === 'is_empty') {
- return buildIsEmptyFilterQuery(filter.id, field.id);
+ return buildIsEmptyFilterQuery(field.id);
}
if (filter.operator === 'is_not_empty') {
- return buildIsNotEmptyFilterQuery(filter.id, field.id);
+ return buildIsNotEmptyFilterQuery(field.id);
}
- if (filter.values.length === 0) {
+ if (filter.value === null) {
return null;
}
- const value = filter.values[0].textValue;
- if (value === null) {
+ if (typeof filter.value !== 'string') {
return null;
}
- const date = new Date(value);
+ 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':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND DATE(na_${filter.id}.text_value) = '${dateString}'`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterLeftJoinNodeAttributesQuery(filter.id, field.id)} AND DATE(na_${filter.id}.text_value) != '${dateString}'`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'is_on_or_after':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND DATE(na_${filter.id}.text_value) >= '${dateString}'`,
- whereQuery: null,
- };
+ operator = '>=';
+ break;
case 'is_on_or_before':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND DATE(na_${filter.id}.text_value) <= '${dateString}'`,
- whereQuery: null,
- };
+ operator = '<=';
+ break;
case 'is_after':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND DATE(na_${filter.id}.text_value) > '${dateString}'`,
- whereQuery: null,
- };
+ operator = '>';
+ break;
case 'is_before':
- return {
- joinQuery: `${buildFilterJoinNodeAttributesQuery(filter.id, field.id)} AND DATE(na_${filter.id}.text_value) < '${dateString}'`,
- whereQuery: null,
- };
+ operator = '<';
+ break;
default:
return null;
}
+
+ if (operator === null) {
+ return null;
+ }
+
+ return `DATE(json_extract(n.attributes, '$.${field.id}')) ${operator} '${dateString}'`;
};
const buildCreatedAtFilterQuery = (
- filter: ViewFilterNode,
+ filter: ViewFieldFilter,
field: CreatedAtFieldNode,
-): FilterQuery | null => {
- if (filter.values.length === 0) {
+): 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;
}
- const value = filter.values[0].textValue;
- if (value === null) {
+ if (typeof filter.value !== 'string') {
return null;
}
- const date = new Date(value);
+ 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':
- return {
- joinQuery: `${buildFilterJoinNodesQuery(filter.id)} AND DATE(n_${filter.id}.created_at) = '${dateString}'`,
- whereQuery: null,
- };
+ operator = '=';
+ break;
case 'is_not_equal_to':
- return {
- joinQuery: `${buildFilterLeftJoinNodesQuery(filter.id)} AND DATE(n_${filter.id}.created_at) != '${dateString}'`,
- whereQuery: null,
- };
+ operator = '!=';
+ break;
case 'is_on_or_after':
- return {
- joinQuery: `${buildFilterJoinNodesQuery(filter.id)} AND DATE(n_${filter.id}.created_at) >= '${dateString}'`,
- whereQuery: null,
- };
+ operator = '>=';
+ break;
case 'is_on_or_before':
- return {
- joinQuery: `${buildFilterJoinNodesQuery(filter.id)} AND DATE(n_${filter.id}.created_at) <= '${dateString}'`,
- whereQuery: null,
- };
+ operator = '<=';
+ break;
case 'is_after':
- return {
- joinQuery: `${buildFilterJoinNodesQuery(filter.id)} AND DATE(n_${filter.id}.created_at) > '${dateString}'`,
- whereQuery: null,
- };
+ operator = '>';
+ break;
case 'is_before':
- return {
- joinQuery: `${buildFilterJoinNodesQuery(filter.id)} AND DATE(n_${filter.id}.created_at) < '${dateString}'`,
- whereQuery: null,
- };
+ operator = '<';
+ break;
default:
return null;
}
-};
-
-const buildIsEmptyFilterQuery = (
- filterId: string,
- fieldId: string,
-): FilterQuery => {
- return {
- joinQuery: buildFilterLeftJoinNodeAttributesQuery(filterId, fieldId),
- whereQuery: `na_${filterId}.node_id IS NULL`,
- };
-};
-const buildIsNotEmptyFilterQuery = (
- filterId: string,
- fieldId: string,
-): FilterQuery => {
- return {
- joinQuery: buildFilterJoinNodeAttributesQuery(filterId, fieldId),
- whereQuery: null,
- };
-};
+ if (operator === null) {
+ return null;
+ }
-const buildFilterJoinNodesQuery = (filterId: string): string => {
- return `JOIN nodes n_${filterId} ON n_${filterId}.id = na.node_id`;
+ return `DATE(n.created_at) ${operator} '${dateString}'`;
};
-const buildFilterLeftJoinNodesQuery = (filterId: string): string => {
- return `LEFT JOIN nodes n_${filterId} ON n_${filterId}.id = na.node_id`;
+const buildIsEmptyFilterQuery = (fieldId: string): string => {
+ return `json_extract(n.attributes, '$.${fieldId}') IS NULL`;
};
-const buildFilterJoinNodeAttributesQuery = (
- filterId: string,
- fieldId: string,
-): string => {
- return `JOIN node_attributes na_${filterId} ON na_${filterId}.node_id = na.node_id AND na_${filterId}.type = '${fieldId}'`;
-};
-
-const buildFilterLeftJoinNodeAttributesQuery = (
- filterId: string,
- fieldId: string,
-): string => {
- return `LEFT JOIN node_attributes na_${filterId} ON na_${filterId}.node_id = na.node_id AND na_${filterId}.type = '${fieldId}'`;
+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 buildSortJoinsQuery = (
- sorts: ViewSortNode[],
- fields: FieldNode[],
-): string => {
- if (sorts.length === 0) {
- return '';
- }
-
- const joinQueries = sorts
- .map((sort) => buildSortJoinQuery(sort, fields))
- .filter((query) => query !== null && query.length > 0);
-
- return joinQueries.join(' ');
-};
-
-const buildSortJoinQuery = (
- sort: ViewSortNode,
- fields: FieldNode[],
-): string | null => {
- const field = fields.find((field) => field.id === sort.fieldId);
- if (!field) {
- return null;
- }
-
- switch (field.dataType) {
- case 'boolean':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'collaborator':
- return null;
- case 'created_at':
- return buildSortLeftJoinNodesQuery(sort.id);
- case 'created_by':
- return null;
- case 'date':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'email':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'file':
- return null;
- case 'multi_select':
- return null;
- case 'number':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'phone':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'select':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'text':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- case 'url':
- return buildSortLeftJoinNodeAttributesQuery(sort.id, field.id);
- default:
- return null;
- }
-};
-
const buildSortOrdersQuery = (
- sorts: ViewSortNode[],
+ sorts: ViewSort[],
fields: FieldNode[],
): string => {
return sorts
@@ -873,7 +711,7 @@ const buildSortOrdersQuery = (
};
const buildSortOrderQuery = (
- sort: ViewSortNode,
+ sort: ViewSort,
fields: FieldNode[],
): string | null => {
const field = fields.find((field) => field.id === sort.fieldId);
@@ -881,45 +719,13 @@ const buildSortOrderQuery = (
return null;
}
- switch (field.dataType) {
- case 'boolean':
- return `na_${sort.id}.number_value ${sort.direction}`;
- case 'collaborator':
- return null;
- case 'created_at':
- return `n_${sort.id}.created_at ${sort.direction}`;
- case 'created_by':
- return null;
- case 'date':
- return `na_${sort.id}.text_value ${sort.direction}`;
- case 'email':
- return `na_${sort.id}.text_value ${sort.direction}`;
- case 'file':
- return null;
- case 'multi_select':
- return null;
- case 'number':
- return `na_${sort.id}.number_value ${sort.direction}`;
- case 'phone':
- return `na_${sort.id}.text_value ${sort.direction}`;
- case 'select':
- return `na_${sort.id}.text_value ${sort.direction}`;
- case 'text':
- return `na_${sort.id}.text_value ${sort.direction}`;
- case 'url':
- return `na_${sort.id}.text_value ${sort.direction}`;
- default:
- return null;
+ if (field.dataType === 'created_at') {
+ return `n.created_at ${sort.direction}`;
}
-};
-const buildSortLeftJoinNodesQuery = (sortId: string): string => {
- return `LEFT JOIN nodes n_${sortId} ON n_${sortId}.id = n.id`;
-};
+ if (field.dataType === 'created_by') {
+ return `n.created_by_id ${sort.direction}`;
+ }
-const buildSortLeftJoinNodeAttributesQuery = (
- sortId: string,
- fieldId: string,
-): string => {
- return `LEFT JOIN node_attributes na_${sortId} ON na_${sortId}.node_id = n.id AND na_${sortId}.type = '${fieldId}'`;
+ return `json_extract(n.attributes, '$.${field.id}') ${sort.direction}`;
};
diff --git a/desktop/src/queries/use-sidebar-query.tsx b/desktop/src/queries/use-sidebar-query.tsx
index dde4b87d..51e2c0cd 100644
--- a/desktop/src/queries/use-sidebar-query.tsx
+++ b/desktop/src/queries/use-sidebar-query.tsx
@@ -1,8 +1,8 @@
import { useWorkspace } from '@/contexts/workspace';
-import { SelectNodeWithAttributes } from '@/data/schemas/workspace';
-import { AttributeTypes, NodeTypes } from '@/lib/constants';
-import { mapNodeWithAttributes } from '@/lib/nodes';
-import { LocalNodeWithAttributes } from '@/types/nodes';
+import { SelectNode } from '@/data/schemas/workspace';
+import { NodeTypes } from '@/lib/constants';
+import { mapNode } from '@/lib/nodes';
+import { LocalNode } from '@/types/nodes';
import {
SidebarChatNode,
SidebarNode,
@@ -19,15 +19,11 @@ export type SidebarQueryResult = {
export const useSidebarQuery = () => {
const workspace = useWorkspace();
- return useQuery<
- QueryResult<SelectNodeWithAttributes>,
- Error,
- SidebarQueryResult,
- string[]
- >({
- queryKey: ['sidebar', workspace.id],
- queryFn: async ({ queryKey }) => {
- const query = sql<SelectNodeWithAttributes>`
+ return useQuery<QueryResult<SelectNode>, Error, SidebarQueryResult, string[]>(
+ {
+ queryKey: ['sidebar', workspace.id],
+ queryFn: async ({ queryKey }) => {
+ const query = sql<SelectNode>`
WITH space_nodes AS (
SELECT *
FROM nodes
@@ -42,60 +38,29 @@ export const useSidebarQuery = () => {
SELECT *
FROM nodes
WHERE parent_id IS NULL AND type = ${NodeTypes.Chat}
- ),
- all_nodes AS (
- SELECT * FROM space_nodes
- UNION ALL
- SELECT * FROM space_children_nodes
- UNION ALL
- SELECT * FROM chat_nodes
)
- SELECT
- n.*,
- CASE
- WHEN COUNT(na.node_id) = 0 THEN json('[]')
- ELSE json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.'updated_by',
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- )
- END as attributes
- FROM all_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ SELECT * FROM space_nodes
+ UNION ALL
+ SELECT * FROM space_children_nodes
+ UNION ALL
+ SELECT * FROM chat_nodes;
`.compile(workspace.schema);
- return await workspace.queryAndSubscribe({
- key: queryKey,
- query,
- });
- },
- select: (
- data: QueryResult<SelectNodeWithAttributes>,
- ): SidebarQueryResult => {
- const rows = data?.rows ?? [];
- return buildSidebarNodes(rows);
+ return await workspace.queryAndSubscribe({
+ key: queryKey,
+ query,
+ });
+ },
+ select: (data: QueryResult<SelectNode>): SidebarQueryResult => {
+ const rows = data?.rows ?? [];
+ return buildSidebarNodes(rows);
+ },
},
- });
+ );
};
-const buildSidebarNodes = (
- rows: SelectNodeWithAttributes[],
-): SidebarQueryResult => {
- const nodes: LocalNodeWithAttributes[] = rows.map(mapNodeWithAttributes);
+const buildSidebarNodes = (rows: SelectNode[]): SidebarQueryResult => {
+ const nodes: LocalNode[] = rows.map(mapNode);
const spaces: SidebarSpaceNode[] = [];
const chats: SidebarChatNode[] = [];
@@ -116,56 +81,32 @@ const buildSidebarNodes = (
};
const buildSpaceNode = (
- node: LocalNodeWithAttributes,
- children: LocalNodeWithAttributes[],
+ node: LocalNode,
+ children: LocalNode[],
): SidebarSpaceNode => {
- const name = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue;
-
return {
id: node.id,
type: node.type,
- name: name ?? null,
- avatar: avatar ?? null,
+ name: node.attributes?.name ?? null,
+ avatar: node.attributes?.avatar ?? null,
children: children.map(buildSidearNode),
};
};
-const buildSidearNode = (node: LocalNodeWithAttributes): SidebarNode => {
- const name = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue;
-
+const buildSidearNode = (node: LocalNode): SidebarNode => {
return {
id: node.id,
type: node.type,
- name: name ?? null,
- avatar: avatar ?? null,
+ name: node.attributes.name ?? null,
+ avatar: node.attributes.avatar ?? null,
};
};
-const buildChatNode = (node: LocalNodeWithAttributes): SidebarChatNode => {
- const name = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Name,
- )?.textValue;
-
- const avatar = node.attributes.find(
- (attr) => attr.type === AttributeTypes.Avatar,
- )?.textValue;
-
+const buildChatNode = (node: LocalNode): SidebarChatNode => {
return {
id: node.id,
type: node.type,
- name: name ?? null,
- avatar: avatar ?? null,
+ name: node.attributes.name ?? null,
+ avatar: node.attributes.avatar ?? null,
};
};
diff --git a/desktop/src/types/databases.ts b/desktop/src/types/databases.ts
index 079278c7..388bfe51 100644
--- a/desktop/src/types/databases.ts
+++ b/desktop/src/types/databases.ts
@@ -1,5 +1,4 @@
import { User } from '@/types/users';
-import { LocalNodeAttribute } from './nodes';
export type DatabaseNode = {
id: string;
@@ -18,16 +17,16 @@ export type TableViewNode = {
fieldWidths: Record<string, number>;
nameWidth: number;
versionId: string;
- filters: ViewFilterNode[];
- sorts: ViewSortNode[];
+ filters: ViewFilter[];
+ sorts: ViewSort[];
};
export type BoardViewNode = {
id: string;
name: string;
type: 'board_view';
- filters: ViewFilterNode[];
- sorts: ViewSortNode[];
+ filters: ViewFilter[];
+ sorts: ViewSort[];
groupBy: string | null;
};
@@ -35,8 +34,8 @@ export type CalendarViewNode = {
id: string;
name: string;
type: 'calendar_view';
- filters: ViewFilterNode[];
- sorts: ViewSortNode[];
+ filters: ViewFilter[];
+ sorts: ViewSort[];
groupBy: string | null;
};
@@ -177,23 +176,27 @@ export type RecordNode = {
createdBy: User;
versionId: string;
- attributes: LocalNodeAttribute[];
+ attributes: any;
};
-export type ViewFilterNode = {
+export type ViewFieldFilter = {
id: string;
+ type: 'field';
fieldId: string;
operator: string;
- values: ViewFilterValueNode[];
+ value: string | number | boolean | string[] | number[] | null;
};
-export type ViewFilterValueNode = {
- textValue: string | null;
- numberValue: number | null;
- foreignNodeId: string | null;
+export type ViewGroupFilter = {
+ id: string;
+ type: 'group';
+ operator: 'and' | 'or';
+ filters: ViewFieldFilter[];
};
-export type ViewSortNode = {
+export type ViewFilter = ViewFieldFilter | ViewGroupFilter;
+
+export type ViewSort = {
id: string;
fieldId: string;
direction: 'asc' | 'desc';
diff --git a/desktop/src/types/editor.ts b/desktop/src/types/editor.ts
index f40dd04e..0016d22c 100644
--- a/desktop/src/types/editor.ts
+++ b/desktop/src/types/editor.ts
@@ -1,5 +1,5 @@
import { Editor, type Range } from '@tiptap/core';
-import { NodeBlock } from '@/types/nodes';
+import { LocalNodeAttributes } from '@/types/nodes';
export type EditorCommandProps = {
editor: Editor;
@@ -21,18 +21,5 @@ export type EditorCommand = {
export type EditorNode = {
id: string;
- type: string;
- parentId: string;
- index: string;
- attributes: EditorNodeAttribute[];
- content: NodeBlock[] | null;
-};
-
-export type EditorNodeAttribute = {
- nodeId: string;
- type: string;
- key: string;
- textValue: string | null;
- numberValue: number | null;
- foreignNodeId: string | null;
+ attributes: LocalNodeAttributes;
};
diff --git a/desktop/src/types/messages.ts b/desktop/src/types/messages.ts
index 64993e3d..5c4ea402 100644
--- a/desktop/src/types/messages.ts
+++ b/desktop/src/types/messages.ts
@@ -1,9 +1,9 @@
-import { LocalNodeWithAttributesAndChildren } from '@/types/nodes';
+import { LocalNodeWithChildren } from '@/types/nodes';
import { User } from '@/types/users';
export type MessageNode = {
id: string;
- content: LocalNodeWithAttributesAndChildren[];
+ content: LocalNodeWithChildren[];
createdAt: string;
author: User;
reactionCounts: MessageReactionCount[];
diff --git a/desktop/src/types/nodes.ts b/desktop/src/types/nodes.ts
index 71b75dc8..10bc5438 100644
--- a/desktop/src/types/nodes.ts
+++ b/desktop/src/types/nodes.ts
@@ -3,7 +3,8 @@ export type LocalNode = {
parentId: string | null;
type: string;
index: string | null;
- content: NodeBlock[] | null;
+ attributes: LocalNodeAttributes;
+ state: string;
createdAt: string;
createdBy: string;
updatedAt: string | null;
@@ -14,25 +15,12 @@ export type LocalNode = {
serverVersionId: string | null;
};
-export type LocalNodeAttribute = {
- nodeId: string;
+export type LocalNodeAttributes = {
type: string;
- key: string;
- textValue: string | null;
- numberValue: number | null;
- foreignNodeId: string | null;
- createdAt: string;
- createdBy: string;
- updatedAt: string | null;
- updatedBy: string | null;
- versionId: string;
- serverCreatedAt: string | null;
- serverUpdatedAt: string | null;
- serverVersionId: string | null;
-};
-
-export type LocalNodeWithAttributes = LocalNode & {
- attributes: LocalNodeAttribute[];
+ parentId?: string | null;
+ index?: string | null;
+ content?: NodeBlock[] | null;
+ [key: string]: any;
};
export type NodeBlock = {
@@ -50,16 +38,13 @@ export type LocalNodeWithChildren = LocalNode & {
children: LocalNodeWithChildren[];
};
-export type LocalNodeWithAttributesAndChildren = LocalNodeWithAttributes & {
- children: LocalNodeWithAttributesAndChildren[];
-};
-
export type ServerNode = {
id: string;
parentId: string | null;
type: string;
index: string | null;
- content: NodeBlock[] | null;
+ attributes: ServerNodeAttributes;
+ state: string;
createdAt: string;
createdBy: string;
updatedAt: string | null;
@@ -69,19 +54,15 @@ export type ServerNode = {
serverUpdatedAt: string | null;
};
-export type ServerNodeAttribute = {
- id: string;
- nodeId: string;
+export type ServerNodeAttributes = {
type: string;
- key: string;
- textValue: string | null;
- numberValue: number | null;
- foreignNodeId: string | null;
- createdAt: string;
- createdBy: string;
- updatedAt: string | null;
- updatedBy: string | null;
- versionId: string;
- serverCreatedAt: string | null;
- serverUpdatedAt: string | null;
+ parentId?: string | null;
+ index?: string | null;
+ content?: NodeBlock[] | null;
+ [key: string]: any;
+};
+
+export type NodeInsertInput = {
+ id: string;
+ attributes: LocalNodeAttributes;
};
diff --git a/desktop/src/types/workspaces.ts b/desktop/src/types/workspaces.ts
index 15c2a03c..b1769169 100644
--- a/desktop/src/types/workspaces.ts
+++ b/desktop/src/types/workspaces.ts
@@ -1,4 +1,4 @@
-import { ServerNode, ServerNodeAttribute } from '@/types/nodes';
+import { ServerNode } from '@/types/nodes';
export enum WorkspaceRole {
Owner = 1,
@@ -21,7 +21,6 @@ export type Workspace = {
export type WorkspaceSyncData = {
nodes: ServerNode[];
- nodeAttributes: ServerNodeAttribute[];
};
export type SidebarNode = {