Open-source and local-first Slack and Notion alternative that puts you in control of your data
TypeScript chatchat-applicationcrdteditorelectronknowledge-baselocal-firstnotionnotion-alternativerealtime-collaborationself-hostedslacksqliteteam-collaborationwikiyjs
Implement mutation for table view customizations
Hakan Shehuab356e671b81
diff --git a/desktop/src/components/databases/tables/table-view-field-header.tsx b/desktop/src/components/databases/tables/table-view-field-header.tsxindex 78457a01..3a72f93e 100644--- a/desktop/src/components/databases/tables/table-view-field-header.tsx+++ b/desktop/src/components/databases/tables/table-view-field-header.tsx@@ -17,13 +17,9 @@ import { useTableView } from '@/contexts/table-view';interface TableViewFieldHeaderProps {field: Field;- index: number;}-export const TableViewFieldHeader = ({- field,- index,-}: TableViewFieldHeaderProps) => {+export const TableViewFieldHeader = ({ field }: TableViewFieldHeaderProps) => {const tableView = useTableView();const canEditDatabase = true;@@ -36,13 +32,10 @@ export const TableViewFieldHeader = ({item: field,canDrag: () => canEditView,end: (_item, monitor) => {- const dropResult = monitor.getDropResult<{ index: number }>();- if (!dropResult?.index) return;+ const dropResult = monitor.getDropResult<{ after: string }>();+ if (!dropResult?.after) return;- // view.updateFieldAttrs({- // ...item.attrs,- // order: dropResult.index,- // });+ tableView.moveField(field.id, dropResult.after);},collect: (monitor) => ({isDragging: monitor.isDragging(),@@ -52,7 +45,7 @@ export const TableViewFieldHeader = ({const [dropMonitor, dropRef] = useDrop({accept: 'table-field-header',drop: () => ({- index,+ after: field.id,}),collect: (monitor) => ({isOver: monitor.isOver(),@@ -106,7 +99,7 @@ export const TableViewFieldHeader = ({className={cn('flex h-8 w-full cursor-pointer flex-row items-center gap-1 p-1 text-sm hover:bg-gray-50',{- 'border-l-2 border-blue-300':+ 'border-r-2 border-blue-300':dropMonitor.isOver && dropMonitor.canDrop,},)}diff --git a/desktop/src/components/databases/tables/table-view-name-header.tsx b/desktop/src/components/databases/tables/table-view-name-header.tsxindex 6405552d..6b4b833a 100644--- a/desktop/src/components/databases/tables/table-view-name-header.tsx+++ b/desktop/src/components/databases/tables/table-view-name-header.tsx@@ -9,12 +9,25 @@ import {import { Separator } from '@/components/ui/separator';import { Input } from '@/components/ui/input';import { useTableView } from '@/contexts/table-view';+import { useDrop } from 'react-dnd';+import { cn } from '@/lib/utils';export const TableViewNameHeader = () => {const tableView = useTableView();const canEditView = true;+ const [dropMonitor, dropRef] = useDrop({+ accept: 'table-field-header',+ drop: () => ({+ after: 'name',+ }),+ collect: (monitor) => ({+ isOver: monitor.isOver(),+ canDrop: monitor.canDrop(),+ }),+ });+return (<ResizabledefaultSize={{@@ -50,7 +63,16 @@ export const TableViewNameHeader = () => {><Popover modal={true}><PopoverTrigger asChild>- <div className="flex h-8 w-full cursor-pointer flex-row items-center gap-1 p-1 text-sm hover:bg-gray-50">+ <div+ className={cn(+ 'flex h-8 w-full cursor-pointer flex-row items-center gap-1 p-1 text-sm hover:bg-gray-50',+ {+ 'border-r-2 border-blue-300':+ dropMonitor.isOver && dropMonitor.canDrop,+ },+ )}+ ref={dropRef}+ ><Icon name="text" /><p>Name</p></div>diff --git a/desktop/src/components/databases/tables/table-view.tsx b/desktop/src/components/databases/tables/table-view.tsxindex f7c1dce7..485d3c8f 100644--- a/desktop/src/components/databases/tables/table-view.tsx+++ b/desktop/src/components/databases/tables/table-view.tsx@@ -8,18 +8,38 @@ import { useDatabase } from '@/contexts/database';import { compareString } from '@/lib/utils';import { FieldType } from '@/types/databases';import { getDefaultFieldWidth, getDefaultNameWidth } from '@/lib/databases';+import { useMutation } from '@tanstack/react-query';+import { sql } from 'kysely';+import { useWorkspace } from '@/contexts/workspace';+import { NeuronId } from '@/lib/id';interface TableViewProps {node: LocalNode;}+interface UpdateHiddenFieldInput {+ fieldId: string;+ hide: boolean;+}++interface UpdateFieldIndexesInput {+ fieldId: string;+ index: string;+}++interface UpdateFieldWidthsInput {+ fieldId: string;+ width: number;+}+export const TableView = ({ node }: TableViewProps) => {+ const workspace = useWorkspace();const database = useDatabase();const attrs = node.attrs ?? {};- const [hiddenFields, setHiddenFields] = React.useState<string[]>(- attrs.hiddenFields ?? [],- );+ const [hiddenFields, setHiddenFields] = React.useState<+ Record<string, number>+ >(attrs.hiddenFields ?? []);const [fieldIndexes, setFieldIndexes] = React.useState<Record<string, string>>(attrs.fieldIndexes ?? {});@@ -30,6 +50,85 @@ export const TableView = ({ node }: TableViewProps) => {attrs.nameWidth ?? getDefaultNameWidth(),);+ const updateHiddenFieldMutation = useMutation({+ mutationFn: async (input: UpdateHiddenFieldInput) => {+ const { fieldId, hide } = input;++ if (hide) {+ const query = sql`+ UPDATE nodes+ SET attrs = json_set(coalesce(attrs, '{}'), '$.hiddenFields.${sql.ref(fieldId)}', 1),+ updated_at = ${new Date().toISOString()},+ updated_by = ${workspace.userId},+ version_id = ${NeuronId.generate(NeuronId.Type.Version)}+ WHERE id = ${node.id}+ `.compile(workspace.schema);++ await workspace.mutate(query);+ } else {+ const query = sql`+ UPDATE nodes+ SET attrs = json_remove(attrs, '$.hiddenFields.${sql.ref(fieldId)}'),+ updated_at = ${new Date().toISOString()},+ updated_by = ${workspace.userId},+ version_id = ${NeuronId.generate(NeuronId.Type.Version)}+ WHERE id = ${node.id} AND attrs IS NOT NULL+ `.compile(workspace.schema);++ await workspace.mutate(query);+ }+ },+ });++ const updateFieldIndexesMutation = useMutation({+ mutationFn: async (input: UpdateFieldIndexesInput) => {+ const { fieldId, index } = input;++ const query = sql`+ UPDATE nodes+ SET attrs = json_set(coalesce(attrs, '{}'), '$.fieldIndexes.${sql.ref(fieldId)}', ${index}),+ updated_at = ${new Date().toISOString()},+ updated_by = ${workspace.userId},+ version_id = ${NeuronId.generate(NeuronId.Type.Version)}+ WHERE id = ${node.id}+ `.compile(workspace.schema);++ await workspace.mutate(query);+ },+ });++ const updateFieldWidthsMutation = useMutation({+ mutationFn: async (input: UpdateFieldWidthsInput) => {+ const { fieldId, width } = input;++ const query = sql`+ UPDATE nodes+ SET attrs = json_set(coalesce(attrs, '{}'), '$.fieldWidths.${sql.ref(fieldId)}', ${width}),+ updated_at = ${new Date().toISOString()},+ updated_by = ${workspace.userId},+ version_id = ${NeuronId.generate(NeuronId.Type.Version)}+ WHERE id = ${node.id}+ `.compile(workspace.schema);++ await workspace.mutate(query);+ },+ });++ const updateNameWidthMutation = useMutation({+ mutationFn: async (width: number) => {+ const query = sql`+ UPDATE nodes+ SET attrs = json_set(coalesce(attrs, '{}'), '$.nameWidth', ${width}),+ updated_at = ${new Date().toISOString()},+ updated_by = ${workspace.userId},+ version_id = ${NeuronId.generate(NeuronId.Type.Version)}+ WHERE id = ${node.id}+ `.compile(workspace.schema);++ await workspace.mutate(query);+ },+ });+React.useEffect(() => {const attrs = node.attrs ?? {};setHiddenFields(attrs.hiddenFields ?? []);@@ -43,7 +142,7 @@ export const TableView = ({ node }: TableViewProps) => {value={{id: node.id,fields: database.fields- .filter((field) => !hiddenFields.includes(field.id))+ .filter((field) => !hiddenFields[field.id]).sort((a, b) =>compareString(fieldIndexes[a.id] ?? a.index,@@ -51,34 +150,76 @@ export const TableView = ({ node }: TableViewProps) => {),),hideField: (id: string) => {- if (hiddenFields.includes(id)) {+ if (hiddenFields[id]) {return;}- setHiddenFields([...hiddenFields, id]);+ setHiddenFields({ ...hiddenFields, [id]: 1 });+ updateHiddenFieldMutation.mutate({ fieldId: id, hide: true });},showField: (id: string) => {- if (!hiddenFields.includes(id)) {+ if (!hiddenFields[id]) {return;}- setHiddenFields(hiddenFields.filter((fieldId) => fieldId !== id));+ const newHiddenFields = { ...hiddenFields };+ delete newHiddenFields[id];+ setHiddenFields(newHiddenFields);+ updateHiddenFieldMutation.mutate({ fieldId: id, hide: false });},getNameWidth: () => nameWidth,resizeName: (width: number) => {setNameWidth(width);+ updateNameWidthMutation.mutate(width);},getFieldWidth: (id: string, type: FieldType) => {return fieldWidths[id] ?? getDefaultFieldWidth(type);},resizeField: (id, width) => {setFieldWidths({ ...fieldWidths, [id]: width });+ updateFieldWidthsMutation.mutate({ fieldId: id, width });},moveField: (id, after) => {- setFieldIndexes({- ...fieldIndexes,- [id]: fieldIndexes[after],- });+ // const field = database.fields.find((f) => f.id === id);+ // if (!field) {+ // return;+ // }+ // const sortedFields = [...database.fields].sort((a, b) =>+ // compareString(+ // fieldIndexes[a.id] ?? a.index,+ // fieldIndexes[b.id] ?? b.index,+ // ),+ // );+ // if (sortedFields.length <= 1) {+ // return;+ // }+ // let beforeIndex: string | null = null;+ // let afterIndex: string | null = null;+ // if (after === 'name') {+ // const firstField = sortedFields[0];+ // if (firstField.id === id) {+ // return;+ // }+ // afterIndex = firstField.index;+ // } else {+ // const afterFieldArrayIndex = sortedFields.findIndex(+ // (f) => f.id === after,+ // );+ // if (afterFieldArrayIndex === -1) {+ // return;+ // }+ // beforeIndex = sortedFields[afterFieldArrayIndex].index;+ // afterIndex =+ // afterFieldArrayIndex < sortedFields.length - 1+ // ? sortedFields[afterFieldArrayIndex + 1].index+ // : null;+ // }+ // const newIndex = generateNodeIndex(beforeIndex, afterIndex);+ // setFieldIndexes({+ // ...fieldIndexes,+ // [id]: newIndex,+ // });+ // updateFieldIndexesMutation.mutate({ fieldId: id, index: newIndex });},}}>