Skip to content

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

Reorder space children in sidebar (#115)

Hakan Shehu66ac097923cf
diff --git a/apps/server/src/jobs/assistant-response.ts b/apps/server/src/jobs/assistant-response.ts
index afb48f96..ee8319ee 100644
--- a/apps/server/src/jobs/assistant-response.ts
+++ b/apps/server/src/jobs/assistant-response.ts
@@ -1,7 +1,7 @@
import {
generateId,
IdType,
- generateNodeIndex,
+ generateFractionalIndex,
getNodeModel,
MessageAttributes,
} from '@colanode/core';
@@ -128,7 +128,7 @@ const createAndPublishResponse = async (
id: blockId,
type: 'paragraph',
content: [{ type: 'text', text: response, marks: [] }],
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
parentId: id,
},
...(citations?.reduce((acc, citation) => {
@@ -142,7 +142,7 @@ const createAndPublishResponse = async (
{ type: 'text', text: citation.quote, marks: [] },
{ type: 'text', text: citation.sourceId, marks: [] },
],
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
parentId: id,
},
};
diff --git a/apps/server/src/lib/blocks.ts b/apps/server/src/lib/blocks.ts
index f070c283..5c2139dc 100644
--- a/apps/server/src/lib/blocks.ts
+++ b/apps/server/src/lib/blocks.ts
@@ -1,4 +1,9 @@
-import { Block, IdType, generateId, generateNodeIndex } from '@colanode/core';
+import {
+ Block,
+ IdType,
+ generateId,
+ generateFractionalIndex,
+} from '@colanode/core';
export const generateWelcomePageBlocks = (
pageId: string
@@ -7,7 +12,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'heading1',
parentId: pageId,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [{ type: 'text', text: 'Welcome to the Colanode!' }],
};
@@ -15,7 +20,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: pageId,
- index: generateNodeIndex(headingBlock.index),
+ index: generateFractionalIndex(headingBlock.index),
content: [
{
type: 'text',
@@ -28,7 +33,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: pageId,
- index: generateNodeIndex(colanodeParagraphBlock.index),
+ index: generateFractionalIndex(colanodeParagraphBlock.index),
content: [
{
type: 'text',
@@ -41,7 +46,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'taskList',
parentId: pageId,
- index: generateNodeIndex(startTypingParagraphBlock.index),
+ index: generateFractionalIndex(startTypingParagraphBlock.index),
content: [],
};
@@ -49,7 +54,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'taskItem',
parentId: taskListBlock.id,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
attrs: {
checked: false,
},
@@ -59,7 +64,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: task1Block.id,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [
{
text: 'Type "/" to see the menu of possible content you can add - headings, paragraphs, blockquotes, todos etc.',
@@ -72,7 +77,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'taskItem',
parentId: taskListBlock.id,
- index: generateNodeIndex(task1Block.index),
+ index: generateFractionalIndex(task1Block.index),
attrs: {
checked: false,
},
@@ -82,7 +87,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: task2Block.id,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [
{
text: 'Highlight any text and use the menu to style your text in different ',
@@ -136,7 +141,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'taskItem',
parentId: taskListBlock.id,
- index: generateNodeIndex(task2Block.index),
+ index: generateFractionalIndex(task2Block.index),
attrs: {
checked: false,
},
@@ -146,7 +151,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: task3Block.id,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [
{
text: 'Use the drag icon on the left to reorder the content',
@@ -159,7 +164,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'taskItem',
parentId: taskListBlock.id,
- index: generateNodeIndex(task3Block.index),
+ index: generateFractionalIndex(task3Block.index),
attrs: {
checked: false,
},
@@ -169,7 +174,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: task4Block.id,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [
{
text: "Add subpages, subfolders or databases using the '/' menu",
@@ -182,7 +187,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'heading2',
parentId: pageId,
- index: generateNodeIndex(taskListBlock.index),
+ index: generateFractionalIndex(taskListBlock.index),
content: [{ type: 'text', text: 'What is a Database?' }],
};
@@ -190,7 +195,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: pageId,
- index: generateNodeIndex(databaseHeadingBlock.index),
+ index: generateFractionalIndex(databaseHeadingBlock.index),
content: [
{
text: 'A database in Colanode is like a powerful spreadsheet that combines tables with rich content. You can use databases to organize and view your information in multiple ways - as tables, kanban boards, calendars, or galleries. Each row in the database is a full page that can contain any type of content, and columns act as properties that help you organize and filter your information.',
@@ -203,7 +208,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: pageId,
- index: generateNodeIndex(databaseParagraphBlock.index),
+ index: generateFractionalIndex(databaseParagraphBlock.index),
content: [
{
text: 'You can create a database by using the "/" menu inside an existing page. You can also create a database by clicking the three dots button in the sidebar near the spaces menu.',
@@ -216,14 +221,14 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'blockquote',
parentId: pageId,
- index: generateNodeIndex(databaseParagraphBlock2.index),
+ index: generateFractionalIndex(databaseParagraphBlock2.index),
};
const blockquoteParagraphBlock: Block = {
id: generateId(IdType.Block),
type: 'paragraph',
parentId: blockquoteBlock.id,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [
{
text: 'Every journey starts with a single step. Block by block, you can build your own world.',
@@ -236,7 +241,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'heading2',
parentId: pageId,
- index: generateNodeIndex(blockquoteBlock.index),
+ index: generateFractionalIndex(blockquoteBlock.index),
content: [{ type: 'text', text: 'Follow Us' }],
};
@@ -244,7 +249,7 @@ export const generateWelcomePageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: pageId,
- index: generateNodeIndex(followUsHeadingBlock.index),
+ index: generateFractionalIndex(followUsHeadingBlock.index),
content: [
{
text: 'Stay updated with our latest developments on ',
@@ -321,7 +326,7 @@ export const generateInitialMessageBlocks = (
id: generateId(IdType.Block),
type: 'paragraph',
parentId: messageId,
- index: generateNodeIndex(),
+ index: generateFractionalIndex(),
content: [
{
type: 'text',
diff --git a/packages/client/src/handlers/mutations/databases/database-create.ts b/packages/client/src/handlers/mutations/databases/database-create.ts
index 106a5f23..d7474f0e 100644
--- a/packages/client/src/handlers/mutations/databases/database-create.ts
+++ b/packages/client/src/handlers/mutations/databases/database-create.ts
@@ -7,7 +7,7 @@ import {
import {
DatabaseAttributes,
generateId,
- generateNodeIndex,
+ generateFractionalIndex,
IdType,
DatabaseViewAttributes,
} from '@colanode/core';
@@ -34,7 +34,7 @@ export class DatabaseCreateMutationHandler
[fieldId]: {
id: fieldId,
type: 'text',
- index: generateNodeIndex(null, null),
+ index: generateFractionalIndex(null, null),
name: 'Comment',
},
},
@@ -43,7 +43,7 @@ export class DatabaseCreateMutationHandler
const viewAttributes: DatabaseViewAttributes = {
type: 'database_view',
name: 'Default',
- index: generateNodeIndex(null, null),
+ index: generateFractionalIndex(null, null),
layout: 'table',
parentId: databaseId,
};
diff --git a/packages/client/src/handlers/mutations/databases/field-create.ts b/packages/client/src/handlers/mutations/databases/field-create.ts
index 3b37a7c1..0f0ed38b 100644
--- a/packages/client/src/handlers/mutations/databases/field-create.ts
+++ b/packages/client/src/handlers/mutations/databases/field-create.ts
@@ -12,7 +12,7 @@ import {
FieldAttributes,
FieldType,
generateId,
- generateNodeIndex,
+ generateFractionalIndex,
IdType,
} from '@colanode/core';
@@ -54,7 +54,7 @@ export class FieldCreateMutationHandler
.map((field) => field.index)
.sort((a, b) => -compareString(a, b))[0];
- const index = generateNodeIndex(maxIndex, null);
+ const index = generateFractionalIndex(maxIndex, null);
const newField: FieldAttributes = {
id: fieldId,
diff --git a/packages/client/src/handlers/mutations/databases/select-option-create.ts b/packages/client/src/handlers/mutations/databases/select-option-create.ts
index 3653509d..cf18d703 100644
--- a/packages/client/src/handlers/mutations/databases/select-option-create.ts
+++ b/packages/client/src/handlers/mutations/databases/select-option-create.ts
@@ -9,7 +9,7 @@ import {
compareString,
DatabaseAttributes,
generateId,
- generateNodeIndex,
+ generateFractionalIndex,
IdType,
} from '@colanode/core';
@@ -49,7 +49,7 @@ export class SelectOptionCreateMutationHandler
.map((selectOption) => selectOption.index)
.sort((a, b) => -compareString(a, b))[0];
- const index = generateNodeIndex(maxIndex, null);
+ const index = generateFractionalIndex(maxIndex, null);
field.options[id] = {
name: input.name,
diff --git a/packages/client/src/handlers/mutations/databases/view-create.ts b/packages/client/src/handlers/mutations/databases/view-create.ts
index 47e80f0b..7b5efd85 100644
--- a/packages/client/src/handlers/mutations/databases/view-create.ts
+++ b/packages/client/src/handlers/mutations/databases/view-create.ts
@@ -7,7 +7,7 @@ import {
} from '@colanode/client/mutations/databases/view-create';
import {
generateId,
- generateNodeIndex,
+ generateFractionalIndex,
IdType,
DatabaseViewAttributes,
} from '@colanode/core';
@@ -45,7 +45,7 @@ export class ViewCreateMutationHandler
const attributes: DatabaseViewAttributes = {
type: 'database_view',
name: input.name,
- index: generateNodeIndex(maxIndex, null),
+ index: generateFractionalIndex(maxIndex, null),
layout: input.viewType,
parentId: input.databaseId,
groupBy: input.groupBy,
diff --git a/packages/client/src/handlers/mutations/index.ts b/packages/client/src/handlers/mutations/index.ts
index 5e749f21..81687e60 100644
--- a/packages/client/src/handlers/mutations/index.ts
+++ b/packages/client/src/handlers/mutations/index.ts
@@ -61,6 +61,7 @@ import { RecordNameUpdateMutationHandler } from './records/record-name-update';
import { ServerCreateMutationHandler } from './servers/server-create';
import { ServerDeleteMutationHandler } from './servers/server-delete';
import { SpaceAvatarUpdateMutationHandler } from './spaces/space-avatar-update';
+import { SpaceChildReorderMutationHandler } from './spaces/space-child-reorder';
import { SpaceCreateMutationHandler } from './spaces/space-create';
import { SpaceDeleteMutationHandler } from './spaces/space-delete';
import { SpaceDescriptionUpdateMutationHandler } from './spaces/space-description-update';
@@ -133,6 +134,7 @@ export const buildMutationHandlerMap = (
'space.avatar.update': new SpaceAvatarUpdateMutationHandler(app),
'space.description.update': new SpaceDescriptionUpdateMutationHandler(app),
'space.name.update': new SpaceNameUpdateMutationHandler(app),
+ 'space.child.reorder': new SpaceChildReorderMutationHandler(app),
'account.update': new AccountUpdateMutationHandler(app),
'view.update': new ViewUpdateMutationHandler(app),
'view.delete': new ViewDeleteMutationHandler(app),
diff --git a/packages/client/src/handlers/mutations/spaces/space-child-reorder.ts b/packages/client/src/handlers/mutations/spaces/space-child-reorder.ts
new file mode 100644
index 00000000..dca386a4
--- /dev/null
+++ b/packages/client/src/handlers/mutations/spaces/space-child-reorder.ts
@@ -0,0 +1,168 @@
+import { SelectNode } from '@colanode/client/databases';
+import { WorkspaceMutationHandlerBase } from '@colanode/client/handlers/mutations/workspace-mutation-handler-base';
+import { MutationHandler } from '@colanode/client/lib/types';
+import {
+ MutationError,
+ MutationErrorCode,
+ SpaceChildReorderMutationInput,
+ SpaceChildReorderMutationOutput,
+} from '@colanode/client/mutations';
+import {
+ compareString,
+ generateFractionalIndex,
+ SpaceAttributes,
+} from '@colanode/core';
+
+interface NodeFractionalIndex {
+ id: string;
+ defaultIndex: string;
+ customIndex: string | null;
+}
+
+export class SpaceChildReorderMutationHandler
+ extends WorkspaceMutationHandlerBase
+ implements MutationHandler<SpaceChildReorderMutationInput>
+{
+ async handleMutation(
+ input: SpaceChildReorderMutationInput
+ ): Promise<SpaceChildReorderMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ const children = await workspace.database
+ .selectFrom('nodes')
+ .where('parent_id', '=', input.spaceId)
+ .orderBy('id')
+ .selectAll()
+ .execute();
+
+ if (children.length === 0) {
+ throw new MutationError(
+ MutationErrorCode.SpaceUpdateFailed,
+ 'Space has no children.'
+ );
+ }
+
+ const result = await workspace.nodes.updateNode<SpaceAttributes>(
+ input.spaceId,
+ (attributes) => {
+ const newIndex = this.generateSpaceChildIndex(
+ attributes,
+ children,
+ input.childId,
+ input.after
+ );
+
+ if (!newIndex) {
+ throw new MutationError(
+ MutationErrorCode.SpaceUpdateFailed,
+ 'Failed to generate new index.'
+ );
+ }
+
+ const childrenSettings = attributes.children ?? {};
+ childrenSettings[input.childId] = {
+ ...(childrenSettings[input.childId] ?? {}),
+ id: input.childId,
+ index: newIndex,
+ };
+
+ attributes.children = childrenSettings;
+ return attributes;
+ }
+ );
+
+ if (result === 'unauthorized') {
+ throw new MutationError(
+ MutationErrorCode.SpaceUpdateForbidden,
+ "You don't have permission to update this space."
+ );
+ }
+
+ return {
+ success: true,
+ };
+ }
+
+ private generateSpaceChildIndex(
+ attributes: SpaceAttributes,
+ children: SelectNode[],
+ childId: string,
+ after: string | null
+ ): string | null {
+ const child = children.find((c) => c.id === childId);
+ if (!child) {
+ return null;
+ }
+
+ const sortedById = children.toSorted((a, b) => compareString(a.id, b.id));
+ const indexes: NodeFractionalIndex[] = [];
+ const childrenSettings = attributes.children ?? {};
+ let lastIndex: string | null = null;
+
+ for (const child of sortedById) {
+ lastIndex = generateFractionalIndex(lastIndex, null);
+ indexes.push({
+ id: child.id,
+ defaultIndex: lastIndex,
+ customIndex: childrenSettings[child.id]?.index ?? null,
+ });
+ }
+
+ const sortedIndexes = indexes.sort((a, b) =>
+ compareString(
+ a.customIndex ?? a.defaultIndex,
+ b.customIndex ?? b.defaultIndex
+ )
+ );
+
+ if (after === null) {
+ const firstIndex = sortedIndexes[0];
+ if (!firstIndex) {
+ return generateFractionalIndex(null, null);
+ }
+
+ const nextIndex = firstIndex.customIndex ?? firstIndex.defaultIndex;
+ return generateFractionalIndex(null, nextIndex);
+ }
+
+ const afterNodeIndex = sortedIndexes.findIndex((node) => node.id === after);
+ if (afterNodeIndex === -1) {
+ return null;
+ }
+
+ const afterNode = sortedIndexes[afterNodeIndex];
+ if (!afterNode) {
+ return null;
+ }
+
+ const previousIndex = afterNode.customIndex ?? afterNode.defaultIndex;
+ let nextIndex: string | null = null;
+ if (afterNodeIndex < sortedIndexes.length - 1) {
+ const nextNode = sortedIndexes[afterNodeIndex + 1];
+ if (!nextNode) {
+ return null;
+ }
+
+ nextIndex = nextNode.customIndex ?? nextNode.defaultIndex;
+ }
+
+ let newIndex = generateFractionalIndex(previousIndex, nextIndex);
+
+ const maxDefaultIndex = sortedIndexes
+ .map((index) => index.defaultIndex)
+ .sort((a, b) => -compareString(a, b))[0]!;
+
+ const newPotentialDefaultIndex = generateFractionalIndex(
+ maxDefaultIndex,
+ null
+ );
+
+ if (newPotentialDefaultIndex === newIndex) {
+ newIndex = generateFractionalIndex(
+ previousIndex,
+ newPotentialDefaultIndex
+ );
+ }
+
+ return newIndex;
+ }
+}
diff --git a/packages/client/src/lib/editor.ts b/packages/client/src/lib/editor.ts
index aad0fc65..a1564dfb 100644
--- a/packages/client/src/lib/editor.ts
+++ b/packages/client/src/lib/editor.ts
@@ -8,7 +8,7 @@ import {
compareString,
EditorNodeTypes,
generateId,
- generateNodeIndex,
+ generateFractionalIndex,
IdType,
RichTextContent,
} from '@colanode/core';
@@ -80,7 +80,7 @@ const mapAndPushContentToBlock = (
blocks.push({
id: id,
- index: index ?? generateNodeIndex(null, null),
+ index: index ?? generateFractionalIndex(null, null),
attrs: attrs.length > 0 ? Object.fromEntries(attrs) : undefined,
parentId: parentId,
type: content.type,
@@ -237,9 +237,9 @@ const validateBlocksIndexes = (blocks: Block[]) => {
afterIndex > currentIndex &&
afterIndex > beforeIndex
) {
- currentBlock.index = generateNodeIndex(beforeIndex, afterIndex);
+ currentBlock.index = generateFractionalIndex(beforeIndex, afterIndex);
} else {
- currentBlock.index = generateNodeIndex(beforeIndex, null);
+ currentBlock.index = generateFractionalIndex(beforeIndex, null);
}
}
}
diff --git a/packages/client/src/mutations/index.ts b/packages/client/src/mutations/index.ts
index be4da921..7f1d9ad2 100644
--- a/packages/client/src/mutations/index.ts
+++ b/packages/client/src/mutations/index.ts
@@ -61,6 +61,7 @@ export * from './spaces/space-create';
export * from './spaces/space-delete';
export * from './spaces/space-description-update';
export * from './spaces/space-name-update';
+export * from './spaces/space-child-reorder';
export * from './workspaces/workspace-create';
export * from './workspaces/workspace-delete';
export * from './workspaces/workspace-metadata-delete';
diff --git a/packages/client/src/mutations/spaces/space-child-reorder.ts b/packages/client/src/mutations/spaces/space-child-reorder.ts
new file mode 100644
index 00000000..be8ba72b
--- /dev/null
+++ b/packages/client/src/mutations/spaces/space-child-reorder.ts
@@ -0,0 +1,21 @@
+export type SpaceChildReorderMutationInput = {
+ type: 'space.child.reorder';
+ accountId: string;
+ workspaceId: string;
+ spaceId: string;
+ childId: string;
+ after: string | null;
+};
+
+export type SpaceChildReorderMutationOutput = {
+ success: boolean;
+};
+
+declare module '@colanode/client/mutations' {
+ interface MutationMap {
+ 'space.child.reorder': {
+ input: SpaceChildReorderMutationInput;
+ output: SpaceChildReorderMutationOutput;
+ };
+ }
+}
diff --git a/packages/core/src/lib/nodes.ts b/packages/core/src/lib/nodes.ts
index 1e7bb870..ca2fd4d6 100644
--- a/packages/core/src/lib/nodes.ts
+++ b/packages/core/src/lib/nodes.ts
@@ -54,7 +54,7 @@ export const extractNodeRole = (
return role;
};
-export const generateNodeIndex = (
+export const generateFractionalIndex = (
previous?: string | null,
next?: string | null
) => {
diff --git a/packages/core/src/registry/nodes/space.ts b/packages/core/src/registry/nodes/space.ts
index 7514634a..407b5199 100644
--- a/packages/core/src/registry/nodes/space.ts
+++ b/packages/core/src/registry/nodes/space.ts
@@ -4,6 +4,13 @@ import { extractNodeRole } from '@colanode/core/lib/nodes';
import { hasNodeRole, hasWorkspaceRole } from '@colanode/core/lib/permissions';
import { NodeModel, nodeRoleEnum } from '@colanode/core/registry/nodes/core';
+export const spaceChildAttributesSchema = z.object({
+ id: z.string(),
+ index: z.string().optional().nullable(),
+});
+
+export type SpaceChildAttributes = z.infer<typeof spaceChildAttributesSchema>;
+
export const spaceAttributesSchema = z.object({
type: z.literal('space'),
name: z.string(),
@@ -11,6 +18,7 @@ export const spaceAttributesSchema = z.object({
avatar: z.string().nullable().optional(),
collaborators: z.record(z.string(), nodeRoleEnum),
visibility: z.enum(['public', 'private']).default('private'),
+ children: z.record(z.string(), spaceChildAttributesSchema).optional(),
});
export type SpaceAttributes = z.infer<typeof spaceAttributesSchema>;
diff --git a/packages/ui/src/components/layouts/sidebars/sidebar-item.tsx b/packages/ui/src/components/layouts/sidebars/sidebar-item.tsx
index 6b485e8a..012a3300 100644
--- a/packages/ui/src/components/layouts/sidebars/sidebar-item.tsx
+++ b/packages/ui/src/components/layouts/sidebars/sidebar-item.tsx
@@ -1,3 +1,6 @@
+import { RefAttributes, useRef } from 'react';
+import { useDrag, useDrop } from 'react-dnd';
+
import { LocalNode } from '@colanode/client/types';
import { ChannelSidebarItem } from '@colanode/ui/components/channels/channel-sidebar-item';
import { ChatSidebarItem } from '@colanode/ui/components/chats/chat-sidebar-item';
@@ -5,12 +8,15 @@ import { DatabaseSidebarItem } from '@colanode/ui/components/databases/database-
import { FolderSidebarItem } from '@colanode/ui/components/folders/folder-sidebar-item';
import { PageSidebarItem } from '@colanode/ui/components/pages/page-sidebar-item';
import { SpaceSidebarItem } from '@colanode/ui/components/spaces/space-sidebar-item';
+import { cn } from '@colanode/ui/lib/utils';
-interface SidebarItemProps {
+interface SidebarItemContentProps {
node: LocalNode;
}
-export const SidebarItem = ({ node }: SidebarItemProps): React.ReactNode => {
+export const SidebarItemContent = ({
+ node,
+}: SidebarItemContentProps): React.ReactNode => {
switch (node.type) {
case 'space':
return <SpaceSidebarItem space={node} />;
@@ -28,3 +34,67 @@ export const SidebarItem = ({ node }: SidebarItemProps): React.ReactNode => {
return null;
}
};
+
+interface SidebarItemProps {
+ node: LocalNode;
+ isActive: boolean;
+ canDrag: boolean;
+ onDragEnd: (after: string | null) => void;
+}
+
+export const SidebarItem = ({
+ node,
+ isActive,
+ canDrag,
+ onDragEnd,
+}: SidebarItemProps): React.ReactNode => {
+ const [, dragRef] = useDrag({
+ type: 'sidebar-item',
+ canDrag: () => canDrag,
+ end: (_item, monitor) => {
+ const dropResult = monitor.getDropResult<{ after: string | null }>();
+ if (!dropResult) {
+ return;
+ }
+
+ if (dropResult.after === node.id) {
+ return;
+ }
+
+ onDragEnd(dropResult.after);
+ },
+ collect: (monitor) => ({
+ isDragging: monitor.isDragging(),
+ }),
+ });
+
+ const [dropMonitor, dropRef] = useDrop({
+ accept: 'sidebar-item',
+ drop: () => ({
+ after: node.id,
+ }),
+ collect: (monitor) => ({
+ isOver: monitor.isOver(),
+ canDrop: monitor.canDrop(),
+ }),
+ });
+
+ const divRef = useRef<HTMLDivElement>(null);
+ const dragDropRef = dragRef(dropRef(divRef));
+
+ return (
+ <div
+ className={cn(
+ 'text-sm flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground cursor-pointer',
+ isActive &&
+ 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
+ dropMonitor.isOver &&
+ dropMonitor.canDrop &&
+ 'border-b-2 border-blue-300'
+ )}
+ ref={dragDropRef as RefAttributes<HTMLDivElement>['ref']}
+ >
+ <SidebarItemContent node={node} />
+ </div>
+ );
+};
diff --git a/packages/ui/src/components/spaces/space-sidebar-dropdown.tsx b/packages/ui/src/components/spaces/space-sidebar-dropdown.tsx
new file mode 100644
index 00000000..1145bc27
--- /dev/null
+++ b/packages/ui/src/components/spaces/space-sidebar-dropdown.tsx
@@ -0,0 +1,127 @@
+import {
+ Database,
+ Ellipsis,
+ Folder,
+ MessageCircle,
+ Plus,
+ Settings,
+ StickyNote,
+} from 'lucide-react';
+import { Fragment, useState } from 'react';
+
+import { LocalSpaceNode } from '@colanode/client/types';
+import { ChannelCreateDialog } from '@colanode/ui/components/channels/channel-create-dialog';
+import { DatabaseCreateDialog } from '@colanode/ui/components/databases/database-create-dialog';
+import { FolderCreateDialog } from '@colanode/ui/components/folders/folder-create-dialog';
+import { PageCreateDialog } from '@colanode/ui/components/pages/page-create-dialog';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@colanode/ui/components/ui/dropdown-menu';
+import { useLayout } from '@colanode/ui/contexts/layout';
+
+interface SpaceSidebarDropdownProps {
+ space: LocalSpaceNode;
+}
+
+export const SpaceSidebarDropdown = ({ space }: SpaceSidebarDropdownProps) => {
+ const layout = useLayout();
+
+ const [openCreatePage, setOpenCreatePage] = useState(false);
+ const [openCreateChannel, setOpenCreateChannel] = useState(false);
+ const [openCreateDatabase, setOpenCreateDatabase] = useState(false);
+ const [openCreateFolder, setOpenCreateFolder] = useState(false);
+
+ return (
+ <Fragment>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button className="text-muted-foreground opacity-0 transition-opacity group-hover/sidebar-space:opacity-100 flex items-center justify-center p-0 mr-1 size-4 focus-visible:outline-none focus-visible:ring-0 cursor-pointer">
+ <Ellipsis />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="ml-1 w-72">
+ <DropdownMenuLabel>
+ {space.attributes.name ?? 'Unnamed'}
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => setOpenCreatePage(true)}
+ className="flex flex-row items-center gap-2 cursor-pointer"
+ >
+ <StickyNote className="size-4" />
+ <span>Add page</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => setOpenCreateChannel(true)}
+ className="flex flex-row items-center gap-2 cursor-pointer"
+ >
+ <MessageCircle className="size-4" />
+ <span>Add channel</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => setOpenCreateDatabase(true)}
+ className="flex flex-row items-center gap-2 cursor-pointer"
+ >
+ <Database className="size-4" />
+ <span>Add database</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => setOpenCreateFolder(true)}
+ className="flex flex-row items-center gap-2 cursor-pointer"
+ >
+ <Folder className="size-4" />
+ <span>Add folder</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => layout.previewLeft(space.id)}
+ className="flex flex-row items-center gap-2 cursor-pointer"
+ >
+ <Settings className="size-4" />
+ <span>Settings</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => layout.previewLeft(space.id)}
+ className="flex flex-row items-center gap-2 cursor-pointer"
+ >
+ <Plus className="size-4" />
+ <span>Add collaborators</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {openCreateChannel && (
+ <ChannelCreateDialog
+ spaceId={space.id}
+ open={openCreateChannel}
+ onOpenChange={setOpenCreateChannel}
+ />
+ )}
+ {openCreatePage && (
+ <PageCreateDialog
+ spaceId={space.id}
+ open={openCreatePage}
+ onOpenChange={setOpenCreatePage}
+ />
+ )}
+ {openCreateDatabase && (
+ <DatabaseCreateDialog
+ spaceId={space.id}
+ open={openCreateDatabase}
+ onOpenChange={setOpenCreateDatabase}
+ />
+ )}
+ {openCreateFolder && (
+ <FolderCreateDialog
+ spaceId={space.id}
+ open={openCreateFolder}
+ onOpenChange={setOpenCreateFolder}
+ />
+ )}
+ </Fragment>
+ );
+};
diff --git a/packages/ui/src/components/spaces/space-sidebar-item.tsx b/packages/ui/src/components/spaces/space-sidebar-item.tsx
index 92392274..8e48acb1 100644
--- a/packages/ui/src/components/spaces/space-sidebar-item.tsx
+++ b/packages/ui/src/components/spaces/space-sidebar-item.tsx
@@ -1,39 +1,23 @@
-import {
- ChevronRight,
- Database,
- Ellipsis,
- Folder,
- MessageCircle,
- Plus,
- Settings,
- StickyNote,
-} from 'lucide-react';
-import { Fragment, useState } from 'react';
+import { ChevronRight } from 'lucide-react';
+import { RefAttributes, useRef } from 'react';
+import { useDrop } from 'react-dnd';
+import { toast } from 'sonner';
import { LocalSpaceNode } from '@colanode/client/types';
-import { compareString } from '@colanode/core';
+import { extractNodeRole } from '@colanode/core';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
-import { ChannelCreateDialog } from '@colanode/ui/components/channels/channel-create-dialog';
-import { DatabaseCreateDialog } from '@colanode/ui/components/databases/database-create-dialog';
-import { FolderCreateDialog } from '@colanode/ui/components/folders/folder-create-dialog';
import { SidebarItem } from '@colanode/ui/components/layouts/sidebars/sidebar-item';
-import { PageCreateDialog } from '@colanode/ui/components/pages/page-create-dialog';
+import { SpaceSidebarDropdown } from '@colanode/ui/components/spaces/space-sidebar-dropdown';
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@colanode/ui/components/ui/collapsible';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from '@colanode/ui/components/ui/dropdown-menu';
import { useLayout } from '@colanode/ui/contexts/layout';
import { useWorkspace } from '@colanode/ui/contexts/workspace';
+import { useMutation } from '@colanode/ui/hooks/use-mutation';
import { useQuery } from '@colanode/ui/hooks/use-query';
+import { sortSpaceChildren } from '@colanode/ui/lib/spaces';
import { cn } from '@colanode/ui/lib/utils';
interface SpaceSidebarItemProps {
@@ -43,6 +27,10 @@ interface SpaceSidebarItemProps {
export const SpaceSidebarItem = ({ space }: SpaceSidebarItemProps) => {
const workspace = useWorkspace();
const layout = useLayout();
+ const mutation = useMutation();
+
+ const role = extractNodeRole(space, workspace.userId);
+ const canEdit = role === 'admin';
const nodeChildrenGetQuery = useQuery({
type: 'node.children.get',
@@ -52,150 +40,92 @@ export const SpaceSidebarItem = ({ space }: SpaceSidebarItemProps) => {
types: ['page', 'channel', 'database', 'folder'],
});
- const children =
- nodeChildrenGetQuery.data?.toSorted((a, b) => compareString(a.id, b.id)) ??
- [];
+ const [dropMonitor, dropRef] = useDrop({
+ accept: 'sidebar-item',
+ drop: () => ({
+ after: null,
+ }),
+ collect: (monitor) => ({
+ isOver: monitor.isOver(),
+ canDrop: monitor.canDrop(),
+ }),
+ });
+
+ const divRef = useRef<HTMLDivElement>(null);
+ const dropDivRef = dropRef(divRef);
+
+ const children = sortSpaceChildren(space, nodeChildrenGetQuery.data ?? []);
- const [openCreatePage, setOpenCreatePage] = useState(false);
- const [openCreateChannel, setOpenCreateChannel] = useState(false);
- const [openCreateDatabase, setOpenCreateDatabase] = useState(false);
- const [openCreateFolder, setOpenCreateFolder] = useState(false);
+ const handleDragEnd = (childId: string, after: string | null) => {
+ mutation.mutate({
+ input: {
+ type: 'space.child.reorder',
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ spaceId: space.id,
+ childId,
+ after,
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ });
+ };
return (
- <Fragment>
- <Collapsible
- key={space.id}
- asChild
- defaultOpen={true}
- className="group/sidebar-space"
+ <Collapsible
+ key={space.id}
+ defaultOpen={true}
+ className="group/sidebar-space"
+ >
+ <div
+ className={cn(
+ 'flex w-full min-w-0 flex-row items-center hover:bg-sidebar-accent hover:text-sidebar-accent-foreground h-8',
+ dropMonitor.isOver &&
+ dropMonitor.canDrop &&
+ 'border-b-2 border-blue-300'
+ )}
+ ref={dropDivRef as RefAttributes<HTMLDivElement>['ref']}
>
- <div>
- <div className="flex w-full min-w-0 flex-row items-center hover:bg-sidebar-accent hover:text-sidebar-accent-foreground h-8">
- <CollapsibleTrigger asChild>
- <button className="group/space-button flex items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm flex-1 cursor-pointer">
- <Avatar
- id={space.id}
- avatar={space.attributes.avatar}
- name={space.attributes.name}
- className="size-4 group-hover/space-button:hidden"
- />
- <ChevronRight className="hidden size-4 transition-transform duration-200 group-hover/space-button:block group-data-[state=open]/sidebar-space:rotate-90" />
- <span>{space.attributes.name}</span>
- </button>
- </CollapsibleTrigger>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button className="text-muted-foreground opacity-0 transition-opacity group-hover/sidebar-space:opacity-100 flex items-center justify-center p-0 mr-1 size-4 focus-visible:outline-none focus-visible:ring-0 cursor-pointer">
- <Ellipsis />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent className="ml-1 w-72">
- <DropdownMenuLabel>
- {space.attributes.name ?? 'Unnamed'}
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={() => setOpenCreatePage(true)}
- className="flex flex-row items-center gap-2 cursor-pointer"
- >
- <StickyNote className="size-4" />
- <span>Add page</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => setOpenCreateChannel(true)}
- className="flex flex-row items-center gap-2 cursor-pointer"
- >
- <MessageCircle className="size-4" />
- <span>Add channel</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => setOpenCreateDatabase(true)}
- className="flex flex-row items-center gap-2 cursor-pointer"
- >
- <Database className="size-4" />
- <span>Add database</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => setOpenCreateFolder(true)}
- className="flex flex-row items-center gap-2 cursor-pointer"
- >
- <Folder className="size-4" />
- <span>Add folder</span>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => layout.previewLeft(space.id)}
- className="flex flex-row items-center gap-2 cursor-pointer"
- >
- <Settings className="size-4" />
- <span>Settings</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => layout.previewLeft(space.id)}
- className="flex flex-row items-center gap-2 cursor-pointer"
- >
- <Plus className="size-4" />
- <span>Add collaborators</span>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- <CollapsibleContent>
- <ul className="mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 mr-0 pr-0">
- {children.map((child) => (
- <li
- key={child.id}
- onClick={() => {
- layout.preview(child.id);
- }}
- onDoubleClick={() => {
- layout.open(child.id);
- }}
- className="cursor-pointer select-none"
- >
- <div
- className={cn(
- 'text-sm flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground cursor-pointer',
- layout.activeTab === child.id &&
- 'bg-sidebar-accent text-sidebar-accent-foreground font-medium'
- )}
- >
- <SidebarItem node={child} />
- </div>
- </li>
- ))}
- </ul>
- </CollapsibleContent>
- </div>
- </Collapsible>
- {openCreateChannel && (
- <ChannelCreateDialog
- spaceId={space.id}
- open={openCreateChannel}
- onOpenChange={setOpenCreateChannel}
- />
- )}
- {openCreatePage && (
- <PageCreateDialog
- spaceId={space.id}
- open={openCreatePage}
- onOpenChange={setOpenCreatePage}
- />
- )}
- {openCreateDatabase && (
- <DatabaseCreateDialog
- spaceId={space.id}
- open={openCreateDatabase}
- onOpenChange={setOpenCreateDatabase}
- />
- )}
- {openCreateFolder && (
- <FolderCreateDialog
- spaceId={space.id}
- open={openCreateFolder}
- onOpenChange={setOpenCreateFolder}
- />
- )}
- </Fragment>
+ <CollapsibleTrigger asChild>
+ <button className="group/space-button flex items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm flex-1 cursor-pointer">
+ <Avatar
+ id={space.id}
+ avatar={space.attributes.avatar}
+ name={space.attributes.name}
+ className="size-4 group-hover/space-button:hidden"
+ />
+ <ChevronRight className="hidden size-4 transition-transform duration-200 group-hover/space-button:block group-data-[state=open]/sidebar-space:rotate-90" />
+ <span>{space.attributes.name}</span>
+ </button>
+ </CollapsibleTrigger>
+ <SpaceSidebarDropdown space={space} />
+ </div>
+ <CollapsibleContent>
+ <ul className="mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 mr-0 pr-0">
+ {children.map((child) => (
+ <li
+ key={child.id}
+ onClick={() => {
+ layout.preview(child.id);
+ }}
+ onDoubleClick={() => {
+ layout.open(child.id);
+ }}
+ className="cursor-pointer select-none"
+ >
+ <SidebarItem
+ node={child}
+ isActive={layout.activeTab === child.id}
+ canDrag={canEdit}
+ onDragEnd={(after) => {
+ handleDragEnd(child.id, after);
+ }}
+ />
+ </li>
+ ))}
+ </ul>
+ </CollapsibleContent>
+ </Collapsible>
);
};
diff --git a/packages/ui/src/lib/databases.ts b/packages/ui/src/lib/databases.ts
index a1fe2ea5..5adb2860 100644
--- a/packages/ui/src/lib/databases.ts
+++ b/packages/ui/src/lib/databases.ts
@@ -4,7 +4,7 @@ import {
FieldAttributes,
FieldType,
FieldValue,
- generateNodeIndex,
+ generateFractionalIndex,
isStringArray,
MultiSelectFieldAttributes,
SelectFieldAttributes,
@@ -1045,45 +1045,49 @@ export const generateViewFieldIndex = (
)
);
- let previousIndex: string | null = null;
- let nextIndex: string | null = null;
if (after === 'name') {
- const lowestIndex = mergedIndexes[0];
- if (!lowestIndex) {
+ const firstField = mergedIndexes[0];
+ if (!firstField) {
return null;
}
- nextIndex = lowestIndex.viewIndex ?? lowestIndex.databaseIndex;
- } else {
- const afterFieldArrayIndex = mergedIndexes.findIndex((f) => f.id === after);
- if (afterFieldArrayIndex === -1) {
- return null;
- }
+ const nextIndex = firstField.viewIndex ?? firstField.databaseIndex;
+ return generateFractionalIndex(null, nextIndex);
+ }
+
+ const afterFieldArrayIndex = mergedIndexes.findIndex((f) => f.id === after);
+ if (afterFieldArrayIndex === -1) {
+ return null;
+ }
+
+ const afterFieldIndex = mergedIndexes[afterFieldArrayIndex];
+ if (!afterFieldIndex) {
+ return null;
+ }
- const afterFieldIndex = mergedIndexes[afterFieldArrayIndex];
- previousIndex =
- afterFieldIndex?.viewIndex ?? afterFieldIndex?.databaseIndex ?? null;
+ const previousIndex =
+ afterFieldIndex?.viewIndex ?? afterFieldIndex?.databaseIndex ?? null;
+ let nextIndex: string | null = null;
- if (afterFieldArrayIndex < mergedIndexes.length) {
- const nextFieldIndex = mergedIndexes[afterFieldArrayIndex + 1];
- nextIndex =
- nextFieldIndex?.viewIndex ?? nextFieldIndex?.databaseIndex ?? null;
- }
+ if (afterFieldArrayIndex < mergedIndexes.length) {
+ const nextFieldIndex = mergedIndexes[afterFieldArrayIndex + 1];
+ nextIndex =
+ nextFieldIndex?.viewIndex ?? nextFieldIndex?.databaseIndex ?? null;
}
- let newIndex = generateNodeIndex(previousIndex, nextIndex);
+ let newIndex = generateFractionalIndex(previousIndex, nextIndex);
- const lastDatabaseField = mergedIndexes.sort((a, b) =>
- compareString(a.databaseIndex, b.databaseIndex)
- )[mergedIndexes.length - 1]!;
+ const maxDatabaseIndex = mergedIndexes
+ .map((f) => f.databaseIndex)
+ .sort((a, b) => -compareString(a, b))[0]!;
- const newPotentialFieldIndex = generateNodeIndex(
- lastDatabaseField.databaseIndex,
+ const newPotentialFieldIndex = generateFractionalIndex(
+ maxDatabaseIndex,
null
);
if (newPotentialFieldIndex === newIndex) {
- newIndex = generateNodeIndex(previousIndex, newPotentialFieldIndex);
+ newIndex = generateFractionalIndex(previousIndex, newPotentialFieldIndex);
}
return newIndex;
diff --git a/packages/ui/src/lib/spaces.ts b/packages/ui/src/lib/spaces.ts
new file mode 100644
index 00000000..09dbd6be
--- /dev/null
+++ b/packages/ui/src/lib/spaces.ts
@@ -0,0 +1,24 @@
+import { LocalNode, LocalSpaceNode } from '@colanode/client/types';
+import { compareString, generateFractionalIndex } from '@colanode/core';
+
+export const sortSpaceChildren = (
+ space: LocalSpaceNode,
+ children: LocalNode[]
+) => {
+ const sortedById = children.toSorted((a, b) => compareString(a.id, b.id));
+ const indexes: Record<string, string> = {};
+ const childrenSettings = space.attributes.children ?? {};
+ let lastIndex: string | null = null;
+
+ for (const child of sortedById) {
+ lastIndex = generateFractionalIndex(lastIndex, null);
+ const customIndex = childrenSettings[child.id]?.index;
+ indexes[child.id] = customIndex ?? lastIndex;
+ }
+
+ return sortedById.sort((a, b) => {
+ const aIndex = indexes[a.id];
+ const bIndex = indexes[b.id];
+ return compareString(aIndex, bIndex);
+ });
+};